diff options
1214 files changed, 23765 insertions, 11576 deletions
diff --git a/contrib/compiler-rt/include/xray/xray_interface.h b/contrib/compiler-rt/include/xray/xray_interface.h index c90025e38aae..c3833f0be357 100644 --- a/contrib/compiler-rt/include/xray/xray_interface.h +++ b/contrib/compiler-rt/include/xray/xray_interface.h @@ -1,4 +1,4 @@ -//===-- xray_interface.h ----------------------------------------*- C++ -*-===// +//===- xray_interface.h -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -11,11 +11,12 @@ // // APIs for controlling XRay functionality explicitly. //===----------------------------------------------------------------------===// + #ifndef XRAY_XRAY_INTERFACE_H #define XRAY_XRAY_INTERFACE_H +#include <cstddef> #include <cstdint> -#include <stddef.h> extern "C" { @@ -25,6 +26,7 @@ enum XRayEntryType { EXIT = 1, TAIL = 2, LOG_ARGS_ENTRY = 3, + CUSTOM_EVENT = 4, }; /// Provide a function to invoke for when instrumentation points are hit. This @@ -64,6 +66,9 @@ extern int __xray_set_handler_arg1(void (*)(int32_t, XRayEntryType, uint64_t)); /// Returns 1 on success, 0 on error. extern int __xray_remove_handler_arg1(); +/// Provide a function to invoke when XRay encounters a custom event. +extern int __xray_set_customevent_handler(void (*entry)(void*, std::size_t)); + enum XRayPatchingStatus { NOT_INITIALIZED = 0, SUCCESS = 1, @@ -96,6 +101,6 @@ extern uintptr_t __xray_function_address(int32_t FuncId); /// encounter errors (when there are no instrumented functions, etc.). extern size_t __xray_max_function_id(); -} +} // end extern "C" -#endif +#endif // XRAY_XRAY_INTERFACE_H diff --git a/contrib/compiler-rt/lib/asan/asan_allocator.h b/contrib/compiler-rt/lib/asan/asan_allocator.h index ee28ecf98cab..ad1aeb58a86b 100644 --- a/contrib/compiler-rt/lib/asan/asan_allocator.h +++ b/contrib/compiler-rt/lib/asan/asan_allocator.h @@ -161,10 +161,17 @@ typedef FlatByteMap<kNumRegions> ByteMap; typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap; # endif typedef CompactSizeClassMap SizeClassMap; -typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, 16, - SizeClassMap, kRegionSizeLog, - ByteMap, - AsanMapUnmapCallback> PrimaryAllocator; +struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = 16; + typedef __asan::SizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = __asan::kRegionSizeLog; + typedef __asan::ByteMap ByteMap; + typedef AsanMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; +}; +typedef SizeClassAllocator32<AP32> PrimaryAllocator; #endif // SANITIZER_CAN_USE_ALLOCATOR64 static const uptr kNumberOfSizeClasses = SizeClassMap::kNumClasses; diff --git a/contrib/compiler-rt/lib/asan/asan_flags.cc b/contrib/compiler-rt/lib/asan/asan_flags.cc index c8ae3faed7c2..6be0d6e94b9a 100644 --- a/contrib/compiler-rt/lib/asan/asan_flags.cc +++ b/contrib/compiler-rt/lib/asan/asan_flags.cc @@ -194,6 +194,10 @@ void InitializeFlags() { Report("WARNING: strchr* interceptors are enabled even though " "replace_str=0. Use intercept_strchr=0 to disable them."); } + if (!f->replace_str && common_flags()->intercept_strndup) { + Report("WARNING: strndup* interceptors are enabled even though " + "replace_str=0. Use intercept_strndup=0 to disable them."); + } } } // namespace __asan diff --git a/contrib/compiler-rt/lib/builtins/adddf3.c b/contrib/compiler-rt/lib/builtins/adddf3.c index 8b7aae0a6f87..c528e9e21f51 100644 --- a/contrib/compiler-rt/lib/builtins/adddf3.c +++ b/contrib/compiler-rt/lib/builtins/adddf3.c @@ -15,8 +15,13 @@ #define DOUBLE_PRECISION #include "fp_add_impl.inc" -ARM_EABI_FNALIAS(dadd, adddf3) - COMPILER_RT_ABI double __adddf3(double a, double b){ return __addXf3__(a, b); } + +#if defined(__ARM_EABI__) +AEABI_RTABI double __aeabi_dadd(double a, double b) { + return __adddf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/addsf3.c b/contrib/compiler-rt/lib/builtins/addsf3.c index 0f5d6ea4097a..fe570687a25e 100644 --- a/contrib/compiler-rt/lib/builtins/addsf3.c +++ b/contrib/compiler-rt/lib/builtins/addsf3.c @@ -15,8 +15,13 @@ #define SINGLE_PRECISION #include "fp_add_impl.inc" -ARM_EABI_FNALIAS(fadd, addsf3) - COMPILER_RT_ABI float __addsf3(float a, float b) { return __addXf3__(a, b); } + +#if defined(__ARM_EABI__) +AEABI_RTABI float __aeabi_fadd(float a, float b) { + return __addsf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/arm/aeabi_cdcmpeq_check_nan.c b/contrib/compiler-rt/lib/builtins/arm/aeabi_cdcmpeq_check_nan.c index 577f6b2c5535..7578433a1df7 100644 --- a/contrib/compiler-rt/lib/builtins/arm/aeabi_cdcmpeq_check_nan.c +++ b/contrib/compiler-rt/lib/builtins/arm/aeabi_cdcmpeq_check_nan.c @@ -8,9 +8,9 @@ //===----------------------------------------------------------------------===// #include <stdint.h> +#include "../int_lib.h" -__attribute__((pcs("aapcs"))) -__attribute__((visibility("hidden"))) +AEABI_RTABI __attribute__((visibility("hidden"))) int __aeabi_cdcmpeq_check_nan(double a, double b) { return __builtin_isnan(a) || __builtin_isnan(b); } diff --git a/contrib/compiler-rt/lib/builtins/arm/aeabi_cfcmpeq_check_nan.c b/contrib/compiler-rt/lib/builtins/arm/aeabi_cfcmpeq_check_nan.c index 992e31fbd8d6..43dde9a49597 100644 --- a/contrib/compiler-rt/lib/builtins/arm/aeabi_cfcmpeq_check_nan.c +++ b/contrib/compiler-rt/lib/builtins/arm/aeabi_cfcmpeq_check_nan.c @@ -8,9 +8,9 @@ //===----------------------------------------------------------------------===// #include <stdint.h> +#include "../int_lib.h" -__attribute__((pcs("aapcs"))) -__attribute__((visibility("hidden"))) +AEABI_RTABI __attribute__((visibility("hidden"))) int __aeabi_cfcmpeq_check_nan(float a, float b) { return __builtin_isnan(a) || __builtin_isnan(b); } diff --git a/contrib/compiler-rt/lib/builtins/arm/aeabi_div0.c b/contrib/compiler-rt/lib/builtins/arm/aeabi_div0.c index ccc95fa5c12e..dc3031326e37 100644 --- a/contrib/compiler-rt/lib/builtins/arm/aeabi_div0.c +++ b/contrib/compiler-rt/lib/builtins/arm/aeabi_div0.c @@ -26,16 +26,18 @@ * line. */ +#include "../int_lib.h" + /* provide an unused declaration to pacify pendantic compilation */ extern unsigned char declaration; #if defined(__ARM_EABI__) -int __attribute__((weak)) __attribute__((visibility("hidden"))) +AEABI_RTABI int __attribute__((weak)) __attribute__((visibility("hidden"))) __aeabi_idiv0(int return_value) { return return_value; } -long long __attribute__((weak)) __attribute__((visibility("hidden"))) +AEABI_RTABI long long __attribute__((weak)) __attribute__((visibility("hidden"))) __aeabi_ldiv0(long long return_value) { return return_value; } diff --git a/contrib/compiler-rt/lib/builtins/arm/aeabi_drsub.c b/contrib/compiler-rt/lib/builtins/arm/aeabi_drsub.c index fc17d5a4cc76..1254886086fb 100644 --- a/contrib/compiler-rt/lib/builtins/arm/aeabi_drsub.c +++ b/contrib/compiler-rt/lib/builtins/arm/aeabi_drsub.c @@ -10,10 +10,10 @@ #define DOUBLE_PRECISION #include "../fp_lib.h" -COMPILER_RT_ABI fp_t +AEABI_RTABI fp_t __aeabi_dsub(fp_t, fp_t); -COMPILER_RT_ABI fp_t +AEABI_RTABI fp_t __aeabi_drsub(fp_t a, fp_t b) { return __aeabi_dsub(b, a); } diff --git a/contrib/compiler-rt/lib/builtins/arm/aeabi_frsub.c b/contrib/compiler-rt/lib/builtins/arm/aeabi_frsub.c index 64258dc7e070..34f2303745bc 100644 --- a/contrib/compiler-rt/lib/builtins/arm/aeabi_frsub.c +++ b/contrib/compiler-rt/lib/builtins/arm/aeabi_frsub.c @@ -10,10 +10,10 @@ #define SINGLE_PRECISION #include "../fp_lib.h" -COMPILER_RT_ABI fp_t +AEABI_RTABI fp_t __aeabi_fsub(fp_t, fp_t); -COMPILER_RT_ABI fp_t +AEABI_RTABI fp_t __aeabi_frsub(fp_t a, fp_t b) { return __aeabi_fsub(b, a); } diff --git a/contrib/compiler-rt/lib/builtins/ashldi3.c b/contrib/compiler-rt/lib/builtins/ashldi3.c index eb4698ac517c..fcb0abdb1fce 100644 --- a/contrib/compiler-rt/lib/builtins/ashldi3.c +++ b/contrib/compiler-rt/lib/builtins/ashldi3.c @@ -18,8 +18,6 @@ /* Precondition: 0 <= b < bits_in_dword */ -ARM_EABI_FNALIAS(llsl, ashldi3) - COMPILER_RT_ABI di_int __ashldi3(di_int a, si_int b) { @@ -41,3 +39,10 @@ __ashldi3(di_int a, si_int b) } return result.all; } + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int __aeabi_llsl(di_int a, si_int b) { + return __ashldi3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/ashrdi3.c b/contrib/compiler-rt/lib/builtins/ashrdi3.c index 14c878bb7793..b4ab4c617ba0 100644 --- a/contrib/compiler-rt/lib/builtins/ashrdi3.c +++ b/contrib/compiler-rt/lib/builtins/ashrdi3.c @@ -18,8 +18,6 @@ /* Precondition: 0 <= b < bits_in_dword */ -ARM_EABI_FNALIAS(lasr, ashrdi3) - COMPILER_RT_ABI di_int __ashrdi3(di_int a, si_int b) { @@ -42,3 +40,10 @@ __ashrdi3(di_int a, si_int b) } return result.all; } + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int __aeabi_lasr(di_int a, si_int b) { + return __ashrdi3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/assembly.h b/contrib/compiler-rt/lib/builtins/assembly.h index af959b24b874..88271270a077 100644 --- a/contrib/compiler-rt/lib/builtins/assembly.h +++ b/contrib/compiler-rt/lib/builtins/assembly.h @@ -44,7 +44,8 @@ #endif #define CONST_SECTION .section .rodata -#if defined(__GNU__) || defined(__ANDROID__) || defined(__FreeBSD__) +#if defined(__GNU__) || defined(__FreeBSD__) || defined(__Fuchsia__) || \ + defined(__linux__) #define NO_EXEC_STACK_DIRECTIVE .section .note.GNU-stack,"",%progbits #else #define NO_EXEC_STACK_DIRECTIVE diff --git a/contrib/compiler-rt/lib/builtins/comparedf2.c b/contrib/compiler-rt/lib/builtins/comparedf2.c index 9e29752231e9..c5bb169d0021 100644 --- a/contrib/compiler-rt/lib/builtins/comparedf2.c +++ b/contrib/compiler-rt/lib/builtins/comparedf2.c @@ -113,8 +113,6 @@ __gedf2(fp_t a, fp_t b) { } } -ARM_EABI_FNALIAS(dcmpun, unorddf2) - COMPILER_RT_ABI int __unorddf2(fp_t a, fp_t b) { const rep_t aAbs = toRep(a) & absMask; @@ -144,3 +142,9 @@ __gtdf2(fp_t a, fp_t b) { return __gedf2(a, b); } +#if defined(__ARM_EABI__) +AEABI_RTABI int __aeabi_dcmpun(fp_t a, fp_t b) { + return __unorddf2(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/comparesf2.c b/contrib/compiler-rt/lib/builtins/comparesf2.c index 1fd50636abaf..4badb5e1b9f7 100644 --- a/contrib/compiler-rt/lib/builtins/comparesf2.c +++ b/contrib/compiler-rt/lib/builtins/comparesf2.c @@ -113,8 +113,6 @@ __gesf2(fp_t a, fp_t b) { } } -ARM_EABI_FNALIAS(fcmpun, unordsf2) - COMPILER_RT_ABI int __unordsf2(fp_t a, fp_t b) { const rep_t aAbs = toRep(a) & absMask; @@ -143,3 +141,10 @@ COMPILER_RT_ABI enum GE_RESULT __gtsf2(fp_t a, fp_t b) { return __gesf2(a, b); } + +#if defined(__ARM_EABI__) +AEABI_RTABI int __aeabi_fcmpun(fp_t a, fp_t b) { + return __unordsf2(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/divdf3.c b/contrib/compiler-rt/lib/builtins/divdf3.c index ab44c2b25fe5..492e32b851e9 100644 --- a/contrib/compiler-rt/lib/builtins/divdf3.c +++ b/contrib/compiler-rt/lib/builtins/divdf3.c @@ -19,8 +19,6 @@ #define DOUBLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(ddiv, divdf3) - COMPILER_RT_ABI fp_t __divdf3(fp_t a, fp_t b) { @@ -183,3 +181,10 @@ __divdf3(fp_t a, fp_t b) { return result; } } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_ddiv(fp_t a, fp_t b) { + return __divdf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/divsf3.c b/contrib/compiler-rt/lib/builtins/divsf3.c index de2e376125b6..aa6289a6d70a 100644 --- a/contrib/compiler-rt/lib/builtins/divsf3.c +++ b/contrib/compiler-rt/lib/builtins/divsf3.c @@ -19,8 +19,6 @@ #define SINGLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(fdiv, divsf3) - COMPILER_RT_ABI fp_t __divsf3(fp_t a, fp_t b) { @@ -167,3 +165,10 @@ __divsf3(fp_t a, fp_t b) { return fromRep(absResult | quotientSign); } } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_fdiv(fp_t a, fp_t b) { + return __divsf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/divsi3.c b/contrib/compiler-rt/lib/builtins/divsi3.c index bab4aefda30a..3852e3990b5b 100644 --- a/contrib/compiler-rt/lib/builtins/divsi3.c +++ b/contrib/compiler-rt/lib/builtins/divsi3.c @@ -16,8 +16,6 @@ /* Returns: a / b */ -ARM_EABI_FNALIAS(idiv, divsi3) - COMPILER_RT_ABI si_int __divsi3(si_int a, si_int b) { @@ -35,3 +33,10 @@ __divsi3(si_int a, si_int b) */ return ((su_int)a/(su_int)b ^ s_a) - s_a; /* negate if s_a == -1 */ } + +#if defined(__ARM_EABI__) +AEABI_RTABI si_int __aeabi_idiv(si_int a, si_int b) { + return __divsi3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/extendhfsf2.c b/contrib/compiler-rt/lib/builtins/extendhfsf2.c index 27115a48c184..e7d9fde8abfc 100644 --- a/contrib/compiler-rt/lib/builtins/extendhfsf2.c +++ b/contrib/compiler-rt/lib/builtins/extendhfsf2.c @@ -12,8 +12,6 @@ #define DST_SINGLE #include "fp_extend_impl.inc" -ARM_EABI_FNALIAS(h2f, extendhfsf2) - // Use a forwarding definition and noinline to implement a poor man's alias, // as there isn't a good cross-platform way of defining one. COMPILER_RT_ABI NOINLINE float __extendhfsf2(uint16_t a) { @@ -23,3 +21,10 @@ COMPILER_RT_ABI NOINLINE float __extendhfsf2(uint16_t a) { COMPILER_RT_ABI float __gnu_h2f_ieee(uint16_t a) { return __extendhfsf2(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI float __aeabi_h2f(uint16_t a) { + return __extendhfsf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/extendsfdf2.c b/contrib/compiler-rt/lib/builtins/extendsfdf2.c index 7a267c2f47ad..b9e7a7471a98 100644 --- a/contrib/compiler-rt/lib/builtins/extendsfdf2.c +++ b/contrib/compiler-rt/lib/builtins/extendsfdf2.c @@ -12,8 +12,13 @@ #define DST_DOUBLE #include "fp_extend_impl.inc" -ARM_EABI_FNALIAS(f2d, extendsfdf2) - COMPILER_RT_ABI double __extendsfdf2(float a) { return __extendXfYf2__(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI double __aeabi_f2d(float a) { + return __extendsfdf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixdfdi.c b/contrib/compiler-rt/lib/builtins/fixdfdi.c index 14283ef42e61..31d76df28255 100644 --- a/contrib/compiler-rt/lib/builtins/fixdfdi.c +++ b/contrib/compiler-rt/lib/builtins/fixdfdi.c @@ -10,7 +10,6 @@ #define DOUBLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(d2lz, fixdfdi) #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; can set the invalid @@ -44,3 +43,15 @@ __fixdfdi(fp_t a) { } #endif + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int +#if defined(__SOFT_FP__) +__aeabi_d2lz(fp_t a) { +#else +__aeabi_d2lz(double a) { +#endif + return __fixdfdi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixdfsi.c b/contrib/compiler-rt/lib/builtins/fixdfsi.c index 704e65bc43a1..fc316dcd0545 100644 --- a/contrib/compiler-rt/lib/builtins/fixdfsi.c +++ b/contrib/compiler-rt/lib/builtins/fixdfsi.c @@ -14,9 +14,14 @@ typedef si_int fixint_t; typedef su_int fixuint_t; #include "fp_fixint_impl.inc" -ARM_EABI_FNALIAS(d2iz, fixdfsi) - COMPILER_RT_ABI si_int __fixdfsi(fp_t a) { return __fixint(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI si_int __aeabi_d2iz(fp_t a) { + return __fixdfsi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixsfdi.c b/contrib/compiler-rt/lib/builtins/fixsfdi.c index fab47e272a25..c43473637d60 100644 --- a/contrib/compiler-rt/lib/builtins/fixsfdi.c +++ b/contrib/compiler-rt/lib/builtins/fixsfdi.c @@ -11,8 +11,6 @@ #define SINGLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(f2lz, fixsfdi) - #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; can set the invalid * flag as a side-effect of computation. @@ -45,3 +43,15 @@ __fixsfdi(fp_t a) { } #endif + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int +#if defined(__SOFT_FP__) +__aeabi_f2lz(fp_t a) { +#else +__aeabi_f2lz(float a) { +#endif + return __fixsfdi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixsfsi.c b/contrib/compiler-rt/lib/builtins/fixsfsi.c index f045536d6857..3276df966460 100644 --- a/contrib/compiler-rt/lib/builtins/fixsfsi.c +++ b/contrib/compiler-rt/lib/builtins/fixsfsi.c @@ -14,9 +14,14 @@ typedef si_int fixint_t; typedef su_int fixuint_t; #include "fp_fixint_impl.inc" -ARM_EABI_FNALIAS(f2iz, fixsfsi) - COMPILER_RT_ABI si_int __fixsfsi(fp_t a) { return __fixint(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI si_int __aeabi_f2iz(fp_t a) { + return __fixsfsi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixunsdfdi.c b/contrib/compiler-rt/lib/builtins/fixunsdfdi.c index 4b0bc9e1d051..b734409709bf 100644 --- a/contrib/compiler-rt/lib/builtins/fixunsdfdi.c +++ b/contrib/compiler-rt/lib/builtins/fixunsdfdi.c @@ -11,8 +11,6 @@ #define DOUBLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(d2ulz, fixunsdfdi) - #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; can set the invalid * flag as a side-effect of computation. @@ -42,3 +40,15 @@ __fixunsdfdi(fp_t a) { } #endif + +#if defined(__ARM_EABI__) +AEABI_RTABI du_int +#if defined(__SOFT_FP__) +__aeabi_d2ulz(fp_t a) { +#else +__aeabi_d2ulz(double a) { +#endif + return __fixunsdfdi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixunsdfsi.c b/contrib/compiler-rt/lib/builtins/fixunsdfsi.c index 232d342d77da..bb3d8e0f831b 100644 --- a/contrib/compiler-rt/lib/builtins/fixunsdfsi.c +++ b/contrib/compiler-rt/lib/builtins/fixunsdfsi.c @@ -13,9 +13,14 @@ typedef su_int fixuint_t; #include "fp_fixuint_impl.inc" -ARM_EABI_FNALIAS(d2uiz, fixunsdfsi) - COMPILER_RT_ABI su_int __fixunsdfsi(fp_t a) { return __fixuint(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI su_int __aeabi_d2uiz(fp_t a) { + return __fixunsdfsi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixunssfdi.c b/contrib/compiler-rt/lib/builtins/fixunssfdi.c index f8ebab854f95..5d92245df0d9 100644 --- a/contrib/compiler-rt/lib/builtins/fixunssfdi.c +++ b/contrib/compiler-rt/lib/builtins/fixunssfdi.c @@ -11,8 +11,6 @@ #define SINGLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(f2ulz, fixunssfdi) - #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; can set the invalid * flag as a side-effect of computation. @@ -43,3 +41,15 @@ __fixunssfdi(fp_t a) { } #endif + +#if defined(__ARM_EABI__) +AEABI_RTABI du_int +#if defined(__SOFT_FP__) +__aeabi_f2ulz(fp_t a) { +#else +__aeabi_f2ulz(float a) { +#endif + return __fixunssfdi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/fixunssfsi.c b/contrib/compiler-rt/lib/builtins/fixunssfsi.c index cc2b05bd84f8..91d5e8ae5d7f 100644 --- a/contrib/compiler-rt/lib/builtins/fixunssfsi.c +++ b/contrib/compiler-rt/lib/builtins/fixunssfsi.c @@ -17,9 +17,14 @@ typedef su_int fixuint_t; #include "fp_fixuint_impl.inc" -ARM_EABI_FNALIAS(f2uiz, fixunssfsi) - COMPILER_RT_ABI su_int __fixunssfsi(fp_t a) { return __fixuint(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI su_int __aeabi_f2uiz(fp_t a) { + return __fixunssfsi(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatdidf.c b/contrib/compiler-rt/lib/builtins/floatdidf.c index 2b023ad08beb..fccb29072407 100644 --- a/contrib/compiler-rt/lib/builtins/floatdidf.c +++ b/contrib/compiler-rt/lib/builtins/floatdidf.c @@ -22,8 +22,6 @@ /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */ -ARM_EABI_FNALIAS(l2d, floatdidf) - #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; we'll set the inexact flag * as a side-effect of this computation. @@ -105,3 +103,10 @@ __floatdidf(di_int a) return fb.f; } #endif + +#if defined(__AEABI__) +AEABI_RTABI double __aeabi_l2d(di_int a) { + return __floatdidf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatdisf.c b/contrib/compiler-rt/lib/builtins/floatdisf.c index 3e47580ef576..dd548165c373 100644 --- a/contrib/compiler-rt/lib/builtins/floatdisf.c +++ b/contrib/compiler-rt/lib/builtins/floatdisf.c @@ -22,8 +22,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(l2f, floatdisf) - COMPILER_RT_ABI float __floatdisf(di_int a) { @@ -78,3 +76,10 @@ __floatdisf(di_int a) ((su_int)a & 0x007FFFFF); /* mantissa */ return fb.f; } + +#if defined(__ARM_EABI__) +AEABI_RTABI float __aeabi_l2f(di_int a) { + return __floatdisf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatsidf.c b/contrib/compiler-rt/lib/builtins/floatsidf.c index 1cf99b782a60..2ae395bdc1db 100644 --- a/contrib/compiler-rt/lib/builtins/floatsidf.c +++ b/contrib/compiler-rt/lib/builtins/floatsidf.c @@ -18,8 +18,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(i2d, floatsidf) - COMPILER_RT_ABI fp_t __floatsidf(int a) { @@ -51,3 +49,10 @@ __floatsidf(int a) { // Insert the sign bit and return return fromRep(result | sign); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_i2d(int a) { + return __floatsidf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatsisf.c b/contrib/compiler-rt/lib/builtins/floatsisf.c index 467dd1d1eaf1..08891fcdf201 100644 --- a/contrib/compiler-rt/lib/builtins/floatsisf.c +++ b/contrib/compiler-rt/lib/builtins/floatsisf.c @@ -18,8 +18,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(i2f, floatsisf) - COMPILER_RT_ABI fp_t __floatsisf(int a) { @@ -57,3 +55,10 @@ __floatsisf(int a) { // Insert the sign bit and return return fromRep(result | sign); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_i2f(int a) { + return __floatsisf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatundidf.c b/contrib/compiler-rt/lib/builtins/floatundidf.c index cfd3a7a3b33f..6c1a931ef2f3 100644 --- a/contrib/compiler-rt/lib/builtins/floatundidf.c +++ b/contrib/compiler-rt/lib/builtins/floatundidf.c @@ -22,8 +22,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(ul2d, floatundidf) - #ifndef __SOFT_FP__ /* Support for systems that have hardware floating-point; we'll set the inexact flag * as a side-effect of this computation. @@ -104,3 +102,10 @@ __floatundidf(du_int a) return fb.f; } #endif + +#if defined(__ARM_EABI__) +AEABI_RTABI double __aeabi_ul2d(du_int a) { + return __floatundidf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatundisf.c b/contrib/compiler-rt/lib/builtins/floatundisf.c index 713a44abc8bd..86841a75dc66 100644 --- a/contrib/compiler-rt/lib/builtins/floatundisf.c +++ b/contrib/compiler-rt/lib/builtins/floatundisf.c @@ -22,8 +22,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(ul2f, floatundisf) - COMPILER_RT_ABI float __floatundisf(du_int a) { @@ -75,3 +73,10 @@ __floatundisf(du_int a) ((su_int)a & 0x007FFFFF); /* mantissa */ return fb.f; } + +#if defined(__ARM_EABI__) +AEABI_RTABI float __aeabi_ul2f(du_int a) { + return __floatundisf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatunsidf.c b/contrib/compiler-rt/lib/builtins/floatunsidf.c index 445e18041c48..8d4807194f0b 100644 --- a/contrib/compiler-rt/lib/builtins/floatunsidf.c +++ b/contrib/compiler-rt/lib/builtins/floatunsidf.c @@ -18,8 +18,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(ui2d, floatunsidf) - COMPILER_RT_ABI fp_t __floatunsidf(unsigned int a) { @@ -40,3 +38,10 @@ __floatunsidf(unsigned int a) { result += (rep_t)(exponent + exponentBias) << significandBits; return fromRep(result); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_ui2d(unsigned int a) { + return __floatunsidf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/floatunsisf.c b/contrib/compiler-rt/lib/builtins/floatunsisf.c index ea6f161adc02..f194c046d2fb 100644 --- a/contrib/compiler-rt/lib/builtins/floatunsisf.c +++ b/contrib/compiler-rt/lib/builtins/floatunsisf.c @@ -18,8 +18,6 @@ #include "int_lib.h" -ARM_EABI_FNALIAS(ui2f, floatunsisf) - COMPILER_RT_ABI fp_t __floatunsisf(unsigned int a) { @@ -48,3 +46,10 @@ __floatunsisf(unsigned int a) { result += (rep_t)(exponent + exponentBias) << significandBits; return fromRep(result); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_ui2f(unsigned int a) { + return __floatunsisf(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/int_lib.h b/contrib/compiler-rt/lib/builtins/int_lib.h index f777c55194f0..edb040af2057 100644 --- a/contrib/compiler-rt/lib/builtins/int_lib.h +++ b/contrib/compiler-rt/lib/builtins/int_lib.h @@ -30,20 +30,19 @@ /* ABI macro definitions */ #if __ARM_EABI__ -# define ARM_EABI_FNALIAS(aeabi_name, name) \ - void __aeabi_##aeabi_name() __attribute__((alias("__" #name))); # if defined(COMPILER_RT_ARMHF_TARGET) || (!defined(__clang__) && \ defined(__GNUC__) && (__GNUC__ < 4 || __GNUC__ == 4 && __GNUC_MINOR__ < 5)) /* The pcs attribute was introduced in GCC 4.5.0 */ # define COMPILER_RT_ABI # else -# define COMPILER_RT_ABI __attribute__((pcs("aapcs"))) +# define COMPILER_RT_ABI __attribute__((__pcs__("aapcs"))) # endif #else -# define ARM_EABI_FNALIAS(aeabi_name, name) # define COMPILER_RT_ABI #endif +#define AEABI_RTABI __attribute__((__pcs__("aapcs"))) + #ifdef _MSC_VER #define ALWAYS_INLINE __forceinline #define NOINLINE __declspec(noinline) diff --git a/contrib/compiler-rt/lib/builtins/lshrdi3.c b/contrib/compiler-rt/lib/builtins/lshrdi3.c index 6b1ea923b778..becbbef4eb09 100644 --- a/contrib/compiler-rt/lib/builtins/lshrdi3.c +++ b/contrib/compiler-rt/lib/builtins/lshrdi3.c @@ -18,8 +18,6 @@ /* Precondition: 0 <= b < bits_in_dword */ -ARM_EABI_FNALIAS(llsr, lshrdi3) - COMPILER_RT_ABI di_int __lshrdi3(di_int a, si_int b) { @@ -41,3 +39,10 @@ __lshrdi3(di_int a, si_int b) } return result.all; } + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int __aeabi_llsr(di_int a, si_int b) { + return __lshrdi3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/muldf3.c b/contrib/compiler-rt/lib/builtins/muldf3.c index 1eb733849e5a..59a60190eba3 100644 --- a/contrib/compiler-rt/lib/builtins/muldf3.c +++ b/contrib/compiler-rt/lib/builtins/muldf3.c @@ -15,8 +15,13 @@ #define DOUBLE_PRECISION #include "fp_mul_impl.inc" -ARM_EABI_FNALIAS(dmul, muldf3) - COMPILER_RT_ABI fp_t __muldf3(fp_t a, fp_t b) { return __mulXf3__(a, b); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_dmul(fp_t a, fp_t b) { + return __muldf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/muldi3.c b/contrib/compiler-rt/lib/builtins/muldi3.c index 2dae44c11b95..6818a9e2f722 100644 --- a/contrib/compiler-rt/lib/builtins/muldi3.c +++ b/contrib/compiler-rt/lib/builtins/muldi3.c @@ -40,8 +40,6 @@ __muldsi3(su_int a, su_int b) /* Returns: a * b */ -ARM_EABI_FNALIAS(lmul, muldi3) - COMPILER_RT_ABI di_int __muldi3(di_int a, di_int b) { @@ -54,3 +52,10 @@ __muldi3(di_int a, di_int b) r.s.high += x.s.high * y.s.low + x.s.low * y.s.high; return r.all; } + +#if defined(__ARM_EABI__) +AEABI_RTABI di_int __aeabi_lmul(di_int a, di_int b) { + return __muldi3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/mulsf3.c b/contrib/compiler-rt/lib/builtins/mulsf3.c index 478b3bc0e0e0..f141af1acc58 100644 --- a/contrib/compiler-rt/lib/builtins/mulsf3.c +++ b/contrib/compiler-rt/lib/builtins/mulsf3.c @@ -15,8 +15,13 @@ #define SINGLE_PRECISION #include "fp_mul_impl.inc" -ARM_EABI_FNALIAS(fmul, mulsf3) - COMPILER_RT_ABI fp_t __mulsf3(fp_t a, fp_t b) { return __mulXf3__(a, b); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_fmul(fp_t a, fp_t b) { + return __mulsf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/negdf2.c b/contrib/compiler-rt/lib/builtins/negdf2.c index d634b421cb79..5e2544cdb4be 100644 --- a/contrib/compiler-rt/lib/builtins/negdf2.c +++ b/contrib/compiler-rt/lib/builtins/negdf2.c @@ -14,9 +14,14 @@ #define DOUBLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(dneg, negdf2) - COMPILER_RT_ABI fp_t __negdf2(fp_t a) { return fromRep(toRep(a) ^ signBit); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_dneg(fp_t a) { + return __negdf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/negsf2.c b/contrib/compiler-rt/lib/builtins/negsf2.c index 29c17be4145f..f90b34335680 100644 --- a/contrib/compiler-rt/lib/builtins/negsf2.c +++ b/contrib/compiler-rt/lib/builtins/negsf2.c @@ -14,9 +14,14 @@ #define SINGLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(fneg, negsf2) - COMPILER_RT_ABI fp_t __negsf2(fp_t a) { return fromRep(toRep(a) ^ signBit); } + +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_fneg(fp_t a) { + return __negsf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/subdf3.c b/contrib/compiler-rt/lib/builtins/subdf3.c index 7a79e5e7765d..38340dfab1a6 100644 --- a/contrib/compiler-rt/lib/builtins/subdf3.c +++ b/contrib/compiler-rt/lib/builtins/subdf3.c @@ -15,11 +15,15 @@ #define DOUBLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(dsub, subdf3) - // Subtraction; flip the sign bit of b and add. COMPILER_RT_ABI fp_t __subdf3(fp_t a, fp_t b) { return __adddf3(a, fromRep(toRep(b) ^ signBit)); } +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_dsub(fp_t a, fp_t b) { + return __subdf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/subsf3.c b/contrib/compiler-rt/lib/builtins/subsf3.c index c3b85144af48..34276b1447ba 100644 --- a/contrib/compiler-rt/lib/builtins/subsf3.c +++ b/contrib/compiler-rt/lib/builtins/subsf3.c @@ -15,11 +15,15 @@ #define SINGLE_PRECISION #include "fp_lib.h" -ARM_EABI_FNALIAS(fsub, subsf3) - // Subtraction; flip the sign bit of b and add. COMPILER_RT_ABI fp_t __subsf3(fp_t a, fp_t b) { return __addsf3(a, fromRep(toRep(b) ^ signBit)); } +#if defined(__ARM_EABI__) +AEABI_RTABI fp_t __aeabi_fsub(fp_t a, fp_t b) { + return __subsf3(a, b); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/truncdfhf2.c b/contrib/compiler-rt/lib/builtins/truncdfhf2.c index 17195cd9e799..4bb71aa178a0 100644 --- a/contrib/compiler-rt/lib/builtins/truncdfhf2.c +++ b/contrib/compiler-rt/lib/builtins/truncdfhf2.c @@ -11,8 +11,13 @@ #define DST_HALF #include "fp_trunc_impl.inc" -ARM_EABI_FNALIAS(d2h, truncdfhf2) - COMPILER_RT_ABI uint16_t __truncdfhf2(double a) { return __truncXfYf2__(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI uint16_t __aeabi_d2h(double a) { + return __truncdfhf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/truncdfsf2.c b/contrib/compiler-rt/lib/builtins/truncdfsf2.c index 46ec11dccd79..8bf58bb23a3b 100644 --- a/contrib/compiler-rt/lib/builtins/truncdfsf2.c +++ b/contrib/compiler-rt/lib/builtins/truncdfsf2.c @@ -11,8 +11,13 @@ #define DST_SINGLE #include "fp_trunc_impl.inc" -ARM_EABI_FNALIAS(d2f, truncdfsf2) - COMPILER_RT_ABI float __truncdfsf2(double a) { return __truncXfYf2__(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI float __aeabi_d2f(double a) { + return __truncdfsf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/truncsfhf2.c b/contrib/compiler-rt/lib/builtins/truncsfhf2.c index 9d61895bfd88..f6ce1fa1de05 100644 --- a/contrib/compiler-rt/lib/builtins/truncsfhf2.c +++ b/contrib/compiler-rt/lib/builtins/truncsfhf2.c @@ -11,8 +11,6 @@ #define DST_HALF #include "fp_trunc_impl.inc" -ARM_EABI_FNALIAS(f2h, truncsfhf2) - // Use a forwarding definition and noinline to implement a poor man's alias, // as there isn't a good cross-platform way of defining one. COMPILER_RT_ABI NOINLINE uint16_t __truncsfhf2(float a) { @@ -22,3 +20,10 @@ COMPILER_RT_ABI NOINLINE uint16_t __truncsfhf2(float a) { COMPILER_RT_ABI uint16_t __gnu_f2h_ieee(float a) { return __truncsfhf2(a); } + +#if defined(__ARM_EABI__) +AEABI_RTABI uint16_t __aeabi_f2h(float a) { + return __truncsfhf2(a); +} +#endif + diff --git a/contrib/compiler-rt/lib/builtins/udivsi3.c b/contrib/compiler-rt/lib/builtins/udivsi3.c index 5d0140cc3e75..8eccf102cc97 100644 --- a/contrib/compiler-rt/lib/builtins/udivsi3.c +++ b/contrib/compiler-rt/lib/builtins/udivsi3.c @@ -18,8 +18,6 @@ /* Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide */ -ARM_EABI_FNALIAS(uidiv, udivsi3) - /* This function should not call __divsi3! */ COMPILER_RT_ABI su_int __udivsi3(su_int n, su_int d) @@ -64,3 +62,10 @@ __udivsi3(su_int n, su_int d) q = (q << 1) | carry; return q; } + +#if defined(__ARM_EABI__) +AEABI_RTABI su_int __aeabi_uidiv(su_int n, su_int d) { + return __udivsi3(n, d); +} +#endif + diff --git a/contrib/compiler-rt/lib/esan/esan_interceptors.cpp b/contrib/compiler-rt/lib/esan/esan_interceptors.cpp index 9740f4dae8fa..62fa13c83822 100644 --- a/contrib/compiler-rt/lib/esan/esan_interceptors.cpp +++ b/contrib/compiler-rt/lib/esan/esan_interceptors.cpp @@ -31,6 +31,8 @@ using namespace __esan; // NOLINT // Get the per-platform defines for what is possible to intercept #include "sanitizer_common/sanitizer_platform_interceptors.h" +DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr) + // TODO(bruening): tsan disables several interceptors (getpwent, etc.) claiming // that interception is a perf hit: should we do the same? diff --git a/contrib/compiler-rt/lib/lsan/lsan_allocator.h b/contrib/compiler-rt/lib/lsan/lsan_allocator.h index fad5adb01a7f..5a0d94c71415 100644 --- a/contrib/compiler-rt/lib/lsan/lsan_allocator.h +++ b/contrib/compiler-rt/lib/lsan/lsan_allocator.h @@ -55,10 +55,18 @@ struct ChunkMetadata { static const uptr kRegionSizeLog = 20; static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog; typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap; -typedef CompactSizeClassMap SizeClassMap; -typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, - sizeof(ChunkMetadata), SizeClassMap, kRegionSizeLog, ByteMap> - PrimaryAllocator; + +struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = sizeof(ChunkMetadata); + typedef __sanitizer::CompactSizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = __lsan::kRegionSizeLog; + typedef __lsan::ByteMap ByteMap; + typedef NoOpMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; +}; +typedef SizeClassAllocator32<AP32> PrimaryAllocator; #elif defined(__x86_64__) || defined(__powerpc64__) struct AP64 { // Allocator64 parameters. Deliberately using a short name. static const uptr kSpaceBeg = 0x600000000000ULL; diff --git a/contrib/compiler-rt/lib/lsan/lsan_common_linux.cc b/contrib/compiler-rt/lib/lsan/lsan_common_linux.cc index fadd0263de73..c903be42d1e7 100644 --- a/contrib/compiler-rt/lib/lsan/lsan_common_linux.cc +++ b/contrib/compiler-rt/lib/lsan/lsan_common_linux.cc @@ -62,8 +62,10 @@ void InitializePlatformSpecificModules() { return; } } - VReport(1, "LeakSanitizer: Dynamic linker not found. " - "TLS will not be handled correctly.\n"); + if (linker == nullptr) { + VReport(1, "LeakSanitizer: Dynamic linker not found. " + "TLS will not be handled correctly.\n"); + } } static int ProcessGlobalRegionsCallback(struct dl_phdr_info *info, size_t size, diff --git a/contrib/compiler-rt/lib/lsan/lsan_common_mac.cc b/contrib/compiler-rt/lib/lsan/lsan_common_mac.cc index a9adcdfff37f..5ee1e228691a 100644 --- a/contrib/compiler-rt/lib/lsan/lsan_common_mac.cc +++ b/contrib/compiler-rt/lib/lsan/lsan_common_mac.cc @@ -144,6 +144,11 @@ void ProcessPlatformSpecificAllocations(Frontier *frontier) { if (info.user_tag == VM_MEMORY_OS_ALLOC_ONCE) { ScanRangeForPointers(address, end_address, frontier, "GLOBAL", kReachable); + + // Recursing over the full memory map is very slow, break out + // early if we don't need the full iteration. + if (!flags()->use_root_regions || !root_regions->size()) + break; } // This additional root region scan is required on Darwin in order to diff --git a/contrib/compiler-rt/lib/msan/msan_allocator.cc b/contrib/compiler-rt/lib/msan/msan_allocator.cc index 6c389f008cf7..1be573faa412 100644 --- a/contrib/compiler-rt/lib/msan/msan_allocator.cc +++ b/contrib/compiler-rt/lib/msan/msan_allocator.cc @@ -47,12 +47,18 @@ struct MsanMapUnmapCallback { static const uptr kRegionSizeLog = 20; static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog; typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap; - typedef CompactSizeClassMap SizeClassMap; - - typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, sizeof(Metadata), - SizeClassMap, kRegionSizeLog, ByteMap, - MsanMapUnmapCallback> PrimaryAllocator; + struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = sizeof(Metadata); + typedef __sanitizer::CompactSizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = __msan::kRegionSizeLog; + typedef __msan::ByteMap ByteMap; + typedef MsanMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; + }; + typedef SizeClassAllocator32<AP32> PrimaryAllocator; #elif defined(__x86_64__) #if SANITIZER_LINUX && !defined(MSAN_LINUX_X86_64_OLD_MAPPING) static const uptr kAllocatorSpace = 0x700000000000ULL; @@ -90,11 +96,18 @@ struct MsanMapUnmapCallback { static const uptr kRegionSizeLog = 20; static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog; typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap; - typedef CompactSizeClassMap SizeClassMap; - typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, sizeof(Metadata), - SizeClassMap, kRegionSizeLog, ByteMap, - MsanMapUnmapCallback> PrimaryAllocator; + struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = sizeof(Metadata); + typedef __sanitizer::CompactSizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = __msan::kRegionSizeLog; + typedef __msan::ByteMap ByteMap; + typedef MsanMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; + }; + typedef SizeClassAllocator32<AP32> PrimaryAllocator; #endif typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache; typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator; diff --git a/contrib/compiler-rt/lib/msan/msan_interceptors.cc b/contrib/compiler-rt/lib/msan/msan_interceptors.cc index 15543bd912d6..0f50693441be 100644 --- a/contrib/compiler-rt/lib/msan/msan_interceptors.cc +++ b/contrib/compiler-rt/lib/msan/msan_interceptors.cc @@ -341,33 +341,6 @@ INTERCEPTOR(char *, __strdup, char *src) { #define MSAN_MAYBE_INTERCEPT___STRDUP #endif -INTERCEPTOR(char *, strndup, char *src, SIZE_T n) { - ENSURE_MSAN_INITED(); - GET_STORE_STACK_TRACE; - // On FreeBSD strndup() leverages strnlen(). - InterceptorScope interceptor_scope; - SIZE_T copy_size = REAL(strnlen)(src, n); - char *res = REAL(strndup)(src, n); - CopyShadowAndOrigin(res, src, copy_size, &stack); - __msan_unpoison(res + copy_size, 1); // \0 - return res; -} - -#if !SANITIZER_FREEBSD -INTERCEPTOR(char *, __strndup, char *src, SIZE_T n) { - ENSURE_MSAN_INITED(); - GET_STORE_STACK_TRACE; - SIZE_T copy_size = REAL(strnlen)(src, n); - char *res = REAL(__strndup)(src, n); - CopyShadowAndOrigin(res, src, copy_size, &stack); - __msan_unpoison(res + copy_size, 1); // \0 - return res; -} -#define MSAN_MAYBE_INTERCEPT___STRNDUP INTERCEPT_FUNCTION(__strndup) -#else -#define MSAN_MAYBE_INTERCEPT___STRNDUP -#endif - INTERCEPTOR(char *, gcvt, double number, SIZE_T ndigit, char *buf) { ENSURE_MSAN_INITED(); char *res = REAL(gcvt)(number, ndigit, buf); @@ -1371,6 +1344,13 @@ int OnExit() { return __msan_memcpy(to, from, size); \ } +#define COMMON_INTERCEPTOR_COPY_STRING(ctx, to, from, size) \ + do { \ + GET_STORE_STACK_TRACE; \ + CopyShadowAndOrigin(to, from, size, &stack); \ + __msan_unpoison(to + size, 1); \ + } while (false) + #include "sanitizer_common/sanitizer_platform_interceptors.h" #include "sanitizer_common/sanitizer_common_interceptors.inc" @@ -1538,8 +1518,6 @@ void InitializeInterceptors() { INTERCEPT_FUNCTION(stpcpy); // NOLINT INTERCEPT_FUNCTION(strdup); MSAN_MAYBE_INTERCEPT___STRDUP; - INTERCEPT_FUNCTION(strndup); - MSAN_MAYBE_INTERCEPT___STRNDUP; INTERCEPT_FUNCTION(strncpy); // NOLINT INTERCEPT_FUNCTION(gcvt); INTERCEPT_FUNCTION(strcat); // NOLINT diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_internal.h b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_internal.h index e939cbe01c3c..d1890f20f810 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_internal.h +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_internal.h @@ -23,21 +23,25 @@ namespace __sanitizer { // purposes. typedef CompactSizeClassMap InternalSizeClassMap; -static const uptr kInternalAllocatorSpace = 0; -static const u64 kInternalAllocatorSize = SANITIZER_MMAP_RANGE_SIZE; static const uptr kInternalAllocatorRegionSizeLog = 20; -#if SANITIZER_WORDSIZE == 32 static const uptr kInternalAllocatorNumRegions = - kInternalAllocatorSize >> kInternalAllocatorRegionSizeLog; + SANITIZER_MMAP_RANGE_SIZE >> kInternalAllocatorRegionSizeLog; +#if SANITIZER_WORDSIZE == 32 typedef FlatByteMap<kInternalAllocatorNumRegions> ByteMap; #else -static const uptr kInternalAllocatorNumRegions = - kInternalAllocatorSize >> kInternalAllocatorRegionSizeLog; typedef TwoLevelByteMap<(kInternalAllocatorNumRegions >> 12), 1 << 12> ByteMap; #endif -typedef SizeClassAllocator32< - kInternalAllocatorSpace, kInternalAllocatorSize, 0, InternalSizeClassMap, - kInternalAllocatorRegionSizeLog, ByteMap> PrimaryInternalAllocator; +struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = 0; + typedef InternalSizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = kInternalAllocatorRegionSizeLog; + typedef __sanitizer::ByteMap ByteMap; + typedef NoOpMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; +}; +typedef SizeClassAllocator32<AP32> PrimaryInternalAllocator; typedef SizeClassAllocatorLocalCache<PrimaryInternalAllocator> InternalAllocatorCache; diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_primary32.h b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_primary32.h index 2882afd1fe1d..0f6f4f7f8503 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_primary32.h +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_allocator_primary32.h @@ -36,13 +36,27 @@ template<class SizeClassAllocator> struct SizeClassAllocator32LocalCache; // // In order to avoid false sharing the objects of this class should be // chache-line aligned. -template <const uptr kSpaceBeg, const u64 kSpaceSize, - const uptr kMetadataSize, class SizeClassMap, - const uptr kRegionSizeLog, - class ByteMap, - class MapUnmapCallback = NoOpMapUnmapCallback> + +struct SizeClassAllocator32FlagMasks { // Bit masks. + enum { + kRandomShuffleChunks = 1, + }; +}; + +template <class Params> class SizeClassAllocator32 { public: + static const uptr kSpaceBeg = Params::kSpaceBeg; + static const u64 kSpaceSize = Params::kSpaceSize; + static const uptr kMetadataSize = Params::kMetadataSize; + typedef typename Params::SizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = Params::kRegionSizeLog; + typedef typename Params::ByteMap ByteMap; + typedef typename Params::MapUnmapCallback MapUnmapCallback; + + static const bool kRandomShuffleChunks = + Params::kFlags & SizeClassAllocator32FlagMasks::kRandomShuffleChunks; + struct TransferBatch { static const uptr kMaxNumCached = SizeClassMap::kMaxNumCachedHint - 2; void SetFromArray(uptr region_beg_unused, void *batch[], uptr count) { @@ -86,8 +100,7 @@ class SizeClassAllocator32 { return SizeClassMap::Size(class_id); } - typedef SizeClassAllocator32<kSpaceBeg, kSpaceSize, kMetadataSize, - SizeClassMap, kRegionSizeLog, ByteMap, MapUnmapCallback> ThisT; + typedef SizeClassAllocator32<Params> ThisT; typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache; void Init(s32 release_to_os_interval_ms) { diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc index 53204b48e300..3c69726d7c91 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc @@ -34,6 +34,8 @@ // COMMON_INTERCEPTOR_MEMSET_IMPL // COMMON_INTERCEPTOR_MEMMOVE_IMPL // COMMON_INTERCEPTOR_MEMCPY_IMPL +// COMMON_INTERCEPTOR_COPY_STRING +// COMMON_INTERCEPTOR_STRNDUP_IMPL //===----------------------------------------------------------------------===// #include "interception/interception.h" @@ -217,6 +219,25 @@ bool PlatformHasDifferentMemcpyAndMemmove(); } #endif +#ifndef COMMON_INTERCEPTOR_COPY_STRING +#define COMMON_INTERCEPTOR_COPY_STRING(ctx, to, from, size) {} +#endif + +#ifndef COMMON_INTERCEPTOR_STRNDUP_IMPL +#define COMMON_INTERCEPTOR_STRNDUP_IMPL(ctx, s, size) \ + COMMON_INTERCEPTOR_ENTER(ctx, strndup, s, size); \ + uptr from_length = internal_strnlen(s, size); \ + uptr copy_length = Min(size, from_length); \ + char *new_mem = (char *)WRAP(malloc)(copy_length + 1); \ + if (common_flags()->intercept_strndup) { \ + COMMON_INTERCEPTOR_READ_RANGE(ctx, s, copy_length + 1); \ + } \ + COMMON_INTERCEPTOR_COPY_STRING(ctx, new_mem, s, copy_length); \ + internal_memcpy(new_mem, s, copy_length); \ + new_mem[copy_length] = '\0'; \ + return new_mem; +#endif + struct FileMetadata { // For open_memstream(). char **addr; @@ -300,6 +321,26 @@ INTERCEPTOR(SIZE_T, strnlen, const char *s, SIZE_T maxlen) { #define INIT_STRNLEN #endif +#if SANITIZER_INTERCEPT_STRNDUP +INTERCEPTOR(char*, strndup, const char *s, uptr size) { + void *ctx; + COMMON_INTERCEPTOR_STRNDUP_IMPL(ctx, s, size); +} +#define INIT_STRNDUP COMMON_INTERCEPT_FUNCTION(strndup) +#else +#define INIT_STRNDUP +#endif // SANITIZER_INTERCEPT_STRNDUP + +#if SANITIZER_INTERCEPT___STRNDUP +INTERCEPTOR(char*, __strndup, const char *s, uptr size) { + void *ctx; + COMMON_INTERCEPTOR_STRNDUP_IMPL(ctx, s, size); +} +#define INIT___STRNDUP COMMON_INTERCEPT_FUNCTION(__strndup) +#else +#define INIT___STRNDUP +#endif // SANITIZER_INTERCEPT___STRNDUP + #if SANITIZER_INTERCEPT_TEXTDOMAIN INTERCEPTOR(char*, textdomain, const char *domainname) { void *ctx; @@ -6163,6 +6204,8 @@ static void InitializeCommonInterceptors() { INIT_TEXTDOMAIN; INIT_STRLEN; INIT_STRNLEN; + INIT_STRNDUP; + INIT___STRNDUP; INIT_STRCMP; INIT_STRNCMP; INIT_STRCASECMP; diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc index 7a5fffcf6165..67a0a5810a28 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc @@ -195,6 +195,9 @@ COMMON_FLAG(bool, intercept_strpbrk, true, COMMON_FLAG(bool, intercept_strlen, true, "If set, uses custom wrappers for strlen and strnlen functions " "to find more errors.") +COMMON_FLAG(bool, intercept_strndup, true, + "If set, uses custom wrappers for strndup functions " + "to find more errors.") COMMON_FLAG(bool, intercept_strchr, true, "If set, uses custom wrappers for strchr, strchrnul, and strrchr " "functions to find more errors.") diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h index e5644ef25e83..a95497467d61 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_platform_interceptors.h @@ -25,6 +25,12 @@ # define SI_NOT_WINDOWS 0 #endif +#if SANITIZER_POSIX +# define SI_POSIX 1 +#else +# define SI_POSIX 0 +#endif + #if SANITIZER_LINUX && !SANITIZER_ANDROID # define SI_LINUX_NOT_ANDROID 1 #else @@ -69,6 +75,12 @@ # define SI_UNIX_NOT_MAC 0 #endif +#if SANITIZER_LINUX && !SANITIZER_FREEBSD +# define SI_LINUX_NOT_FREEBSD 1 +# else +# define SI_LINUX_NOT_FREEBSD 0 +#endif + #define SANITIZER_INTERCEPT_STRLEN 1 #define SANITIZER_INTERCEPT_STRNLEN SI_NOT_MAC #define SANITIZER_INTERCEPT_STRCMP 1 @@ -86,6 +98,8 @@ #define SANITIZER_INTERCEPT_MEMMOVE 1 #define SANITIZER_INTERCEPT_MEMCPY 1 #define SANITIZER_INTERCEPT_MEMCMP 1 +#define SANITIZER_INTERCEPT_STRNDUP SI_POSIX +#define SANITIZER_INTERCEPT___STRNDUP SI_LINUX_NOT_FREEBSD #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070 # define SI_MAC_DEPLOYMENT_BELOW_10_7 1 diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h index 9dbb5ef0f4f6..5aad6b959ad4 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps.h @@ -70,6 +70,7 @@ class MemoryMappingLayout { bool NextSegmentLoad(uptr *start, uptr *end, uptr *offset, char filename[], uptr filename_size, ModuleArch *arch, u8 *uuid, uptr *protection); + void GetSegmentAddrRange(uptr *start, uptr *end, uptr vmaddr, uptr vmsize); int current_image_; u32 current_magic_; u32 current_filetype_; diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc index fdf85b77a680..7e4a44be95b6 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_linux.cc @@ -18,8 +18,8 @@ namespace __sanitizer { void ReadProcMaps(ProcSelfMapsBuff *proc_maps) { - CHECK(ReadFileToBuffer("/proc/self/maps", &proc_maps->data, - &proc_maps->mmaped_size, &proc_maps->len)); + ReadFileToBuffer("/proc/self/maps", &proc_maps->data, &proc_maps->mmaped_size, + &proc_maps->len); } static bool IsOneOf(char c, char c1, char c2) { diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc index be59b481f5a1..0b4171a90f60 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc @@ -18,6 +18,7 @@ #include <mach-o/dyld.h> #include <mach-o/loader.h> +#include <mach/mach.h> // These are not available in older macOS SDKs. #ifndef CPU_SUBTYPE_X86_64_H @@ -71,6 +72,13 @@ void MemoryMappingLayout::Reset() { internal_memset(current_uuid_, 0, kModuleUUIDSize); } +// The dyld load address should be unchanged throughout process execution, +// and it is expensive to compute once many libraries have been loaded, +// so cache it here and do not reset. +static mach_header *dyld_hdr = 0; +static const char kDyldPath[] = "/usr/lib/dyld"; +static const int kDyldImageIdx = -1; + // static void MemoryMappingLayout::CacheMemoryMappings() { // No-op on Mac for now. @@ -95,14 +103,12 @@ bool MemoryMappingLayout::NextSegmentLoad(uptr *start, uptr *end, uptr *offset, const char *lc = current_load_cmd_addr_; current_load_cmd_addr_ += ((const load_command *)lc)->cmdsize; if (((const load_command *)lc)->cmd == kLCSegment) { - const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_); const SegmentCommand* sc = (const SegmentCommand *)lc; - if (start) *start = sc->vmaddr + dlloff; + GetSegmentAddrRange(start, end, sc->vmaddr, sc->vmsize); if (protection) { // Return the initial protection. *protection = sc->initprot; } - if (end) *end = sc->vmaddr + sc->vmsize + dlloff; if (offset) { if (current_filetype_ == /*MH_EXECUTE*/ 0x2) { *offset = sc->vmaddr; @@ -111,8 +117,12 @@ bool MemoryMappingLayout::NextSegmentLoad(uptr *start, uptr *end, uptr *offset, } } if (filename) { - internal_strncpy(filename, _dyld_get_image_name(current_image_), - filename_size); + if (current_image_ == kDyldImageIdx) { + internal_strncpy(filename, kDyldPath, filename_size); + } else { + internal_strncpy(filename, _dyld_get_image_name(current_image_), + filename_size); + } } if (arch) { *arch = current_arch_; @@ -180,11 +190,74 @@ static bool IsModuleInstrumented(const load_command *first_lc) { return false; } +// _dyld_get_image_header() and related APIs don't report dyld itself. +// We work around this by manually recursing through the memory map +// until we hit a Mach header matching dyld instead. These recurse +// calls are expensive, but the first memory map generation occurs +// early in the process, when dyld is one of the only images loaded, +// so it will be hit after only a few iterations. +static mach_header *get_dyld_image_header() { + mach_port_name_t port; + if (task_for_pid(mach_task_self(), internal_getpid(), &port) != + KERN_SUCCESS) { + return nullptr; + } + + unsigned depth = 1; + vm_size_t size = 0; + vm_address_t address = 0; + kern_return_t err = KERN_SUCCESS; + mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64; + + while (true) { + struct vm_region_submap_info_64 info; + err = vm_region_recurse_64(port, &address, &size, &depth, + (vm_region_info_t)&info, &count); + if (err != KERN_SUCCESS) return nullptr; + + if (size >= sizeof(mach_header) && + info.protection & MemoryMappingLayout::kProtectionRead) { + mach_header *hdr = (mach_header *)address; + if ((hdr->magic == MH_MAGIC || hdr->magic == MH_MAGIC_64) && + hdr->filetype == MH_DYLINKER) { + return hdr; + } + } + address += size; + } +} + +const mach_header *get_dyld_hdr() { + if (!dyld_hdr) dyld_hdr = get_dyld_image_header(); + + return dyld_hdr; +} + +void MemoryMappingLayout::GetSegmentAddrRange(uptr *start, uptr *end, + uptr vmaddr, uptr vmsize) { + if (current_image_ == kDyldImageIdx) { + // vmaddr is masked with 0xfffff because on macOS versions < 10.12, + // it contains an absolute address rather than an offset for dyld. + // To make matters even more complicated, this absolute address + // isn't actually the absolute segment address, but the offset portion + // of the address is accurate when combined with the dyld base address, + // and the mask will give just this offset. + if (start) *start = (vmaddr & 0xfffff) + (uptr)get_dyld_hdr(); + if (end) *end = (vmaddr & 0xfffff) + vmsize + (uptr)get_dyld_hdr(); + } else { + const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_); + if (start) *start = vmaddr + dlloff; + if (end) *end = vmaddr + vmsize + dlloff; + } +} + bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset, char filename[], uptr filename_size, uptr *protection, ModuleArch *arch, u8 *uuid) { - for (; current_image_ >= 0; current_image_--) { - const mach_header* hdr = _dyld_get_image_header(current_image_); + for (; current_image_ >= kDyldImageIdx; current_image_--) { + const mach_header *hdr = (current_image_ == kDyldImageIdx) + ? get_dyld_hdr() + : _dyld_get_image_header(current_image_); if (!hdr) continue; if (current_load_cmd_count_ < 0) { // Set up for this image; diff --git a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc index 20b8760935bd..0c27c472f02e 100644 --- a/contrib/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc +++ b/contrib/compiler-rt/lib/sanitizer_common/sanitizer_stoptheworld_mac.cc @@ -170,6 +170,10 @@ PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP( internal_memcpy(buffer, ®s, sizeof(regs)); *sp = regs.SP_REG; + // On x86_64 and aarch64, we must account for the stack redzone, which is 128 + // bytes. + if (SANITIZER_WORDSIZE == 64) *sp -= 128; + return REGISTERS_AVAILABLE; } diff --git a/contrib/compiler-rt/lib/scudo/scudo_allocator.cpp b/contrib/compiler-rt/lib/scudo/scudo_allocator.cpp index 5420fc9649ca..ce69ddf55531 100644 --- a/contrib/compiler-rt/lib/scudo/scudo_allocator.cpp +++ b/contrib/compiler-rt/lib/scudo/scudo_allocator.cpp @@ -15,6 +15,7 @@ //===----------------------------------------------------------------------===// #include "scudo_allocator.h" +#include "scudo_crc32.h" #include "scudo_tls.h" #include "scudo_utils.h" @@ -34,21 +35,28 @@ static uptr Cookie; // at compilation or at runtime. static atomic_uint8_t HashAlgorithm = { CRC32Software }; -SANITIZER_WEAK_ATTRIBUTE u32 computeHardwareCRC32(u32 Crc, uptr Data); - -INLINE u32 computeCRC32(u32 Crc, uptr Data, u8 HashType) { - // If SSE4.2 is defined here, it was enabled everywhere, as opposed to only - // for scudo_crc32.cpp. This means that other SSE instructions were likely - // emitted at other places, and as a result there is no reason to not use - // the hardware version of the CRC32. +INLINE u32 computeCRC32(uptr Crc, uptr Value, uptr *Array, uptr ArraySize) { + // If the hardware CRC32 feature is defined here, it was enabled everywhere, + // as opposed to only for scudo_crc32.cpp. This means that other hardware + // specific instructions were likely emitted at other places, and as a + // result there is no reason to not use it here. #if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) - return computeHardwareCRC32(Crc, Data); + Crc = CRC32_INTRINSIC(Crc, Value); + for (uptr i = 0; i < ArraySize; i++) + Crc = CRC32_INTRINSIC(Crc, Array[i]); + return Crc; #else - if (computeHardwareCRC32 && HashType == CRC32Hardware) - return computeHardwareCRC32(Crc, Data); - else - return computeSoftwareCRC32(Crc, Data); -#endif // defined(__SSE4_2__) + if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) { + Crc = computeHardwareCRC32(Crc, Value); + for (uptr i = 0; i < ArraySize; i++) + Crc = computeHardwareCRC32(Crc, Array[i]); + return Crc; + } + Crc = computeSoftwareCRC32(Crc, Value); + for (uptr i = 0; i < ArraySize; i++) + Crc = computeSoftwareCRC32(Crc, Array[i]); + return Crc; +#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) } static ScudoBackendAllocator &getBackendAllocator(); @@ -65,8 +73,9 @@ struct ScudoChunk : UnpackedHeader { // Returns the usable size for a chunk, meaning the amount of bytes from the // beginning of the user data to the end of the backend allocated chunk. uptr getUsableSize(UnpackedHeader *Header) { - uptr Size = getBackendAllocator().GetActuallyAllocatedSize( - getAllocBeg(Header)); + uptr Size = + getBackendAllocator().GetActuallyAllocatedSize(getAllocBeg(Header), + Header->FromPrimary); if (Size == 0) return 0; return Size - AlignedChunkHeaderSize - (Header->Offset << MinAlignmentLog); @@ -78,10 +87,8 @@ struct ScudoChunk : UnpackedHeader { ZeroChecksumHeader.Checksum = 0; uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)]; memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder)); - u8 HashType = atomic_load_relaxed(&HashAlgorithm); - u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(this), HashType); - for (uptr i = 0; i < ARRAY_SIZE(HeaderHolder); i++) - Crc = computeCRC32(Crc, HeaderHolder[i], HashType); + u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(this), HeaderHolder, + ARRAY_SIZE(HeaderHolder)); return static_cast<u16>(Crc); } @@ -195,10 +202,10 @@ void initScudo() { CHECK(!ScudoInitIsRunning && "Scudo init calls itself!"); ScudoInitIsRunning = true; - // Check is SSE4.2 is supported, if so, opt for the CRC32 hardware version. - if (testCPUFeature(CRC32CPUFeature)) { + // Check if hardware CRC32 is supported in the binary and by the platform, if + // so, opt for the CRC32 hardware version of the checksum. + if (computeHardwareCRC32 && testCPUFeature(CRC32CPUFeature)) atomic_store_relaxed(&HashAlgorithm, CRC32Hardware); - } initFlags(); @@ -215,7 +222,8 @@ struct QuarantineCallback { explicit QuarantineCallback(AllocatorCache *Cache) : Cache_(Cache) {} - // Chunk recycling function, returns a quarantined chunk to the backend. + // Chunk recycling function, returns a quarantined chunk to the backend, + // first making sure it hasn't been tampered with. void Recycle(ScudoChunk *Chunk) { UnpackedHeader Header; Chunk->loadHeader(&Header); @@ -225,17 +233,19 @@ struct QuarantineCallback { } Chunk->eraseHeader(); void *Ptr = Chunk->getAllocBeg(&Header); - getBackendAllocator().Deallocate(Cache_, Ptr); + getBackendAllocator().Deallocate(Cache_, Ptr, Header.FromPrimary); } - /// Internal quarantine allocation and deallocation functions. + // Internal quarantine allocation and deallocation functions. We first check + // that the batches are indeed serviced by the Primary. + // TODO(kostyak): figure out the best way to protect the batches. + COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize); void *Allocate(uptr Size) { - // TODO(kostyak): figure out the best way to protect the batches. - return getBackendAllocator().Allocate(Cache_, Size, MinAlignment); + return getBackendAllocator().Allocate(Cache_, Size, MinAlignment, true); } void Deallocate(void *Ptr) { - getBackendAllocator().Deallocate(Cache_, Ptr); + getBackendAllocator().Deallocate(Cache_, Ptr, true); } AllocatorCache *Cache_; @@ -353,58 +363,55 @@ struct ScudoAllocator { Size = 1; uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize; - if (Alignment > MinAlignment) - NeededSize += Alignment; - if (NeededSize >= MaxAllowedMallocSize) + uptr AlignedSize = (Alignment > MinAlignment) ? + NeededSize + (Alignment - AlignedChunkHeaderSize) : NeededSize; + if (AlignedSize >= MaxAllowedMallocSize) return BackendAllocator.ReturnNullOrDieOnBadRequest(); - // Primary backed and Secondary backed allocations have a different - // treatment. We deal with alignment requirements of Primary serviced - // allocations here, but the Secondary will take care of its own alignment - // needs, which means we also have to work around some limitations of the - // combined allocator to accommodate the situation. - bool FromPrimary = PrimaryAllocator::CanAllocate(NeededSize, MinAlignment); + // Primary and Secondary backed allocations have a different treatment. We + // deal with alignment requirements of Primary serviced allocations here, + // but the Secondary will take care of its own alignment needs. + bool FromPrimary = PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment); void *Ptr; uptr Salt; + uptr AllocationSize = FromPrimary ? AlignedSize : NeededSize; uptr AllocationAlignment = FromPrimary ? MinAlignment : Alignment; ScudoThreadContext *ThreadContext = getThreadContextAndLock(); if (LIKELY(ThreadContext)) { Salt = getPrng(ThreadContext)->getNext(); Ptr = BackendAllocator.Allocate(getAllocatorCache(ThreadContext), - NeededSize, AllocationAlignment); + AllocationSize, AllocationAlignment, + FromPrimary); ThreadContext->unlock(); } else { SpinMutexLock l(&FallbackMutex); Salt = FallbackPrng.getNext(); - Ptr = BackendAllocator.Allocate(&FallbackAllocatorCache, NeededSize, - AllocationAlignment); + Ptr = BackendAllocator.Allocate(&FallbackAllocatorCache, AllocationSize, + AllocationAlignment, FromPrimary); } if (!Ptr) return BackendAllocator.ReturnNullOrDieOnOOM(); - uptr AllocBeg = reinterpret_cast<uptr>(Ptr); - // If the allocation was serviced by the secondary, the returned pointer - // accounts for ChunkHeaderSize to pass the alignment check of the combined - // allocator. Adjust it here. - if (!FromPrimary) { - AllocBeg -= AlignedChunkHeaderSize; - if (Alignment > MinAlignment) - NeededSize -= Alignment; - } - // If requested, we will zero out the entire contents of the returned chunk. if ((ForceZeroContents || ZeroContents) && FromPrimary) - memset(Ptr, 0, BackendAllocator.GetActuallyAllocatedSize(Ptr)); + memset(Ptr, 0, + BackendAllocator.GetActuallyAllocatedSize(Ptr, FromPrimary)); + UnpackedHeader Header = {}; + uptr AllocBeg = reinterpret_cast<uptr>(Ptr); uptr UserBeg = AllocBeg + AlignedChunkHeaderSize; - if (!IsAligned(UserBeg, Alignment)) + if (!IsAligned(UserBeg, Alignment)) { + // Since the Secondary takes care of alignment, a non-aligned pointer + // means it is from the Primary. It is also the only case where the offset + // field of the header would be non-zero. + CHECK(FromPrimary); UserBeg = RoundUpTo(UserBeg, Alignment); - CHECK_LE(UserBeg + Size, AllocBeg + NeededSize); - UnpackedHeader Header = {}; + uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg; + Header.Offset = Offset >> MinAlignmentLog; + } + CHECK_LE(UserBeg + Size, AllocBeg + AllocationSize); Header.State = ChunkAllocated; - uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg; - Header.Offset = Offset >> MinAlignmentLog; Header.AllocType = Type; if (FromPrimary) { Header.FromPrimary = FromPrimary; @@ -431,17 +438,20 @@ struct ScudoAllocator { // with no additional security value. void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header, uptr Size) { + bool FromPrimary = Header->FromPrimary; bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0); if (BypassQuarantine) { Chunk->eraseHeader(); void *Ptr = Chunk->getAllocBeg(Header); ScudoThreadContext *ThreadContext = getThreadContextAndLock(); if (LIKELY(ThreadContext)) { - getBackendAllocator().Deallocate(getAllocatorCache(ThreadContext), Ptr); + getBackendAllocator().Deallocate(getAllocatorCache(ThreadContext), Ptr, + FromPrimary); ThreadContext->unlock(); } else { SpinMutexLock Lock(&FallbackMutex); - getBackendAllocator().Deallocate(&FallbackAllocatorCache, Ptr); + getBackendAllocator().Deallocate(&FallbackAllocatorCache, Ptr, + FromPrimary); } } else { UnpackedHeader NewHeader = *Header; diff --git a/contrib/compiler-rt/lib/scudo/scudo_allocator.h b/contrib/compiler-rt/lib/scudo/scudo_allocator.h index f159deffb1d5..523808750eec 100644 --- a/contrib/compiler-rt/lib/scudo/scudo_allocator.h +++ b/contrib/compiler-rt/lib/scudo/scudo_allocator.h @@ -80,7 +80,7 @@ const uptr AllocatorSize = 0x10000000000ULL; // 1T. const uptr AllocatorSize = 0x40000000000ULL; // 4T. # endif typedef DefaultSizeClassMap SizeClassMap; -struct AP { +struct AP64 { static const uptr kSpaceBeg = AllocatorSpace; static const uptr kSpaceSize = AllocatorSize; static const uptr kMetadataSize = 0; @@ -89,7 +89,7 @@ struct AP { static const uptr kFlags = SizeClassAllocator64FlagMasks::kRandomShuffleChunks; }; -typedef SizeClassAllocator64<AP> PrimaryAllocator; +typedef SizeClassAllocator64<AP64> PrimaryAllocator; #else // Currently, the 32-bit Sanitizer allocator has not yet benefited from all the // security improvements brought to the 64-bit one. This makes the 32-bit @@ -102,16 +102,27 @@ typedef FlatByteMap<NumRegions> ByteMap; typedef TwoLevelByteMap<(NumRegions >> 12), 1 << 12> ByteMap; # endif // SANITIZER_WORDSIZE typedef DefaultSizeClassMap SizeClassMap; -typedef SizeClassAllocator32<0, SANITIZER_MMAP_RANGE_SIZE, 0, SizeClassMap, - RegionSizeLog, ByteMap> PrimaryAllocator; +struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = 0; + typedef __scudo::SizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = RegionSizeLog; + typedef __scudo::ByteMap ByteMap; + typedef NoOpMapUnmapCallback MapUnmapCallback; + static const uptr kFlags = + SizeClassAllocator32FlagMasks::kRandomShuffleChunks; +}; +typedef SizeClassAllocator32<AP32> PrimaryAllocator; #endif // SANITIZER_CAN_USE_ALLOCATOR64 #include "scudo_allocator_secondary.h" +#include "scudo_allocator_combined.h" typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache; typedef ScudoLargeMmapAllocator SecondaryAllocator; -typedef CombinedAllocator<PrimaryAllocator, AllocatorCache, SecondaryAllocator> - ScudoBackendAllocator; +typedef ScudoCombinedAllocator<PrimaryAllocator, AllocatorCache, + SecondaryAllocator> ScudoBackendAllocator; void initScudo(); diff --git a/contrib/compiler-rt/lib/scudo/scudo_allocator_combined.h b/contrib/compiler-rt/lib/scudo/scudo_allocator_combined.h new file mode 100644 index 000000000000..c978db55a9d9 --- /dev/null +++ b/contrib/compiler-rt/lib/scudo/scudo_allocator_combined.h @@ -0,0 +1,84 @@ +//===-- scudo_allocator_combined.h ------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// Scudo Combined Allocator, dispatches allocation & deallocation requests to +/// the Primary or the Secondary backend allocators. +/// +//===----------------------------------------------------------------------===// + +#ifndef SCUDO_ALLOCATOR_COMBINED_H_ +#define SCUDO_ALLOCATOR_COMBINED_H_ + +#ifndef SCUDO_ALLOCATOR_H_ +#error "This file must be included inside scudo_allocator.h." +#endif + +template <class PrimaryAllocator, class AllocatorCache, + class SecondaryAllocator> +class ScudoCombinedAllocator { + public: + void Init(bool AllocatorMayReturnNull, s32 ReleaseToOSIntervalMs) { + Primary.Init(ReleaseToOSIntervalMs); + Secondary.Init(AllocatorMayReturnNull); + Stats.Init(); + atomic_store_relaxed(&MayReturnNull, AllocatorMayReturnNull); + } + + void *Allocate(AllocatorCache *Cache, uptr Size, uptr Alignment, + bool FromPrimary) { + if (FromPrimary) + return Cache->Allocate(&Primary, Primary.ClassID(Size)); + return Secondary.Allocate(&Stats, Size, Alignment); + } + + void *ReturnNullOrDieOnBadRequest() { + if (atomic_load_relaxed(&MayReturnNull)) + return nullptr; + ReportAllocatorCannotReturnNull(false); + } + + void *ReturnNullOrDieOnOOM() { + if (atomic_load_relaxed(&MayReturnNull)) + return nullptr; + ReportAllocatorCannotReturnNull(true); + } + + void Deallocate(AllocatorCache *Cache, void *Ptr, bool FromPrimary) { + if (FromPrimary) + Cache->Deallocate(&Primary, Primary.GetSizeClass(Ptr), Ptr); + else + Secondary.Deallocate(&Stats, Ptr); + } + + uptr GetActuallyAllocatedSize(void *Ptr, bool FromPrimary) { + if (FromPrimary) + return Primary.GetActuallyAllocatedSize(Ptr); + return Secondary.GetActuallyAllocatedSize(Ptr); + } + + void InitCache(AllocatorCache *Cache) { + Cache->Init(&Stats); + } + + void DestroyCache(AllocatorCache *Cache) { + Cache->Destroy(&Primary, &Stats); + } + + void GetStats(AllocatorStatCounters StatType) const { + Stats.Get(StatType); + } + + private: + PrimaryAllocator Primary; + SecondaryAllocator Secondary; + AllocatorGlobalStats Stats; + atomic_uint8_t MayReturnNull; +}; + +#endif // SCUDO_ALLOCATOR_COMBINED_H_ diff --git a/contrib/compiler-rt/lib/scudo/scudo_allocator_secondary.h b/contrib/compiler-rt/lib/scudo/scudo_allocator_secondary.h index fbc7f247d708..2950909b547e 100644 --- a/contrib/compiler-rt/lib/scudo/scudo_allocator_secondary.h +++ b/contrib/compiler-rt/lib/scudo/scudo_allocator_secondary.h @@ -26,20 +26,19 @@ class ScudoLargeMmapAllocator { void Init(bool AllocatorMayReturnNull) { PageSize = GetPageSizeCached(); - atomic_store(&MayReturnNull, AllocatorMayReturnNull, memory_order_relaxed); + atomic_store_relaxed(&MayReturnNull, AllocatorMayReturnNull); } void *Allocate(AllocatorStats *Stats, uptr Size, uptr Alignment) { + uptr UserSize = Size - AlignedChunkHeaderSize; // The Scudo frontend prevents us from allocating more than // MaxAllowedMallocSize, so integer overflow checks would be superfluous. uptr MapSize = Size + SecondaryHeaderSize; + if (Alignment > MinAlignment) + MapSize += Alignment; MapSize = RoundUpTo(MapSize, PageSize); // Account for 2 guard pages, one before and one after the chunk. MapSize += 2 * PageSize; - // The size passed to the Secondary comprises the alignment, if large - // enough. Subtract it here to get the requested size, including header. - if (Alignment > MinAlignment) - Size -= Alignment; uptr MapBeg = reinterpret_cast<uptr>(MmapNoAccess(MapSize)); if (MapBeg == ~static_cast<uptr>(0)) @@ -51,32 +50,32 @@ class ScudoLargeMmapAllocator { // initial guard page, and both headers. This is the pointer that has to // abide by alignment requirements. uptr UserBeg = MapBeg + PageSize + HeadersSize; + uptr UserEnd = UserBeg + UserSize; // In the rare event of larger alignments, we will attempt to fit the mmap // area better and unmap extraneous memory. This will also ensure that the // offset and unused bytes field of the header stay small. if (Alignment > MinAlignment) { - if (UserBeg & (Alignment - 1)) - UserBeg += Alignment - (UserBeg & (Alignment - 1)); - CHECK_GE(UserBeg, MapBeg); - uptr NewMapBeg = RoundDownTo(UserBeg - HeadersSize, PageSize) - PageSize; - CHECK_GE(NewMapBeg, MapBeg); - uptr NewMapEnd = RoundUpTo(UserBeg + (Size - AlignedChunkHeaderSize), - PageSize) + PageSize; - CHECK_LE(NewMapEnd, MapEnd); - // Unmap the extra memory if it's large enough, on both sides. - uptr Diff = NewMapBeg - MapBeg; - if (Diff > PageSize) - UnmapOrDie(reinterpret_cast<void *>(MapBeg), Diff); - Diff = MapEnd - NewMapEnd; - if (Diff > PageSize) - UnmapOrDie(reinterpret_cast<void *>(NewMapEnd), Diff); - MapBeg = NewMapBeg; - MapEnd = NewMapEnd; - MapSize = NewMapEnd - NewMapBeg; + if (!IsAligned(UserBeg, Alignment)) { + UserBeg = RoundUpTo(UserBeg, Alignment); + CHECK_GE(UserBeg, MapBeg); + uptr NewMapBeg = RoundDownTo(UserBeg - HeadersSize, PageSize) - + PageSize; + CHECK_GE(NewMapBeg, MapBeg); + if (NewMapBeg != MapBeg) { + UnmapOrDie(reinterpret_cast<void *>(MapBeg), NewMapBeg - MapBeg); + MapBeg = NewMapBeg; + } + UserEnd = UserBeg + UserSize; + } + uptr NewMapEnd = RoundUpTo(UserEnd, PageSize) + PageSize; + if (NewMapEnd != MapEnd) { + UnmapOrDie(reinterpret_cast<void *>(NewMapEnd), MapEnd - NewMapEnd); + MapEnd = NewMapEnd; + } + MapSize = MapEnd - MapBeg; } - uptr UserEnd = UserBeg + (Size - AlignedChunkHeaderSize); CHECK_LE(UserEnd, MapEnd - PageSize); // Actually mmap the memory, preserving the guard pages on either side. CHECK_EQ(MapBeg + PageSize, reinterpret_cast<uptr>( @@ -94,25 +93,15 @@ class ScudoLargeMmapAllocator { Stats->Add(AllocatorStatMapped, MapSize - 2 * PageSize); } - return reinterpret_cast<void *>(UserBeg); - } - - void *ReturnNullOrDieOnBadRequest() { - if (atomic_load(&MayReturnNull, memory_order_acquire)) - return nullptr; - ReportAllocatorCannotReturnNull(false); + return reinterpret_cast<void *>(Ptr); } void *ReturnNullOrDieOnOOM() { - if (atomic_load(&MayReturnNull, memory_order_acquire)) + if (atomic_load_relaxed(&MayReturnNull)) return nullptr; ReportAllocatorCannotReturnNull(true); } - void SetMayReturnNull(bool AllocatorMayReturnNull) { - atomic_store(&MayReturnNull, AllocatorMayReturnNull, memory_order_release); - } - void Deallocate(AllocatorStats *Stats, void *Ptr) { SecondaryHeader *Header = getHeader(Ptr); { @@ -123,14 +112,6 @@ class ScudoLargeMmapAllocator { UnmapOrDie(reinterpret_cast<void *>(Header->MapBeg), Header->MapSize); } - uptr TotalMemoryUsed() { - UNIMPLEMENTED(); - } - - bool PointerIsMine(const void *Ptr) { - UNIMPLEMENTED(); - } - uptr GetActuallyAllocatedSize(void *Ptr) { SecondaryHeader *Header = getHeader(Ptr); // Deduct PageSize as MapSize includes the trailing guard page. @@ -138,39 +119,9 @@ class ScudoLargeMmapAllocator { return MapEnd - reinterpret_cast<uptr>(Ptr); } - void *GetMetaData(const void *Ptr) { - UNIMPLEMENTED(); - } - - void *GetBlockBegin(const void *Ptr) { - UNIMPLEMENTED(); - } - - void *GetBlockBeginFastLocked(void *Ptr) { - UNIMPLEMENTED(); - } - - void PrintStats() { - UNIMPLEMENTED(); - } - - void ForceLock() { - UNIMPLEMENTED(); - } - - void ForceUnlock() { - UNIMPLEMENTED(); - } - - void ForEachChunk(ForEachChunkCallback Callback, void *Arg) { - UNIMPLEMENTED(); - } - private: // A Secondary allocated chunk header contains the base of the mapping and - // its size. Currently, the base is always a page before the header, but - // we might want to extend that number in the future based on the size of - // the allocation. + // its size, which comprises the guard pages. struct SecondaryHeader { uptr MapBeg; uptr MapSize; diff --git a/contrib/compiler-rt/lib/scudo/scudo_crc32.cpp b/contrib/compiler-rt/lib/scudo/scudo_crc32.cpp index 56be22f4ee62..a267dc4e3fb8 100644 --- a/contrib/compiler-rt/lib/scudo/scudo_crc32.cpp +++ b/contrib/compiler-rt/lib/scudo/scudo_crc32.cpp @@ -12,24 +12,7 @@ /// //===----------------------------------------------------------------------===// -#include "sanitizer_common/sanitizer_internal_defs.h" - -// Hardware CRC32 is supported at compilation via the following: -// - for i386 & x86_64: -msse4.2 -// - for ARM & AArch64: -march=armv8-a+crc or -mcrc -// An additional check must be performed at runtime as well to make sure the -// emitted instructions are valid on the target host. - -#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) -# ifdef __SSE4_2__ -# include <smmintrin.h> -# define CRC32_INTRINSIC FIRST_32_SECOND_64(_mm_crc32_u32, _mm_crc32_u64) -# endif -# ifdef __ARM_FEATURE_CRC32 -# include <arm_acle.h> -# define CRC32_INTRINSIC FIRST_32_SECOND_64(__crc32cw, __crc32cd) -# endif -#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) +#include "scudo_crc32.h" namespace __scudo { diff --git a/contrib/compiler-rt/lib/scudo/scudo_crc32.h b/contrib/compiler-rt/lib/scudo/scudo_crc32.h new file mode 100644 index 000000000000..5ffcc62658cc --- /dev/null +++ b/contrib/compiler-rt/lib/scudo/scudo_crc32.h @@ -0,0 +1,101 @@ +//===-- scudo_crc32.h -------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// Scudo chunk header checksum related definitions. +/// +//===----------------------------------------------------------------------===// + +#ifndef SCUDO_CRC32_H_ +#define SCUDO_CRC32_H_ + +#include "sanitizer_common/sanitizer_internal_defs.h" + +// Hardware CRC32 is supported at compilation via the following: +// - for i386 & x86_64: -msse4.2 +// - for ARM & AArch64: -march=armv8-a+crc or -mcrc +// An additional check must be performed at runtime as well to make sure the +// emitted instructions are valid on the target host. + +#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) +# ifdef __SSE4_2__ +# include <smmintrin.h> +# define CRC32_INTRINSIC FIRST_32_SECOND_64(_mm_crc32_u32, _mm_crc32_u64) +# endif +# ifdef __ARM_FEATURE_CRC32 +# include <arm_acle.h> +# define CRC32_INTRINSIC FIRST_32_SECOND_64(__crc32cw, __crc32cd) +# endif +#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32) + +namespace __scudo { + +enum : u8 { + CRC32Software = 0, + CRC32Hardware = 1, +}; + +const static u32 CRC32Table[] = { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d +}; + +INLINE u32 computeSoftwareCRC32(u32 Crc, uptr Data) { + for (uptr i = 0; i < sizeof(Data); i++) { + Crc = CRC32Table[(Crc ^ Data) & 0xff] ^ (Crc >> 8); + Data >>= 8; + } + return Crc; +} + +SANITIZER_WEAK_ATTRIBUTE u32 computeHardwareCRC32(u32 Crc, uptr Data); + +} // namespace __scudo + +#endif // SCUDO_CRC32_H_ diff --git a/contrib/compiler-rt/lib/scudo/scudo_utils.h b/contrib/compiler-rt/lib/scudo/scudo_utils.h index 484b0c859e3d..7198476f42cf 100644 --- a/contrib/compiler-rt/lib/scudo/scudo_utils.h +++ b/contrib/compiler-rt/lib/scudo/scudo_utils.h @@ -53,65 +53,6 @@ struct Xorshift128Plus { u64 State[2]; }; -enum : u8 { - CRC32Software = 0, - CRC32Hardware = 1, -}; - -const static u32 CRC32Table[] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -INLINE u32 computeSoftwareCRC32(u32 Crc, uptr Data) { - for (uptr i = 0; i < sizeof(Data); i++) { - Crc = CRC32Table[(Crc ^ Data) & 0xff] ^ (Crc >> 8); - Data >>= 8; - } - return Crc; -} - } // namespace __scudo #endif // SCUDO_UTILS_H_ diff --git a/contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.h b/contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.h index e92a0f35705e..2cf2e168454d 100644 --- a/contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.h +++ b/contrib/compiler-rt/lib/tsan/rtl/tsan_rtl.h @@ -55,16 +55,22 @@ namespace __tsan { #if !SANITIZER_GO struct MapUnmapCallback; #if defined(__mips64) || defined(__aarch64__) || defined(__powerpc__) -static const uptr kAllocatorSpace = 0; -static const uptr kAllocatorSize = SANITIZER_MMAP_RANGE_SIZE; static const uptr kAllocatorRegionSizeLog = 20; static const uptr kAllocatorNumRegions = - kAllocatorSize >> kAllocatorRegionSizeLog; + SANITIZER_MMAP_RANGE_SIZE >> kAllocatorRegionSizeLog; typedef TwoLevelByteMap<(kAllocatorNumRegions >> 12), 1 << 12, MapUnmapCallback> ByteMap; -typedef SizeClassAllocator32<kAllocatorSpace, kAllocatorSize, 0, - CompactSizeClassMap, kAllocatorRegionSizeLog, ByteMap, - MapUnmapCallback> PrimaryAllocator; +struct AP32 { + static const uptr kSpaceBeg = 0; + static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE; + static const uptr kMetadataSize = 0; + typedef __sanitizer::CompactSizeClassMap SizeClassMap; + static const uptr kRegionSizeLog = kAllocatorRegionSizeLog; + typedef __tsan::ByteMap ByteMap; + typedef __tsan::MapUnmapCallback MapUnmapCallback; + static const uptr kFlags = 0; +}; +typedef SizeClassAllocator32<AP32> PrimaryAllocator; #else struct AP64 { // Allocator64 parameters. Deliberately using a short name. static const uptr kSpaceBeg = Mapping::kHeapMemBeg; diff --git a/contrib/compiler-rt/lib/xray/xray_AArch64.cc b/contrib/compiler-rt/lib/xray/xray_AArch64.cc index 8d1c7c5d807f..f26e77dd7fc1 100644 --- a/contrib/compiler-rt/lib/xray/xray_AArch64.cc +++ b/contrib/compiler-rt/lib/xray/xray_AArch64.cc @@ -18,8 +18,7 @@ #include <atomic> #include <cassert> - -extern "C" void __clear_cache(void* start, void* end); +extern "C" void __clear_cache(void *start, void *end); namespace __xray { @@ -86,8 +85,8 @@ inline static bool patchSled(const bool Enable, const uint32_t FuncId, reinterpret_cast<std::atomic<uint32_t> *>(FirstAddress), uint32_t(PatchOpcodes::PO_B32), std::memory_order_release); } - __clear_cache(reinterpret_cast<char*>(FirstAddress), - reinterpret_cast<char*>(CurAddress)); + __clear_cache(reinterpret_cast<char *>(FirstAddress), + reinterpret_cast<char *>(CurAddress)); return true; } @@ -107,6 +106,12 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, return patchSled(Enable, FuncId, Sled, __xray_FunctionTailExit); } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) + XRAY_NEVER_INSTRUMENT { // FIXME: Implement in aarch64? + return false; +} + // FIXME: Maybe implement this better? bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT { return true; } diff --git a/contrib/compiler-rt/lib/xray/xray_arm.cc b/contrib/compiler-rt/lib/xray/xray_arm.cc index 26d673ec23a0..da4efcdd2b17 100644 --- a/contrib/compiler-rt/lib/xray/xray_arm.cc +++ b/contrib/compiler-rt/lib/xray/xray_arm.cc @@ -18,7 +18,7 @@ #include <atomic> #include <cassert> -extern "C" void __clear_cache(void* start, void* end); +extern "C" void __clear_cache(void *start, void *end); namespace __xray { @@ -122,8 +122,8 @@ inline static bool patchSled(const bool Enable, const uint32_t FuncId, reinterpret_cast<std::atomic<uint32_t> *>(FirstAddress), uint32_t(PatchOpcodes::PO_B20), std::memory_order_release); } - __clear_cache(reinterpret_cast<char*>(FirstAddress), - reinterpret_cast<char*>(CurAddress)); + __clear_cache(reinterpret_cast<char *>(FirstAddress), + reinterpret_cast<char *>(CurAddress)); return true; } @@ -143,6 +143,12 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, return patchSled(Enable, FuncId, Sled, __xray_FunctionTailExit); } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) + XRAY_NEVER_INSTRUMENT { // FIXME: Implement in arm? + return false; +} + // FIXME: Maybe implement this better? bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT { return true; } diff --git a/contrib/compiler-rt/lib/xray/xray_fdr_log_records.h b/contrib/compiler-rt/lib/xray/xray_fdr_log_records.h index 36d9410d16f6..3d6d38892c76 100644 --- a/contrib/compiler-rt/lib/xray/xray_fdr_log_records.h +++ b/contrib/compiler-rt/lib/xray/xray_fdr_log_records.h @@ -29,6 +29,7 @@ struct alignas(16) MetadataRecord { NewCPUId, TSCWrap, WalltimeMarker, + CustomEventMarker, }; // Use 7 bits to identify this record type. /* RecordKinds */ uint8_t RecordKind : 7; diff --git a/contrib/compiler-rt/lib/xray/xray_fdr_logging.cc b/contrib/compiler-rt/lib/xray/xray_fdr_logging.cc index e538b477a3de..a7e1382c3865 100644 --- a/contrib/compiler-rt/lib/xray/xray_fdr_logging.cc +++ b/contrib/compiler-rt/lib/xray/xray_fdr_logging.cc @@ -41,45 +41,12 @@ namespace __xray { // Global BufferQueue. std::shared_ptr<BufferQueue> BQ; -__sanitizer::atomic_sint32_t LoggingStatus = { - XRayLogInitStatus::XRAY_LOG_UNINITIALIZED}; - __sanitizer::atomic_sint32_t LogFlushStatus = { XRayLogFlushStatus::XRAY_LOG_NOT_FLUSHING}; -std::unique_ptr<FDRLoggingOptions> FDROptions; - -XRayLogInitStatus fdrLoggingInit(std::size_t BufferSize, std::size_t BufferMax, - void *Options, - size_t OptionsSize) XRAY_NEVER_INSTRUMENT { - if (OptionsSize != sizeof(FDRLoggingOptions)) - return static_cast<XRayLogInitStatus>(__sanitizer::atomic_load( - &LoggingStatus, __sanitizer::memory_order_acquire)); - s32 CurrentStatus = XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; - if (!__sanitizer::atomic_compare_exchange_strong( - &LoggingStatus, &CurrentStatus, - XRayLogInitStatus::XRAY_LOG_INITIALIZING, - __sanitizer::memory_order_release)) - return static_cast<XRayLogInitStatus>(CurrentStatus); - - FDROptions.reset(new FDRLoggingOptions()); - memcpy(FDROptions.get(), Options, OptionsSize); - bool Success = false; - BQ = std::make_shared<BufferQueue>(BufferSize, BufferMax, Success); - if (!Success) { - Report("BufferQueue init failed.\n"); - return XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; - } - - // Install the actual handleArg0 handler after initialising the buffers. - __xray_set_handler(fdrLoggingHandleArg0); +FDRLoggingOptions FDROptions; - __sanitizer::atomic_store(&LoggingStatus, - XRayLogInitStatus::XRAY_LOG_INITIALIZED, - __sanitizer::memory_order_release); - Report("XRay FDR init successful.\n"); - return XRayLogInitStatus::XRAY_LOG_INITIALIZED; -} +__sanitizer::SpinMutex FDROptionsMutex; // Must finalize before flushing. XRayLogFlushStatus fdrLoggingFlush() XRAY_NEVER_INSTRUMENT { @@ -108,7 +75,11 @@ XRayLogFlushStatus fdrLoggingFlush() XRAY_NEVER_INSTRUMENT { // (fixed-sized) and let the tools reading the buffers deal with the data // afterwards. // - int Fd = FDROptions->Fd; + int Fd = -1; + { + __sanitizer::SpinMutexLock Guard(&FDROptionsMutex); + Fd = FDROptions.Fd; + } if (Fd == -1) Fd = getLogFD(); if (Fd == -1) { @@ -120,8 +91,8 @@ XRayLogFlushStatus fdrLoggingFlush() XRAY_NEVER_INSTRUMENT { // Test for required CPU features and cache the cycle frequency static bool TSCSupported = probeRequiredCPUFeatures(); - static uint64_t CycleFrequency = TSCSupported ? getTSCFrequency() - : __xray::NanosecondsPerSecond; + static uint64_t CycleFrequency = + TSCSupported ? getTSCFrequency() : __xray::NanosecondsPerSecond; XRayFileHeader Header; Header.Version = 1; @@ -192,8 +163,8 @@ XRayLogInitStatus fdrLoggingReset() XRAY_NEVER_INSTRUMENT { return XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; } -void fdrLoggingHandleArg0(int32_t FuncId, - XRayEntryType Entry) XRAY_NEVER_INSTRUMENT { +static std::tuple<uint64_t, unsigned char> +getTimestamp() XRAY_NEVER_INSTRUMENT { // We want to get the TSC as early as possible, so that we can check whether // we've seen this CPU before. We also do it before we load anything else, to // allow for forward progress with the scheduling. @@ -203,7 +174,7 @@ void fdrLoggingHandleArg0(int32_t FuncId, // Test once for required CPU features static bool TSCSupported = probeRequiredCPUFeatures(); - if(TSCSupported) { + if (TSCSupported) { TSC = __xray::readTSC(CPU); } else { // FIXME: This code needs refactoring as it appears in multiple locations @@ -216,9 +187,102 @@ void fdrLoggingHandleArg0(int32_t FuncId, CPU = 0; TSC = TS.tv_sec * __xray::NanosecondsPerSecond + TS.tv_nsec; } + return std::make_tuple(TSC, CPU); +} + +void fdrLoggingHandleArg0(int32_t FuncId, + XRayEntryType Entry) XRAY_NEVER_INSTRUMENT { + auto TSC_CPU = getTimestamp(); + __xray_fdr_internal::processFunctionHook(FuncId, Entry, std::get<0>(TSC_CPU), + std::get<1>(TSC_CPU), clock_gettime, + LoggingStatus, BQ); +} - __xray_fdr_internal::processFunctionHook(FuncId, Entry, TSC, CPU, - clock_gettime, LoggingStatus, BQ); +void fdrLoggingHandleCustomEvent(void *Event, + std::size_t EventSize) XRAY_NEVER_INSTRUMENT { + using namespace __xray_fdr_internal; + auto TSC_CPU = getTimestamp(); + auto &TSC = std::get<0>(TSC_CPU); + auto &CPU = std::get<1>(TSC_CPU); + thread_local bool Running = false; + RecursionGuard Guard{Running}; + if (!Guard) { + assert(Running && "RecursionGuard is buggy!"); + return; + } + if (EventSize > std::numeric_limits<int32_t>::max()) { + using Empty = struct {}; + static Empty Once = [&] { + Report("Event size too large = %zu ; > max = %d\n", EventSize, + std::numeric_limits<int32_t>::max()); + return Empty(); + }(); + (void)Once; + } + int32_t ReducedEventSize = static_cast<int32_t>(EventSize); + if (!isLogInitializedAndReady(LocalBQ, TSC, CPU, clock_gettime)) + return; + + // Here we need to prepare the log to handle: + // - The metadata record we're going to write. (16 bytes) + // - The additional data we're going to write. Currently, that's the size of + // the event we're going to dump into the log as free-form bytes. + if (!prepareBuffer(clock_gettime, MetadataRecSize + EventSize)) { + LocalBQ = nullptr; + return; + } + + // Write the custom event metadata record, which consists of the following + // information: + // - 8 bytes (64-bits) for the full TSC when the event started. + // - 4 bytes (32-bits) for the length of the data. + MetadataRecord CustomEvent; + CustomEvent.Type = uint8_t(RecordType::Metadata); + CustomEvent.RecordKind = + uint8_t(MetadataRecord::RecordKinds::CustomEventMarker); + constexpr auto TSCSize = sizeof(std::get<0>(TSC_CPU)); + std::memcpy(&CustomEvent.Data, &ReducedEventSize, sizeof(int32_t)); + std::memcpy(&CustomEvent.Data[sizeof(int32_t)], &TSC, TSCSize); + std::memcpy(RecordPtr, &CustomEvent, sizeof(CustomEvent)); + RecordPtr += sizeof(CustomEvent); + std::memcpy(RecordPtr, Event, ReducedEventSize); + endBufferIfFull(); +} + +XRayLogInitStatus fdrLoggingInit(std::size_t BufferSize, std::size_t BufferMax, + void *Options, + size_t OptionsSize) XRAY_NEVER_INSTRUMENT { + if (OptionsSize != sizeof(FDRLoggingOptions)) + return static_cast<XRayLogInitStatus>(__sanitizer::atomic_load( + &LoggingStatus, __sanitizer::memory_order_acquire)); + s32 CurrentStatus = XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; + if (!__sanitizer::atomic_compare_exchange_strong( + &LoggingStatus, &CurrentStatus, + XRayLogInitStatus::XRAY_LOG_INITIALIZING, + __sanitizer::memory_order_release)) + return static_cast<XRayLogInitStatus>(CurrentStatus); + + { + __sanitizer::SpinMutexLock Guard(&FDROptionsMutex); + memcpy(&FDROptions, Options, OptionsSize); + } + + bool Success = false; + BQ = std::make_shared<BufferQueue>(BufferSize, BufferMax, Success); + if (!Success) { + Report("BufferQueue init failed.\n"); + return XRayLogInitStatus::XRAY_LOG_UNINITIALIZED; + } + + // Install the actual handleArg0 handler after initialising the buffers. + __xray_set_handler(fdrLoggingHandleArg0); + __xray_set_customevent_handler(fdrLoggingHandleCustomEvent); + + __sanitizer::atomic_store(&LoggingStatus, + XRayLogInitStatus::XRAY_LOG_INITIALIZED, + __sanitizer::memory_order_release); + Report("XRay FDR init successful.\n"); + return XRayLogInitStatus::XRAY_LOG_INITIALIZED; } } // namespace __xray diff --git a/contrib/compiler-rt/lib/xray/xray_fdr_logging_impl.h b/contrib/compiler-rt/lib/xray/xray_fdr_logging_impl.h index ce360cb03ea7..4a1d80fd0eba 100644 --- a/contrib/compiler-rt/lib/xray/xray_fdr_logging_impl.h +++ b/contrib/compiler-rt/lib/xray/xray_fdr_logging_impl.h @@ -37,6 +37,9 @@ namespace __xray { +__sanitizer::atomic_sint32_t LoggingStatus = { + XRayLogInitStatus::XRAY_LOG_UNINITIALIZED}; + /// We expose some of the state transitions when FDR logging mode is operating /// such that we can simulate a series of log events that may occur without /// and test with determinism without worrying about the real CPU time. @@ -123,12 +126,21 @@ thread_local uint8_t NumTailCalls = 0; constexpr auto MetadataRecSize = sizeof(MetadataRecord); constexpr auto FunctionRecSize = sizeof(FunctionRecord); +// We use a thread_local variable to keep track of which CPUs we've already +// run, and the TSC times for these CPUs. This allows us to stop repeating the +// CPU field in the function records. +// +// We assume that we'll support only 65536 CPUs for x86_64. +thread_local uint16_t CurrentCPU = std::numeric_limits<uint16_t>::max(); +thread_local uint64_t LastTSC = 0; +thread_local uint64_t LastFunctionEntryTSC = 0; + class ThreadExitBufferCleanup { - std::weak_ptr<BufferQueue> Buffers; + std::shared_ptr<BufferQueue> &Buffers; BufferQueue::Buffer &Buffer; public: - explicit ThreadExitBufferCleanup(std::weak_ptr<BufferQueue> BQ, + explicit ThreadExitBufferCleanup(std::shared_ptr<BufferQueue> &BQ, BufferQueue::Buffer &Buffer) XRAY_NEVER_INSTRUMENT : Buffers(BQ), Buffer(Buffer) {} @@ -142,17 +154,24 @@ public: // the queue. assert((RecordPtr + MetadataRecSize) - static_cast<char *>(Buffer.Buffer) >= static_cast<ptrdiff_t>(MetadataRecSize)); - if (auto BQ = Buffers.lock()) { + if (Buffers) { writeEOBMetadata(); - auto EC = BQ->releaseBuffer(Buffer); + auto EC = Buffers->releaseBuffer(Buffer); if (EC != BufferQueue::ErrorCode::Ok) Report("Failed to release buffer at %p; error=%s\n", Buffer.Buffer, BufferQueue::getErrorString(EC)); + Buffers = nullptr; return; } } }; +// Make sure a thread that's ever called handleArg0 has a thread-local +// live reference to the buffer queue for this particular instance of +// FDRLogging, and that we're going to clean it up when the thread exits. +thread_local std::shared_ptr<BufferQueue> LocalBQ = nullptr; +thread_local ThreadExitBufferCleanup Cleanup(LocalBQ, Buffer); + class RecursionGuard { bool &Running; const bool Valid; @@ -176,7 +195,7 @@ public: } }; -static inline bool loggingInitialized( +inline bool loggingInitialized( const __sanitizer::atomic_sint32_t &LoggingStatus) XRAY_NEVER_INSTRUMENT { return __sanitizer::atomic_load(&LoggingStatus, __sanitizer::memory_order_acquire) == @@ -185,8 +204,8 @@ static inline bool loggingInitialized( } // namespace -static inline void writeNewBufferPreamble(pid_t Tid, timespec TS, - char *&MemPtr) XRAY_NEVER_INSTRUMENT { +inline void writeNewBufferPreamble(pid_t Tid, timespec TS, + char *&MemPtr) XRAY_NEVER_INSTRUMENT { static constexpr int InitRecordsCount = 2; std::aligned_storage<sizeof(MetadataRecord)>::type Records[InitRecordsCount]; { @@ -222,9 +241,8 @@ static inline void writeNewBufferPreamble(pid_t Tid, timespec TS, NumTailCalls = 0; } -static inline void setupNewBuffer(int (*wall_clock_reader)(clockid_t, - struct timespec *)) - XRAY_NEVER_INSTRUMENT { +inline void setupNewBuffer(int (*wall_clock_reader)( + clockid_t, struct timespec *)) XRAY_NEVER_INSTRUMENT { RecordPtr = static_cast<char *>(Buffer.Buffer); pid_t Tid = syscall(SYS_gettid); timespec TS{0, 0}; @@ -235,8 +253,8 @@ static inline void setupNewBuffer(int (*wall_clock_reader)(clockid_t, NumTailCalls = 0; } -static inline void writeNewCPUIdMetadata(uint16_t CPU, uint64_t TSC, - char *&MemPtr) XRAY_NEVER_INSTRUMENT { +inline void writeNewCPUIdMetadata(uint16_t CPU, uint64_t TSC, + char *&MemPtr) XRAY_NEVER_INSTRUMENT { MetadataRecord NewCPUId; NewCPUId.Type = uint8_t(RecordType::Metadata); NewCPUId.RecordKind = uint8_t(MetadataRecord::RecordKinds::NewCPUId); @@ -253,12 +271,12 @@ static inline void writeNewCPUIdMetadata(uint16_t CPU, uint64_t TSC, NumTailCalls = 0; } -static inline void writeNewCPUIdMetadata(uint16_t CPU, - uint64_t TSC) XRAY_NEVER_INSTRUMENT { +inline void writeNewCPUIdMetadata(uint16_t CPU, + uint64_t TSC) XRAY_NEVER_INSTRUMENT { writeNewCPUIdMetadata(CPU, TSC, RecordPtr); } -static inline void writeEOBMetadata(char *&MemPtr) XRAY_NEVER_INSTRUMENT { +inline void writeEOBMetadata(char *&MemPtr) XRAY_NEVER_INSTRUMENT { MetadataRecord EOBMeta; EOBMeta.Type = uint8_t(RecordType::Metadata); EOBMeta.RecordKind = uint8_t(MetadataRecord::RecordKinds::EndOfBuffer); @@ -269,12 +287,12 @@ static inline void writeEOBMetadata(char *&MemPtr) XRAY_NEVER_INSTRUMENT { NumTailCalls = 0; } -static inline void writeEOBMetadata() XRAY_NEVER_INSTRUMENT { +inline void writeEOBMetadata() XRAY_NEVER_INSTRUMENT { writeEOBMetadata(RecordPtr); } -static inline void writeTSCWrapMetadata(uint64_t TSC, - char *&MemPtr) XRAY_NEVER_INSTRUMENT { +inline void writeTSCWrapMetadata(uint64_t TSC, + char *&MemPtr) XRAY_NEVER_INSTRUMENT { MetadataRecord TSCWrap; TSCWrap.Type = uint8_t(RecordType::Metadata); TSCWrap.RecordKind = uint8_t(MetadataRecord::RecordKinds::TSCWrap); @@ -289,13 +307,13 @@ static inline void writeTSCWrapMetadata(uint64_t TSC, NumTailCalls = 0; } -static inline void writeTSCWrapMetadata(uint64_t TSC) XRAY_NEVER_INSTRUMENT { +inline void writeTSCWrapMetadata(uint64_t TSC) XRAY_NEVER_INSTRUMENT { writeTSCWrapMetadata(TSC, RecordPtr); } -static inline void writeFunctionRecord(int FuncId, uint32_t TSCDelta, - XRayEntryType EntryType, - char *&MemPtr) XRAY_NEVER_INSTRUMENT { +inline void writeFunctionRecord(int FuncId, uint32_t TSCDelta, + XRayEntryType EntryType, + char *&MemPtr) XRAY_NEVER_INSTRUMENT { std::aligned_storage<sizeof(FunctionRecord), alignof(FunctionRecord)>::type AlignedFuncRecordBuffer; auto &FuncRecord = @@ -339,6 +357,17 @@ static inline void writeFunctionRecord(int FuncId, uint32_t TSCDelta, FuncRecord.RecordKind = uint8_t(FunctionRecord::RecordKinds::FunctionTailExit); break; + case XRayEntryType::CUSTOM_EVENT: { + // This is a bug in patching, so we'll report it once and move on. + static bool Once = [&] { + Report("Internal error: patched an XRay custom event call as a function; " + "func id = %d\n", + FuncId); + return true; + }(); + (void)Once; + return; + } } std::memcpy(MemPtr, &AlignedFuncRecordBuffer, sizeof(FunctionRecord)); @@ -346,8 +375,9 @@ static inline void writeFunctionRecord(int FuncId, uint32_t TSCDelta, } static uint64_t thresholdTicks() { - static uint64_t TicksPerSec = probeRequiredCPUFeatures() ? getTSCFrequency() : - __xray::NanosecondsPerSecond; + static uint64_t TicksPerSec = probeRequiredCPUFeatures() + ? getTSCFrequency() + : __xray::NanosecondsPerSecond; static const uint64_t ThresholdTicks = TicksPerSec * flags()->xray_fdr_log_func_duration_threshold_us / 1000000; return ThresholdTicks; @@ -397,9 +427,8 @@ static void rewindRecentCall(uint64_t TSC, uint64_t &LastTSC, RewindingRecordPtr -= FunctionRecSize; RewindingTSC -= ExpectedTailExit.TSCDelta; AlignedFuncStorage FunctionEntryBuffer; - const auto &ExpectedFunctionEntry = - *reinterpret_cast<FunctionRecord *>(std::memcpy( - &FunctionEntryBuffer, RewindingRecordPtr, FunctionRecSize)); + const auto &ExpectedFunctionEntry = *reinterpret_cast<FunctionRecord *>( + std::memcpy(&FunctionEntryBuffer, RewindingRecordPtr, FunctionRecSize)); assert(ExpectedFunctionEntry.RecordKind == uint8_t(FunctionRecord::RecordKinds::FunctionEnter) && "Expected to find function entry when rewinding tail call."); @@ -422,7 +451,7 @@ static void rewindRecentCall(uint64_t TSC, uint64_t &LastTSC, } } -static inline bool releaseThreadLocalBuffer(BufferQueue *BQ) { +inline bool releaseThreadLocalBuffer(BufferQueue *BQ) { auto EC = BQ->releaseBuffer(Buffer); if (EC != BufferQueue::ErrorCode::Ok) { Report("Failed to release buffer at %p; error=%s\n", Buffer.Buffer, @@ -432,11 +461,29 @@ static inline bool releaseThreadLocalBuffer(BufferQueue *BQ) { return true; } -static inline void processFunctionHook( - int32_t FuncId, XRayEntryType Entry, uint64_t TSC, unsigned char CPU, - int (*wall_clock_reader)(clockid_t, struct timespec *), - __sanitizer::atomic_sint32_t &LoggingStatus, - const std::shared_ptr<BufferQueue> &BQ) XRAY_NEVER_INSTRUMENT { +inline bool prepareBuffer(int (*wall_clock_reader)(clockid_t, + struct timespec *), + size_t MaxSize) XRAY_NEVER_INSTRUMENT { + char *BufferStart = static_cast<char *>(Buffer.Buffer); + if ((RecordPtr + MaxSize) > (BufferStart + Buffer.Size - MetadataRecSize)) { + writeEOBMetadata(); + if (!releaseThreadLocalBuffer(LocalBQ.get())) + return false; + auto EC = LocalBQ->getBuffer(Buffer); + if (EC != BufferQueue::ErrorCode::Ok) { + Report("Failed to acquire a buffer; error=%s\n", + BufferQueue::getErrorString(EC)); + return false; + } + setupNewBuffer(wall_clock_reader); + } + return true; +} + +inline bool isLogInitializedAndReady( + std::shared_ptr<BufferQueue> &LocalBQ, uint64_t TSC, unsigned char CPU, + int (*wall_clock_reader)(clockid_t, + struct timespec *)) XRAY_NEVER_INSTRUMENT { // Bail out right away if logging is not initialized yet. // We should take the opportunity to release the buffer though. auto Status = __sanitizer::atomic_load(&LoggingStatus, @@ -446,44 +493,19 @@ static inline void processFunctionHook( (Status == XRayLogInitStatus::XRAY_LOG_FINALIZING || Status == XRayLogInitStatus::XRAY_LOG_FINALIZED)) { writeEOBMetadata(); - if (!releaseThreadLocalBuffer(BQ.get())) - return; + if (!releaseThreadLocalBuffer(LocalBQ.get())) + return false; RecordPtr = nullptr; + LocalBQ = nullptr; + return false; } - return; - } - - // We use a thread_local variable to keep track of which CPUs we've already - // run, and the TSC times for these CPUs. This allows us to stop repeating the - // CPU field in the function records. - // - // We assume that we'll support only 65536 CPUs for x86_64. - thread_local uint16_t CurrentCPU = std::numeric_limits<uint16_t>::max(); - thread_local uint64_t LastTSC = 0; - thread_local uint64_t LastFunctionEntryTSC = 0; - - // Make sure a thread that's ever called handleArg0 has a thread-local - // live reference to the buffer queue for this particular instance of - // FDRLogging, and that we're going to clean it up when the thread exits. - thread_local auto LocalBQ = BQ; - thread_local ThreadExitBufferCleanup Cleanup(LocalBQ, Buffer); - - // Prevent signal handler recursion, so in case we're already in a log writing - // mode and the signal handler comes in (and is also instrumented) then we - // don't want to be clobbering potentially partial writes already happening in - // the thread. We use a simple thread_local latch to only allow one on-going - // handleArg0 to happen at any given time. - thread_local bool Running = false; - RecursionGuard Guard{Running}; - if (!Guard) { - assert(Running == true && "RecursionGuard is buggy!"); - return; + return false; } if (!loggingInitialized(LoggingStatus) || LocalBQ->finalizing()) { writeEOBMetadata(); - if (!releaseThreadLocalBuffer(BQ.get())) - return; + if (!releaseThreadLocalBuffer(LocalBQ.get())) + return false; RecordPtr = nullptr; } @@ -496,19 +518,57 @@ static inline void processFunctionHook( LS != XRayLogInitStatus::XRAY_LOG_FINALIZED) Report("Failed to acquire a buffer; error=%s\n", BufferQueue::getErrorString(EC)); - return; + return false; } setupNewBuffer(wall_clock_reader); } if (CurrentCPU == std::numeric_limits<uint16_t>::max()) { - // This means this is the first CPU this thread has ever run on. We set the - // current CPU and record this as the first TSC we've seen. + // This means this is the first CPU this thread has ever run on. We set + // the current CPU and record this as the first TSC we've seen. CurrentCPU = CPU; writeNewCPUIdMetadata(CPU, TSC); } + return true; +} // namespace __xray_fdr_internal + +inline void endBufferIfFull() XRAY_NEVER_INSTRUMENT { + auto BufferStart = static_cast<char *>(Buffer.Buffer); + if ((RecordPtr + MetadataRecSize) - BufferStart == MetadataRecSize) { + writeEOBMetadata(); + if (!releaseThreadLocalBuffer(LocalBQ.get())) + return; + RecordPtr = nullptr; + } +} + +inline void processFunctionHook( + int32_t FuncId, XRayEntryType Entry, uint64_t TSC, unsigned char CPU, + int (*wall_clock_reader)(clockid_t, struct timespec *), + __sanitizer::atomic_sint32_t &LoggingStatus, + const std::shared_ptr<BufferQueue> &BQ) XRAY_NEVER_INSTRUMENT { + // Prevent signal handler recursion, so in case we're already in a log writing + // mode and the signal handler comes in (and is also instrumented) then we + // don't want to be clobbering potentially partial writes already happening in + // the thread. We use a simple thread_local latch to only allow one on-going + // handleArg0 to happen at any given time. + thread_local bool Running = false; + RecursionGuard Guard{Running}; + if (!Guard) { + assert(Running == true && "RecursionGuard is buggy!"); + return; + } + + // In case the reference has been cleaned up before, we make sure we + // initialize it to the provided BufferQueue. + if (LocalBQ == nullptr) + LocalBQ = BQ; + + if (!isLogInitializedAndReady(LocalBQ, TSC, CPU, wall_clock_reader)) + return; + // Before we go setting up writing new function entries, we need to be really // careful about the pointer math we're doing. This means we need to ensure // that the record we are about to write is going to fit into the buffer, @@ -545,25 +605,15 @@ static inline void processFunctionHook( // bytes in the end of the buffer, we need to write out the EOB, get a new // Buffer, set it up properly before doing any further writing. // - char *BufferStart = static_cast<char *>(Buffer.Buffer); - if ((RecordPtr + (MetadataRecSize + FunctionRecSize)) - BufferStart < - static_cast<ptrdiff_t>(MetadataRecSize)) { - writeEOBMetadata(); - if (!releaseThreadLocalBuffer(LocalBQ.get())) - return; - auto EC = LocalBQ->getBuffer(Buffer); - if (EC != BufferQueue::ErrorCode::Ok) { - Report("Failed to acquire a buffer; error=%s\n", - BufferQueue::getErrorString(EC)); - return; - } - setupNewBuffer(wall_clock_reader); + if (!prepareBuffer(wall_clock_reader, FunctionRecSize + MetadataRecSize)) { + LocalBQ = nullptr; + return; } // By this point, we are now ready to write at most 24 bytes (one metadata // record and one function record). - BufferStart = static_cast<char *>(Buffer.Buffer); - assert((RecordPtr + (MetadataRecSize + FunctionRecSize)) - BufferStart >= + assert((RecordPtr + (MetadataRecSize + FunctionRecSize)) - + static_cast<char *>(Buffer.Buffer) >= static_cast<ptrdiff_t>(MetadataRecSize) && "Misconfigured BufferQueue provided; Buffer size not large enough."); @@ -586,7 +636,6 @@ static inline void processFunctionHook( // FunctionRecord. In this case we write down just a FunctionRecord with // the correct TSC delta. // - uint32_t RecordTSCDelta = 0; if (CPU != CurrentCPU) { // We've moved to a new CPU. @@ -619,21 +668,27 @@ static inline void processFunctionHook( break; rewindRecentCall(TSC, LastTSC, LastFunctionEntryTSC, FuncId); return; // without writing log. + case XRayEntryType::CUSTOM_EVENT: { + // This is a bug in patching, so we'll report it once and move on. + static bool Once = [&] { + Report("Internal error: patched an XRay custom event call as a function; " + "func id = %d", + FuncId); + return true; + }(); + (void)Once; + return; + } } writeFunctionRecord(FuncId, RecordTSCDelta, Entry, RecordPtr); // If we've exhausted the buffer by this time, we then release the buffer to // make sure that other threads may start using this buffer. - if ((RecordPtr + MetadataRecSize) - BufferStart == MetadataRecSize) { - writeEOBMetadata(); - if (!releaseThreadLocalBuffer(LocalBQ.get())) - return; - RecordPtr = nullptr; - } + endBufferIfFull(); } } // namespace __xray_fdr_internal - } // namespace __xray + #endif // XRAY_XRAY_FDR_LOGGING_IMPL_H diff --git a/contrib/compiler-rt/lib/xray/xray_interface.cc b/contrib/compiler-rt/lib/xray/xray_interface.cc index 26f0ab122db2..c437a72e3f05 100644 --- a/contrib/compiler-rt/lib/xray/xray_interface.cc +++ b/contrib/compiler-rt/lib/xray/xray_interface.cc @@ -50,6 +50,9 @@ __sanitizer::atomic_uintptr_t XRayPatchedFunction{0}; // This is the function to call from the arg1-enabled sleds/trampolines. __sanitizer::atomic_uintptr_t XRayArgLogger{0}; +// This is the function to call when we encounter a custom event log call. +__sanitizer::atomic_uintptr_t XRayPatchedCustomEvent{0}; + // MProtectHelper is an RAII wrapper for calls to mprotect(...) that will undo // any successful mprotect(...) changes. This is used to make a page writeable // and executable, and upon destruction if it was successful in doing so returns @@ -97,7 +100,19 @@ int __xray_set_handler(void (*entry)(int32_t, __sanitizer::memory_order_acquire)) { __sanitizer::atomic_store(&__xray::XRayPatchedFunction, - reinterpret_cast<uint64_t>(entry), + reinterpret_cast<uintptr_t>(entry), + __sanitizer::memory_order_release); + return 1; + } + return 0; +} + +int __xray_set_customevent_handler(void (*entry)(void *, size_t)) + XRAY_NEVER_INSTRUMENT { + if (__sanitizer::atomic_load(&XRayInitialized, + __sanitizer::memory_order_acquire)) { + __sanitizer::atomic_store(&__xray::XRayPatchedCustomEvent, + reinterpret_cast<uintptr_t>(entry), __sanitizer::memory_order_release); return 1; } @@ -161,6 +176,9 @@ inline bool patchSled(const XRaySledEntry &Sled, bool Enable, case XRayEntryType::LOG_ARGS_ENTRY: Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_ArgLoggerEntry); break; + case XRayEntryType::CUSTOM_EVENT: + Success = patchCustomEvent(Enable, FuncId, Sled); + break; default: Report("Unsupported sled kind '%d' @%04x\n", Sled.Address, int(Sled.Kind)); return false; @@ -301,6 +319,7 @@ int __xray_set_handler_arg1(void (*Handler)(int32_t, XRayEntryType, uint64_t)) { __sanitizer::memory_order_release); return 1; } + int __xray_remove_handler_arg1() { return __xray_set_handler_arg1(nullptr); } uintptr_t __xray_function_address(int32_t FuncId) XRAY_NEVER_INSTRUMENT { diff --git a/contrib/compiler-rt/lib/xray/xray_interface_internal.h b/contrib/compiler-rt/lib/xray/xray_interface_internal.h index ef0c6b15809b..4a2784612fcb 100644 --- a/contrib/compiler-rt/lib/xray/xray_interface_internal.h +++ b/contrib/compiler-rt/lib/xray/xray_interface_internal.h @@ -60,6 +60,7 @@ bool patchFunctionEntry(bool Enable, uint32_t FuncId, bool patchFunctionExit(bool Enable, uint32_t FuncId, const XRaySledEntry &Sled); bool patchFunctionTailExit(bool Enable, uint32_t FuncId, const XRaySledEntry &Sled); +bool patchCustomEvent(bool Enable, uint32_t FuncId, const XRaySledEntry &Sled); } // namespace __xray @@ -70,6 +71,7 @@ extern void __xray_FunctionEntry(); extern void __xray_FunctionExit(); extern void __xray_FunctionTailExit(); extern void __xray_ArgLoggerEntry(); +extern void __xray_CustomEvent(); } #endif diff --git a/contrib/compiler-rt/lib/xray/xray_mips.cc b/contrib/compiler-rt/lib/xray/xray_mips.cc index c8ff39936c5a..cd863304db29 100644 --- a/contrib/compiler-rt/lib/xray/xray_mips.cc +++ b/contrib/compiler-rt/lib/xray/xray_mips.cc @@ -95,7 +95,8 @@ inline static bool patchSled(const bool Enable, const uint32_t FuncId, // B #44 if (Enable) { - uint32_t LoTracingHookAddr = reinterpret_cast<int32_t>(TracingHook) & 0xffff; + uint32_t LoTracingHookAddr = + reinterpret_cast<int32_t>(TracingHook) & 0xffff; uint32_t HiTracingHookAddr = (reinterpret_cast<int32_t>(TracingHook) >> 16) & 0xffff; uint32_t LoFunctionID = FuncId & 0xffff; @@ -151,6 +152,12 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, return patchSled(Enable, FuncId, Sled, __xray_FunctionExit); } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT { + // FIXME: Implement in mips? + return false; +} + } // namespace __xray extern "C" void __xray_ArgLoggerEntry() XRAY_NEVER_INSTRUMENT { diff --git a/contrib/compiler-rt/lib/xray/xray_mips64.cc b/contrib/compiler-rt/lib/xray/xray_mips64.cc index 21136848c8af..fa8fdd5abccc 100644 --- a/contrib/compiler-rt/lib/xray/xray_mips64.cc +++ b/contrib/compiler-rt/lib/xray/xray_mips64.cc @@ -93,7 +93,8 @@ inline static bool patchSled(const bool Enable, const uint32_t FuncId, if (Enable) { uint32_t LoTracingHookAddr = reinterpret_cast<int64_t>(TracingHook) & 0xffff; - uint32_t HiTracingHookAddr = (reinterpret_cast<int64_t>(TracingHook) >> 16) & 0xffff; + uint32_t HiTracingHookAddr = + (reinterpret_cast<int64_t>(TracingHook) >> 16) & 0xffff; uint32_t HigherTracingHookAddr = (reinterpret_cast<int64_t>(TracingHook) >> 32) & 0xffff; uint32_t HighestTracingHookAddr = @@ -160,6 +161,11 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, return patchSled(Enable, FuncId, Sled, __xray_FunctionExit); } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT { + // FIXME: Implement in mips64? + return false; +} } // namespace __xray extern "C" void __xray_ArgLoggerEntry() XRAY_NEVER_INSTRUMENT { diff --git a/contrib/compiler-rt/lib/xray/xray_powerpc64.cc b/contrib/compiler-rt/lib/xray/xray_powerpc64.cc index 6a7554cfc1b6..ab03cb10042f 100644 --- a/contrib/compiler-rt/lib/xray/xray_powerpc64.cc +++ b/contrib/compiler-rt/lib/xray/xray_powerpc64.cc @@ -93,6 +93,12 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, // FIXME: Maybe implement this better? bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT { return true; } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT { + // FIXME: Implement in powerpc64? + return false; +} + } // namespace __xray extern "C" void __xray_ArgLoggerEntry() XRAY_NEVER_INSTRUMENT { diff --git a/contrib/compiler-rt/lib/xray/xray_trampoline_powerpc64_asm.S b/contrib/compiler-rt/lib/xray/xray_trampoline_powerpc64_asm.S index d43231ead22c..250e2e5be67a 100644 --- a/contrib/compiler-rt/lib/xray/xray_trampoline_powerpc64_asm.S +++ b/contrib/compiler-rt/lib/xray/xray_trampoline_powerpc64_asm.S @@ -145,27 +145,91 @@ __xray_FunctionEntry: .p2align 4 __xray_FunctionExit: std 0, 16(1) - ld 0, -8(1) # FuncId - stdu 1, -72(1) -# Spill r3, f1, and vsr34, the return value registers. + stdu 1, -256(1) +# Spill r3-r4, f1-f8, and vsr34-vsr41, which are return registers. +# If this appears to be slow, the caller needs to pass in number of generic, +# floating point, and vector parameters, so that we only spill those live ones. std 3, 32(1) - mr 3, 0 - addi 4, 1, 40 - stxsdx 1, 0, 4 + ld 3, 248(1) # FuncId + std 4, 40(1) addi 4, 1, 48 + stxsdx 1, 0, 4 + addi 4, 1, 56 + stxsdx 2, 0, 4 + addi 4, 1, 64 + stxsdx 3, 0, 4 + addi 4, 1, 72 + stxsdx 4, 0, 4 + addi 4, 1, 80 + stxsdx 5, 0, 4 + addi 4, 1, 88 + stxsdx 6, 0, 4 + addi 4, 1, 96 + stxsdx 7, 0, 4 + addi 4, 1, 104 + stxsdx 8, 0, 4 + addi 4, 1, 112 stxvd2x 34, 0, 4 + addi 4, 1, 128 + stxvd2x 35, 0, 4 + addi 4, 1, 144 + stxvd2x 36, 0, 4 + addi 4, 1, 160 + stxvd2x 37, 0, 4 + addi 4, 1, 176 + stxvd2x 38, 0, 4 + addi 4, 1, 192 + stxvd2x 39, 0, 4 + addi 4, 1, 208 + stxvd2x 40, 0, 4 + addi 4, 1, 224 + stxvd2x 41, 0, 4 + std 2, 240(1) mflr 0 - std 0, 64(1) + std 0, 248(1) + li 4, 1 bl _ZN6__xray23CallXRayPatchedFunctionEi13XRayEntryType nop - ld 0, 64(1) - mtlr 0 - ld 3, 32(1) - addi 4, 1, 40 - lxsdx 1, 0, 4 + addi 4, 1, 48 + lxsdx 1, 0, 4 + addi 4, 1, 56 + lxsdx 2, 0, 4 + addi 4, 1, 64 + lxsdx 3, 0, 4 + addi 4, 1, 72 + lxsdx 4, 0, 4 + addi 4, 1, 80 + lxsdx 5, 0, 4 + addi 4, 1, 88 + lxsdx 6, 0, 4 + addi 4, 1, 96 + lxsdx 7, 0, 4 + addi 4, 1, 104 + lxsdx 8, 0, 4 + addi 4, 1, 112 lxvd2x 34, 0, 4 - addi 1, 1, 72 + addi 4, 1, 128 + lxvd2x 35, 0, 4 + addi 4, 1, 144 + lxvd2x 36, 0, 4 + addi 4, 1, 160 + lxvd2x 37, 0, 4 + addi 4, 1, 176 + lxvd2x 38, 0, 4 + addi 4, 1, 192 + lxvd2x 39, 0, 4 + addi 4, 1, 208 + lxvd2x 40, 0, 4 + addi 4, 1, 224 + lxvd2x 41, 0, 4 + ld 0, 248(1) + mtlr 0 + ld 2, 240(1) + ld 3, 32(1) + ld 4, 40(1) + + addi 1, 1, 256 ld 0, 16(1) blr diff --git a/contrib/compiler-rt/lib/xray/xray_trampoline_x86_64.S b/contrib/compiler-rt/lib/xray/xray_trampoline_x86_64.S index 847ecef8d425..b59eedc4bb1b 100644 --- a/contrib/compiler-rt/lib/xray/xray_trampoline_x86_64.S +++ b/contrib/compiler-rt/lib/xray/xray_trampoline_x86_64.S @@ -176,9 +176,15 @@ __xray_ArgLoggerEntry: je .Larg1entryFail .Larg1entryLog: - movq %rdi, %rdx // first argument will become the third - xorq %rsi, %rsi // XRayEntryType::ENTRY into the second - movl %r10d, %edi // 32-bit function ID becomes the first + + // First argument will become the third + movq %rdi, %rdx + + // XRayEntryType::ENTRY into the second + xorq %rsi, %rsi + + // 32-bit function ID becomes the first + movl %r10d, %edi callq *%rax .Larg1entryFail: @@ -189,4 +195,38 @@ __xray_ArgLoggerEntry: .size __xray_ArgLoggerEntry, .Larg1entryEnd-__xray_ArgLoggerEntry .cfi_endproc +//===----------------------------------------------------------------------===// + + .global __xray_CustomEvent + .align 16, 0x90 + .type __xray_CustomEvent,@function +__xray_CustomEvent: + .cfi_startproc + subq $16, %rsp + .cfi_def_cfa_offset 24 + movq %rbp, 8(%rsp) + movq %rax, 0(%rsp) + + // We take two arguments to this trampoline, which should be in rdi and rsi + // already. We also make sure that we stash %rax because we use that register + // to call the logging handler. + movq _ZN6__xray22XRayPatchedCustomEventE(%rip), %rax + testq %rax,%rax + je .LcustomEventCleanup + + // At this point we know that rcx and rdx already has the data, so we just + // call the logging handler. + callq *%rax + +.LcustomEventCleanup: + movq 0(%rsp), %rax + movq 8(%rsp), %rbp + addq $16, %rsp + .cfi_def_cfa_offset 8 + retq + +.Ltmp8: + .size __xray_CustomEvent, .Ltmp8-__xray_CustomEvent + .cfi_endproc + NO_EXEC_STACK_DIRECTIVE diff --git a/contrib/compiler-rt/lib/xray/xray_x86_64.cc b/contrib/compiler-rt/lib/xray/xray_x86_64.cc index 2e9a8d270c33..e34806fa1cea 100644 --- a/contrib/compiler-rt/lib/xray/xray_x86_64.cc +++ b/contrib/compiler-rt/lib/xray/xray_x86_64.cc @@ -75,8 +75,10 @@ uint64_t getTSCFrequency() XRAY_NEVER_INSTRUMENT { static constexpr uint8_t CallOpCode = 0xe8; static constexpr uint16_t MovR10Seq = 0xba41; static constexpr uint16_t Jmp9Seq = 0x09eb; +static constexpr uint16_t Jmp20Seq = 0x14eb; static constexpr uint8_t JmpOpCode = 0xe9; static constexpr uint8_t RetOpCode = 0xc3; +static constexpr uint16_t NopwSeq = 0x9066; static constexpr int64_t MinOffset{std::numeric_limits<int32_t>::min()}; static constexpr int64_t MaxOffset{std::numeric_limits<int32_t>::max()}; @@ -201,6 +203,40 @@ bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId, return true; } +bool patchCustomEvent(const bool Enable, const uint32_t FuncId, + const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT { + // Here we do the dance of replacing the following sled: + // + // xray_sled_n: + // jmp +19 // 2 bytes + // ... + // + // With the following: + // + // nopw // 2 bytes* + // ... + // + // We need to do this in the following order: + // + // 1. Overwrite the 5-byte nop with the call (relative), where (relative) is + // the relative offset to the __xray_CustomEvent trampoline. + // 2. Do a two-byte atomic write over the 'jmp +24' to turn it into a 'nopw'. + // This allows us to "enable" this code once the changes have committed. + // + // The "unpatch" should just turn the 'nopw' back to a 'jmp +24'. + // + if (Enable) { + std::atomic_store_explicit( + reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), NopwSeq, + std::memory_order_release); + } else { + std::atomic_store_explicit( + reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp20Seq, + std::memory_order_release); + } + return false; +} + // We determine whether the CPU we're running on has the correct features we // need. In x86_64 this will be rdtscp support. bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT { diff --git a/contrib/libc++/include/__bsd_locale_fallbacks.h b/contrib/libc++/include/__bsd_locale_fallbacks.h index cbc8ad226fd2..3425ce659b7e 100644 --- a/contrib/libc++/include/__bsd_locale_fallbacks.h +++ b/contrib/libc++/include/__bsd_locale_fallbacks.h @@ -19,27 +19,24 @@ _LIBCPP_BEGIN_NAMESPACE_STD -typedef _VSTD::remove_pointer<locale_t>::type __use_locale_struct; -typedef _VSTD::unique_ptr<__use_locale_struct, decltype(&uselocale)> __locale_raii; - inline _LIBCPP_ALWAYS_INLINE decltype(MB_CUR_MAX) __libcpp_mb_cur_max_l(locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return MB_CUR_MAX; } inline _LIBCPP_ALWAYS_INLINE wint_t __libcpp_btowc_l(int __c, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return btowc(__c); } inline _LIBCPP_ALWAYS_INLINE int __libcpp_wctob_l(wint_t __c, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return wctob(__c); } @@ -47,14 +44,14 @@ inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_wcsnrtombs_l(char *__dest, const wchar_t **__src, size_t __nwc, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return wcsnrtombs(__dest, __src, __nwc, __len, __ps); } inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_wcrtomb_l(char *__s, wchar_t __wc, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return wcrtomb(__s, __wc, __ps); } @@ -62,7 +59,7 @@ inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_mbsnrtowcs_l(wchar_t * __dest, const char **__src, size_t __nms, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbsnrtowcs(__dest, __src, __nms, __len, __ps); } @@ -70,28 +67,28 @@ inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_mbrtowc_l(wchar_t *__pwc, const char *__s, size_t __n, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbrtowc(__pwc, __s, __n, __ps); } inline _LIBCPP_ALWAYS_INLINE int __libcpp_mbtowc_l(wchar_t *__pwc, const char *__pmb, size_t __max, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbtowc(__pwc, __pmb, __max); } inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_mbrlen_l(const char *__s, size_t __n, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbrlen(__s, __n, __ps); } inline _LIBCPP_ALWAYS_INLINE lconv *__libcpp_localeconv_l(locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return localeconv(); } @@ -99,7 +96,7 @@ inline _LIBCPP_ALWAYS_INLINE size_t __libcpp_mbsrtowcs_l(wchar_t *__dest, const char **__src, size_t __len, mbstate_t *__ps, locale_t __l) { - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); return mbsrtowcs(__dest, __src, __len, __ps); } @@ -107,7 +104,7 @@ inline int __libcpp_snprintf_l(char *__s, size_t __n, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vsnprintf(__s, __n, __format, __va); va_end(__va); return __res; @@ -117,7 +114,7 @@ inline int __libcpp_asprintf_l(char **__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vasprintf(__s, __format, __va); va_end(__va); return __res; @@ -127,7 +124,7 @@ inline int __libcpp_sscanf_l(const char *__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); - __locale_raii __current( uselocale(__l), uselocale ); + __libcpp_locale_guard __current(__l); int __res = vsscanf(__s, __format, __va); va_end(__va); return __res; diff --git a/contrib/libc++/include/__config b/contrib/libc++/include/__config index 2a2907494b2b..4ad700e234c2 100644 --- a/contrib/libc++/include/__config +++ b/contrib/libc++/include/__config @@ -129,6 +129,12 @@ #define __has_keyword(__x) !(__is_identifier(__x)) +#ifdef __has_include +#define __libcpp_has_include(__x) __has_include(__x) +#else +#define __libcpp_has_include(__x) 0 +#endif + #if defined(__clang__) #define _LIBCPP_COMPILER_CLANG # ifndef __apple_build_version__ @@ -968,7 +974,7 @@ _LIBCPP_FUNC_VIS extern "C" void __sanitizer_annotate_contiguous_container( # if defined(__GNUC__) && ((__GNUC__ >= 5) || (__GNUC__ == 4 && \ (__GNUC_MINOR__ >= 3 || __GNUC_PATCHLEVEL__ >= 2))) && !defined(__GXX_RTTI) # define _LIBCPP_NO_RTTI -# elif defined(_LIBCPP_MSVC) && !defined(_CPPRTTI) +# elif defined(_LIBCPP_COMPILER_MSVC) && !defined(_CPPRTTI) # define _LIBCPP_NO_RTTI # endif #endif @@ -980,6 +986,7 @@ _LIBCPP_FUNC_VIS extern "C" void __sanitizer_annotate_contiguous_container( // Thread API #if !defined(_LIBCPP_HAS_NO_THREADS) && \ !defined(_LIBCPP_HAS_THREAD_API_PTHREAD) && \ + !defined(_LIBCPP_HAS_THREAD_API_WIN32) && \ !defined(_LIBCPP_HAS_THREAD_API_EXTERNAL) # if defined(__FreeBSD__) || \ defined(__Fuchsia__) || \ @@ -987,7 +994,8 @@ _LIBCPP_FUNC_VIS extern "C" void __sanitizer_annotate_contiguous_container( defined(__linux__) || \ defined(__APPLE__) || \ defined(__CloudABI__) || \ - defined(__sun__) + defined(__sun__) || \ + (defined(__MINGW32__) && __libcpp_has_include(<pthread.h>)) # define _LIBCPP_HAS_THREAD_API_PTHREAD # elif defined(_LIBCPP_WIN32API) # define _LIBCPP_HAS_THREAD_API_WIN32 diff --git a/contrib/libc++/include/__locale b/contrib/libc++/include/__locale index 4184e7e03489..cf3ba23b9092 100644 --- a/contrib/libc++/include/__locale +++ b/contrib/libc++/include/__locale @@ -49,6 +49,25 @@ _LIBCPP_BEGIN_NAMESPACE_STD +#if !defined(_LIBCPP_LOCALE__L_EXTENSIONS) || defined(_LIBCPP_MSVCRT) +struct __libcpp_locale_guard { + _LIBCPP_INLINE_VISIBILITY + __libcpp_locale_guard(locale_t& __loc) : __old_loc_(uselocale(__loc)) {} + + _LIBCPP_INLINE_VISIBILITY + ~__libcpp_locale_guard() { + if (__old_loc_) + uselocale(__old_loc_); + } + + locale_t __old_loc_; +private: + __libcpp_locale_guard(__libcpp_locale_guard const&); + __libcpp_locale_guard& operator=(__libcpp_locale_guard const&); +}; +#endif + + class _LIBCPP_TYPE_VIS locale; template <class _Facet> diff --git a/contrib/libc++/include/__mutex_base b/contrib/libc++/include/__mutex_base index a6d5e79c4c86..7f5e2ea2810e 100644 --- a/contrib/libc++/include/__mutex_base +++ b/contrib/libc++/include/__mutex_base @@ -15,6 +15,7 @@ #include <chrono> #include <system_error> #include <__threading_support> +#include <__undef_min_max> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header diff --git a/contrib/libc++/include/__threading_support b/contrib/libc++/include/__threading_support index 080ebd256b8f..385fff32b350 100644 --- a/contrib/libc++/include/__threading_support +++ b/contrib/libc++/include/__threading_support @@ -30,6 +30,7 @@ #include <Windows.h> #include <process.h> #include <fibersapi.h> +#include <__undef_min_max> #endif #if defined(_LIBCPP_HAS_THREAD_LIBRARY_EXTERNAL) || \ diff --git a/contrib/libc++/include/__undef_min_max b/contrib/libc++/include/__undef_min_max index f4ca091def45..71db3965e3cd 100644 --- a/contrib/libc++/include/__undef_min_max +++ b/contrib/libc++/include/__undef_min_max @@ -10,7 +10,7 @@ #ifdef min #if !defined(_LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS) -#if defined(_LIBCPP_MSVC) +#if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("macro min is incompatible with C++. Try #define NOMINMAX " "before any Windows header. #undefing min") #else @@ -22,7 +22,7 @@ _LIBCPP_WARNING("macro min is incompatible with C++. Try #define NOMINMAX " #ifdef max #if !defined(_LIBCPP_DISABLE_MACRO_CONFLICT_WARNINGS) -#if defined(_LIBCPP_MSVC) +#if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("macro max is incompatible with C++. Try #define NOMINMAX " "before any Windows header. #undefing max") #else diff --git a/contrib/libc++/include/algorithm b/contrib/libc++/include/algorithm index c3517a11bb0d..08ca23ff6168 100644 --- a/contrib/libc++/include/algorithm +++ b/contrib/libc++/include/algorithm @@ -644,8 +644,8 @@ template <class BidirectionalIterator, class Compare> #if defined(__IBMCPP__) #include "support/ibm/support.h" #endif -#if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__) -#include "support/win32/support.h" +#if defined(_LIBCPP_COMPILER_MSVC) +#include <intrin.h> #endif #include <__undef_min_max> @@ -783,51 +783,132 @@ struct __debug_less // Precondition: __x != 0 inline _LIBCPP_INLINE_VISIBILITY -unsigned -__ctz(unsigned __x) -{ +unsigned __ctz(unsigned __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned>(__builtin_ctz(__x)); +#else + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + static_assert(sizeof(unsigned long) == 4, ""); + unsigned long where; + // Search from LSB to MSB for first set bit. + // Returns zero if no set bit is found. + if (_BitScanForward(&where, mask)) + return where; + return 32; +#endif } inline _LIBCPP_INLINE_VISIBILITY -unsigned long -__ctz(unsigned long __x) -{ +unsigned long __ctz(unsigned long __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned long>(__builtin_ctzl(__x)); +#else + static_assert(sizeof(unsigned long) == sizeof(unsigned), ""); + return __ctz(static_cast<unsigned>(__x)); +#endif } inline _LIBCPP_INLINE_VISIBILITY -unsigned long long -__ctz(unsigned long long __x) -{ +unsigned long long __ctz(unsigned long long __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned long long>(__builtin_ctzll(__x)); +#else + unsigned long where; +// Search from LSB to MSB for first set bit. +// Returns zero if no set bit is found. +#if defined(_LIBCPP_HAS_BITSCAN64) + (defined(_M_AMD64) || defined(__x86_64__)) + if (_BitScanForward64(&where, mask)) + return static_cast<int>(where); +#else + // Win32 doesn't have _BitScanForward64 so emulate it with two 32 bit calls. + // Scan the Low Word. + if (_BitScanForward(&where, static_cast<unsigned long>(mask))) + return where; + // Scan the High Word. + if (_BitScanForward(&where, static_cast<unsigned long>(mask >> 32))) + return where + 32; // Create a bit offset from the LSB. +#endif + return 64; +#endif // _LIBCPP_COMPILER_MSVC } // Precondition: __x != 0 inline _LIBCPP_INLINE_VISIBILITY -unsigned -__clz(unsigned __x) -{ +unsigned __clz(unsigned __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned>(__builtin_clz(__x)); +#else + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + static_assert(sizeof(unsigned long) == 4, ""); + unsigned long where; + // Search from LSB to MSB for first set bit. + // Returns zero if no set bit is found. + if (_BitScanReverse(&where, mask)) + return 31 - where; + return 32; // Undefined Behavior. +#endif } inline _LIBCPP_INLINE_VISIBILITY -unsigned long -__clz(unsigned long __x) -{ +unsigned long __clz(unsigned long __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned long>(__builtin_clzl (__x)); +#else + static_assert(sizeof(unsigned) == sizeof(unsigned long), ""); + return __clz(static_cast<unsigned>(__x)); +#endif } inline _LIBCPP_INLINE_VISIBILITY -unsigned long long -__clz(unsigned long long __x) -{ +unsigned long long __clz(unsigned long long __x) { +#ifndef _LIBCPP_COMPILER_MSVC return static_cast<unsigned long long>(__builtin_clzll(__x)); +#else + unsigned long where; +// BitScanReverse scans from MSB to LSB for first set bit. +// Returns 0 if no set bit is found. +#if defined(_LIBCPP_HAS_BITSCAN64) + if (_BitScanReverse64(&where, mask)) + return static_cast<int>(63 - where); +#else + // Scan the high 32 bits. + if (_BitScanReverse(&where, static_cast<unsigned long>(mask >> 32))) + return 63 - (where + 32); // Create a bit offset from the MSB. + // Scan the low 32 bits. + if (_BitScanReverse(&where, static_cast<unsigned long>(mask))) + return 63 - where; +#endif + return 64; // Undefined Behavior. +#endif // _LIBCPP_COMPILER_MSVC +} + +inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned __x) { +#ifndef _LIBCPP_COMPILER_MSVC + return __builtin_popcount (__x); +#else + static_assert(sizeof(unsigned) == 4, ""); + return __popcnt(__x); +#endif +} + +inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned long __x) { +#ifndef _LIBCPP_COMPILER_MSVC + return __builtin_popcountl (__x); +#else + static_assert(sizeof(unsigned long) == 4, ""); + return __popcnt(__x); +#endif } -inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned __x) {return __builtin_popcount (__x);} -inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned long __x) {return __builtin_popcountl (__x);} -inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned long long __x) {return __builtin_popcountll(__x);} +inline _LIBCPP_INLINE_VISIBILITY int __pop_count(unsigned long long __x) { +#ifndef _LIBCPP_COMPILER_MSVC + return __builtin_popcountll(__x); +#else + static_assert(sizeof(unsigned long long) == 8, ""); + return __popcnt64(__x); +#endif +} // all_of diff --git a/contrib/libc++/include/ctype.h b/contrib/libc++/include/ctype.h index 22d6c49be9e1..e97ff3c48876 100644 --- a/contrib/libc++/include/ctype.h +++ b/contrib/libc++/include/ctype.h @@ -40,15 +40,6 @@ int toupper(int c); #ifdef __cplusplus -#if defined(_LIBCPP_MSVCRT) -// We support including .h headers inside 'extern "C"' contexts, so switch -// back to C++ linkage before including these C++ headers. -extern "C++" { - #include "support/win32/support.h" - #include "support/win32/locale_win32.h" -} -#endif // _LIBCPP_MSVCRT - #undef isalnum #undef isalpha #undef isblank diff --git a/contrib/libc++/include/experimental/numeric b/contrib/libc++/include/experimental/numeric index d1209dbec15b..6488a68eca6c 100644 --- a/contrib/libc++/include/experimental/numeric +++ b/contrib/libc++/include/experimental/numeric @@ -66,11 +66,11 @@ struct __abs<_Result, _Source, false> { template<class _Tp> -_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY -_Tp __gcd(_Tp __m, _Tp __n) +_LIBCPP_CONSTEXPR _LIBCPP_HIDDEN +inline _Tp __gcd(_Tp __m, _Tp __n) { static_assert((!is_signed<_Tp>::value), "" ); - return __n == 0 ? __m : __gcd<_Tp>(__n, __m % __n); + return __n == 0 ? __m : _VSTD_LFTS_V2::__gcd<_Tp>(__n, __m % __n); } @@ -84,8 +84,9 @@ gcd(_Tp __m, _Up __n) static_assert((!is_same<typename remove_cv<_Up>::type, bool>::value), "Second argument to gcd cannot be bool" ); using _Rp = common_type_t<_Tp,_Up>; using _Wp = make_unsigned_t<_Rp>; - return static_cast<_Rp>(__gcd(static_cast<_Wp>(__abs<_Rp, _Tp>()(__m)), - static_cast<_Wp>(__abs<_Rp, _Up>()(__n)))); + return static_cast<_Rp>(_VSTD_LFTS_V2::__gcd( + static_cast<_Wp>(__abs<_Rp, _Tp>()(__m)), + static_cast<_Wp>(__abs<_Rp, _Up>()(__n)))); } template<class _Tp, class _Up> @@ -100,7 +101,7 @@ lcm(_Tp __m, _Up __n) return 0; using _Rp = common_type_t<_Tp,_Up>; - _Rp __val1 = __abs<_Rp, _Tp>()(__m) / gcd(__m, __n); + _Rp __val1 = __abs<_Rp, _Tp>()(__m) / _VSTD_LFTS_V2::gcd(__m, __n); _Rp __val2 = __abs<_Rp, _Up>()(__n); _LIBCPP_ASSERT((numeric_limits<_Rp>::max() / __val1 > __val2), "Overflow in lcm"); return __val1 * __val2; diff --git a/contrib/libc++/include/ext/hash_map b/contrib/libc++/include/ext/hash_map index 66f2b11c0594..998e8f65994e 100644 --- a/contrib/libc++/include/ext/hash_map +++ b/contrib/libc++/include/ext/hash_map @@ -207,7 +207,7 @@ template <class Key, class T, class Hash, class Pred, class Alloc> #include <ext/__hash> #if __DEPRECATED -#if defined(_LIBCPP_MSVC) +#if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("Use of the header <ext/hash_map> is deprecated. Migrate to <unordered_map>") #else # warning Use of the header <ext/hash_map> is deprecated. Migrate to <unordered_map> diff --git a/contrib/libc++/include/ext/hash_set b/contrib/libc++/include/ext/hash_set index 916ed6910d7d..38f81ed3b5c8 100644 --- a/contrib/libc++/include/ext/hash_set +++ b/contrib/libc++/include/ext/hash_set @@ -199,7 +199,7 @@ template <class Value, class Hash, class Pred, class Alloc> #include <ext/__hash> #if __DEPRECATED -#if defined(_LIBCPP_MSVC) +#if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("Use of the header <ext/hash_set> is deprecated. Migrate to <unordered_set>") #else # warning Use of the header <ext/hash_set> is deprecated. Migrate to <unordered_set> diff --git a/contrib/libc++/include/limits b/contrib/libc++/include/limits index 609c4d4ed95a..4755c57cf903 100644 --- a/contrib/libc++/include/limits +++ b/contrib/libc++/include/limits @@ -111,8 +111,8 @@ template<> class numeric_limits<cv long double>; #include <__undef_min_max> -#if defined(_LIBCPP_MSVCRT) -#include "support/win32/limits_win32.h" +#if defined(_LIBCPP_COMPILER_MSVC) +#include "support/win32/limits_msvc_win32.h" #endif // _LIBCPP_MSVCRT #if defined(__IBMCPP__) diff --git a/contrib/libc++/include/locale b/contrib/libc++/include/locale index ad1c1f0083ec..d29a2dc70a5b 100644 --- a/contrib/libc++/include/locale +++ b/contrib/libc++/include/locale @@ -233,9 +233,6 @@ _LIBCPP_BEGIN_NAMESPACE_STD #define __cloc_defined #endif -typedef _VSTD::remove_pointer<locale_t>::type __locale_struct; -typedef _VSTD::unique_ptr<__locale_struct, decltype(&freelocale)> __locale_unique_ptr; - // __scan_keyword // Scans [__b, __e) until a match is found in the basic_strings range // [__kb, __ke) or until it can be shown that there is no match in [__kb, __ke). diff --git a/contrib/libc++/include/memory b/contrib/libc++/include/memory index 41ab01b46f7e..4201c92dd723 100644 --- a/contrib/libc++/include/memory +++ b/contrib/libc++/include/memory @@ -996,11 +996,11 @@ struct __rebind_pointer { // allocator_traits -namespace __has_pointer_type_imp +struct __has_pointer_type_imp { template <class _Up> static __two __test(...); template <class _Up> static char __test(typename _Up::pointer* = 0); -} +}; template <class _Tp> struct __has_pointer_type @@ -3924,7 +3924,10 @@ private: template <class _Yp, class _OrigPtr> _LIBCPP_INLINE_VISIBILITY - void + typename enable_if<is_convertible<_OrigPtr*, + const enable_shared_from_this<_Yp>* + >::value, + void>::type __enable_weak_this(const enable_shared_from_this<_Yp>* __e, _OrigPtr* __ptr) _NOEXCEPT { @@ -3943,6 +3946,7 @@ private: template <class _Up> friend class _LIBCPP_TEMPLATE_VIS weak_ptr; }; + template<class _Tp> inline _LIBCPP_CONSTEXPR diff --git a/contrib/libc++/include/numeric b/contrib/libc++/include/numeric index 8f25146938a4..9c98cdbe262e 100644 --- a/contrib/libc++/include/numeric +++ b/contrib/libc++/include/numeric @@ -222,11 +222,11 @@ struct __abs<_Result, _Source, false> { template<class _Tp> -_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY +_LIBCPP_CONSTEXPR _LIBCPP_HIDDEN _Tp __gcd(_Tp __m, _Tp __n) { static_assert((!is_signed<_Tp>::value), ""); - return __n == 0 ? __m : __gcd<_Tp>(__n, __m % __n); + return __n == 0 ? __m : _VSTD::__gcd<_Tp>(__n, __m % __n); } @@ -240,8 +240,9 @@ gcd(_Tp __m, _Up __n) static_assert((!is_same<typename remove_cv<_Up>::type, bool>::value), "Second argument to gcd cannot be bool" ); using _Rp = common_type_t<_Tp,_Up>; using _Wp = make_unsigned_t<_Rp>; - return static_cast<_Rp>(__gcd(static_cast<_Wp>(__abs<_Rp, _Tp>()(__m)), - static_cast<_Wp>(__abs<_Rp, _Up>()(__n)))); + return static_cast<_Rp>(_VSTD::__gcd( + static_cast<_Wp>(__abs<_Rp, _Tp>()(__m)), + static_cast<_Wp>(__abs<_Rp, _Up>()(__n)))); } template<class _Tp, class _Up> @@ -256,7 +257,7 @@ lcm(_Tp __m, _Up __n) return 0; using _Rp = common_type_t<_Tp,_Up>; - _Rp __val1 = __abs<_Rp, _Tp>()(__m) / gcd(__m, __n); + _Rp __val1 = __abs<_Rp, _Tp>()(__m) / _VSTD::gcd(__m, __n); _Rp __val2 = __abs<_Rp, _Up>()(__n); _LIBCPP_ASSERT((numeric_limits<_Rp>::max() / __val1 > __val2), "Overflow in lcm"); return __val1 * __val2; diff --git a/contrib/libc++/include/stdio.h b/contrib/libc++/include/stdio.h index 56fb2d83bb28..dc534970f9d8 100644 --- a/contrib/libc++/include/stdio.h +++ b/contrib/libc++/include/stdio.h @@ -111,8 +111,9 @@ void perror(const char* s); // snprintf #if defined(_LIBCPP_MSVCRT) -extern "C++" { -#include "support/win32/support.h" +extern "C" { +int vasprintf(char **sptr, const char *__restrict fmt, va_list ap); +int asprintf(char **sptr, const char *__restrict fmt, ...); } #endif diff --git a/contrib/libc++/include/stdlib.h b/contrib/libc++/include/stdlib.h index 12fd676a15f5..f11c5e76226e 100644 --- a/contrib/libc++/include/stdlib.h +++ b/contrib/libc++/include/stdlib.h @@ -97,10 +97,6 @@ void *aligned_alloc(size_t alignment, size_t size); // C11 extern "C++" { -#ifdef _LIBCPP_MSVCRT -#include "support/win32/locale_win32.h" -#endif // _LIBCPP_MSVCRT - #undef abs #undef div #undef labs diff --git a/contrib/libc++/include/string_view b/contrib/libc++/include/string_view index 5c42b36ca565..e59f099f16e7 100644 --- a/contrib/libc++/include/string_view +++ b/contrib/libc++/include/string_view @@ -103,7 +103,6 @@ namespace std { constexpr const_pointer data() const noexcept; // 7.7, basic_string_view modifiers - constexpr void clear() noexcept; constexpr void remove_prefix(size_type n); constexpr void remove_suffix(size_type n); constexpr void swap(basic_string_view& s) noexcept; @@ -293,13 +292,6 @@ public: // [string.view.modifiers], modifiers: _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY - void clear() _NOEXCEPT - { - __data = nullptr; - __size = 0; - } - - _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY void remove_prefix(size_type __n) _NOEXCEPT { _LIBCPP_ASSERT(__n <= size(), "remove_prefix() can't remove more than size()"); diff --git a/contrib/libc++/include/variant b/contrib/libc++/include/variant index 88f7b240d029..ba15ed8c4a14 100644 --- a/contrib/libc++/include/variant +++ b/contrib/libc++/include/variant @@ -425,30 +425,21 @@ struct __base { constexpr auto __fmatrix = __make_fmatrix<_Visitor&&, decltype(_VSTD::forward<_Vs>(__vs).__as_base())...>(); - const size_t __indices[] = {__vs.index()...}; - return __at(__fmatrix, __indices)(_VSTD::forward<_Visitor>(__visitor), - _VSTD::forward<_Vs>(__vs).__as_base()...); + return __at(__fmatrix, __vs.index()...)( + _VSTD::forward<_Visitor>(__visitor), + _VSTD::forward<_Vs>(__vs).__as_base()...); } private: template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY - static constexpr const _Tp& __at_impl(const _Tp& __elem, const size_t*) { - return __elem; - } - - template <class _Tp, size_t _Np> - inline _LIBCPP_INLINE_VISIBILITY - static constexpr auto&& __at_impl(const array<_Tp, _Np>& __elems, - const size_t* __index) { - return __at_impl(__elems[*__index], __index + 1); - } + static constexpr const _Tp& __at(const _Tp& __elem) { return __elem; } - template <class _Tp, size_t _Np, size_t _Ip> + template <class _Tp, size_t _Np, typename... _Indices> inline _LIBCPP_INLINE_VISIBILITY static constexpr auto&& __at(const array<_Tp, _Np>& __elems, - const size_t (&__indices)[_Ip]) { - return __at_impl(__elems, begin(__indices)); + size_t __index, _Indices... __indices) { + return __at(__elems[__index], __indices...); } template <class _Fp, class... _Fs> @@ -1140,7 +1131,7 @@ public: : __impl(in_place_index<_Ip>, _VSTD::forward<_Arg>(__arg)) {} template <size_t _Ip, class... _Args, - enable_if_t<(_Ip < sizeof...(_Types)), int> = 0, + class = enable_if_t<(_Ip < sizeof...(_Types)), int>, class _Tp = variant_alternative_t<_Ip, variant<_Types...>>, enable_if_t<is_constructible_v<_Tp, _Args...>, int> = 0> inline _LIBCPP_INLINE_VISIBILITY diff --git a/contrib/libc++/include/wchar.h b/contrib/libc++/include/wchar.h index c0c6ef754fbe..25a318faff25 100644 --- a/contrib/libc++/include/wchar.h +++ b/contrib/libc++/include/wchar.h @@ -166,9 +166,12 @@ inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD } #endif -#if defined(__cplusplus) && (defined(_LIBCPP_MSVCRT) || defined(__MINGW32__)) -extern "C++" { -#include <support/win32/support.h> // pull in *swprintf defines +#if defined(__cplusplus) && defined(_LIBCPP_MSVCRT) +extern "C" { +size_t mbsnrtowcs(wchar_t *__restrict dst, const char **__restrict src, + size_t nmc, size_t len, mbstate_t *__restrict ps); +size_t wcsnrtombs(char *__restrict dst, const wchar_t **__restrict src, + size_t nwc, size_t len, mbstate_t *__restrict ps); } // extern "C++" #endif // __cplusplus && _LIBCPP_MSVCRT diff --git a/contrib/libc++/src/include/atomic_support.h b/contrib/libc++/src/include/atomic_support.h index 378541b23256..08847e630705 100644 --- a/contrib/libc++/src/include/atomic_support.h +++ b/contrib/libc++/src/include/atomic_support.h @@ -29,7 +29,7 @@ #endif #if !defined(_LIBCPP_HAS_ATOMIC_BUILTINS) && !defined(_LIBCPP_HAS_NO_THREADS) -# if defined(_LIBCPP_MSVC) +# if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("Building libc++ without __atomic builtins is unsupported") # else # warning Building libc++ without __atomic builtins is unsupported diff --git a/contrib/libc++/src/locale.cpp b/contrib/libc++/src/locale.cpp index 1ed9b41fd4ad..4163c2c0af65 100644 --- a/contrib/libc++/src/locale.cpp +++ b/contrib/libc++/src/locale.cpp @@ -45,6 +45,24 @@ _LIBCPP_BEGIN_NAMESPACE_STD +struct __libcpp_unique_locale { + __libcpp_unique_locale(const char* nm) : __loc_(newlocale(LC_ALL_MASK, nm, 0)) {} + + ~__libcpp_unique_locale() { + if (__loc_) + freelocale(__loc_); + } + + explicit operator bool() const { return __loc_; } + + locale_t& get() { return __loc_; } + + locale_t __loc_; +private: + __libcpp_unique_locale(__libcpp_unique_locale const&); + __libcpp_unique_locale& operator=(__libcpp_unique_locale const&); +}; + #ifdef __cloc_defined locale_t __cloc() { // In theory this could create a race condition. In practice @@ -4185,7 +4203,7 @@ __widen_from_utf8<32>::~__widen_from_utf8() static bool checked_string_to_wchar_convert(wchar_t& dest, const char* ptr, - __locale_struct* loc) { + locale_t loc) { if (*ptr == '\0') return false; mbstate_t mb = {}; @@ -4200,7 +4218,7 @@ static bool checked_string_to_wchar_convert(wchar_t& dest, static bool checked_string_to_char_convert(char& dest, const char* ptr, - __locale_struct* __loc) { + locale_t __loc) { if (*ptr == '\0') return false; if (!ptr[1]) { @@ -4295,8 +4313,8 @@ numpunct_byname<char>::__init(const char* nm) { if (strcmp(nm, "C") != 0) { - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("numpunct_byname<char>::numpunct_byname" " failed to construct for " + string(nm)); @@ -4333,8 +4351,8 @@ numpunct_byname<wchar_t>::__init(const char* nm) { if (strcmp(nm, "C") != 0) { - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("numpunct_byname<wchar_t>::numpunct_byname" " failed to construct for " + string(nm)); @@ -5820,8 +5838,8 @@ void moneypunct_byname<char, false>::init(const char* nm) { typedef moneypunct<char, false> base; - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); @@ -5864,8 +5882,8 @@ void moneypunct_byname<char, true>::init(const char* nm) { typedef moneypunct<char, true> base; - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); @@ -5924,8 +5942,8 @@ void moneypunct_byname<wchar_t, false>::init(const char* nm) { typedef moneypunct<wchar_t, false> base; - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); lconv* lc = __libcpp_localeconv_l(loc.get()); @@ -5989,8 +6007,8 @@ void moneypunct_byname<wchar_t, true>::init(const char* nm) { typedef moneypunct<wchar_t, true> base; - __locale_unique_ptr loc(newlocale(LC_ALL_MASK, nm, 0), freelocale); - if (loc == nullptr) + __libcpp_unique_locale loc(nm); + if (!loc) __throw_runtime_error("moneypunct_byname" " failed to construct for " + string(nm)); diff --git a/contrib/libc++/src/string.cpp b/contrib/libc++/src/string.cpp index cd644330b3a7..d7ebdd3e5c9a 100644 --- a/contrib/libc++/src/string.cpp +++ b/contrib/libc++/src/string.cpp @@ -13,9 +13,6 @@ #include "cerrno" #include "limits" #include "stdexcept" -#ifdef _LIBCPP_MSVCRT -#include "support/win32/support.h" -#endif // _LIBCPP_MSVCRT #include <stdio.h> _LIBCPP_BEGIN_NAMESPACE_STD @@ -430,7 +427,7 @@ get_swprintf() #ifndef _LIBCPP_MSVCRT return swprintf; #else - return static_cast<int (__cdecl*)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...)>(swprintf); + return static_cast<int (__cdecl*)(wchar_t* __restrict, size_t, const wchar_t*__restrict, ...)>(_snwprintf); #endif } diff --git a/contrib/libc++/src/support/runtime/exception_pointer_msvc.ipp b/contrib/libc++/src/support/runtime/exception_pointer_msvc.ipp index a8cd0e8d304d..eab5d30a9487 100644 --- a/contrib/libc++/src/support/runtime/exception_pointer_msvc.ipp +++ b/contrib/libc++/src/support/runtime/exception_pointer_msvc.ipp @@ -10,6 +10,7 @@ #include <stdio.h> #include <stdlib.h> +#include <yvals.h> // for _CRTIMP2_PURE _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL __ExceptionPtrCreate(_Out_ void*); _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL __ExceptionPtrDestroy(_Inout_ void*); diff --git a/contrib/libc++/src/thread.cpp b/contrib/libc++/src/thread.cpp index 3f283c385b76..412a8fa0a620 100644 --- a/contrib/libc++/src/thread.cpp +++ b/contrib/libc++/src/thread.cpp @@ -99,7 +99,7 @@ thread::hardware_concurrency() _NOEXCEPT #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. -# if defined(_LIBCPP_MSVC) +# if defined(_LIBCPP_WARNING) _LIBCPP_WARNING("hardware_concurrency not yet implemented") # else # warning hardware_concurrency not yet implemented diff --git a/contrib/llvm/include/llvm/ADT/APInt.h b/contrib/llvm/include/llvm/ADT/APInt.h index c3822e35906a..94fbd1a29bf9 100644 --- a/contrib/llvm/include/llvm/ADT/APInt.h +++ b/contrib/llvm/include/llvm/ADT/APInt.h @@ -157,6 +157,11 @@ private: return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)]; } + /// Utility method to change the bit width of this APInt to new bit width, + /// allocating and/or deallocating as necessary. There is no guarantee on the + /// value of any bits upon return. Caller should populate the bits after. + void reallocate(unsigned NewBitWidth); + /// \brief Convert a char array into an APInt /// /// \param radix 2, 8, 10, 16, or 36 @@ -1437,6 +1442,12 @@ public: /// as "bitPosition". void flipBit(unsigned bitPosition); + /// Negate this APInt in place. + void negate() { + flipAllBits(); + ++(*this); + } + /// Insert the bits from a smaller APInt starting at bitPosition. void insertBits(const APInt &SubBits, unsigned bitPosition); @@ -1646,12 +1657,7 @@ public: /// re-interprets the bits as a double. Note that it is valid to do this on /// any bit width. Exactly 64 bits will be translated. double bitsToDouble() const { - union { - uint64_t I; - double D; - } T; - T.I = (isSingleWord() ? U.VAL : U.pVal[0]); - return T.D; + return BitsToDouble(getWord(0)); } /// \brief Converts APInt bits to a double @@ -1660,12 +1666,7 @@ public: /// re-interprets the bits as a float. Note that it is valid to do this on /// any bit width. Exactly 32 bits will be translated. float bitsToFloat() const { - union { - unsigned I; - float F; - } T; - T.I = unsigned((isSingleWord() ? U.VAL : U.pVal[0])); - return T.F; + return BitsToFloat(getWord(0)); } /// \brief Converts a double to APInt bits. @@ -1673,12 +1674,7 @@ public: /// The conversion does not do a translation from double to integer, it just /// re-interprets the bits of the double. static APInt doubleToBits(double V) { - union { - uint64_t I; - double D; - } T; - T.D = V; - return APInt(sizeof T * CHAR_BIT, T.I); + return APInt(sizeof(double) * CHAR_BIT, DoubleToBits(V)); } /// \brief Converts a float to APInt bits. @@ -1686,12 +1682,7 @@ public: /// The conversion does not do a translation from float to integer, it just /// re-interprets the bits of the float. static APInt floatToBits(float V) { - union { - unsigned I; - float F; - } T; - T.F = V; - return APInt(sizeof T * CHAR_BIT, T.I); + return APInt(sizeof(float) * CHAR_BIT, FloatToBits(V)); } /// @} @@ -1852,10 +1843,9 @@ public: unsigned); /// DST = LHS * RHS, where DST has width the sum of the widths of the - /// operands. No overflow occurs. DST must be disjoint from both - /// operands. Returns the number of parts required to hold the result. - static unsigned tcFullMultiply(WordType *, const WordType *, - const WordType *, unsigned, unsigned); + /// operands. No overflow occurs. DST must be disjoint from both operands. + static void tcFullMultiply(WordType *, const WordType *, + const WordType *, unsigned, unsigned); /// If RHS is zero LHS and REMAINDER are left unchanged, return one. /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set @@ -1997,8 +1987,7 @@ inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { } inline APInt operator-(APInt v) { - v.flipAllBits(); - ++v; + v.negate(); return v; } diff --git a/contrib/llvm/include/llvm/ADT/BitVector.h b/contrib/llvm/include/llvm/ADT/BitVector.h index e835f1516225..4a2af7cd68a6 100644 --- a/contrib/llvm/include/llvm/ADT/BitVector.h +++ b/contrib/llvm/include/llvm/ADT/BitVector.h @@ -255,7 +255,7 @@ public: /// find_prev - Returns the index of the first set bit that precedes the /// the bit at \p PriorTo. Returns -1 if all previous bits are unset. - int find_prev(unsigned PriorTo) { + int find_prev(unsigned PriorTo) const { if (PriorTo == 0) return -1; diff --git a/contrib/llvm/include/llvm/ADT/STLExtras.h b/contrib/llvm/include/llvm/ADT/STLExtras.h index 15945adbe589..8c28412bb607 100644 --- a/contrib/llvm/include/llvm/ADT/STLExtras.h +++ b/contrib/llvm/include/llvm/ADT/STLExtras.h @@ -706,6 +706,18 @@ struct is_one_of<T, U, Ts...> { std::is_same<T, U>::value || is_one_of<T, Ts...>::value; }; +/// \brief traits class for checking whether type T is a base class for all +/// the given types in the variadic list. +template <typename T, typename... Ts> struct are_base_of { + static const bool value = true; +}; + +template <typename T, typename U, typename... Ts> +struct are_base_of<T, U, Ts...> { + static const bool value = + std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value; +}; + //===----------------------------------------------------------------------===// // Extra additions for arrays //===----------------------------------------------------------------------===// @@ -1079,7 +1091,7 @@ private: /// /// std::vector<char> Items = {'A', 'B', 'C', 'D'}; /// for (auto X : enumerate(Items)) { -/// printf("Item %d - %c\n", X.Index, X.Value); +/// printf("Item %d - %c\n", X.index(), X.value()); /// } /// /// Output: diff --git a/contrib/llvm/include/llvm/ADT/StringExtras.h b/contrib/llvm/include/llvm/ADT/StringExtras.h index 26f11924b771..1c109be3bab3 100644 --- a/contrib/llvm/include/llvm/ADT/StringExtras.h +++ b/contrib/llvm/include/llvm/ADT/StringExtras.h @@ -106,6 +106,13 @@ static inline std::string fromHex(StringRef Input) { return Output; } +/// \brief Convert the string \p S to an integer of the specified type using +/// the radix \p Base. If \p Base is 0, auto-detects the radix. +/// Returns true if the number was successfully converted, false otherwise. +template <typename N> bool to_integer(StringRef S, N &Num, unsigned Base = 0) { + return !S.getAsInteger(Base, Num); +} + static inline std::string utostr(uint64_t X, bool isNeg = false) { char Buffer[21]; char *BufPtr = std::end(Buffer); diff --git a/contrib/llvm/include/llvm/Analysis/CallGraph.h b/contrib/llvm/include/llvm/Analysis/CallGraph.h index cc4788d3edae..01469a25c96c 100644 --- a/contrib/llvm/include/llvm/Analysis/CallGraph.h +++ b/contrib/llvm/include/llvm/Analysis/CallGraph.h @@ -41,12 +41,6 @@ /// of all of the caller-callee relationships, which is useful for /// transformations. /// -/// The CallGraph class also attempts to figure out what the root of the -/// CallGraph is, which it currently does by looking for a function named -/// 'main'. If no function named 'main' is found, the external node is used as -/// the entry node, reflecting the fact that any function without internal -/// linkage could be called into (which is common for libraries). -/// //===----------------------------------------------------------------------===// #ifndef LLVM_ANALYSIS_CALLGRAPH_H @@ -82,10 +76,6 @@ class CallGraph { /// \brief A map from \c Function* to \c CallGraphNode*. FunctionMapTy FunctionMap; - /// \brief Root is root of the call graph, or the external node if a 'main' - /// function couldn't be found. - CallGraphNode *Root; - /// \brief This node has edges to all external functions and those internal /// functions that have their address taken. CallGraphNode *ExternalCallingNode; diff --git a/contrib/llvm/include/llvm/Analysis/ProfileSummaryInfo.h b/contrib/llvm/include/llvm/Analysis/ProfileSummaryInfo.h index 75c4cbd03706..c5f97083af4d 100644 --- a/contrib/llvm/include/llvm/Analysis/ProfileSummaryInfo.h +++ b/contrib/llvm/include/llvm/Analysis/ProfileSummaryInfo.h @@ -67,8 +67,8 @@ public: } /// Returns the profile count for \p CallInst. - static Optional<uint64_t> getProfileCount(const Instruction *CallInst, - BlockFrequencyInfo *BFI); + Optional<uint64_t> getProfileCount(const Instruction *CallInst, + BlockFrequencyInfo *BFI); /// \brief Returns true if \p F has hot function entry. bool isFunctionEntryHot(const Function *F); /// Returns true if \p F has hot function entry or hot call edge. diff --git a/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h b/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h index 85350fa159d6..ceca6cb389a1 100644 --- a/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h +++ b/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h @@ -568,27 +568,16 @@ private: Predicates.insert(P); } - /*implicit*/ ExitLimit(const SCEV *E) - : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {} + /*implicit*/ ExitLimit(const SCEV *E); ExitLimit( const SCEV *E, const SCEV *M, bool MaxOrZero, - ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) - : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { - assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || - !isa<SCEVCouldNotCompute>(MaxNotTaken)) && - "Exact is not allowed to be less precise than Max"); - for (auto *PredSet : PredSetList) - for (auto *P : *PredSet) - addPredicate(P); - } + ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList); ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero, - const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) - : ExitLimit(E, M, MaxOrZero, {&PredSet}) {} + const SmallPtrSetImpl<const SCEVPredicate *> &PredSet); - ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero) - : ExitLimit(E, M, MaxOrZero, None) {} + ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero); /// Test whether this ExitLimit contains any computed information, or /// whether it's all SCEVCouldNotCompute values. @@ -782,7 +771,7 @@ private: /// Set the memoized range for the given SCEV. const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint, - ConstantRange &&CR) { + ConstantRange CR) { DenseMap<const SCEV *, ConstantRange> &Cache = Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges; diff --git a/contrib/llvm/include/llvm/Analysis/TargetLibraryInfo.def b/contrib/llvm/include/llvm/Analysis/TargetLibraryInfo.def index 099a3c7cf2ac..9cbe917c146d 100644 --- a/contrib/llvm/include/llvm/Analysis/TargetLibraryInfo.def +++ b/contrib/llvm/include/llvm/Analysis/TargetLibraryInfo.def @@ -161,6 +161,60 @@ TLI_DEFINE_STRING_INTERNAL("_Znwm") /// void *new(unsigned long, nothrow); TLI_DEFINE_ENUM_INTERNAL(ZnwmRKSt9nothrow_t) TLI_DEFINE_STRING_INTERNAL("_ZnwmRKSt9nothrow_t") +/// double __acos_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(acos_finite) +TLI_DEFINE_STRING_INTERNAL("__acos_finite") +/// float __acosf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(acosf_finite) +TLI_DEFINE_STRING_INTERNAL("__acosf_finite") +/// double __acosh_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(acosh_finite) +TLI_DEFINE_STRING_INTERNAL("__acosh_finite") +/// float __acoshf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(acoshf_finite) +TLI_DEFINE_STRING_INTERNAL("__acoshf_finite") +/// long double __acoshl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(acoshl_finite) +TLI_DEFINE_STRING_INTERNAL("__acoshl_finite") +/// long double __acosl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(acosl_finite) +TLI_DEFINE_STRING_INTERNAL("__acosl_finite") +/// double __asin_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(asin_finite) +TLI_DEFINE_STRING_INTERNAL("__asin_finite") +/// float __asinf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(asinf_finite) +TLI_DEFINE_STRING_INTERNAL("__asinf_finite") +/// long double __asinl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(asinl_finite) +TLI_DEFINE_STRING_INTERNAL("__asinl_finite") +/// double atan2_finite(double y, double x); +TLI_DEFINE_ENUM_INTERNAL(atan2_finite) +TLI_DEFINE_STRING_INTERNAL("__atan2_finite") +/// float atan2f_finite(float y, float x); +TLI_DEFINE_ENUM_INTERNAL(atan2f_finite) +TLI_DEFINE_STRING_INTERNAL("__atan2f_finite") +/// long double atan2l_finite(long double y, long double x); +TLI_DEFINE_ENUM_INTERNAL(atan2l_finite) +TLI_DEFINE_STRING_INTERNAL("__atan2l_finite") +/// double __atanh_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(atanh_finite) +TLI_DEFINE_STRING_INTERNAL("__atanh_finite") +/// float __atanhf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(atanhf_finite) +TLI_DEFINE_STRING_INTERNAL("__atanhf_finite") +/// long double __atanhl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(atanhl_finite) +TLI_DEFINE_STRING_INTERNAL("__atanhl_finite") +/// double __cosh_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(cosh_finite) +TLI_DEFINE_STRING_INTERNAL("__cosh_finite") +/// float __coshf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(coshf_finite) +TLI_DEFINE_STRING_INTERNAL("__coshf_finite") +/// long double __coshl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(coshl_finite) +TLI_DEFINE_STRING_INTERNAL("__coshl_finite") /// double __cospi(double x); TLI_DEFINE_ENUM_INTERNAL(cospi) TLI_DEFINE_STRING_INTERNAL("__cospi") @@ -180,12 +234,66 @@ TLI_DEFINE_STRING_INTERNAL("__cxa_guard_acquire") /// void __cxa_guard_release(guard_t *guard); TLI_DEFINE_ENUM_INTERNAL(cxa_guard_release) TLI_DEFINE_STRING_INTERNAL("__cxa_guard_release") +/// double __exp10_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(exp10_finite) +TLI_DEFINE_STRING_INTERNAL("__exp10_finite") +/// float __exp10f_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(exp10f_finite) +TLI_DEFINE_STRING_INTERNAL("__exp10f_finite") +/// long double __exp10l_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(exp10l_finite) +TLI_DEFINE_STRING_INTERNAL("__exp10l_finite") +/// double __exp2_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(exp2_finite) +TLI_DEFINE_STRING_INTERNAL("__exp2_finite") +/// float __exp2f_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(exp2f_finite) +TLI_DEFINE_STRING_INTERNAL("__exp2f_finite") +/// long double __exp2l_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(exp2l_finite) +TLI_DEFINE_STRING_INTERNAL("__exp2l_finite") +/// double __exp_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(exp_finite) +TLI_DEFINE_STRING_INTERNAL("__exp_finite") +/// float __expf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(expf_finite) +TLI_DEFINE_STRING_INTERNAL("__expf_finite") +/// long double __expl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(expl_finite) +TLI_DEFINE_STRING_INTERNAL("__expl_finite") /// int __isoc99_scanf (const char *format, ...) TLI_DEFINE_ENUM_INTERNAL(dunder_isoc99_scanf) TLI_DEFINE_STRING_INTERNAL("__isoc99_scanf") /// int __isoc99_sscanf(const char *s, const char *format, ...) TLI_DEFINE_ENUM_INTERNAL(dunder_isoc99_sscanf) TLI_DEFINE_STRING_INTERNAL("__isoc99_sscanf") +/// double __log10_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(log10_finite) +TLI_DEFINE_STRING_INTERNAL("__log10_finite") +/// float __log10f_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(log10f_finite) +TLI_DEFINE_STRING_INTERNAL("__log10f_finite") +/// long double __log10l_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(log10l_finite) +TLI_DEFINE_STRING_INTERNAL("__log10l_finite") +/// double __log2_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(log2_finite) +TLI_DEFINE_STRING_INTERNAL("__log2_finite") +/// float __log2f_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(log2f_finite) +TLI_DEFINE_STRING_INTERNAL("__log2f_finite") +/// long double __log2l_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(log2l_finite) +TLI_DEFINE_STRING_INTERNAL("__log2l_finite") +/// double __log_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(log_finite) +TLI_DEFINE_STRING_INTERNAL("__log_finite") +/// float __logf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(logf_finite) +TLI_DEFINE_STRING_INTERNAL("__logf_finite") +/// long double __logl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(logl_finite) +TLI_DEFINE_STRING_INTERNAL("__logl_finite") /// void *__memcpy_chk(void *s1, const void *s2, size_t n, size_t s1size); TLI_DEFINE_ENUM_INTERNAL(memcpy_chk) TLI_DEFINE_STRING_INTERNAL("__memcpy_chk") @@ -199,13 +307,30 @@ TLI_DEFINE_STRING_INTERNAL("__memset_chk") // int __nvvm_reflect(const char *) TLI_DEFINE_ENUM_INTERNAL(nvvm_reflect) TLI_DEFINE_STRING_INTERNAL("__nvvm_reflect") - +/// double __pow_finite(double x, double y); +TLI_DEFINE_ENUM_INTERNAL(pow_finite) +TLI_DEFINE_STRING_INTERNAL("__pow_finite") +/// float _powf_finite(float x, float y); +TLI_DEFINE_ENUM_INTERNAL(powf_finite) +TLI_DEFINE_STRING_INTERNAL("__powf_finite") +/// long double __powl_finite(long double x, long double y); +TLI_DEFINE_ENUM_INTERNAL(powl_finite) +TLI_DEFINE_STRING_INTERNAL("__powl_finite") /// double __sincospi_stret(double x); TLI_DEFINE_ENUM_INTERNAL(sincospi_stret) TLI_DEFINE_STRING_INTERNAL("__sincospi_stret") /// float __sincospif_stret(float x); TLI_DEFINE_ENUM_INTERNAL(sincospif_stret) TLI_DEFINE_STRING_INTERNAL("__sincospif_stret") +/// double __sinh_finite(double x); +TLI_DEFINE_ENUM_INTERNAL(sinh_finite) +TLI_DEFINE_STRING_INTERNAL("__sinh_finite") +/// float _sinhf_finite(float x); +TLI_DEFINE_ENUM_INTERNAL(sinhf_finite) +TLI_DEFINE_STRING_INTERNAL("__sinhf_finite") +/// long double __sinhl_finite(long double x); +TLI_DEFINE_ENUM_INTERNAL(sinhl_finite) +TLI_DEFINE_STRING_INTERNAL("__sinhl_finite") /// double __sinpi(double x); TLI_DEFINE_ENUM_INTERNAL(sinpi) TLI_DEFINE_STRING_INTERNAL("__sinpi") diff --git a/contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h b/contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h index b9639dba1881..0a0af384c3e6 100644 --- a/contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h +++ b/contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h @@ -537,6 +537,9 @@ public: /// \return The width of the largest scalar or vector register type. unsigned getRegisterBitWidth(bool Vector) const; + /// \return The width of the smallest vector register type. + unsigned getMinVectorRegisterBitWidth() const; + /// \return True if it should be considered for address type promotion. /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is /// profitable without finding other extensions fed by the same input. @@ -740,6 +743,22 @@ public: unsigned ChainSizeInBytes, VectorType *VecTy) const; + /// Flags describing the kind of vector reduction. + struct ReductionFlags { + ReductionFlags() : IsMaxOp(false), IsSigned(false), NoNaN(false) {} + bool IsMaxOp; ///< If the op a min/max kind, true if it's a max operation. + bool IsSigned; ///< Whether the operation is a signed int reduction. + bool NoNaN; ///< If op is an fp min/max, whether NaNs may be present. + }; + + /// \returns True if the target wants to handle the given reduction idiom in + /// the intrinsics form instead of the shuffle form. + bool useReductionIntrinsic(unsigned Opcode, Type *Ty, + ReductionFlags Flags) const; + + /// \returns True if the target wants to expand the given reduction intrinsic + /// into a shuffle sequence. + bool shouldExpandReduction(const IntrinsicInst *II) const; /// @} private: @@ -824,6 +843,7 @@ public: Type *Ty) = 0; virtual unsigned getNumberOfRegisters(bool Vector) = 0; virtual unsigned getRegisterBitWidth(bool Vector) = 0; + virtual unsigned getMinVectorRegisterBitWidth() = 0; virtual bool shouldConsiderAddressTypePromotion( const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0; virtual unsigned getCacheLineSize() = 0; @@ -895,6 +915,9 @@ public: virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const = 0; + virtual bool useReductionIntrinsic(unsigned Opcode, Type *Ty, + ReductionFlags) const = 0; + virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0; }; template <typename T> @@ -1057,6 +1080,9 @@ public: unsigned getRegisterBitWidth(bool Vector) override { return Impl.getRegisterBitWidth(Vector); } + unsigned getMinVectorRegisterBitWidth() override { + return Impl.getMinVectorRegisterBitWidth(); + } bool shouldConsiderAddressTypePromotion( const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override { return Impl.shouldConsiderAddressTypePromotion( @@ -1200,6 +1226,13 @@ public: VectorType *VecTy) const override { return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); } + bool useReductionIntrinsic(unsigned Opcode, Type *Ty, + ReductionFlags Flags) const override { + return Impl.useReductionIntrinsic(Opcode, Ty, Flags); + } + bool shouldExpandReduction(const IntrinsicInst *II) const override { + return Impl.shouldExpandReduction(II); + } }; template <typename T> diff --git a/contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h b/contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h index d7fda9e14b05..550e84ad90c4 100644 --- a/contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h +++ b/contrib/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h @@ -311,6 +311,8 @@ public: unsigned getRegisterBitWidth(bool Vector) { return 32; } + unsigned getMinVectorRegisterBitWidth() { return 128; } + bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) { @@ -456,6 +458,16 @@ public: VectorType *VecTy) const { return VF; } + + bool useReductionIntrinsic(unsigned Opcode, Type *Ty, + TTI::ReductionFlags Flags) const { + return false; + } + + bool shouldExpandReduction(const IntrinsicInst *II) const { + return true; + } + protected: // Obtain the minimum required size to hold the value (without the sign) // In case of a vector it returns the min required size for one element. diff --git a/contrib/llvm/include/llvm/Analysis/ValueTracking.h b/contrib/llvm/include/llvm/Analysis/ValueTracking.h index a54c39e3ea3a..f5f323c6b797 100644 --- a/contrib/llvm/include/llvm/Analysis/ValueTracking.h +++ b/contrib/llvm/include/llvm/Analysis/ValueTracking.h @@ -56,6 +56,11 @@ template <typename T> class ArrayRef; const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr, OptimizationRemarkEmitter *ORE = nullptr); + /// Returns the known bits rather than passing by reference. + KnownBits computeKnownBits(const Value *V, const DataLayout &DL, + unsigned Depth = 0, AssumptionCache *AC = nullptr, + const Instruction *CxtI = nullptr, + const DominatorTree *DT = nullptr); /// Compute known bits from the range metadata. /// \p KnownZero the set of bits that are known to be zero /// \p KnownOne the set of bits that are known to be one @@ -68,14 +73,6 @@ template <typename T> class ArrayRef; const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr); - /// Determine whether the sign bit is known to be zero or one. Convenience - /// wrapper around computeKnownBits. - void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, - const DataLayout &DL, unsigned Depth = 0, - AssumptionCache *AC = nullptr, - const Instruction *CxtI = nullptr, - const DominatorTree *DT = nullptr); - /// Return true if the given value is known to have exactly one bit set when /// defined. For vectors return true if every element is known to be a power /// of two when defined. Supports values with integer or pointer type and diff --git a/contrib/llvm/include/llvm/Bitcode/BitcodeReader.h b/contrib/llvm/include/llvm/Bitcode/BitcodeReader.h index 54f990d00233..31ffb7645f3a 100644 --- a/contrib/llvm/include/llvm/Bitcode/BitcodeReader.h +++ b/contrib/llvm/include/llvm/Bitcode/BitcodeReader.h @@ -152,10 +152,11 @@ namespace llvm { /// Parse the module summary index out of an IR file and return the module /// summary index object if found, or an empty summary if not. If Path refers - /// to an empty file and the -ignore-empty-index-file cl::opt flag is passed + /// to an empty file and IgnoreEmptyThinLTOIndexFile is true, then /// this function will return nullptr. Expected<std::unique_ptr<ModuleSummaryIndex>> - getModuleSummaryIndexForFile(StringRef Path); + getModuleSummaryIndexForFile(StringRef Path, + bool IgnoreEmptyThinLTOIndexFile = false); /// isBitcodeWrapper - Return true if the given bytes are the magic bytes /// for an LLVM IR bitcode wrapper. diff --git a/contrib/llvm/include/llvm/CodeGen/ExpandReductions.h b/contrib/llvm/include/llvm/CodeGen/ExpandReductions.h new file mode 100644 index 000000000000..c6aaaad967b3 --- /dev/null +++ b/contrib/llvm/include/llvm/CodeGen/ExpandReductions.h @@ -0,0 +1,24 @@ +//===----- ExpandReductions.h - Expand experimental reduction intrinsics --===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CODEGEN_EXPANDREDUCTIONS_H +#define LLVM_CODEGEN_EXPANDREDUCTIONS_H + +#include "llvm/IR/PassManager.h" + +namespace llvm { + +class ExpandReductionsPass + : public PassInfoMixin<ExpandReductionsPass> { +public: + PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); +}; +} // end namespace llvm + +#endif // LLVM_CODEGEN_EXPANDREDUCTIONS_H diff --git a/contrib/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h b/contrib/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h index 30d67eb49923..21354ae20ed1 100644 --- a/contrib/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h +++ b/contrib/llvm/include/llvm/CodeGen/GlobalISel/LegalizerInfo.h @@ -145,7 +145,7 @@ public: /// Iterate the given function (typically something like doubling the width) /// on Ty until we find a legal type for this operation. - LLT findLegalType(const InstrAspect &Aspect, + Optional<LLT> findLegalType(const InstrAspect &Aspect, function_ref<LLT(LLT)> NextType) const { LegalizeAction Action; const TypeMap &Map = Actions[Aspect.Opcode - FirstOp][Aspect.Idx]; @@ -153,8 +153,12 @@ public: do { Ty = NextType(Ty); auto ActionIt = Map.find(Ty); - if (ActionIt == Map.end()) - Action = DefaultActions.find(Aspect.Opcode)->second; + if (ActionIt == Map.end()) { + auto DefaultIt = DefaultActions.find(Aspect.Opcode); + if (DefaultIt == DefaultActions.end()) + return None; + Action = DefaultIt->second; + } else Action = ActionIt->second; } while(Action != Legal); @@ -163,11 +167,14 @@ public: /// Find what type it's actually OK to perform the given operation on, given /// the general approach we've decided to take. - LLT findLegalType(const InstrAspect &Aspect, LegalizeAction Action) const; + Optional<LLT> findLegalType(const InstrAspect &Aspect, LegalizeAction Action) const; std::pair<LegalizeAction, LLT> findLegalAction(const InstrAspect &Aspect, LegalizeAction Action) const { - return std::make_pair(Action, findLegalType(Aspect, Action)); + auto LegalType = findLegalType(Aspect, Action); + if (!LegalType) + return std::make_pair(LegalizeAction::Unsupported, LLT()); + return std::make_pair(Action, *LegalType); } /// Find the specified \p Aspect in the primary (explicitly set) Actions diff --git a/contrib/llvm/include/llvm/CodeGen/GlobalISel/Utils.h b/contrib/llvm/include/llvm/CodeGen/GlobalISel/Utils.h index 92bc9736141a..69d507069808 100644 --- a/contrib/llvm/include/llvm/CodeGen/GlobalISel/Utils.h +++ b/contrib/llvm/include/llvm/CodeGen/GlobalISel/Utils.h @@ -30,6 +30,7 @@ class TargetInstrInfo; class TargetPassConfig; class TargetRegisterInfo; class Twine; +class ConstantFP; /// Try to constrain Reg so that it is usable by argument OpIdx of the /// provided MCInstrDesc \p II. If this fails, create a new virtual @@ -62,6 +63,8 @@ void reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, Optional<int64_t> getConstantVRegVal(unsigned VReg, const MachineRegisterInfo &MRI); +const ConstantFP* getConstantFPVRegVal(unsigned VReg, + const MachineRegisterInfo &MRI); } // End namespace llvm. #endif diff --git a/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h b/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h index ca0f3fbad892..f2a9a9f73ca6 100644 --- a/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h +++ b/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h @@ -644,6 +644,13 @@ namespace ISD { /// of a call sequence, and carry arbitrary information that target might /// want to know. The first operand is a chain, the rest are specified by /// the target and not touched by the DAG optimizers. + /// Targets that may use stack to pass call arguments define additional + /// operands: + /// - size of the call frame part that must be set up within the + /// CALLSEQ_START..CALLSEQ_END pair, + /// - part of the call frame prepared prior to CALLSEQ_START. + /// Both these parameters must be constants, their sum is the total call + /// frame size. /// CALLSEQ_START..CALLSEQ_END pairs may not be nested. CALLSEQ_START, // Beginning of a call sequence CALLSEQ_END, // End of a call sequence @@ -783,6 +790,20 @@ namespace ISD { /// known nonzero constant. The only operand here is the chain. GET_DYNAMIC_AREA_OFFSET, + /// Generic reduction nodes. These nodes represent horizontal vector + /// reduction operations, producing a scalar result. + /// The STRICT variants perform reductions in sequential order. The first + /// operand is an initial scalar accumulator value, and the second operand + /// is the vector to reduce. + VECREDUCE_STRICT_FADD, VECREDUCE_STRICT_FMUL, + /// These reductions are non-strict, and have a single vector operand. + VECREDUCE_FADD, VECREDUCE_FMUL, + VECREDUCE_ADD, VECREDUCE_MUL, + VECREDUCE_AND, VECREDUCE_OR, VECREDUCE_XOR, + VECREDUCE_SMAX, VECREDUCE_SMIN, VECREDUCE_UMAX, VECREDUCE_UMIN, + /// FMIN/FMAX nodes can have flags, for NaN/NoNaN variants. + VECREDUCE_FMAX, VECREDUCE_FMIN, + /// BUILTIN_OP_END - This must be the last enum value in this list. /// The target-specific pre-isel opcode values start here. BUILTIN_OP_END diff --git a/contrib/llvm/include/llvm/CodeGen/MachineCombinerPattern.h b/contrib/llvm/include/llvm/CodeGen/MachineCombinerPattern.h index 11238016d447..8c54ae925470 100644 --- a/contrib/llvm/include/llvm/CodeGen/MachineCombinerPattern.h +++ b/contrib/llvm/include/llvm/CodeGen/MachineCombinerPattern.h @@ -48,6 +48,8 @@ enum class MachineCombinerPattern { FMULADDD_OP2, FMULSUBD_OP1, FMULSUBD_OP2, + FNMULSUBS_OP1, + FNMULSUBD_OP1, FMLAv1i32_indexed_OP1, FMLAv1i32_indexed_OP2, FMLAv1i64_indexed_OP1, diff --git a/contrib/llvm/include/llvm/CodeGen/Passes.h b/contrib/llvm/include/llvm/CodeGen/Passes.h index 42299b529410..8a5a1997386f 100644 --- a/contrib/llvm/include/llvm/CodeGen/Passes.h +++ b/contrib/llvm/include/llvm/CodeGen/Passes.h @@ -68,6 +68,10 @@ namespace llvm { /// matching during instruction selection. FunctionPass *createCodeGenPreparePass(const TargetMachine *TM = nullptr); + /// createScalarizeMaskedMemIntrinPass - Replace masked load, store, gather + /// and scatter intrinsics with scalar code when target doesn't support them. + FunctionPass *createScalarizeMaskedMemIntrinPass(); + /// AtomicExpandID -- Lowers atomic operations in terms of either cmpxchg /// load-linked/store-conditional loops. extern char &AtomicExpandID; @@ -129,6 +133,10 @@ namespace llvm { // instruction and update the MachineFunctionInfo with that information. extern char &ShrinkWrapID; + /// LiveRangeShrink pass. Move instruction close to its definition to shrink + /// the definition's live range. + extern char &LiveRangeShrinkID; + /// Greedy register allocator. extern char &RAGreedyID; @@ -405,6 +413,10 @@ namespace llvm { /// printing assembly. ModulePass *createMachineOutlinerPass(); + /// This pass expands the experimental reduction intrinsics into sequences of + /// shuffles. + FunctionPass *createExpandReductionsPass(); + } // End llvm namespace /// Target machine pass initializer for passes with dependencies. Use with diff --git a/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h b/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h index 9e1d148c7ce5..d761661f763e 100644 --- a/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h +++ b/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h @@ -406,7 +406,7 @@ public: /// certain types of nodes together, or eliminating superfluous nodes. The /// Level argument controls whether Combine is allowed to produce nodes and /// types that are illegal on the target. - void Combine(CombineLevel Level, AliasAnalysis &AA, + void Combine(CombineLevel Level, AliasAnalysis *AA, CodeGenOpt::Level OptLevel); /// This transforms the SelectionDAG into a SelectionDAG that @@ -737,11 +737,15 @@ public: /// \brief Create a logical NOT operation as (XOR Val, BooleanOne). SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT); - /// Return a new CALLSEQ_START node, which always must have a glue result - /// (to ensure it's not CSE'd). CALLSEQ_START does not have a useful SDLoc. - SDValue getCALLSEQ_START(SDValue Chain, SDValue Op, const SDLoc &DL) { + /// Return a new CALLSEQ_START node, that starts new call frame, in which + /// InSize bytes are set up inside CALLSEQ_START..CALLSEQ_END sequence and + /// OutSize specifies part of the frame set up prior to the sequence. + SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, + const SDLoc &DL) { SDVTList VTs = getVTList(MVT::Other, MVT::Glue); - SDValue Ops[] = { Chain, Op }; + SDValue Ops[] = { Chain, + getIntPtrConstant(InSize, DL, true), + getIntPtrConstant(OutSize, DL, true) }; return getNode(ISD::CALLSEQ_START, DL, VTs, Ops); } diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h index e9012db7602d..f3122f0bf7f0 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/CVTypeVisitor.h @@ -26,6 +26,7 @@ public: void addTypeServerHandler(TypeServerHandler &Handler); + Error visitTypeRecord(CVType &Record, TypeIndex Index); Error visitTypeRecord(CVType &Record); Error visitMemberRecord(CVMemberRecord &Record); @@ -37,6 +38,9 @@ public: Error visitFieldListMemberStream(BinaryStreamReader Reader); private: + Expected<bool> handleTypeServer(CVType &Record); + Error finishVisitation(CVType &Record); + /// The interface to the class that gets notified of each visitation. TypeVisitorCallbacks &Callbacks; diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/RandomAccessTypeVisitor.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/RandomAccessTypeVisitor.h new file mode 100644 index 000000000000..35a8010f1163 --- /dev/null +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/RandomAccessTypeVisitor.h @@ -0,0 +1,103 @@ +//===- RandomAccessTypeVisitor.h ------------------------------ *- C++ --*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_DEBUGINFO_CODEVIEW_RANDOMACCESSTYPEVISITOR_H +#define LLVM_DEBUGINFO_CODEVIEW_RANDOMACCESSTYPEVISITOR_H + +#include "llvm/ADT/TinyPtrVector.h" +#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" +#include "llvm/DebugInfo/CodeView/TypeDatabase.h" +#include "llvm/DebugInfo/CodeView/TypeDatabaseVisitor.h" +#include "llvm/DebugInfo/CodeView/TypeDeserializer.h" +#include "llvm/DebugInfo/CodeView/TypeIndex.h" +#include "llvm/DebugInfo/CodeView/TypeRecord.h" +#include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h" +#include "llvm/Support/Error.h" + +namespace llvm { +namespace codeview { + +class TypeDatabase; +class TypeServerHandler; +class TypeVisitorCallbacks; + +/// \brief Provides amortized O(1) random access to a CodeView type stream. +/// Normally to access a type from a type stream, you must know its byte +/// offset into the type stream, because type records are variable-lengthed. +/// However, this is not the way we prefer to access them. For example, given +/// a symbol record one of the fields may be the TypeIndex of the symbol's +/// type record. Or given a type record such as an array type, there might +/// be a TypeIndex for the element type. Sequential access is perfect when +/// we're just dumping every entry, but it's very poor for real world usage. +/// +/// Type streams in PDBs contain an additional field which is a list of pairs +/// containing indices and their corresponding offsets, roughly every ~8KB of +/// record data. This general idea need not be confined to PDBs though. By +/// supplying such an array, the producer of a type stream can allow the +/// consumer much better access time, because the consumer can find the nearest +/// index in this array, and do a linear scan forward only from there. +/// +/// RandomAccessTypeVisitor implements this algorithm, but additionally goes one +/// step further by caching offsets of every record that has been visited at +/// least once. This way, even repeated visits of the same record will never +/// require more than one linear scan. For a type stream of N elements divided +/// into M chunks of roughly equal size, this yields a worst case lookup time +/// of O(N/M) and an amortized time of O(1). +class RandomAccessTypeVisitor { + typedef FixedStreamArray<TypeIndexOffset> PartialOffsetArray; + +public: + RandomAccessTypeVisitor(const CVTypeArray &Types, uint32_t NumRecords, + PartialOffsetArray PartialOffsets); + + Error visitTypeIndex(TypeIndex Index, TypeVisitorCallbacks &Callbacks); + + const TypeDatabase &database() const { return Database; } + +private: + Error visitRangeForType(TypeIndex TI); + Error visitRange(TypeIndex Begin, uint32_t BeginOffset, TypeIndex End); + + /// Visited records get automatically added to the type database. + TypeDatabase Database; + + /// The type array to allow random access visitation of. + const CVTypeArray &Types; + + /// The database visitor which adds new records to the database. + TypeDatabaseVisitor DatabaseVisitor; + + /// The deserializer which deserializes new records. + TypeDeserializer Deserializer; + + /// The visitation callback pipeline to use. By default this contains a + /// deserializer and a type database visitor. But the callback specified + /// in the constructor is also added. + TypeVisitorCallbackPipeline Pipeline; + + /// The visitor used to visit the internal pipeline for deserialization and + /// database maintenance. + CVTypeVisitor InternalVisitor; + + /// A vector mapping type indices to type offset. For every record that has + /// been visited, contains the absolute offset of that record in the record + /// array. + std::vector<uint32_t> KnownOffsets; + + /// An array of index offsets for the given type stream, allowing log(N) + /// lookups of a type record by index. Similar to KnownOffsets but only + /// contains offsets for some type indices, some of which may not have + /// ever been visited. + PartialOffsetArray PartialOffsets; +}; + +} // end namespace codeview +} // end namespace llvm + +#endif // LLVM_DEBUGINFO_CODEVIEW_RANDOMACCESSTYPEVISITOR_H diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h index be7b19e7df0c..92c15ebd8b2b 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h @@ -10,6 +10,7 @@ #ifndef LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASE_H #define LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASE_H +#include "llvm/ADT/BitVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" @@ -20,14 +21,16 @@ namespace llvm { namespace codeview { class TypeDatabase { + friend class RandomAccessTypeVisitor; + public: - explicit TypeDatabase(uint32_t ExpectedSize); + explicit TypeDatabase(uint32_t Capacity); - /// Gets the type index for the next type record. - TypeIndex getNextTypeIndex() const; + /// Records the name of a type, and reserves its type index. + TypeIndex appendType(StringRef Name, const CVType &Data); /// Records the name of a type, and reserves its type index. - void recordType(StringRef Name, const CVType &Data); + void recordType(StringRef Name, TypeIndex Index, const CVType &Data); /// Saves the name in a StringSet and creates a stable StringRef. StringRef saveTypeName(StringRef TypeName); @@ -37,13 +40,21 @@ public: const CVType &getTypeRecord(TypeIndex Index) const; CVType &getTypeRecord(TypeIndex Index); - bool containsTypeIndex(TypeIndex Index) const; + bool contains(TypeIndex Index) const; uint32_t size() const; + uint32_t capacity() const; + bool empty() const; + + TypeIndex getAppendIndex() const; private: + void grow(); + BumpPtrAllocator Allocator; + uint32_t Count = 0; + /// All user defined type records in .debug$T live in here. Type indices /// greater than 0x1000 are user defined. Subtract 0x1000 from the index to /// index into this vector. @@ -51,6 +62,8 @@ private: SmallVector<CVType, 10> TypeRecords; StringSaver TypeNameStorage; + + BitVector ValidRecords; }; } } diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabaseVisitor.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabaseVisitor.h index 39d234cf9814..c064e19a7e90 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabaseVisitor.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDatabaseVisitor.h @@ -10,6 +10,8 @@ #ifndef LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASEVISITOR_H #define LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASEVISITOR_H +#include "llvm/ADT/PointerUnion.h" + #include "llvm/DebugInfo/CodeView/TypeDatabase.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" #include "llvm/DebugInfo/CodeView/TypeRecord.h" @@ -21,11 +23,12 @@ namespace codeview { /// Dumper for CodeView type streams found in COFF object files and PDB files. class TypeDatabaseVisitor : public TypeVisitorCallbacks { public: - explicit TypeDatabaseVisitor(TypeDatabase &TypeDB) : TypeDB(TypeDB) {} + explicit TypeDatabaseVisitor(TypeDatabase &TypeDB) : TypeDB(&TypeDB) {} /// Paired begin/end actions for all types. Receives all record data, /// including the fixed-length record prefix. Error visitTypeBegin(CVType &Record) override; + Error visitTypeBegin(CVType &Record, TypeIndex Index) override; Error visitTypeEnd(CVType &Record) override; Error visitMemberBegin(CVMemberRecord &Record) override; Error visitMemberEnd(CVMemberRecord &Record) override; @@ -39,12 +42,18 @@ public: #include "TypeRecords.def" private: + StringRef getTypeName(TypeIndex Index) const; + StringRef saveTypeName(StringRef Name); + bool IsInFieldList = false; /// Name of the current type. Only valid before visitTypeEnd. StringRef Name; + /// Current type index. Only valid before visitTypeEnd, and if we are + /// visiting a random access type database. + Optional<TypeIndex> CurrentTypeIndex; - TypeDatabase &TypeDB; + TypeDatabase *TypeDB; }; } // end namespace codeview diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h index 0e3443789170..2142d4a2dec7 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDeserializer.h @@ -46,6 +46,10 @@ public: return Mapping->Mapping.visitTypeBegin(Record); } + Error visitTypeBegin(CVType &Record, TypeIndex Index) override { + return visitTypeBegin(Record); + } + Error visitTypeEnd(CVType &Record) override { assert(Mapping && "Not in a type mapping!"); auto EC = Mapping->Mapping.visitTypeEnd(Record); diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h index 00bb09137e48..6f10afb30d60 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeDumpVisitor.h @@ -45,6 +45,7 @@ public: /// Paired begin/end actions for all types. Receives all record data, /// including the fixed-length record prefix. Error visitTypeBegin(CVType &Record) override; + Error visitTypeBegin(CVType &Record, TypeIndex Index) override; Error visitTypeEnd(CVType &Record) override; Error visitMemberBegin(CVMemberRecord &Record) override; Error visitMemberEnd(CVMemberRecord &Record) override; diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h index 3c11d248fa72..b5d695fc49d5 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeIndex.h @@ -106,6 +106,15 @@ public: bool isNoneType() const { return *this == None(); } + uint32_t toArrayIndex() const { + assert(!isSimple()); + return getIndex() - FirstNonSimpleIndex; + } + + static TypeIndex fromArrayIndex(uint32_t Index) { + return TypeIndex(Index + FirstNonSimpleIndex); + } + SimpleTypeKind getSimpleKind() const { assert(isSimple()); return static_cast<SimpleTypeKind>(Index & SimpleKindMask); @@ -159,6 +168,39 @@ public: static TypeIndex Float32() { return TypeIndex(SimpleTypeKind::Float32); } static TypeIndex Float64() { return TypeIndex(SimpleTypeKind::Float64); } + TypeIndex &operator+=(unsigned N) { + Index += N; + return *this; + } + + TypeIndex &operator++() { + Index += 1; + return *this; + } + + TypeIndex operator++(int) { + TypeIndex Copy = *this; + operator++(); + return Copy; + } + + TypeIndex &operator-=(unsigned N) { + assert(Index >= N); + Index -= N; + return *this; + } + + TypeIndex &operator--() { + Index -= 1; + return *this; + } + + TypeIndex operator--(int) { + TypeIndex Copy = *this; + operator--(); + return Copy; + } + friend inline bool operator==(const TypeIndex &A, const TypeIndex &B) { return A.getIndex() == B.getIndex(); } @@ -183,10 +225,30 @@ public: return A.getIndex() >= B.getIndex(); } + friend inline TypeIndex operator+(const TypeIndex &A, uint32_t N) { + TypeIndex Result(A); + Result += N; + return Result; + } + + friend inline TypeIndex operator-(const TypeIndex &A, uint32_t N) { + assert(A.getIndex() >= N); + TypeIndex Result(A); + Result -= N; + return Result; + } + private: support::ulittle32_t Index; }; +// Used for pseudo-indexing an array of type records. An array of such records +// sorted by TypeIndex can allow log(N) lookups even though such a type record +// stream does not provide random access. +struct TypeIndexOffset { + TypeIndex Type; + support::ulittle32_t Offset; +}; } } diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h index f25129691041..ed48df33249f 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h @@ -47,6 +47,14 @@ public: return Error::success(); } + Error visitTypeBegin(CVType &Record, TypeIndex Index) override { + for (auto Visitor : Pipeline) { + if (auto EC = Visitor->visitTypeBegin(Record, Index)) + return EC; + } + return Error::success(); + } + Error visitTypeEnd(CVType &Record) override { for (auto Visitor : Pipeline) { if (auto EC = Visitor->visitTypeEnd(Record)) diff --git a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h index 5e27df346b00..2950c7d27cb6 100644 --- a/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h +++ b/contrib/llvm/include/llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h @@ -26,8 +26,15 @@ public: virtual Error visitUnknownType(CVType &Record) { return Error::success(); } /// Paired begin/end actions for all types. Receives all record data, /// including the fixed-length record prefix. visitTypeBegin() should return - /// the type of the Record, or an error if it cannot be determined. + /// the type of the Record, or an error if it cannot be determined. Exactly + /// one of the two visitTypeBegin methods will be called, depending on whether + /// records are being visited sequentially or randomly. An implementation + /// should be prepared to handle both (or assert if it can't handle random + /// access visitation). virtual Error visitTypeBegin(CVType &Record) { return Error::success(); } + virtual Error visitTypeBegin(CVType &Record, TypeIndex Index) { + return Error::success(); + } virtual Error visitTypeEnd(CVType &Record) { return Error::success(); } virtual Error visitUnknownMember(CVMemberRecord &Record) { diff --git a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h index 3fae8b441439..ca82a68ead31 100644 --- a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h +++ b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h @@ -43,13 +43,6 @@ namespace llvm { class MemoryBuffer; class raw_ostream; -// In place of applying the relocations to the data we've read from disk we use -// a separate mapping table to the side and checking that at locations in the -// dwarf where we expect relocated values. This adds a bit of complexity to the -// dwarf parsing/extraction at the benefit of not allocating memory for the -// entire size of the debug info sections. -typedef DenseMap<uint64_t, std::pair<uint8_t, int64_t>> RelocAddrMap; - /// Reads a value from data extractor and applies a relocation to the result if /// one exists for the given offset. uint64_t getRelocatedValue(const DataExtractor &Data, uint32_t Size, diff --git a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h index e21245b97b73..39a7ef71de97 100644 --- a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h +++ b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugLine.h @@ -30,7 +30,7 @@ public: struct FileNameEntry { FileNameEntry() = default; - StringRef Name = StringRef(); + StringRef Name; uint64_t DirIdx = 0; uint64_t ModTime = 0; uint64_t Length = 0; diff --git a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h index 9172df5bfac6..23a573b7a9fa 100644 --- a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h +++ b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugRangeList.h @@ -22,8 +22,13 @@ namespace llvm { class raw_ostream; +struct DWARFAddressRange { + uint64_t LowPC; + uint64_t HighPC; +}; + /// DWARFAddressRangesVector - represents a set of absolute address ranges. -typedef std::vector<std::pair<uint64_t, uint64_t>> DWARFAddressRangesVector; +typedef std::vector<DWARFAddressRange> DWARFAddressRangesVector; class DWARFDebugRangeList { public: diff --git a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h index af01bddeed15..f1e03bb4c2e1 100644 --- a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h +++ b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFRelocMap.h @@ -16,7 +16,17 @@ namespace llvm { -typedef DenseMap<uint64_t, std::pair<uint8_t, int64_t>> RelocAddrMap; +struct RelocAddrEntry { + uint8_t Width; + int64_t Value; +}; + +// In place of applying the relocations to the data we've read from disk we use +// a separate mapping table to the side and checking that at locations in the +// dwarf where we expect relocated values. This adds a bit of complexity to the +// dwarf parsing/extraction at the benefit of not allocating memory for the +// entire size of the debug info sections. +typedef DenseMap<uint64_t, RelocAddrEntry> RelocAddrMap; } // end namespace llvm diff --git a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h index 8e12bcd2c8e2..b9f14be85926 100644 --- a/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h +++ b/contrib/llvm/include/llvm/DebugInfo/DWARF/DWARFVerifier.h @@ -40,7 +40,7 @@ class DWARFVerifier { /// /// @param Die The DWARF DIE that owns the attribute value /// @param AttrValue The DWARF attribute value to check - void verifyDebugInfoAttribute(DWARFDie &Die, DWARFAttribute &AttrValue); + void verifyDebugInfoAttribute(const DWARFDie &Die, DWARFAttribute &AttrValue); /// Verifies the attribute's DWARF form. /// @@ -51,7 +51,7 @@ class DWARFVerifier { /// /// @param Die The DWARF DIE that owns the attribute value /// @param AttrValue The DWARF attribute value to check - void verifyDebugInfoForm(DWARFDie &Die, DWARFAttribute &AttrValue); + void verifyDebugInfoForm(const DWARFDie &Die, DWARFAttribute &AttrValue); /// Verifies the all valid references that were found when iterating through /// all of the DIE attributes. @@ -60,7 +60,7 @@ class DWARFVerifier { /// offset matches. This helps to ensure if a DWARF link phase moved things /// around, that it doesn't create invalid references by failing to relocate /// CU relative and absolute references. - void veifyDebugInfoReferences(); + void verifyDebugInfoReferences(); /// Verify the the DW_AT_stmt_list encoding and value and ensure that no /// compile units that have the same DW_AT_stmt_list value. diff --git a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h index 979b8454dd5e..771272d6a47d 100644 --- a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h +++ b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/RawTypes.h @@ -73,13 +73,6 @@ struct SecMapEntry { support::ulittle32_t SecByteLength; // Byte count of the segment or group. }; -// Used for serialized hash table in TPI stream. -// In the reference, it is an array of TI and cbOff pair. -struct TypeIndexOffset { - codeview::TypeIndex Type; - support::ulittle32_t Offset; -}; - /// Some of the values are stored in bitfields. Since this needs to be portable /// across compilers and architectures (big / little endian in particular) we /// can't use the actual structures below, but must instead do the shifting diff --git a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h index 9fef9bee5e1a..4579cbf4227b 100644 --- a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h +++ b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStream.h @@ -47,7 +47,7 @@ public: uint32_t getHashKeySize() const; uint32_t getNumHashBuckets() const; FixedStreamArray<support::ulittle32_t> getHashValues() const; - FixedStreamArray<TypeIndexOffset> getTypeIndexOffsets() const; + FixedStreamArray<codeview::TypeIndexOffset> getTypeIndexOffsets() const; HashTable &getHashAdjusters(); codeview::CVTypeRange types(bool *HadError) const; @@ -62,7 +62,7 @@ private: std::unique_ptr<BinaryStream> HashStream; FixedStreamArray<support::ulittle32_t> HashValues; - FixedStreamArray<TypeIndexOffset> TypeIndexOffsets; + FixedStreamArray<codeview::TypeIndexOffset> TypeIndexOffsets; HashTable HashAdjusters; const TpiStreamHeader *Header; diff --git a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h index a29ed0b610d3..6c609c34665c 100644 --- a/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h +++ b/contrib/llvm/include/llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h @@ -75,7 +75,7 @@ private: Optional<PdbRaw_TpiVer> VerHeader; std::vector<ArrayRef<uint8_t>> TypeRecords; std::vector<uint32_t> TypeHashes; - std::vector<TypeIndexOffset> TypeIndexOffsets; + std::vector<codeview::TypeIndexOffset> TypeIndexOffsets; uint32_t HashStreamIndex = kInvalidStreamIndex; std::unique_ptr<BinaryByteStream> HashValueStream; diff --git a/contrib/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h b/contrib/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h index 7e7f7358938a..1bb911d09cfb 100644 --- a/contrib/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h +++ b/contrib/llvm/include/llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h @@ -172,6 +172,11 @@ private: return nullptr; } + void removeModulesFromBaseLayer(BaseLayerT &BaseLayer) { + for (auto &BLH : BaseLayerHandles) + BaseLayer.removeModuleSet(BLH); + } + std::unique_ptr<JITSymbolResolver> ExternalSymbolResolver; std::unique_ptr<ResourceOwner<RuntimeDyld::MemoryManager>> MemMgr; std::unique_ptr<IndirectStubsMgrT> StubsMgr; @@ -204,6 +209,11 @@ public: CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)), CloneStubsIntoPartitions(CloneStubsIntoPartitions) {} + ~CompileOnDemandLayer() { + while (!LogicalDylibs.empty()) + removeModuleSet(LogicalDylibs.begin()); + } + /// @brief Add a module to the compile-on-demand layer. template <typename ModuleSetT, typename MemoryManagerPtrT, typename SymbolResolverPtrT> @@ -239,6 +249,7 @@ public: /// This will remove all modules in the layers below that were derived from /// the module represented by H. void removeModuleSet(ModuleSetHandleT H) { + H->removeModulesFromBaseLayer(BaseLayer); LogicalDylibs.erase(H); } @@ -478,6 +489,8 @@ private: return 0; } + LD.BaseLayerHandles.push_back(PartH); + return CalledAddr; } diff --git a/contrib/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h b/contrib/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h index 02f59d6a831a..a19c30631c57 100644 --- a/contrib/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h +++ b/contrib/llvm/include/llvm/ExecutionEngine/Orc/OrcRemoteTargetClient.h @@ -144,16 +144,16 @@ public: void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { - UnfinalizedEHFrames.push_back( - std::make_pair(LoadAddr, static_cast<uint32_t>(Size))); + UnfinalizedEHFrames.push_back({LoadAddr, Size}); } - void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, - size_t Size) override { - auto Err = Client.deregisterEHFrames(LoadAddr, Size); - // FIXME: Add error poll. - assert(!Err && "Failed to register remote EH frames."); - (void)Err; + void deregisterEHFrames() override { + for (auto &Frame : RegisteredEHFrames) { + auto Err = Client.deregisterEHFrames(Frame.Addr, Frame.Size); + // FIXME: Add error poll. + assert(!Err && "Failed to register remote EH frames."); + (void)Err; + } } void notifyObjectLoaded(RuntimeDyld &Dyld, @@ -320,7 +320,7 @@ public: Unfinalized.clear(); for (auto &EHFrame : UnfinalizedEHFrames) { - if (auto Err = Client.registerEHFrames(EHFrame.first, EHFrame.second)) { + if (auto Err = Client.registerEHFrames(EHFrame.Addr, EHFrame.Size)) { // FIXME: Replace this once finalizeMemory can return an Error. handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { if (ErrMsg) { @@ -331,7 +331,8 @@ public: return false; } } - UnfinalizedEHFrames.clear(); + RegisteredEHFrames = std::move(UnfinalizedEHFrames); + UnfinalizedEHFrames = {}; return false; } @@ -387,7 +388,13 @@ public: ResourceIdMgr::ResourceId Id; std::vector<ObjectAllocs> Unmapped; std::vector<ObjectAllocs> Unfinalized; - std::vector<std::pair<uint64_t, uint32_t>> UnfinalizedEHFrames; + + struct EHFrame { + JITTargetAddress Addr; + uint64_t Size; + }; + std::vector<EHFrame> UnfinalizedEHFrames; + std::vector<EHFrame> RegisteredEHFrames; }; /// Remote indirect stubs manager. diff --git a/contrib/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h b/contrib/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h index babcc7f26aab..5b3426afe584 100644 --- a/contrib/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h +++ b/contrib/llvm/include/llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h @@ -120,6 +120,10 @@ private: buildInitialSymbolTable(PFC->Objects); } + ~ConcreteLinkedObjectSet() override { + MemMgr->deregisterEHFrames(); + } + void setHandle(ObjSetHandleT H) { PFC->Handle = H; } diff --git a/contrib/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h b/contrib/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h index 5638717790bb..74535fe948ff 100644 --- a/contrib/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h +++ b/contrib/llvm/include/llvm/ExecutionEngine/RTDyldMemoryManager.h @@ -69,13 +69,8 @@ public: /// Deregister EH frames in the current proces. static void deregisterEHFramesInProcess(uint8_t *Addr, size_t Size); - void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { - registerEHFramesInProcess(Addr, Size); - } - - void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { - deregisterEHFramesInProcess(Addr, Size); - } + void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override; + void deregisterEHFrames() override; /// This method returns the address of the specified function or variable in /// the current process. @@ -139,6 +134,13 @@ public: /// MCJIT or RuntimeDyld. Use getSymbolAddress instead. virtual void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true); + +private: + struct EHFrame { + uint8_t *Addr; + size_t Size; + }; + std::vector<EHFrame> EHFrames; }; // Create wrappers for C Binding types (see CBindingWrapping.h). diff --git a/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h b/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h index 13a5f9922c51..9470866dc0d6 100644 --- a/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h +++ b/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h @@ -150,8 +150,7 @@ public: /// be the case for local execution) these two values will be the same. virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) = 0; - virtual void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr, - size_t Size) = 0; + virtual void deregisterEHFrames() = 0; /// This method is called when object loading is complete and section page /// permissions can be applied. It is up to the memory manager implementation diff --git a/contrib/llvm/include/llvm/IR/Attributes.h b/contrib/llvm/include/llvm/IR/Attributes.h index cbe681684a5c..d4a896c01867 100644 --- a/contrib/llvm/include/llvm/IR/Attributes.h +++ b/contrib/llvm/include/llvm/IR/Attributes.h @@ -35,6 +35,7 @@ namespace llvm { class AttrBuilder; class AttributeImpl; class AttributeListImpl; +class AttributeList; class AttributeSetNode; template<typename T> struct DenseMapInfo; class Function; @@ -227,14 +228,51 @@ public: bool operator==(const AttributeSet &O) { return SetNode == O.SetNode; } bool operator!=(const AttributeSet &O) { return !(*this == O); } + /// Add an argument attribute. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet addAttribute(LLVMContext &C, + Attribute::AttrKind Kind) const; + + /// Add a target-dependent attribute. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet addAttribute(LLVMContext &C, StringRef Kind, + StringRef Value = StringRef()) const; + + /// Add attributes to the attribute set. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet addAttributes(LLVMContext &C, AttributeSet AS) const; + + /// Remove the specified attribute from this set. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet removeAttribute(LLVMContext &C, + Attribute::AttrKind Kind) const; + + /// Remove the specified attribute from this set. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet removeAttribute(LLVMContext &C, + StringRef Kind) const; + + /// Remove the specified attributes from this set. Because + /// attribute sets are immutable, this returns a new set. + AttributeSet removeAttributes(LLVMContext &C, + const AttrBuilder &AttrsToRemove) const; + + /// Return the number of attributes in this set. unsigned getNumAttributes() const; + /// Return true if attributes exists in this set. bool hasAttributes() const { return SetNode != nullptr; } + /// Return true if the attribute exists in this set. bool hasAttribute(Attribute::AttrKind Kind) const; + + /// Return true if the attribute exists in this set. bool hasAttribute(StringRef Kind) const; + /// Return the attribute object. Attribute getAttribute(Attribute::AttrKind Kind) const; + + /// Return the target-dependent attribute object. Attribute getAttribute(StringRef Kind) const; unsigned getAlignment() const; @@ -248,6 +286,9 @@ public: iterator begin() const; iterator end() const; +#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) + void dump() const; +#endif }; //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/include/llvm/IR/CallingConv.h b/contrib/llvm/include/llvm/IR/CallingConv.h index 39fb3f1c791b..801e88aba4d1 100644 --- a/contrib/llvm/include/llvm/IR/CallingConv.h +++ b/contrib/llvm/include/llvm/IR/CallingConv.h @@ -201,6 +201,10 @@ namespace CallingConv { /// shaders) AMDGPU_HS = 93, + /// Calling convention used for special MSP430 rtlib functions + /// which have an "optimized" convention using additional registers. + MSP430_BUILTIN = 94, + /// The highest possible calling convention ID. Must be some 2^k - 1. MaxID = 1023 }; diff --git a/contrib/llvm/include/llvm/IR/Constants.h b/contrib/llvm/include/llvm/IR/Constants.h index ad83b21c7bf3..5db9b3bb5048 100644 --- a/contrib/llvm/include/llvm/IR/Constants.h +++ b/contrib/llvm/include/llvm/IR/Constants.h @@ -26,6 +26,7 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/Constant.h" #include "llvm/IR/DerivedTypes.h" @@ -452,7 +453,14 @@ class ConstantStruct final : public ConstantAggregate { public: // ConstantStruct accessors static Constant *get(StructType *T, ArrayRef<Constant*> V); - static Constant *get(StructType *T, ...) LLVM_END_WITH_NULL; + + template <typename... Csts> + static typename std::enable_if<are_base_of<Constant, Csts...>::value, + Constant *>::type + get(StructType *T, Csts *... Vs) { + SmallVector<Constant *, 8> Values({Vs...}); + return get(T, Values); + } /// Return an anonymous struct that has the specified elements. /// If the struct is possibly empty, then you must specify a context. diff --git a/contrib/llvm/include/llvm/IR/DebugInfoMetadata.h b/contrib/llvm/include/llvm/IR/DebugInfoMetadata.h index 0331d5229e7f..358106aac43b 100644 --- a/contrib/llvm/include/llvm/IR/DebugInfoMetadata.h +++ b/contrib/llvm/include/llvm/IR/DebugInfoMetadata.h @@ -16,8 +16,11 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/BitmaskEnum.h" +#include "llvm/ADT/iterator_range.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/Metadata.h" #include "llvm/Support/Casting.h" @@ -56,10 +59,6 @@ namespace llvm { -class DIBuilder; - -template <typename T> class Optional; - /// Holds a subclass of DINode. /// /// FIXME: This class doesn't currently make much sense. Previously it was a @@ -94,9 +93,9 @@ public: bool operator!=(const TypedDINodeRef<T> &X) const { return MD != X.MD; } }; -typedef TypedDINodeRef<DINode> DINodeRef; -typedef TypedDINodeRef<DIScope> DIScopeRef; -typedef TypedDINodeRef<DIType> DITypeRef; +using DINodeRef = TypedDINodeRef<DINode>; +using DIScopeRef = TypedDINodeRef<DIScope>; +using DITypeRef = TypedDINodeRef<DIType>; class DITypeRefArray { const MDTuple *N = nullptr; @@ -240,7 +239,8 @@ public: }; template <class T> struct simplify_type<const TypedDINodeRef<T>> { - typedef Metadata *SimpleType; + using SimpleType = Metadata *; + static SimpleType getSimplifiedValue(const TypedDINodeRef<T> &MD) { return MD; } @@ -799,15 +799,18 @@ public: assert(getTag() == dwarf::DW_TAG_ptr_to_member_type); return DITypeRef(getExtraData()); } + DIObjCProperty *getObjCProperty() const { return dyn_cast_or_null<DIObjCProperty>(getExtraData()); } + Constant *getStorageOffsetInBits() const { assert(getTag() == dwarf::DW_TAG_member && isBitField()); if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) return C->getValue(); return nullptr; } + Constant *getConstant() const { assert(getTag() == dwarf::DW_TAG_member && isStaticMember()); if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData())) @@ -970,9 +973,11 @@ public: #endif replaceOperandWith(4, Elements.get()); } + void replaceVTableHolder(DITypeRef VTableHolder) { replaceOperandWith(5, VTableHolder); } + void replaceTemplateParams(DITemplateParameterArray TemplateParams) { replaceOperandWith(6, TemplateParams.get()); } @@ -1031,6 +1036,7 @@ public: DITypeRefArray getTypeArray() const { return cast_or_null<MDTuple>(getRawTypeArray()); } + Metadata *getRawTypeArray() const { return getOperand(3); } static bool classof(const Metadata *MD) { @@ -1319,6 +1325,7 @@ public: unsigned getLine() const { return SubclassData32; } unsigned getColumn() const { return SubclassData16; } DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); } + DILocation *getInlinedAt() const { return cast_or_null<DILocation>(getRawInlinedAt()); } @@ -1452,7 +1459,6 @@ public: static bool classof(const Metadata *MD) { return MD->getMetadataID() == DILocationKind; } - }; /// Subprogram description. @@ -2087,6 +2093,7 @@ public: return F->getFilename(); return ""; } + StringRef getDirectory() const { if (auto *F = getFile()) return F->getDirectory(); @@ -2143,6 +2150,7 @@ public: ArrayRef<uint64_t> getElements() const { return Elements; } unsigned getNumElements() const { return Elements.size(); } + uint64_t getElement(unsigned I) const { assert(I < Elements.size() && "Index out of range"); return Elements[I]; @@ -2151,7 +2159,8 @@ public: /// Determine whether this represents a standalone constant value. bool isConstant() const; - typedef ArrayRef<uint64_t>::iterator element_iterator; + using element_iterator = ArrayRef<uint64_t>::iterator; + element_iterator elements_begin() const { return getElements().begin(); } element_iterator elements_end() const { return getElements().end(); } @@ -2276,6 +2285,10 @@ public: /// Append \p Ops with operations to apply the \p Offset. static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset); + /// If this is a constant offset, extract it. If there is no expression, + /// return true with an offset of zero. + bool extractIfOffset(int64_t &Offset) const; + /// Constants for DIExpression::prepend. enum { NoDeref = false, WithDeref = true, WithStackValue = true }; @@ -2509,6 +2522,7 @@ public: return F->getFilename(); return ""; } + StringRef getDirectory() const { if (auto *F = getFile()) return F->getDirectory(); @@ -2609,10 +2623,13 @@ public: TempDIGlobalVariableExpression clone() const { return cloneImpl(); } Metadata *getRawVariable() const { return getOperand(0); } + DIGlobalVariable *getVariable() const { return cast_or_null<DIGlobalVariable>(getRawVariable()); } + Metadata *getRawExpression() const { return getOperand(1); } + DIExpression *getExpression() const { return cast_or_null<DIExpression>(getRawExpression()); } diff --git a/contrib/llvm/include/llvm/IR/DebugLoc.h b/contrib/llvm/include/llvm/IR/DebugLoc.h index 202be3da14da..aa74f361cda2 100644 --- a/contrib/llvm/include/llvm/IR/DebugLoc.h +++ b/contrib/llvm/include/llvm/IR/DebugLoc.h @@ -80,6 +80,22 @@ namespace llvm { static DebugLoc get(unsigned Line, unsigned Col, const MDNode *Scope, const MDNode *InlinedAt = nullptr); + enum { ReplaceLastInlinedAt = true }; + /// Rebuild the entire inlined-at chain for this instruction so that the top of + /// the chain now is inlined-at the new call site. + /// \param InlinedAt The new outermost inlined-at in the chain. + /// \param ReplaceLast Replace the last location in the inlined-at chain. + static DebugLoc appendInlinedAt(DebugLoc DL, DILocation *InlinedAt, + LLVMContext &Ctx, + DenseMap<const MDNode *, MDNode *> &Cache, + bool ReplaceLast = false); + + /// Reparent all debug locations referenced by \c I that belong to \c OrigSP + /// to become (possibly indirect) children of \c NewSP. + static void reparentDebugInfo(Instruction &I, DISubprogram *OrigSP, + DISubprogram *NewSP, + DenseMap<const MDNode *, MDNode *> &Cache); + unsigned getLine() const; unsigned getCol() const; MDNode *getScope() const; diff --git a/contrib/llvm/include/llvm/IR/DerivedTypes.h b/contrib/llvm/include/llvm/IR/DerivedTypes.h index 05e99157b8dc..a92321a44511 100644 --- a/contrib/llvm/include/llvm/IR/DerivedTypes.h +++ b/contrib/llvm/include/llvm/IR/DerivedTypes.h @@ -1,4 +1,4 @@ -//===-- llvm/DerivedTypes.h - Classes for handling data types ---*- C++ -*-===// +//===- llvm/DerivedTypes.h - Classes for handling data types ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -19,6 +19,7 @@ #define LLVM_IR_DERIVEDTYPES_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/Type.h" #include "llvm/Support/Casting.h" @@ -122,7 +123,8 @@ public: bool isVarArg() const { return getSubclassData()!=0; } Type *getReturnType() const { return ContainedTys[0]; } - typedef Type::subtype_iterator param_iterator; + using param_iterator = Type::subtype_iterator; + param_iterator param_begin() const { return ContainedTys + 1; } param_iterator param_end() const { return &ContainedTys[NumContainedTys]; } ArrayRef<Type *> params() const { @@ -197,8 +199,7 @@ public: /// generator for a target expects). /// class StructType : public CompositeType { - StructType(LLVMContext &C) - : CompositeType(C, StructTyID), SymbolTableEntry(nullptr) {} + StructType(LLVMContext &C) : CompositeType(C, StructTyID) {} enum { /// This is the contents of the SubClassData field. @@ -212,7 +213,7 @@ class StructType : public CompositeType { /// symbol table entry (maintained by LLVMContext) for the struct. /// This is null if the type is an literal struct or if it is a identified /// type that has an empty name. - void *SymbolTableEntry; + void *SymbolTableEntry = nullptr; public: StructType(const StructType &) = delete; @@ -228,7 +229,14 @@ public: static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements, StringRef Name, bool isPacked = false); static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements); - static StructType *create(StringRef Name, Type *elt1, ...) LLVM_END_WITH_NULL; + template <class... Tys> + static typename std::enable_if<are_base_of<Type, Tys...>::value, + StructType *>::type + create(StringRef Name, Type *elt1, Tys *... elts) { + assert(elt1 && "Cannot create a struct type with no elements with this"); + SmallVector<llvm::Type *, 8> StructFields({elt1, elts...}); + return create(StructFields, Name); + } /// This static method is the primary way to create a literal StructType. static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements, @@ -240,7 +248,15 @@ public: /// This static method is a convenience method for creating structure types by /// specifying the elements as arguments. Note that this method always returns /// a non-packed struct, and requires at least one element type. - static StructType *get(Type *elt1, ...) LLVM_END_WITH_NULL; + template <class... Tys> + static typename std::enable_if<are_base_of<Type, Tys...>::value, + StructType *>::type + get(Type *elt1, Tys *... elts) { + assert(elt1 && "Cannot create a struct type with no elements with this"); + LLVMContext &Ctx = elt1->getContext(); + SmallVector<llvm::Type *, 8> StructFields({elt1, elts...}); + return llvm::StructType::get(Ctx, StructFields); + } bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; } @@ -269,13 +285,21 @@ public: /// Specify a body for an opaque identified type. void setBody(ArrayRef<Type*> Elements, bool isPacked = false); - void setBody(Type *elt1, ...) LLVM_END_WITH_NULL; + + template <typename... Tys> + typename std::enable_if<are_base_of<Type, Tys...>::value, void>::type + setBody(Type *elt1, Tys *... elts) { + assert(elt1 && "Cannot create a struct type with no elements with this"); + SmallVector<llvm::Type *, 8> StructFields({elt1, elts...}); + setBody(StructFields); + } /// Return true if the specified type is valid as a element type. static bool isValidElementType(Type *ElemTy); // Iterator access to the elements. - typedef Type::subtype_iterator element_iterator; + using element_iterator = Type::subtype_iterator; + element_iterator element_begin() const { return ContainedTys; } element_iterator element_end() const { return &ContainedTys[NumContainedTys];} ArrayRef<Type *> const elements() const { diff --git a/contrib/llvm/include/llvm/IR/DiagnosticInfo.h b/contrib/llvm/include/llvm/IR/DiagnosticInfo.h index 458c3cf29b0d..5497652135bd 100644 --- a/contrib/llvm/include/llvm/IR/DiagnosticInfo.h +++ b/contrib/llvm/include/llvm/IR/DiagnosticInfo.h @@ -15,7 +15,6 @@ #ifndef LLVM_IR_DIAGNOSTICINFO_H #define LLVM_IR_DIAGNOSTICINFO_H -#include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" @@ -120,18 +119,18 @@ public: virtual void print(DiagnosticPrinter &DP) const = 0; }; -typedef std::function<void(const DiagnosticInfo &)> DiagnosticHandlerFunction; +using DiagnosticHandlerFunction = std::function<void(const DiagnosticInfo &)>; /// Diagnostic information for inline asm reporting. /// This is basically a message and an optional location. class DiagnosticInfoInlineAsm : public DiagnosticInfo { private: /// Optional line information. 0 if not set. - unsigned LocCookie; + unsigned LocCookie = 0; /// Message to be reported. const Twine &MsgStr; /// Optional origin of the problem. - const Instruction *Instr; + const Instruction *Instr = nullptr; public: /// \p MsgStr is the message to be reported to the frontend. @@ -139,8 +138,7 @@ public: /// for the whole life time of the Diagnostic. DiagnosticInfoInlineAsm(const Twine &MsgStr, DiagnosticSeverity Severity = DS_Error) - : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr), - Instr(nullptr) {} + : DiagnosticInfo(DK_InlineAsm, Severity), MsgStr(MsgStr) {} /// \p LocCookie if non-zero gives the line number for this report. /// \p MsgStr gives the message. @@ -149,7 +147,7 @@ public: DiagnosticInfoInlineAsm(unsigned LocCookie, const Twine &MsgStr, DiagnosticSeverity Severity = DS_Error) : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(LocCookie), - MsgStr(MsgStr), Instr(nullptr) {} + MsgStr(MsgStr) {} /// \p Instr gives the original instruction that triggered the diagnostic. /// \p MsgStr gives the message. @@ -294,10 +292,10 @@ public: DiagnosticInfoSampleProfile(StringRef FileName, const Twine &Msg, DiagnosticSeverity Severity = DS_Error) : DiagnosticInfo(DK_SampleProfile, Severity), FileName(FileName), - LineNum(0), Msg(Msg) {} + Msg(Msg) {} DiagnosticInfoSampleProfile(const Twine &Msg, DiagnosticSeverity Severity = DS_Error) - : DiagnosticInfo(DK_SampleProfile, Severity), LineNum(0), Msg(Msg) {} + : DiagnosticInfo(DK_SampleProfile, Severity), Msg(Msg) {} /// \see DiagnosticInfo::print. void print(DiagnosticPrinter &DP) const override; @@ -316,7 +314,7 @@ private: /// Line number where the diagnostic occurred. If 0, no line number will /// be emitted in the message. - unsigned LineNum; + unsigned LineNum = 0; /// Message to report. const Twine &Msg; @@ -351,8 +349,9 @@ class DiagnosticLocation { StringRef Filename; unsigned Line = 0; unsigned Column = 0; + public: - DiagnosticLocation() {} + DiagnosticLocation() = default; DiagnosticLocation(const DebugLoc &DL); DiagnosticLocation(const DISubprogram *SP); @@ -796,6 +795,7 @@ private: const Twine &Msg) : OptimizationRemarkAnalysis(DK_OptimizationRemarkAnalysisFPCommute, PassName, Fn, Loc, Msg) {} + friend void emitOptimizationRemarkAnalysisFPCommute( LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg); @@ -1012,6 +1012,7 @@ public: void print(DiagnosticPrinter &DP) const override; }; + } // end namespace llvm #endif // LLVM_IR_DIAGNOSTICINFO_H diff --git a/contrib/llvm/include/llvm/IR/Function.h b/contrib/llvm/include/llvm/IR/Function.h index c12a125b6352..8a2a6ed87eb2 100644 --- a/contrib/llvm/include/llvm/IR/Function.h +++ b/contrib/llvm/include/llvm/IR/Function.h @@ -1,4 +1,4 @@ -//===-- llvm/Function.h - Class to represent a single function --*- C++ -*-===// +//===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -22,15 +22,19 @@ #include "llvm/ADT/ilist_node.h" #include "llvm/ADT/iterator_range.h" #include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" #include "llvm/IR/Argument.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallingConv.h" +#include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalObject.h" +#include "llvm/IR/GlobalValue.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/OperandTraits.h" #include "llvm/IR/SymbolTableListTraits.h" #include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include <cassert> #include <cstddef> @@ -40,27 +44,31 @@ namespace llvm { -template <typename T> class Optional; class AssemblyAnnotationWriter; -class FunctionType; -class LLVMContext; +class Constant; class DISubprogram; +class LLVMContext; +class Module; +template <typename T> class Optional; +class raw_ostream; +class Type; +class User; class Function : public GlobalObject, public ilist_node<Function> { public: - typedef SymbolTableList<BasicBlock> BasicBlockListType; + using BasicBlockListType = SymbolTableList<BasicBlock>; // BasicBlock iterators... - typedef BasicBlockListType::iterator iterator; - typedef BasicBlockListType::const_iterator const_iterator; + using iterator = BasicBlockListType::iterator; + using const_iterator = BasicBlockListType::const_iterator; - typedef Argument *arg_iterator; - typedef const Argument *const_arg_iterator; + using arg_iterator = Argument *; + using const_arg_iterator = const Argument *; private: // Important things that make up a function! - BasicBlockListType BasicBlocks; ///< The basic blocks - mutable Argument *Arguments; ///< The formal arguments + BasicBlockListType BasicBlocks; ///< The basic blocks + mutable Argument *Arguments = nullptr; ///< The formal arguments size_t NumArgs; std::unique_ptr<ValueSymbolTable> SymTab; ///< Symbol table of args/instructions @@ -124,10 +132,12 @@ public: // Provide fast operand accessors. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); + /// Returns the FunctionType for me. FunctionType *getFunctionType() const { return cast<FunctionType>(getValueType()); } + /// Returns the type of the ret val. Type *getReturnType() const { return getFunctionType()->getReturnType(); } @@ -484,7 +494,7 @@ public: /// copyAttributesFrom - copy all additional attributes (those not needed to /// create a Function) from the Function Src to this one. - void copyAttributesFrom(const GlobalValue *Src) override; + void copyAttributesFrom(const Function *Src); /// deleteBody - This method deletes the body of the function, and converts /// the linkage to external. @@ -497,12 +507,12 @@ public: /// removeFromParent - This method unlinks 'this' from the containing module, /// but does not delete it. /// - void removeFromParent() override; + void removeFromParent(); /// eraseFromParent - This method unlinks 'this' from the containing module /// and deletes it. /// - void eraseFromParent() override; + void eraseFromParent(); /// Steal arguments from another function. /// diff --git a/contrib/llvm/include/llvm/IR/GetElementPtrTypeIterator.h b/contrib/llvm/include/llvm/IR/GetElementPtrTypeIterator.h index 490bff29cf38..f017a449d33f 100644 --- a/contrib/llvm/include/llvm/IR/GetElementPtrTypeIterator.h +++ b/contrib/llvm/include/llvm/IR/GetElementPtrTypeIterator.h @@ -21,7 +21,9 @@ #include "llvm/IR/Operator.h" #include "llvm/IR/User.h" #include "llvm/Support/Casting.h" +#include <cassert> #include <cstddef> +#include <cstdint> #include <iterator> namespace llvm { @@ -29,13 +31,13 @@ namespace llvm { template<typename ItTy = User::const_op_iterator> class generic_gep_type_iterator : public std::iterator<std::forward_iterator_tag, Type *, ptrdiff_t> { - typedef std::iterator<std::forward_iterator_tag, - Type *, ptrdiff_t> super; + using super = std::iterator<std::forward_iterator_tag, Type *, ptrdiff_t>; ItTy OpIt; PointerUnion<StructType *, Type *> CurTy; enum : uint64_t { Unbounded = -1ull }; uint64_t NumElements = Unbounded; + generic_gep_type_iterator() = default; public: @@ -121,7 +123,7 @@ namespace llvm { } }; - typedef generic_gep_type_iterator<> gep_type_iterator; + using gep_type_iterator = generic_gep_type_iterator<>; inline gep_type_iterator gep_type_begin(const User *GEP) { auto *GEPOp = cast<GEPOperator>(GEP); diff --git a/contrib/llvm/include/llvm/IR/GlobalAlias.h b/contrib/llvm/include/llvm/IR/GlobalAlias.h index 37a291dfeb7a..d4bf0d7e1ed4 100644 --- a/contrib/llvm/include/llvm/IR/GlobalAlias.h +++ b/contrib/llvm/include/llvm/IR/GlobalAlias.h @@ -59,15 +59,19 @@ public: // Linkage, Type, Parent and AddressSpace taken from the Aliasee. static GlobalAlias *create(const Twine &Name, GlobalValue *Aliasee); + void copyAttributesFrom(const GlobalValue *Src) { + GlobalValue::copyAttributesFrom(Src); + } + /// removeFromParent - This method unlinks 'this' from the containing module, /// but does not delete it. /// - void removeFromParent() override; + void removeFromParent(); /// eraseFromParent - This method unlinks 'this' from the containing module /// and deletes it. /// - void eraseFromParent() override; + void eraseFromParent(); /// These methods retrieve and set alias target. void setAliasee(Constant *Aliasee); diff --git a/contrib/llvm/include/llvm/IR/GlobalIFunc.h b/contrib/llvm/include/llvm/IR/GlobalIFunc.h index bfaa9960cb13..d90c7c78ed26 100644 --- a/contrib/llvm/include/llvm/IR/GlobalIFunc.h +++ b/contrib/llvm/include/llvm/IR/GlobalIFunc.h @@ -47,12 +47,16 @@ public: LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent); + void copyAttributesFrom(const GlobalIFunc *Src) { + GlobalValue::copyAttributesFrom(Src); + } + /// This method unlinks 'this' from the containing module, but does not /// delete it. - void removeFromParent() final; + void removeFromParent(); /// This method unlinks 'this' from the containing module and deletes it. - void eraseFromParent() final; + void eraseFromParent(); /// These methods retrieve and set ifunc resolver function. void setResolver(Constant *Resolver) { diff --git a/contrib/llvm/include/llvm/IR/GlobalObject.h b/contrib/llvm/include/llvm/IR/GlobalObject.h index f3789bafefe3..fc38f698027b 100644 --- a/contrib/llvm/include/llvm/IR/GlobalObject.h +++ b/contrib/llvm/include/llvm/IR/GlobalObject.h @@ -150,8 +150,10 @@ public: void addTypeMetadata(unsigned Offset, Metadata *TypeID); - void copyAttributesFrom(const GlobalValue *Src) override; +protected: + void copyAttributesFrom(const GlobalObject *Src); +public: // Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const Value *V) { return V->getValueID() == Value::FunctionVal || diff --git a/contrib/llvm/include/llvm/IR/GlobalValue.h b/contrib/llvm/include/llvm/IR/GlobalValue.h index bb30fa8be867..0793a1c0ee2e 100644 --- a/contrib/llvm/include/llvm/IR/GlobalValue.h +++ b/contrib/llvm/include/llvm/IR/GlobalValue.h @@ -435,14 +435,20 @@ public: bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); } +protected: /// Copy all additional attributes (those not needed to create a GlobalValue) /// from the GlobalValue Src to this one. - virtual void copyAttributesFrom(const GlobalValue *Src); + void copyAttributesFrom(const GlobalValue *Src); - /// If special LLVM prefix that is used to inform the asm printer to not emit - /// usual symbol prefix before the symbol name is used then return linkage - /// name after skipping this special LLVM prefix. - static StringRef getRealLinkageName(StringRef Name) { +public: + /// If the given string begins with the GlobalValue name mangling escape + /// character '\1', drop it. + /// + /// This function applies a specific mangling that is used in PGO profiles, + /// among other things. If you're trying to get a symbol name for an + /// arbitrary GlobalValue, this is not the function you're looking for; see + /// Mangler.h. + static StringRef dropLLVMManglingEscape(StringRef Name) { if (!Name.empty() && Name[0] == '\1') return Name.substr(1); return Name; @@ -530,10 +536,10 @@ public: /// This method unlinks 'this' from the containing module, but does not delete /// it. - virtual void removeFromParent() = 0; + void removeFromParent(); /// This method unlinks 'this' from the containing module and deletes it. - virtual void eraseFromParent() = 0; + void eraseFromParent(); /// Get the module that this global value is contained inside of... Module *getParent() { return Parent; } diff --git a/contrib/llvm/include/llvm/IR/GlobalVariable.h b/contrib/llvm/include/llvm/IR/GlobalVariable.h index 3b545d811d44..21d334c8f01d 100644 --- a/contrib/llvm/include/llvm/IR/GlobalVariable.h +++ b/contrib/llvm/include/llvm/IR/GlobalVariable.h @@ -24,6 +24,7 @@ #include "llvm/ADT/Twine.h" #include "llvm/ADT/ilist_node.h" #include "llvm/IR/GlobalObject.h" +#include "llvm/IR/Attributes.h" #include "llvm/IR/OperandTraits.h" #include "llvm/IR/Value.h" #include <cassert> @@ -41,6 +42,7 @@ class DIGlobalVariableExpression; class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> { friend class SymbolTableListTraits<GlobalVariable>; + AttributeSet Attrs; bool isConstantGlobal : 1; // Is this a global constant? bool isExternallyInitializedConstant : 1; // Is this a global whose value // can change from its initial @@ -156,17 +158,17 @@ public: /// copyAttributesFrom - copy all additional attributes (those not needed to /// create a GlobalVariable) from the GlobalVariable Src to this one. - void copyAttributesFrom(const GlobalValue *Src) override; + void copyAttributesFrom(const GlobalVariable *Src); /// removeFromParent - This method unlinks 'this' from the containing module, /// but does not delete it. /// - void removeFromParent() override; + void removeFromParent(); /// eraseFromParent - This method unlinks 'this' from the containing module /// and deletes it. /// - void eraseFromParent() override; + void eraseFromParent(); /// Drop all references in preparation to destroy the GlobalVariable. This /// drops not only the reference to the initializer but also to any metadata. @@ -178,6 +180,61 @@ public: /// Fill the vector with all debug info attachements. void getDebugInfo(SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const; + /// Add attribute to this global. + void addAttribute(Attribute::AttrKind Kind) { + Attrs = Attrs.addAttribute(getContext(), Kind); + } + + /// Add attribute to this global. + void addAttribute(StringRef Kind, StringRef Val = StringRef()) { + Attrs = Attrs.addAttribute(getContext(), Kind, Val); + } + + /// Return true if the attribute exists. + bool hasAttribute(Attribute::AttrKind Kind) const { + return Attrs.hasAttribute(Kind); + } + + /// Return true if the attribute exists. + bool hasAttribute(StringRef Kind) const { + return Attrs.hasAttribute(Kind); + } + + /// Return true if any attributes exist. + bool hasAttributes() const { + return Attrs.hasAttributes(); + } + + /// Return the attribute object. + Attribute getAttribute(Attribute::AttrKind Kind) const { + return Attrs.getAttribute(Kind); + } + + /// Return the attribute object. + Attribute getAttribute(StringRef Kind) const { + return Attrs.getAttribute(Kind); + } + + /// Return the attribute set for this global + AttributeSet getAttributes() const { + return Attrs; + } + + /// Return attribute set as list with index. + /// FIXME: This may not be required once ValueEnumerators + /// in bitcode-writer can enumerate attribute-set. + AttributeList getAttributesAsList(unsigned index) const { + if (!hasAttributes()) + return AttributeList(); + std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}}; + return AttributeList::get(getContext(), AS); + } + + /// Set attribute list for this global + void setAttributes(AttributeSet A) { + Attrs = A; + } + // Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const Value *V) { return V->getValueID() == Value::GlobalVariableVal; diff --git a/contrib/llvm/include/llvm/IR/IRBuilder.h b/contrib/llvm/include/llvm/IR/IRBuilder.h index bc689f3b01d7..9d4c13c29f68 100644 --- a/contrib/llvm/include/llvm/IR/IRBuilder.h +++ b/contrib/llvm/include/llvm/IR/IRBuilder.h @@ -454,6 +454,45 @@ public: MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr); + /// \brief Create a vector fadd reduction intrinsic of the source vector. + /// The first parameter is a scalar accumulator value for ordered reductions. + CallInst *CreateFAddReduce(Value *Acc, Value *Src); + + /// \brief Create a vector fmul reduction intrinsic of the source vector. + /// The first parameter is a scalar accumulator value for ordered reductions. + CallInst *CreateFMulReduce(Value *Acc, Value *Src); + + /// \brief Create a vector int add reduction intrinsic of the source vector. + CallInst *CreateAddReduce(Value *Src); + + /// \brief Create a vector int mul reduction intrinsic of the source vector. + CallInst *CreateMulReduce(Value *Src); + + /// \brief Create a vector int AND reduction intrinsic of the source vector. + CallInst *CreateAndReduce(Value *Src); + + /// \brief Create a vector int OR reduction intrinsic of the source vector. + CallInst *CreateOrReduce(Value *Src); + + /// \brief Create a vector int XOR reduction intrinsic of the source vector. + CallInst *CreateXorReduce(Value *Src); + + /// \brief Create a vector integer max reduction intrinsic of the source + /// vector. + CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false); + + /// \brief Create a vector integer min reduction intrinsic of the source + /// vector. + CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false); + + /// \brief Create a vector float max reduction intrinsic of the source + /// vector. + CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false); + + /// \brief Create a vector float min reduction intrinsic of the source + /// vector. + CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false); + /// \brief Create a lifetime.start intrinsic. /// /// If the pointer isn't i8* it will be converted. diff --git a/contrib/llvm/include/llvm/IR/InstrTypes.h b/contrib/llvm/include/llvm/IR/InstrTypes.h index d16a5d318d78..61ca90de7393 100644 --- a/contrib/llvm/include/llvm/IR/InstrTypes.h +++ b/contrib/llvm/include/llvm/IR/InstrTypes.h @@ -65,27 +65,15 @@ protected: // Out of line virtual method, so the vtable, etc has a home. ~TerminatorInst() override; - /// Virtual methods - Terminators should overload these and provide inline - /// overrides of non-V methods. - virtual BasicBlock *getSuccessorV(unsigned idx) const = 0; - virtual unsigned getNumSuccessorsV() const = 0; - virtual void setSuccessorV(unsigned idx, BasicBlock *B) = 0; - public: /// Return the number of successors that this terminator has. - unsigned getNumSuccessors() const { - return getNumSuccessorsV(); - } + unsigned getNumSuccessors() const; /// Return the specified successor. - BasicBlock *getSuccessor(unsigned idx) const { - return getSuccessorV(idx); - } + BasicBlock *getSuccessor(unsigned idx) const; /// Update the specified successor to point at the provided block. - void setSuccessor(unsigned idx, BasicBlock *B) { - setSuccessorV(idx, B); - } + void setSuccessor(unsigned idx, BasicBlock *B); // Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const Instruction *I) { diff --git a/contrib/llvm/include/llvm/IR/Instruction.h b/contrib/llvm/include/llvm/IR/Instruction.h index 90c3175122fd..fca29900f4c2 100644 --- a/contrib/llvm/include/llvm/IR/Instruction.h +++ b/contrib/llvm/include/llvm/IR/Instruction.h @@ -456,6 +456,12 @@ public: /// higher. bool isAtomic() const; + /// Return true if this atomic instruction loads from memory. + bool hasAtomicLoad() const; + + /// Return true if this atomic instruction stores to memory. + bool hasAtomicStore() const; + /// Return true if this instruction may throw an exception. bool mayThrow() const; diff --git a/contrib/llvm/include/llvm/IR/Instructions.h b/contrib/llvm/include/llvm/IR/Instructions.h index 844a7273eca9..c26701af27ce 100644 --- a/contrib/llvm/include/llvm/IR/Instructions.h +++ b/contrib/llvm/include/llvm/IR/Instructions.h @@ -1,4 +1,4 @@ -//===-- llvm/Instructions.h - Instruction subclass definitions --*- C++ -*-===// +//===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -17,6 +17,7 @@ #define LLVM_IR_INSTRUCTIONS_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/ADT/None.h" #include "llvm/ADT/SmallVector.h" @@ -24,21 +25,25 @@ #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/Attributes.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constant.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/OperandTraits.h" #include "llvm/IR/Type.h" #include "llvm/IR/Use.h" #include "llvm/IR/User.h" +#include "llvm/IR/Value.h" #include "llvm/Support/AtomicOrdering.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> #include <cstddef> #include <cstdint> +#include <iterator> namespace llvm { @@ -264,6 +269,7 @@ public: } bool isSimple() const { return !isAtomic() && !isVolatile(); } + bool isUnordered() const { return (getOrdering() == AtomicOrdering::NotAtomic || getOrdering() == AtomicOrdering::Unordered) && @@ -386,6 +392,7 @@ public: } bool isSimple() const { return !isAtomic() && !isVolatile(); } + bool isUnordered() const { return (getOrdering() == AtomicOrdering::NotAtomic || getOrdering() == AtomicOrdering::Unordered) && @@ -836,10 +843,7 @@ class GetElementPtrInst : public Instruction { Type *SourceElementType; Type *ResultElementType; - void anchor() override; - GetElementPtrInst(const GetElementPtrInst &GEPI); - void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); /// Constructors - Create a getelementptr instruction with a base pointer an /// list of indices. The first ctor can optionally insert before an existing @@ -852,6 +856,9 @@ class GetElementPtrInst : public Instruction { ArrayRef<Value *> IdxList, unsigned Values, const Twine &NameStr, BasicBlock *InsertAtEnd); + void anchor() override; + void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); + protected: // Note: Instruction needs to be a friend here to call cloneImpl. friend class Instruction; @@ -2261,6 +2268,19 @@ public: return Mask; } + /// Change values in a shuffle permute mask assuming the two vector operands + /// of length InVecNumElts have swapped position. + static void commuteShuffleMask(MutableArrayRef<int> Mask, + unsigned InVecNumElts) { + for (int &Idx : Mask) { + if (Idx == -1) + continue; + Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; + assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 && + "shufflevector mask index out of range"); + } + } + // Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const Instruction *I) { return I->getOpcode() == Instruction::ShuffleVector; @@ -2288,6 +2308,7 @@ class ExtractValueInst : public UnaryInstruction { SmallVector<unsigned, 4> Indices; ExtractValueInst(const ExtractValueInst &EVI); + /// Constructors - Create a extractvalue instruction with a base aggregate /// value and a list of indices. The first ctor can optionally insert before /// an existing instruction, the second appends the new instruction to the @@ -2333,7 +2354,8 @@ public: /// Null is returned if the indices are invalid for the specified type. static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); - typedef const unsigned* idx_iterator; + using idx_iterator = const unsigned*; + inline idx_iterator idx_begin() const { return Indices.begin(); } inline idx_iterator idx_end() const { return Indices.end(); } inline iterator_range<idx_iterator> indices() const { @@ -2455,7 +2477,8 @@ public: /// Transparently provide more efficient getOperand methods. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); - typedef const unsigned* idx_iterator; + using idx_iterator = const unsigned*; + inline idx_iterator idx_begin() const { return Indices.begin(); } inline idx_iterator idx_end() const { return Indices.end(); } inline iterator_range<idx_iterator> indices() const { @@ -2606,8 +2629,8 @@ public: // Block iterator interface. This provides access to the list of incoming // basic blocks, which parallels the list of incoming values. - typedef BasicBlock **block_iterator; - typedef BasicBlock * const *const_block_iterator; + using block_iterator = BasicBlock **; + using const_block_iterator = BasicBlock * const *; block_iterator block_begin() { Use::UserRef *ref = @@ -2656,9 +2679,11 @@ public: "All operands to PHI node must be the same type as the PHI node!"); setOperand(i, V); } + static unsigned getOperandNumForIncomingValue(unsigned i) { return i; } + static unsigned getIncomingValueNumForOperand(unsigned i) { return i; } @@ -2937,9 +2962,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; template <> @@ -3047,9 +3074,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; template <> @@ -3123,7 +3152,7 @@ public: protected: // Expose the switch type we're parameterized with to the iterator. - typedef SwitchInstT SwitchInstType; + using SwitchInstType = SwitchInstT; SwitchInstT *SI; ptrdiff_t Index; @@ -3164,8 +3193,8 @@ public: } }; - typedef CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock> - ConstCaseHandle; + using ConstCaseHandle = + CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; class CaseHandle : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { @@ -3192,7 +3221,7 @@ public: : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, std::random_access_iterator_tag, CaseHandleT> { - typedef typename CaseHandleT::SwitchInstType SwitchInstT; + using SwitchInstT = typename CaseHandleT::SwitchInstType; CaseHandleT Case; @@ -3254,8 +3283,8 @@ public: const CaseHandleT &operator*() const { return Case; } }; - typedef CaseIteratorImpl<CaseHandle> CaseIt; - typedef CaseIteratorImpl<ConstCaseHandle> ConstCaseIt; + using CaseIt = CaseIteratorImpl<CaseHandle>; + using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; static SwitchInst *Create(Value *Value, BasicBlock *Default, unsigned NumCases, @@ -3411,9 +3440,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; template <> @@ -3516,9 +3547,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; template <> @@ -3639,6 +3672,7 @@ public: return new (Values) InvokeInst(Func, IfNormal, IfException, Args, None, Values, NameStr, InsertAtEnd); } + static InvokeInst *Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles, @@ -3996,9 +4030,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const { if (Attrs.hasAttribute(AttributeList::FunctionIndex, Kind)) @@ -4095,9 +4131,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; template <> @@ -4202,13 +4240,14 @@ private: } public: - typedef std::pointer_to_unary_function<Value *, BasicBlock *> DerefFnTy; - typedef mapped_iterator<op_iterator, DerefFnTy> handler_iterator; - typedef iterator_range<handler_iterator> handler_range; - typedef std::pointer_to_unary_function<const Value *, const BasicBlock *> - ConstDerefFnTy; - typedef mapped_iterator<const_op_iterator, ConstDerefFnTy> const_handler_iterator; - typedef iterator_range<const_handler_iterator> const_handler_range; + using DerefFnTy = std::pointer_to_unary_function<Value *, BasicBlock *>; + using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; + using handler_range = iterator_range<handler_iterator>; + using ConstDerefFnTy = + std::pointer_to_unary_function<const Value *, const BasicBlock *>; + using const_handler_iterator = + mapped_iterator<const_op_iterator, ConstDerefFnTy>; + using const_handler_range = iterator_range<const_handler_iterator>; /// Returns an iterator that points to the first handler in CatchSwitchInst. handler_iterator handler_begin() { @@ -4278,9 +4317,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned Idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned Idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned Idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned Idx, BasicBlock *B); }; template <> @@ -4443,9 +4484,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned Idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned Idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned Idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned Idx, BasicBlock *B); }; template <> @@ -4531,9 +4574,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned Idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned Idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned Idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned Idx, BasicBlock *B); // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. @@ -4586,9 +4631,11 @@ public: } private: - BasicBlock *getSuccessorV(unsigned idx) const override; - unsigned getNumSuccessorsV() const override; - void setSuccessorV(unsigned idx, BasicBlock *B) override; + friend TerminatorInst; + + BasicBlock *getSuccessorV(unsigned idx) const; + unsigned getNumSuccessorsV() const; + void setSuccessorV(unsigned idx, BasicBlock *B); }; //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/include/llvm/IR/Intrinsics.td b/contrib/llvm/include/llvm/IR/Intrinsics.td index 7b78d4d3d34a..19f6045568f4 100644 --- a/contrib/llvm/include/llvm/IR/Intrinsics.td +++ b/contrib/llvm/include/llvm/IR/Intrinsics.td @@ -812,6 +812,50 @@ def int_memcpy_element_atomic : Intrinsic<[], [IntrArgMemOnly, NoCapture<0>, NoCapture<1>, WriteOnly<0>, ReadOnly<1>]>; +//===------------------------ Reduction Intrinsics ------------------------===// +// +def int_experimental_vector_reduce_fadd : Intrinsic<[llvm_anyfloat_ty], + [llvm_anyfloat_ty, + llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_fmul : Intrinsic<[llvm_anyfloat_ty], + [llvm_anyfloat_ty, + llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_add : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_mul : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_and : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_or : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_xor : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_smax : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_smin : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_umax : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_umin : Intrinsic<[llvm_anyint_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_fmax : Intrinsic<[llvm_anyfloat_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; +def int_experimental_vector_reduce_fmin : Intrinsic<[llvm_anyfloat_ty], + [llvm_anyvector_ty], + [IntrNoMem]>; + //===----- Intrinsics that are used to provide predicate information -----===// def int_ssa_copy : Intrinsic<[llvm_any_ty], [LLVMMatchType<0>], diff --git a/contrib/llvm/include/llvm/IR/LLVMContext.h b/contrib/llvm/include/llvm/IR/LLVMContext.h index d13d5ddaeb3c..ad011fb72e6a 100644 --- a/contrib/llvm/include/llvm/IR/LLVMContext.h +++ b/contrib/llvm/include/llvm/IR/LLVMContext.h @@ -1,4 +1,4 @@ -//===-- llvm/LLVMContext.h - Class for managing "global" state --*- C++ -*-===// +//===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -37,7 +37,9 @@ class StringRef; class Twine; namespace yaml { + class Output; + } // end namespace yaml /// This is an important class for using LLVM in a threaded context. It @@ -134,17 +136,17 @@ public: void enableDebugTypeODRUniquing(); void disableDebugTypeODRUniquing(); - typedef void (*InlineAsmDiagHandlerTy)(const SMDiagnostic&, void *Context, - unsigned LocCookie); + using InlineAsmDiagHandlerTy = void (*)(const SMDiagnostic&, void *Context, + unsigned LocCookie); /// Defines the type of a diagnostic handler. /// \see LLVMContext::setDiagnosticHandler. /// \see LLVMContext::diagnose. - typedef void (*DiagnosticHandlerTy)(const DiagnosticInfo &DI, void *Context); + using DiagnosticHandlerTy = void (*)(const DiagnosticInfo &DI, void *Context); /// Defines the type of a yield callback. /// \see LLVMContext::setYieldCallback. - typedef void (*YieldCallbackTy)(LLVMContext *Context, void *OpaqueHandle); + using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle); /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked /// when problems with inline asm are detected by the backend. The first diff --git a/contrib/llvm/include/llvm/IR/LegacyPassManager.h b/contrib/llvm/include/llvm/IR/LegacyPassManager.h index 5257a0eed488..9a376a151505 100644 --- a/contrib/llvm/include/llvm/IR/LegacyPassManager.h +++ b/contrib/llvm/include/llvm/IR/LegacyPassManager.h @@ -98,6 +98,9 @@ private: // Create wrappers for C Binding types (see CBindingWrapping.h). DEFINE_STDCXX_CONVERSION_FUNCTIONS(legacy::PassManagerBase, LLVMPassManagerRef) +/// If -time-passes has been specified, report the timings immediately and then +/// reset the timers to zero. +void reportAndResetTimings(); } // End llvm namespace #endif diff --git a/contrib/llvm/include/llvm/IR/Module.h b/contrib/llvm/include/llvm/IR/Module.h index 67c35cd22b34..3024d9e27a2f 100644 --- a/contrib/llvm/include/llvm/IR/Module.h +++ b/contrib/llvm/include/llvm/IR/Module.h @@ -1,4 +1,4 @@ -//===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===// +//===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -16,6 +16,10 @@ #define LLVM_IR_MODULE_H #include "llvm/ADT/iterator_range.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/IR/Attributes.h" #include "llvm/IR/Comdat.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" @@ -23,20 +27,27 @@ #include "llvm/IR/GlobalIFunc.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Metadata.h" +#include "llvm/IR/SymbolTableListTraits.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/CodeGen.h" -#include "llvm/Support/DataTypes.h" +#include "llvm-c/Types.h" +#include <cstddef> +#include <cstdint> +#include <iterator> +#include <memory> +#include <string> +#include <vector> namespace llvm { -template <typename T> class Optional; + class Error; class FunctionType; class GVMaterializer; class LLVMContext; class MemoryBuffer; class RandomNumberGenerator; -class StructType; template <class PtrType> class SmallPtrSetImpl; +class StructType; /// A Module instance is used to store all the information related to an /// LLVM module. Modules are the top level container of all other LLVM @@ -54,47 +65,47 @@ class Module { /// @{ public: /// The type for the list of global variables. - typedef SymbolTableList<GlobalVariable> GlobalListType; + using GlobalListType = SymbolTableList<GlobalVariable>; /// The type for the list of functions. - typedef SymbolTableList<Function> FunctionListType; + using FunctionListType = SymbolTableList<Function>; /// The type for the list of aliases. - typedef SymbolTableList<GlobalAlias> AliasListType; + using AliasListType = SymbolTableList<GlobalAlias>; /// The type for the list of ifuncs. - typedef SymbolTableList<GlobalIFunc> IFuncListType; + using IFuncListType = SymbolTableList<GlobalIFunc>; /// The type for the list of named metadata. - typedef ilist<NamedMDNode> NamedMDListType; + using NamedMDListType = ilist<NamedMDNode>; /// The type of the comdat "symbol" table. - typedef StringMap<Comdat> ComdatSymTabType; + using ComdatSymTabType = StringMap<Comdat>; /// The Global Variable iterator. - typedef GlobalListType::iterator global_iterator; + using global_iterator = GlobalListType::iterator; /// The Global Variable constant iterator. - typedef GlobalListType::const_iterator const_global_iterator; + using const_global_iterator = GlobalListType::const_iterator; /// The Function iterators. - typedef FunctionListType::iterator iterator; + using iterator = FunctionListType::iterator; /// The Function constant iterator - typedef FunctionListType::const_iterator const_iterator; + using const_iterator = FunctionListType::const_iterator; /// The Function reverse iterator. - typedef FunctionListType::reverse_iterator reverse_iterator; + using reverse_iterator = FunctionListType::reverse_iterator; /// The Function constant reverse iterator. - typedef FunctionListType::const_reverse_iterator const_reverse_iterator; + using const_reverse_iterator = FunctionListType::const_reverse_iterator; /// The Global Alias iterators. - typedef AliasListType::iterator alias_iterator; + using alias_iterator = AliasListType::iterator; /// The Global Alias constant iterator - typedef AliasListType::const_iterator const_alias_iterator; + using const_alias_iterator = AliasListType::const_iterator; /// The Global IFunc iterators. - typedef IFuncListType::iterator ifunc_iterator; + using ifunc_iterator = IFuncListType::iterator; /// The Global IFunc constant iterator - typedef IFuncListType::const_iterator const_ifunc_iterator; + using const_ifunc_iterator = IFuncListType::const_iterator; /// The named metadata iterators. - typedef NamedMDListType::iterator named_metadata_iterator; + using named_metadata_iterator = NamedMDListType::iterator; /// The named metadata constant iterators. - typedef NamedMDListType::const_iterator const_named_metadata_iterator; + using const_named_metadata_iterator = NamedMDListType::const_iterator; /// This enumeration defines the supported behaviors of module flags. enum ModFlagBehavior { @@ -141,6 +152,7 @@ public: ModFlagBehavior Behavior; MDString *Key; Metadata *Val; + ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V) : Behavior(B), Key(K), Val(V) {} }; @@ -483,9 +495,11 @@ public: const GlobalListType &getGlobalList() const { return GlobalList; } /// Get the Module's list of global variables. GlobalListType &getGlobalList() { return GlobalList; } + static GlobalListType Module::*getSublistAccess(GlobalVariable*) { return &Module::GlobalList; } + /// Get the Module's list of functions (constant). const FunctionListType &getFunctionList() const { return FunctionList; } /// Get the Module's list of functions. @@ -493,31 +507,39 @@ public: static FunctionListType Module::*getSublistAccess(Function*) { return &Module::FunctionList; } + /// Get the Module's list of aliases (constant). const AliasListType &getAliasList() const { return AliasList; } /// Get the Module's list of aliases. AliasListType &getAliasList() { return AliasList; } + static AliasListType Module::*getSublistAccess(GlobalAlias*) { return &Module::AliasList; } + /// Get the Module's list of ifuncs (constant). const IFuncListType &getIFuncList() const { return IFuncList; } /// Get the Module's list of ifuncs. IFuncListType &getIFuncList() { return IFuncList; } + static IFuncListType Module::*getSublistAccess(GlobalIFunc*) { return &Module::IFuncList; } + /// Get the Module's list of named metadata (constant). const NamedMDListType &getNamedMDList() const { return NamedMDList; } /// Get the Module's list of named metadata. NamedMDListType &getNamedMDList() { return NamedMDList; } + static NamedMDListType Module::*getSublistAccess(NamedMDNode*) { return &Module::NamedMDList; } + /// Get the symbol table of global variable and function identifiers const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; } /// Get the Module's symbol table of global variable and function identifiers. ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; } + /// Get the Module's symbol table for COMDATs (constant). const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; } /// Get the Module's symbol table for COMDATs. @@ -602,11 +624,11 @@ public: /// @name Convenience iterators /// @{ - typedef concat_iterator<GlobalObject, iterator, global_iterator> - global_object_iterator; - typedef concat_iterator<const GlobalObject, const_iterator, - const_global_iterator> - const_global_object_iterator; + using global_object_iterator = + concat_iterator<GlobalObject, iterator, global_iterator>; + using const_global_object_iterator = + concat_iterator<const GlobalObject, const_iterator, + const_global_iterator>; iterator_range<global_object_iterator> global_objects() { return concat<GlobalObject>(functions(), globals()); @@ -627,13 +649,12 @@ public: return global_objects().end(); } - typedef concat_iterator<GlobalValue, iterator, global_iterator, - alias_iterator, ifunc_iterator> - global_value_iterator; - typedef concat_iterator<const GlobalValue, const_iterator, - const_global_iterator, const_alias_iterator, - const_ifunc_iterator> - const_global_value_iterator; + using global_value_iterator = + concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator, + ifunc_iterator>; + using const_global_value_iterator = + concat_iterator<const GlobalValue, const_iterator, const_global_iterator, + const_alias_iterator, const_ifunc_iterator>; iterator_range<global_value_iterator> global_values() { return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); @@ -682,28 +703,35 @@ public: : public std::iterator<std::input_iterator_tag, DICompileUnit *> { NamedMDNode *CUs; unsigned Idx; + void SkipNoDebugCUs(); + public: explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx) : CUs(CUs), Idx(Idx) { SkipNoDebugCUs(); } + debug_compile_units_iterator &operator++() { ++Idx; SkipNoDebugCUs(); return *this; } + debug_compile_units_iterator operator++(int) { debug_compile_units_iterator T(*this); ++Idx; return T; } + bool operator==(const debug_compile_units_iterator &I) const { return Idx == I.Idx; } + bool operator!=(const debug_compile_units_iterator &I) const { return Idx != I.Idx; } + DICompileUnit *operator*() const; DICompileUnit *operator->() const; }; @@ -833,6 +861,6 @@ inline Module *unwrap(LLVMModuleProviderRef MP) { return reinterpret_cast<Module*>(MP); } -} // End llvm namespace +} // end namespace llvm -#endif +#endif // LLVM_IR_MODULE_H diff --git a/contrib/llvm/include/llvm/IR/ModuleSummaryIndex.h b/contrib/llvm/include/llvm/IR/ModuleSummaryIndex.h index 53570bdf16f4..c46c609609e2 100644 --- a/contrib/llvm/include/llvm/IR/ModuleSummaryIndex.h +++ b/contrib/llvm/include/llvm/IR/ModuleSummaryIndex.h @@ -1,4 +1,4 @@ -//===-- llvm/ModuleSummaryIndex.h - Module Summary Index --------*- C++ -*-===// +//===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -16,21 +16,33 @@ #ifndef LLVM_IR_MODULESUMMARYINDEX_H #define LLVM_IR_MODULESUMMARYINDEX_H +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/DenseSet.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" #include "llvm/IR/Module.h" - +#include "llvm/IR/GlobalValue.h" +#include <algorithm> #include <array> +#include <cassert> +#include <cstddef> +#include <cstdint> +#include <map> +#include <memory> +#include <string> +#include <utility> +#include <vector> namespace llvm { namespace yaml { + template <typename T> struct MappingTraits; -} + +} // end namespace yaml /// \brief Class to accumulate and hold information about a callee. struct CalleeInfo { @@ -47,7 +59,7 @@ struct CalleeInfo { class GlobalValueSummary; -typedef std::vector<std::unique_ptr<GlobalValueSummary>> GlobalValueSummaryList; +using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>; struct GlobalValueSummaryInfo { /// The GlobalValue corresponding to this summary. This is only used in @@ -66,19 +78,22 @@ struct GlobalValueSummaryInfo { /// likely incur less overhead, as the value type is not very small and the size /// of the map is unknown, resulting in inefficiencies due to repeated /// insertions and resizing. -typedef std::map<GlobalValue::GUID, GlobalValueSummaryInfo> - GlobalValueSummaryMapTy; +using GlobalValueSummaryMapTy = + std::map<GlobalValue::GUID, GlobalValueSummaryInfo>; /// Struct that holds a reference to a particular GUID in a global value /// summary. struct ValueInfo { const GlobalValueSummaryMapTy::value_type *Ref = nullptr; + ValueInfo() = default; ValueInfo(const GlobalValueSummaryMapTy::value_type *Ref) : Ref(Ref) {} + operator bool() const { return Ref; } GlobalValue::GUID getGUID() const { return Ref->first; } const GlobalValue *getValue() const { return Ref->second.GV; } + ArrayRef<std::unique_ptr<GlobalValueSummary>> getSummaryList() const { return Ref->second.SummaryList; } @@ -88,9 +103,11 @@ template <> struct DenseMapInfo<ValueInfo> { static inline ValueInfo getEmptyKey() { return ValueInfo((GlobalValueSummaryMapTy::value_type *)-1); } + static inline ValueInfo getTombstoneKey() { return ValueInfo((GlobalValueSummaryMapTy::value_type *)-2); } + static bool isEqual(ValueInfo L, ValueInfo R) { return L.Ref == R.Ref; } static unsigned getHashValue(ValueInfo I) { return (uintptr_t)I.Ref; } }; @@ -138,7 +155,7 @@ private: /// This is the hash of the name of the symbol in the original file. It is /// identical to the GUID for global symbols, but differs for local since the /// GUID includes the module level id in the hash. - GlobalValue::GUID OriginalName; + GlobalValue::GUID OriginalName = 0; /// \brief Path of module IR containing value's definition, used to locate /// module during importing. @@ -157,7 +174,7 @@ private: protected: GlobalValueSummary(SummaryKind K, GVFlags Flags, std::vector<ValueInfo> Refs) - : Kind(K), Flags(Flags), OriginalName(0), RefEdgeList(std::move(Refs)) {} + : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {} public: virtual ~GlobalValueSummary() = default; @@ -242,7 +259,7 @@ public: class FunctionSummary : public GlobalValueSummary { public: /// <CalleeValueInfo, CalleeInfo> call edge pair. - typedef std::pair<ValueInfo, CalleeInfo> EdgeTy; + using EdgeTy = std::pair<ValueInfo, CalleeInfo>; /// An "identifier" for a virtual function. This contains the type identifier /// represented as a GUID and the offset from the address point to the virtual @@ -376,12 +393,15 @@ public: template <> struct DenseMapInfo<FunctionSummary::VFuncId> { static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; } + static FunctionSummary::VFuncId getTombstoneKey() { return {0, uint64_t(-2)}; } + static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) { return L.GUID == R.GUID && L.Offset == R.Offset; } + static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; } }; @@ -389,14 +409,17 @@ template <> struct DenseMapInfo<FunctionSummary::ConstVCall> { static FunctionSummary::ConstVCall getEmptyKey() { return {{0, uint64_t(-1)}, {}}; } + static FunctionSummary::ConstVCall getTombstoneKey() { return {{0, uint64_t(-2)}, {}}; } + static bool isEqual(FunctionSummary::ConstVCall L, FunctionSummary::ConstVCall R) { return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) && L.Args == R.Args; } + static unsigned getHashValue(FunctionSummary::ConstVCall I) { return I.VFunc.GUID; } @@ -477,20 +500,20 @@ struct TypeIdSummary { }; /// 160 bits SHA1 -typedef std::array<uint32_t, 5> ModuleHash; +using ModuleHash = std::array<uint32_t, 5>; /// Type used for iterating through the global value summary map. -typedef GlobalValueSummaryMapTy::const_iterator const_gvsummary_iterator; -typedef GlobalValueSummaryMapTy::iterator gvsummary_iterator; +using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator; +using gvsummary_iterator = GlobalValueSummaryMapTy::iterator; /// String table to hold/own module path strings, which additionally holds the /// module ID assigned to each module during the plugin step, as well as a hash /// of the module. The StringMap makes a copy of and owns inserted strings. -typedef StringMap<std::pair<uint64_t, ModuleHash>> ModulePathStringTableTy; +using ModulePathStringTableTy = StringMap<std::pair<uint64_t, ModuleHash>>; /// Map of global value GUID to its summary, used to identify values defined in /// a particular module, and provide efficient access to their summary. -typedef std::map<GlobalValue::GUID, GlobalValueSummary *> GVSummaryMapTy; +using GVSummaryMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>; /// Class to hold module path string table and global value map, /// and encapsulate methods for operating on them. @@ -697,6 +720,6 @@ public: StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const; }; -} // End llvm namespace +} // end namespace llvm -#endif +#endif // LLVM_IR_MODULESUMMARYINDEX_H diff --git a/contrib/llvm/include/llvm/IR/PassManager.h b/contrib/llvm/include/llvm/IR/PassManager.h index c845112baa45..d03b7b65f81e 100644 --- a/contrib/llvm/include/llvm/IR/PassManager.h +++ b/contrib/llvm/include/llvm/IR/PassManager.h @@ -39,8 +39,8 @@ #define LLVM_IR_PASSMANAGER_H #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" @@ -48,9 +48,15 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/TypeName.h" #include "llvm/Support/raw_ostream.h" -#include "llvm/Support/type_traits.h" +#include <algorithm> +#include <cassert> +#include <cstring> +#include <iterator> #include <list> #include <memory> +#include <tuple> +#include <type_traits> +#include <utility> #include <vector> namespace llvm { @@ -469,15 +475,16 @@ public: } template <typename PassT> void addPass(PassT Pass) { - typedef detail::PassModel<IRUnitT, PassT, PreservedAnalyses, - AnalysisManagerT, ExtraArgTs...> - PassModelT; + using PassModelT = + detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT, + ExtraArgTs...>; + Passes.emplace_back(new PassModelT(std::move(Pass))); } private: - typedef detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...> - PassConceptT; + using PassConceptT = + detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>; std::vector<std::unique_ptr<PassConceptT>> Passes; @@ -486,12 +493,14 @@ private: }; extern template class PassManager<Module>; + /// \brief Convenience typedef for a pass manager over modules. -typedef PassManager<Module> ModulePassManager; +using ModulePassManager = PassManager<Module>; extern template class PassManager<Function>; + /// \brief Convenience typedef for a pass manager over functions. -typedef PassManager<Function> FunctionPassManager; +using FunctionPassManager = PassManager<Function>; /// \brief A container for analyses that lazily runs them and caches their /// results. @@ -504,11 +513,11 @@ public: private: // Now that we've defined our invalidator, we can define the concept types. - typedef detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator> - ResultConceptT; - typedef detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator, - ExtraArgTs...> - PassConceptT; + using ResultConceptT = + detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>; + using PassConceptT = + detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator, + ExtraArgTs...>; /// \brief List of analysis pass IDs and associated concept pointers. /// @@ -516,18 +525,18 @@ private: /// erases. Provides the analysis ID to enable finding iterators to a given /// entry in maps below, and provides the storage for the actual result /// concept. - typedef std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>> - AnalysisResultListT; + using AnalysisResultListT = + std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>; /// \brief Map type from IRUnitT pointer to our custom list type. - typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT; + using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>; /// \brief Map type from a pair of analysis ID and IRUnitT pointer to an /// iterator into a particular result list (which is where the actual analysis /// result is stored). - typedef DenseMap<std::pair<AnalysisKey *, IRUnitT *>, - typename AnalysisResultListT::iterator> - AnalysisResultMapT; + using AnalysisResultMapT = + DenseMap<std::pair<AnalysisKey *, IRUnitT *>, + typename AnalysisResultListT::iterator>; public: /// API to communicate dependencies between analyses during invalidation. @@ -558,10 +567,10 @@ public: /// dependecies on it will become invalid as a result. template <typename PassT> bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) { - typedef detail::AnalysisResultModel<IRUnitT, PassT, - typename PassT::Result, - PreservedAnalyses, Invalidator> - ResultModelT; + using ResultModelT = + detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, + PreservedAnalyses, Invalidator>; + return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA); } @@ -672,9 +681,11 @@ public: "This analysis pass was not registered prior to being queried"); ResultConceptT &ResultConcept = getResultImpl(PassT::ID(), IR, ExtraArgs...); - typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, - PreservedAnalyses, Invalidator> - ResultModelT; + + using ResultModelT = + detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, + PreservedAnalyses, Invalidator>; + return static_cast<ResultModelT &>(ResultConcept).Result; } @@ -692,9 +703,10 @@ public: if (!ResultConcept) return nullptr; - typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, - PreservedAnalyses, Invalidator> - ResultModelT; + using ResultModelT = + detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, + PreservedAnalyses, Invalidator>; + return &static_cast<ResultModelT *>(ResultConcept)->Result; } @@ -717,10 +729,10 @@ public: /// hashtable.) template <typename PassBuilderT> bool registerPass(PassBuilderT &&PassBuilder) { - typedef decltype(PassBuilder()) PassT; - typedef detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses, - Invalidator, ExtraArgTs...> - PassModelT; + using PassT = decltype(PassBuilder()); + using PassModelT = + detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses, + Invalidator, ExtraArgTs...>; auto &PassPtr = AnalysisPasses[PassT::ID()]; if (PassPtr) @@ -876,7 +888,8 @@ private: } /// \brief Map type from module analysis pass ID to pass concept pointer. - typedef DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>> AnalysisPassMapT; + using AnalysisPassMapT = + DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>; /// \brief Collection of module analysis passes, indexed by ID. AnalysisPassMapT AnalysisPasses; @@ -896,12 +909,14 @@ private: }; extern template class AnalysisManager<Module>; + /// \brief Convenience typedef for the Module analysis manager. -typedef AnalysisManager<Module> ModuleAnalysisManager; +using ModuleAnalysisManager = AnalysisManager<Module>; extern template class AnalysisManager<Function>; + /// \brief Convenience typedef for the Function analysis manager. -typedef AnalysisManager<Function> FunctionAnalysisManager; +using FunctionAnalysisManager = AnalysisManager<Function>; /// \brief An analysis over an "outer" IR unit that provides access to an /// analysis manager over an "inner" IR unit. The inner unit must be contained @@ -927,20 +942,14 @@ public: class Result { public: explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {} + Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) { // We have to null out the analysis manager in the moved-from state // because we are taking ownership of the responsibilty to clear the // analysis state. Arg.InnerAM = nullptr; } - Result &operator=(Result &&RHS) { - InnerAM = RHS.InnerAM; - // We have to null out the analysis manager in the moved-from state - // because we are taking ownership of the responsibilty to clear the - // analysis state. - RHS.InnerAM = nullptr; - return *this; - } + ~Result() { // InnerAM is cleared in a moved from state where there is nothing to do. if (!InnerAM) @@ -951,6 +960,15 @@ public: InnerAM->clear(); } + Result &operator=(Result &&RHS) { + InnerAM = RHS.InnerAM; + // We have to null out the analysis manager in the moved-from state + // because we are taking ownership of the responsibilty to clear the + // analysis state. + RHS.InnerAM = nullptr; + return *this; + } + /// \brief Accessor for the analysis manager. AnalysisManagerT &getManager() { return *InnerAM; } @@ -988,6 +1006,7 @@ public: private: friend AnalysisInfoMixin< InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>; + static AnalysisKey Key; AnalysisManagerT *InnerAM; @@ -998,8 +1017,8 @@ AnalysisKey InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key; /// Provide the \c FunctionAnalysisManager to \c Module proxy. -typedef InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> - FunctionAnalysisManagerModuleProxy; +using FunctionAnalysisManagerModuleProxy = + InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>; /// Specialization of the invalidate method for the \c /// FunctionAnalysisManagerModuleProxy's result. @@ -1097,6 +1116,7 @@ public: private: friend AnalysisInfoMixin< OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>; + static AnalysisKey Key; const AnalysisManagerT *AM; @@ -1109,8 +1129,8 @@ AnalysisKey extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>; /// Provide the \c ModuleAnalysisManager to \c Function proxy. -typedef OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> - ModuleAnalysisManagerFunctionProxy; +using ModuleAnalysisManagerFunctionProxy = + OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>; /// \brief Trivial adaptor that maps from a module to its functions. /// @@ -1274,6 +1294,6 @@ RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) { return RepeatedPass<PassT>(Count, std::move(P)); } -} +} // end namespace llvm -#endif +#endif // LLVM_IR_PASSMANAGER_H diff --git a/contrib/llvm/include/llvm/IR/PassManagerInternal.h b/contrib/llvm/include/llvm/IR/PassManagerInternal.h index 387dc4c65c43..9195d4dfa428 100644 --- a/contrib/llvm/include/llvm/IR/PassManagerInternal.h +++ b/contrib/llvm/include/llvm/IR/PassManagerInternal.h @@ -27,7 +27,6 @@ namespace llvm { template <typename IRUnitT> class AllAnalysesOn; template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager; -class Invalidator; class PreservedAnalyses; /// \brief Implementation details of the pass manager interfaces. @@ -116,7 +115,7 @@ struct AnalysisResultConcept { /// \brief SFINAE metafunction for computing whether \c ResultT provides an /// \c invalidate member function. template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod { - typedef char EnabledType; + using EnabledType = char; struct DisabledType { char a, b; }; @@ -124,7 +123,7 @@ template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod { // Purely to help out MSVC which fails to disable the below specialization, // explicitly enable using the result type's invalidate routine if we can // successfully call that routine. - template <typename T> struct Nonce { typedef EnabledType Type; }; + template <typename T> struct Nonce { using Type = EnabledType; }; template <typename T> static typename Nonce<decltype(std::declval<T>().invalidate( std::declval<IRUnitT &>(), std::declval<PreservedAnalyses>()))>::Type @@ -280,9 +279,9 @@ struct AnalysisPassModel : AnalysisPassConcept<IRUnitT, PreservedAnalysesT, } // FIXME: Replace PassT::Result with type traits when we use C++11. - typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, - PreservedAnalysesT, InvalidatorT> - ResultModelT; + using ResultModelT = + AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, + PreservedAnalysesT, InvalidatorT>; /// \brief The model delegates to the \c PassT::run method. /// diff --git a/contrib/llvm/include/llvm/IR/PatternMatch.h b/contrib/llvm/include/llvm/IR/PatternMatch.h index 31a76b4ed6c3..6b2b22e82b95 100644 --- a/contrib/llvm/include/llvm/IR/PatternMatch.h +++ b/contrib/llvm/include/llvm/IR/PatternMatch.h @@ -29,11 +29,19 @@ #ifndef LLVM_IR_PATTERNMATCH_H #define LLVM_IR_PATTERNMATCH_H +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/APInt.h" #include "llvm/IR/CallSite.h" +#include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Operator.h" +#include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" +#include <cstdint> namespace llvm { namespace PatternMatch { @@ -172,7 +180,9 @@ inline match_nan m_NaN() { return match_nan(); } struct apint_match { const APInt *&Res; + apint_match(const APInt *&R) : Res(R) {} + template <typename ITy> bool match(ITy *V) { if (auto *CI = dyn_cast<ConstantInt>(V)) { Res = &CI->getValue(); @@ -230,7 +240,9 @@ template <typename Predicate> struct cst_pred_ty : public Predicate { /// satisfy a specified predicate, and bind them to an APInt. template <typename Predicate> struct api_pred_ty : public Predicate { const APInt *&Res; + api_pred_ty(const APInt *&R) : Res(R) {} + template <typename ITy> bool match(ITy *V) { if (const auto *CI = dyn_cast<ConstantInt>(V)) if (this->isValue(CI->getValue())) { @@ -294,6 +306,7 @@ inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) { return template <typename Class> struct bind_ty { Class *&VR; + bind_ty(Class *&V) : VR(V) {} template <typename ITy> bool match(ITy *V) { @@ -326,6 +339,7 @@ inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; } /// \brief Match a specified Value*. struct specificval_ty { const Value *Val; + specificval_ty(const Value *V) : Val(V) {} template <typename ITy> bool match(ITy *V) { return V == Val; } @@ -338,6 +352,7 @@ inline specificval_ty m_Specific(const Value *V) { return V; } /// that value. struct specific_fpval { double Val; + specific_fpval(double V) : Val(V) {} template <typename ITy> bool match(ITy *V) { @@ -360,6 +375,7 @@ inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); } struct bind_const_intval_ty { uint64_t &VR; + bind_const_intval_ty(uint64_t &V) : VR(V) {} template <typename ITy> bool match(ITy *V) { @@ -376,6 +392,7 @@ struct bind_const_intval_ty { // value. struct specific_intval { uint64_t Val; + specific_intval(uint64_t V) : Val(V) {} template <typename ITy> bool match(ITy *V) { @@ -939,6 +956,7 @@ template <typename LHS> inline fneg_match<LHS> m_FNeg(const LHS &L) { struct br_match { BasicBlock *&Succ; + br_match(BasicBlock *&Succ) : Succ(Succ) {} template <typename OpTy> bool match(OpTy *V) { @@ -956,6 +974,7 @@ inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); } template <typename Cond_t> struct brc_match { Cond_t Cond; BasicBlock *&T, *&F; + brc_match(const Cond_t &C, BasicBlock *&t, BasicBlock *&f) : Cond(C), T(t), F(f) {} @@ -1202,6 +1221,7 @@ m_UnordFMin(const LHS &L, const RHS &R) { template <typename Opnd_t> struct Argument_match { unsigned OpI; Opnd_t Val; + Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {} template <typename OpTy> bool match(OpTy *V) { @@ -1219,6 +1239,7 @@ inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) { /// \brief Intrinsic matchers. struct IntrinsicID_match { unsigned ID; + IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {} template <typename OpTy> bool match(OpTy *V) { @@ -1239,21 +1260,23 @@ template <typename T0 = void, typename T1 = void, typename T2 = void, typename T9 = void, typename T10 = void> struct m_Intrinsic_Ty; template <typename T0> struct m_Intrinsic_Ty<T0> { - typedef match_combine_and<IntrinsicID_match, Argument_match<T0>> Ty; + using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>; }; template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> { - typedef match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>> - Ty; + using Ty = + match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>; }; template <typename T0, typename T1, typename T2> struct m_Intrinsic_Ty<T0, T1, T2> { - typedef match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty, - Argument_match<T2>> Ty; + using Ty = + match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty, + Argument_match<T2>>; }; template <typename T0, typename T1, typename T2, typename T3> struct m_Intrinsic_Ty<T0, T1, T2, T3> { - typedef match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty, - Argument_match<T3>> Ty; + using Ty = + match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty, + Argument_match<T3>>; }; /// \brief Match intrinsic calls like this: @@ -1437,4 +1460,4 @@ m_c_UMax(const LHS &L, const RHS &R) { } // end namespace PatternMatch } // end namespace llvm -#endif +#endif // LLVM_IR_PATTERNMATCH_H diff --git a/contrib/llvm/include/llvm/IR/ProfileSummary.h b/contrib/llvm/include/llvm/IR/ProfileSummary.h index f4248014c6e1..d85ce8c443ec 100644 --- a/contrib/llvm/include/llvm/IR/ProfileSummary.h +++ b/contrib/llvm/include/llvm/IR/ProfileSummary.h @@ -1,4 +1,4 @@ -//===-- ProfileSummary.h - Profile summary data structure. ------*- C++ -*-===// +//===- ProfileSummary.h - Profile summary data structure. -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -11,21 +11,17 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_SUPPORT_PROFILE_SUMMARY_H -#define LLVM_SUPPORT_PROFILE_SUMMARY_H +#ifndef LLVM_IR_PROFILESUMMARY_H +#define LLVM_IR_PROFILESUMMARY_H +#include <algorithm> #include <cstdint> -#include <utility> #include <vector> -#include "llvm/Support/Casting.h" - namespace llvm { class LLVMContext; class Metadata; -class MDTuple; -class MDNode; // The profile summary is one or more (Cutoff, MinCount, NumCounts) triplets. // The semantics of counts depend on the type of profile. For instrumentation @@ -37,12 +33,13 @@ struct ProfileSummaryEntry { uint32_t Cutoff; ///< The required percentile of counts. uint64_t MinCount; ///< The minimum count for this percentile. uint64_t NumCounts; ///< Number of counts >= the minimum count. + ProfileSummaryEntry(uint32_t TheCutoff, uint64_t TheMinCount, uint64_t TheNumCounts) : Cutoff(TheCutoff), MinCount(TheMinCount), NumCounts(TheNumCounts) {} }; -typedef std::vector<ProfileSummaryEntry> SummaryEntryVector; +using SummaryEntryVector = std::vector<ProfileSummaryEntry>; class ProfileSummary { public: @@ -59,6 +56,7 @@ private: public: static const int Scale = 1000000; + ProfileSummary(Kind K, SummaryEntryVector DetailedSummary, uint64_t TotalCount, uint64_t MaxCount, uint64_t MaxInternalCount, uint64_t MaxFunctionCount, @@ -67,6 +65,7 @@ public: TotalCount(TotalCount), MaxCount(MaxCount), MaxInternalCount(MaxInternalCount), MaxFunctionCount(MaxFunctionCount), NumCounts(NumCounts), NumFunctions(NumFunctions) {} + Kind getKind() const { return PSK; } /// \brief Return summary information as metadata. Metadata *getMD(LLVMContext &Context); @@ -82,4 +81,5 @@ public: }; } // end namespace llvm -#endif + +#endif // LLVM_IR_PROFILESUMMARY_H diff --git a/contrib/llvm/include/llvm/IR/Statepoint.h b/contrib/llvm/include/llvm/IR/Statepoint.h index 03151cd7c8f7..f01607614a0c 100644 --- a/contrib/llvm/include/llvm/IR/Statepoint.h +++ b/contrib/llvm/include/llvm/IR/Statepoint.h @@ -1,4 +1,4 @@ -//===-- llvm/IR/Statepoint.h - gc.statepoint utilities ----------*- C++ -*-===// +//===- llvm/IR/Statepoint.h - gc.statepoint utilities -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -24,10 +24,12 @@ #include "llvm/IR/CallSite.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/Casting.h" +#include "llvm/Support/MathExtras.h" #include <cassert> #include <cstddef> #include <cstdint> @@ -87,7 +89,7 @@ protected: } public: - typedef typename CallSiteTy::arg_iterator arg_iterator; + using arg_iterator = typename CallSiteTy::arg_iterator; enum { IDPos = 0, @@ -300,8 +302,9 @@ public: class ImmutableStatepoint : public StatepointBase<const Function, const Instruction, const Value, ImmutableCallSite> { - typedef StatepointBase<const Function, const Instruction, const Value, - ImmutableCallSite> Base; + using Base = + StatepointBase<const Function, const Instruction, const Value, + ImmutableCallSite>; public: explicit ImmutableStatepoint(const Instruction *I) : Base(I) {} @@ -312,7 +315,7 @@ public: /// to a gc.statepoint. class Statepoint : public StatepointBase<Function, Instruction, Value, CallSite> { - typedef StatepointBase<Function, Instruction, Value, CallSite> Base; + using Base = StatepointBase<Function, Instruction, Value, CallSite>; public: explicit Statepoint(Instruction *I) : Base(I) {} @@ -327,6 +330,7 @@ public: return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate || I->getIntrinsicID() == Intrinsic::experimental_gc_result; } + static inline bool classof(const Value *V) { return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V)); } @@ -369,6 +373,7 @@ public: static inline bool classof(const IntrinsicInst *I) { return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate; } + static inline bool classof(const Value *V) { return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V)); } @@ -403,6 +408,7 @@ public: static inline bool classof(const IntrinsicInst *I) { return I->getIntrinsicID() == Intrinsic::experimental_gc_result; } + static inline bool classof(const Value *V) { return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V)); } diff --git a/contrib/llvm/include/llvm/IR/SymbolTableListTraits.h b/contrib/llvm/include/llvm/IR/SymbolTableListTraits.h index 49a5fb21297d..87ce902c2811 100644 --- a/contrib/llvm/include/llvm/IR/SymbolTableListTraits.h +++ b/contrib/llvm/include/llvm/IR/SymbolTableListTraits.h @@ -48,7 +48,7 @@ class ValueSymbolTable; template <typename NodeTy> struct SymbolTableListParentType {}; #define DEFINE_SYMBOL_TABLE_PARENT_TYPE(NODE, PARENT) \ - template <> struct SymbolTableListParentType<NODE> { typedef PARENT type; }; + template <> struct SymbolTableListParentType<NODE> { using type = PARENT; }; DEFINE_SYMBOL_TABLE_PARENT_TYPE(Instruction, BasicBlock) DEFINE_SYMBOL_TABLE_PARENT_TYPE(BasicBlock, Function) DEFINE_SYMBOL_TABLE_PARENT_TYPE(Argument, Function) @@ -65,10 +65,10 @@ template <typename NodeTy> class SymbolTableList; // template <typename ValueSubClass> class SymbolTableListTraits : public ilist_alloc_traits<ValueSubClass> { - typedef SymbolTableList<ValueSubClass> ListTy; - typedef typename simple_ilist<ValueSubClass>::iterator iterator; - typedef - typename SymbolTableListParentType<ValueSubClass>::type ItemParentClass; + using ListTy = SymbolTableList<ValueSubClass>; + using iterator = typename simple_ilist<ValueSubClass>::iterator; + using ItemParentClass = + typename SymbolTableListParentType<ValueSubClass>::type; public: SymbolTableListTraits() = default; diff --git a/contrib/llvm/include/llvm/IR/TrackingMDRef.h b/contrib/llvm/include/llvm/IR/TrackingMDRef.h index 12b196432006..bdec904ad1e1 100644 --- a/contrib/llvm/include/llvm/IR/TrackingMDRef.h +++ b/contrib/llvm/include/llvm/IR/TrackingMDRef.h @@ -139,31 +139,35 @@ public: bool hasTrivialDestructor() const { return Ref.hasTrivialDestructor(); } }; -typedef TypedTrackingMDRef<MDNode> TrackingMDNodeRef; -typedef TypedTrackingMDRef<ValueAsMetadata> TrackingValueAsMetadataRef; +using TrackingMDNodeRef = TypedTrackingMDRef<MDNode>; +using TrackingValueAsMetadataRef = TypedTrackingMDRef<ValueAsMetadata>; // Expose the underlying metadata to casting. template <> struct simplify_type<TrackingMDRef> { - typedef Metadata *SimpleType; + using SimpleType = Metadata *; + static SimpleType getSimplifiedValue(TrackingMDRef &MD) { return MD.get(); } }; template <> struct simplify_type<const TrackingMDRef> { - typedef Metadata *SimpleType; + using SimpleType = Metadata *; + static SimpleType getSimplifiedValue(const TrackingMDRef &MD) { return MD.get(); } }; template <class T> struct simplify_type<TypedTrackingMDRef<T>> { - typedef T *SimpleType; + using SimpleType = T *; + static SimpleType getSimplifiedValue(TypedTrackingMDRef<T> &MD) { return MD.get(); } }; template <class T> struct simplify_type<const TypedTrackingMDRef<T>> { - typedef T *SimpleType; + using SimpleType = T *; + static SimpleType getSimplifiedValue(const TypedTrackingMDRef<T> &MD) { return MD.get(); } diff --git a/contrib/llvm/include/llvm/IR/Type.h b/contrib/llvm/include/llvm/IR/Type.h index e6a0df937e9b..82362107e41e 100644 --- a/contrib/llvm/include/llvm/IR/Type.h +++ b/contrib/llvm/include/llvm/IR/Type.h @@ -1,4 +1,4 @@ -//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===// +//===- llvm/Type.h - Classes for handling data types ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -18,21 +18,22 @@ #include "llvm/ADT/APFloat.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Casting.h" -#include "llvm/Support/DataTypes.h" +#include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" +#include <cassert> +#include <cstdint> +#include <iterator> namespace llvm { -class PointerType; +template<class GraphType> struct GraphTraits; class IntegerType; -class raw_ostream; -class Module; class LLVMContext; -class LLVMContextImpl; +class PointerType; +class raw_ostream; class StringRef; -template<class GraphType> struct GraphTraits; /// The instances of the Type class are immutable: once they are created, /// they are never changed. Also note that only one instance of a particular @@ -86,9 +87,9 @@ private: protected: friend class LLVMContextImpl; + explicit Type(LLVMContext &C, TypeID tid) - : Context(C), ID(tid), SubclassData(0), - NumContainedTys(0), ContainedTys(nullptr) {} + : Context(C), ID(tid), SubclassData(0) {} ~Type() = default; unsigned getSubclassData() const { return SubclassData; } @@ -100,14 +101,14 @@ protected: } /// Keeps track of how many Type*'s there are in the ContainedTys list. - unsigned NumContainedTys; + unsigned NumContainedTys = 0; /// A pointer to the array of Types contained by this Type. For example, this /// includes the arguments of a function type, the elements of a structure, /// the pointee of a pointer, the element type of an array, etc. This pointer /// may be 0 for types that don't contain other types (Integer, Double, /// Float). - Type * const *ContainedTys; + Type * const *ContainedTys = nullptr; static bool isSequentialType(TypeID TyID) { return TyID == ArrayTyID || TyID == VectorTyID; @@ -122,6 +123,7 @@ public: /// inlined with the operands when printing an instruction. void print(raw_ostream &O, bool IsForDebug = false, bool NoDetails = false) const; + void dump() const; /// Return the LLVMContext in which this type was uniqued. @@ -299,14 +301,16 @@ public: //===--------------------------------------------------------------------===// // Type Iteration support. // - typedef Type * const *subtype_iterator; + using subtype_iterator = Type * const *; + subtype_iterator subtype_begin() const { return ContainedTys; } subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];} ArrayRef<Type*> subtypes() const { return makeArrayRef(subtype_begin(), subtype_end()); } - typedef std::reverse_iterator<subtype_iterator> subtype_reverse_iterator; + using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>; + subtype_reverse_iterator subtype_rbegin() const { return subtype_reverse_iterator(subtype_end()); } @@ -348,6 +352,7 @@ public: } inline uint64_t getArrayNumElements() const; + Type *getArrayElementType() const { assert(getTypeID() == ArrayTyID); return ContainedTys[0]; @@ -444,8 +449,8 @@ template <> struct isa_impl<PointerType, Type> { // graph of sub types. template <> struct GraphTraits<Type *> { - typedef Type *NodeRef; - typedef Type::subtype_iterator ChildIteratorType; + using NodeRef = Type *; + using ChildIteratorType = Type::subtype_iterator; static NodeRef getEntryNode(Type *T) { return T; } static ChildIteratorType child_begin(NodeRef N) { return N->subtype_begin(); } @@ -453,8 +458,8 @@ template <> struct GraphTraits<Type *> { }; template <> struct GraphTraits<const Type*> { - typedef const Type *NodeRef; - typedef Type::subtype_iterator ChildIteratorType; + using NodeRef = const Type *; + using ChildIteratorType = Type::subtype_iterator; static NodeRef getEntryNode(NodeRef T) { return T; } static ChildIteratorType child_begin(NodeRef N) { return N->subtype_begin(); } @@ -474,6 +479,6 @@ inline LLVMTypeRef *wrap(Type **Tys) { return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys)); } -} // End llvm namespace +} // end namespace llvm -#endif +#endif // LLVM_IR_TYPE_H diff --git a/contrib/llvm/include/llvm/IR/TypeFinder.h b/contrib/llvm/include/llvm/IR/TypeFinder.h index 48c4f1161aa1..c050c388d398 100644 --- a/contrib/llvm/include/llvm/IR/TypeFinder.h +++ b/contrib/llvm/include/llvm/IR/TypeFinder.h @@ -44,8 +44,8 @@ public: void run(const Module &M, bool onlyNamed); void clear(); - typedef std::vector<StructType*>::iterator iterator; - typedef std::vector<StructType*>::const_iterator const_iterator; + using iterator = std::vector<StructType*>::iterator; + using const_iterator = std::vector<StructType*>::const_iterator; iterator begin() { return StructTypes.begin(); } iterator end() { return StructTypes.end(); } diff --git a/contrib/llvm/include/llvm/IR/Use.h b/contrib/llvm/include/llvm/IR/Use.h index 6b56546f4421..d3a59d8a060e 100644 --- a/contrib/llvm/include/llvm/IR/Use.h +++ b/contrib/llvm/include/llvm/IR/Use.h @@ -1,4 +1,4 @@ -//===-- llvm/Use.h - Definition of the Use class ----------------*- C++ -*-===// +//===- llvm/Use.h - Definition of the Use class -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -27,14 +27,14 @@ #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/Compiler.h" #include "llvm-c/Types.h" namespace llvm { -class Value; -class User; -class Use; template <typename> struct simplify_type; +class User; +class Value; /// \brief A Use represents the edge between a Value definition and its users. /// @@ -65,23 +65,27 @@ public: /// use the LSB regardless of pointer alignment on different targets. struct UserRefPointerTraits { static inline void *getAsVoidPointer(User *P) { return P; } + static inline User *getFromVoidPointer(void *P) { return (User *)P; } + enum { NumLowBitsAvailable = 1 }; }; // A type for the word following an array of hung-off Uses in memory, which is // a pointer back to their User with the bottom bit set. - typedef PointerIntPair<User *, 1, unsigned, UserRefPointerTraits> UserRef; + using UserRef = PointerIntPair<User *, 1, unsigned, UserRefPointerTraits>; /// Pointer traits for the Prev PointerIntPair. This ensures we always use /// the two LSBs regardless of pointer alignment on different targets. struct PrevPointerTraits { static inline void *getAsVoidPointer(Use **P) { return P; } + static inline Use **getFromVoidPointer(void *P) { return (Use **)P; } + enum { NumLowBitsAvailable = 2 }; }; @@ -95,9 +99,11 @@ private: enum PrevPtrTag { zeroDigitTag, oneDigitTag, stopTag, fullStopTag }; /// Constructor - Use(PrevPtrTag tag) : Val(nullptr) { Prev.setInt(tag); } + Use(PrevPtrTag tag) { Prev.setInt(tag); } public: + friend class Value; + operator Value *() const { return Val; } Value *get() const { return Val; } @@ -133,7 +139,7 @@ public: private: const Use *getImpliedUser() const LLVM_READONLY; - Value *Val; + Value *Val = nullptr; Use *Next; PointerIntPair<Use **, 2, PrevPtrTag, PrevPointerTraits> Prev; @@ -153,18 +159,18 @@ private: if (Next) Next->setPrev(StrippedPrev); } - - friend class Value; }; /// \brief Allow clients to treat uses just like values when using /// casting operators. template <> struct simplify_type<Use> { - typedef Value *SimpleType; + using SimpleType = Value *; + static SimpleType getSimplifiedValue(Use &Val) { return Val.get(); } }; template <> struct simplify_type<const Use> { - typedef /*const*/ Value *SimpleType; + using SimpleType = /*const*/ Value *; + static SimpleType getSimplifiedValue(const Use &Val) { return Val.get(); } }; diff --git a/contrib/llvm/include/llvm/IR/UseListOrder.h b/contrib/llvm/include/llvm/IR/UseListOrder.h index ebe99223facd..a8b394fc6302 100644 --- a/contrib/llvm/include/llvm/IR/UseListOrder.h +++ b/contrib/llvm/include/llvm/IR/UseListOrder.h @@ -37,7 +37,7 @@ struct UseListOrder { UseListOrder &operator=(UseListOrder &&) = default; }; -typedef std::vector<UseListOrder> UseListOrderStack; +using UseListOrderStack = std::vector<UseListOrder>; } // end namespace llvm diff --git a/contrib/llvm/include/llvm/IR/User.h b/contrib/llvm/include/llvm/IR/User.h index 54758a9b6d6a..7b9d451aaf53 100644 --- a/contrib/llvm/include/llvm/IR/User.h +++ b/contrib/llvm/include/llvm/IR/User.h @@ -1,4 +1,4 @@ -//===-- llvm/User.h - User class definition ---------------------*- C++ -*-===// +//===- llvm/User.h - User class definition ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -114,6 +114,7 @@ protected: ? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx] : OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx]; } + template <int Idx> Use &Op() { return OpFrom<Idx>(this); } @@ -205,10 +206,10 @@ public: // --------------------------------------------------------------------------- // Operand Iterator interface... // - typedef Use* op_iterator; - typedef const Use* const_op_iterator; - typedef iterator_range<op_iterator> op_range; - typedef iterator_range<const_op_iterator> const_op_range; + using op_iterator = Use*; + using const_op_iterator = const Use*; + using op_range = iterator_range<op_iterator>; + using const_op_range = iterator_range<const_op_iterator>; op_iterator op_begin() { return getOperandList(); } const_op_iterator op_begin() const { return getOperandList(); } @@ -252,6 +253,7 @@ public: ptrdiff_t, const Value *, const Value *> { explicit const_value_op_iterator(const Use *U = nullptr) : iterator_adaptor_base(U) {} + const Value *operator*() const { return *I; } const Value *operator->() const { return operator*(); } }; @@ -290,6 +292,7 @@ public: return isa<Instruction>(V) || isa<Constant>(V); } }; + // Either Use objects, or a Use pointer can be prepended to User. static_assert(alignof(Use) >= alignof(User), "Alignment is insufficient after objects prepended to User"); @@ -297,13 +300,15 @@ static_assert(alignof(Use *) >= alignof(User), "Alignment is insufficient after objects prepended to User"); template<> struct simplify_type<User::op_iterator> { - typedef Value* SimpleType; + using SimpleType = Value*; + static SimpleType getSimplifiedValue(User::op_iterator &Val) { return Val->get(); } }; template<> struct simplify_type<User::const_op_iterator> { - typedef /*const*/ Value* SimpleType; + using SimpleType = /*const*/ Value*; + static SimpleType getSimplifiedValue(User::const_op_iterator &Val) { return Val->get(); } diff --git a/contrib/llvm/include/llvm/IR/Value.h b/contrib/llvm/include/llvm/IR/Value.h index 00f821399257..96a370dcc35f 100644 --- a/contrib/llvm/include/llvm/IR/Value.h +++ b/contrib/llvm/include/llvm/IR/Value.h @@ -1,4 +1,4 @@ -//===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===// +//===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -44,12 +44,12 @@ class LLVMContext; class Module; class ModuleSlotTracker; class raw_ostream; +template<typename ValueTy> class StringMapEntry; class StringRef; class Twine; class Type; -template<typename ValueTy> class StringMapEntry; -typedef StringMapEntry<Value*> ValueName; +using ValueName = StringMapEntry<Value*>; //===----------------------------------------------------------------------===// // Value Class @@ -120,9 +120,11 @@ private: template <typename UseT> // UseT == 'Use' or 'const Use' class use_iterator_impl : public std::iterator<std::forward_iterator_tag, UseT *> { + friend class Value; + UseT *U; + explicit use_iterator_impl(UseT *u) : U(u) {} - friend class Value; public: use_iterator_impl() : U() {} @@ -309,8 +311,9 @@ public: return UseList == nullptr; } - typedef use_iterator_impl<Use> use_iterator; - typedef use_iterator_impl<const Use> const_use_iterator; + using use_iterator = use_iterator_impl<Use>; + using const_use_iterator = use_iterator_impl<const Use>; + use_iterator materialized_use_begin() { return use_iterator(UseList); } const_use_iterator materialized_use_begin() const { return const_use_iterator(UseList); @@ -345,8 +348,9 @@ public: return UseList == nullptr; } - typedef user_iterator_impl<User> user_iterator; - typedef user_iterator_impl<const User> const_user_iterator; + using user_iterator = user_iterator_impl<User>; + using const_user_iterator = user_iterator_impl<const User>; + user_iterator materialized_user_begin() { return user_iterator(UseList); } const_user_iterator materialized_user_begin() const { return const_user_iterator(UseList); @@ -560,7 +564,6 @@ public: /// block. const Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const; - Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) { return const_cast<Value *>( static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB)); @@ -606,7 +609,7 @@ private: Use *Merged; Use **Next = &Merged; - for (;;) { + while (true) { if (!L) { *Next = R; break; diff --git a/contrib/llvm/include/llvm/IR/ValueHandle.h b/contrib/llvm/include/llvm/IR/ValueHandle.h index 393618d5511b..b45cc7b6dc02 100644 --- a/contrib/llvm/include/llvm/IR/ValueHandle.h +++ b/contrib/llvm/include/llvm/IR/ValueHandle.h @@ -17,10 +17,10 @@ #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" +#include <cassert> namespace llvm { -class ValueHandleBase; -template<typename From> struct simplify_type; /// \brief This is the common base class of value handles. /// @@ -29,6 +29,7 @@ template<typename From> struct simplify_type; /// below for details. class ValueHandleBase { friend class Value; + protected: /// \brief This indicates what sub class the handle actually is. /// @@ -40,24 +41,23 @@ protected: : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {} ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS) - : PrevPair(nullptr, Kind), Next(nullptr), Val(RHS.getValPtr()) { + : PrevPair(nullptr, Kind), Val(RHS.getValPtr()) { if (isValid(getValPtr())) AddToExistingUseList(RHS.getPrevPtr()); } private: PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair; - ValueHandleBase *Next; - - Value *Val; + ValueHandleBase *Next = nullptr; + Value *Val = nullptr; void setValPtr(Value *V) { Val = V; } public: explicit ValueHandleBase(HandleBaseKind Kind) - : PrevPair(nullptr, Kind), Next(nullptr), Val(nullptr) {} + : PrevPair(nullptr, Kind) {} ValueHandleBase(HandleBaseKind Kind, Value *V) - : PrevPair(nullptr, Kind), Next(nullptr), Val(V) { + : PrevPair(nullptr, Kind), Val(V) { if (isValid(getValPtr())) AddToUseList(); } @@ -162,11 +162,13 @@ public: // Specialize simplify_type to allow WeakVH to participate in // dyn_cast, isa, etc. template <> struct simplify_type<WeakVH> { - typedef Value *SimpleType; + using SimpleType = Value *; + static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; } }; template <> struct simplify_type<const WeakVH> { - typedef Value *SimpleType; + using SimpleType = Value *; + static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; } }; @@ -205,11 +207,13 @@ public: // Specialize simplify_type to allow WeakTrackingVH to participate in // dyn_cast, isa, etc. template <> struct simplify_type<WeakTrackingVH> { - typedef Value *SimpleType; + using SimpleType = Value *; + static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; } }; template <> struct simplify_type<const WeakTrackingVH> { - typedef Value *SimpleType; + using SimpleType = Value *; + static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) { return WVH; } @@ -236,7 +240,7 @@ class AssertingVH : public ValueHandleBase #endif { - friend struct DenseMapInfo<AssertingVH<ValueTy> >; + friend struct DenseMapInfo<AssertingVH<ValueTy>>; #ifndef NDEBUG Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); } @@ -282,20 +286,23 @@ public: // Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap. template<typename T> -struct DenseMapInfo<AssertingVH<T> > { +struct DenseMapInfo<AssertingVH<T>> { static inline AssertingVH<T> getEmptyKey() { AssertingVH<T> Res; Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey()); return Res; } + static inline AssertingVH<T> getTombstoneKey() { AssertingVH<T> Res; Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey()); return Res; } + static unsigned getHashValue(const AssertingVH<T> &Val) { return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr()); } + static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) { return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(), RHS.getRawValPtr()); @@ -303,7 +310,7 @@ struct DenseMapInfo<AssertingVH<T> > { }; template <typename T> -struct isPodLike<AssertingVH<T> > { +struct isPodLike<AssertingVH<T>> { #ifdef NDEBUG static const bool value = true; #else @@ -356,7 +363,7 @@ public: static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); } public: - TrackingVH() {} + TrackingVH() = default; TrackingVH(ValueTy *P) { setValPtr(P); } operator ValueTy*() const { @@ -495,10 +502,12 @@ public: PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {} PoisoningVH(const PoisoningVH &RHS) : CallbackVH(RHS), Poisoned(RHS.Poisoned) {} + ~PoisoningVH() { if (Poisoned) clearValPtr(); } + PoisoningVH &operator=(const PoisoningVH &RHS) { if (Poisoned) clearValPtr(); @@ -523,14 +532,17 @@ template <typename T> struct DenseMapInfo<PoisoningVH<T>> { Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey()); return Res; } + static inline PoisoningVH<T> getTombstoneKey() { PoisoningVH<T> Res; Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey()); return Res; } + static unsigned getHashValue(const PoisoningVH<T> &Val) { return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr()); } + static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) { return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(), RHS.getRawValPtr()); @@ -545,6 +557,6 @@ template <typename T> struct isPodLike<PoisoningVH<T>> { #endif }; -} // End llvm namespace +} // end namespace llvm -#endif +#endif // LLVM_IR_VALUEHANDLE_H diff --git a/contrib/llvm/include/llvm/IR/ValueMap.h b/contrib/llvm/include/llvm/IR/ValueMap.h index 9648e1989f94..11d5823ee479 100644 --- a/contrib/llvm/include/llvm/IR/ValueMap.h +++ b/contrib/llvm/include/llvm/IR/ValueMap.h @@ -46,7 +46,6 @@ namespace llvm { template<typename KeyT, typename ValueT, typename Config> class ValueMapCallbackVH; - template<typename DenseMapT, typename KeyT> class ValueMapIterator; template<typename DenseMapT, typename KeyT> @@ -57,7 +56,7 @@ class ValueMapConstIterator; /// as possible with future versions of ValueMap. template<typename KeyT, typename MutexT = sys::Mutex> struct ValueMapConfig { - typedef MutexT mutex_type; + using mutex_type = MutexT; /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's /// false, the ValueMap will leave the original mapping in place. @@ -87,21 +86,21 @@ template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT>> class ValueMap { friend class ValueMapCallbackVH<KeyT, ValueT, Config>; - typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH; - typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH>> MapT; - typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT; - typedef typename Config::ExtraData ExtraData; + using ValueMapCVH = ValueMapCallbackVH<KeyT, ValueT, Config>; + using MapT = DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH>>; + using MDMapT = DenseMap<const Metadata *, TrackingMDRef>; + using ExtraData = typename Config::ExtraData; + MapT Map; Optional<MDMapT> MDMap; ExtraData Data; - bool MayMapMetadata = true; public: - typedef KeyT key_type; - typedef ValueT mapped_type; - typedef std::pair<KeyT, ValueT> value_type; - typedef unsigned size_type; + using key_type = KeyT; + using mapped_type = ValueT; + using value_type = std::pair<KeyT, ValueT>; + using size_type = unsigned; explicit ValueMap(unsigned NumInitBuckets = 64) : Map(NumInitBuckets), Data() {} @@ -132,8 +131,9 @@ public: return Where->second.get(); } - typedef ValueMapIterator<MapT, KeyT> iterator; - typedef ValueMapConstIterator<MapT, KeyT> const_iterator; + using iterator = ValueMapIterator<MapT, KeyT>; + using const_iterator = ValueMapConstIterator<MapT, KeyT>; + inline iterator begin() { return iterator(Map.begin()); } inline iterator end() { return iterator(Map.end()); } inline const_iterator begin() const { return const_iterator(Map.begin()); } @@ -244,8 +244,8 @@ class ValueMapCallbackVH final : public CallbackVH { friend class ValueMap<KeyT, ValueT, Config>; friend struct DenseMapInfo<ValueMapCallbackVH>; - typedef ValueMap<KeyT, ValueT, Config> ValueMapT; - typedef typename std::remove_pointer<KeyT>::type KeySansPointerT; + using ValueMapT = ValueMap<KeyT, ValueT, Config>; + using KeySansPointerT = typename std::remove_pointer<KeyT>::type; ValueMapT *Map; @@ -298,7 +298,7 @@ public: template<typename KeyT, typename ValueT, typename Config> struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config>> { - typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH; + using VH = ValueMapCallbackVH<KeyT, ValueT, Config>; static inline VH getEmptyKey() { return VH(DenseMapInfo<Value *>::getEmptyKey()); @@ -330,8 +330,8 @@ class ValueMapIterator : public std::iterator<std::forward_iterator_tag, std::pair<KeyT, typename DenseMapT::mapped_type>, ptrdiff_t> { - typedef typename DenseMapT::iterator BaseT; - typedef typename DenseMapT::mapped_type ValueT; + using BaseT = typename DenseMapT::iterator; + using ValueT = typename DenseMapT::mapped_type; BaseT I; @@ -344,7 +344,9 @@ public: struct ValueTypeProxy { const KeyT first; ValueT& second; + ValueTypeProxy *operator->() { return this; } + operator std::pair<KeyT, ValueT>() const { return std::make_pair(first, second); } @@ -380,8 +382,8 @@ class ValueMapConstIterator : public std::iterator<std::forward_iterator_tag, std::pair<KeyT, typename DenseMapT::mapped_type>, ptrdiff_t> { - typedef typename DenseMapT::const_iterator BaseT; - typedef typename DenseMapT::mapped_type ValueT; + using BaseT = typename DenseMapT::const_iterator; + using ValueT = typename DenseMapT::mapped_type; BaseT I; diff --git a/contrib/llvm/include/llvm/IR/ValueSymbolTable.h b/contrib/llvm/include/llvm/IR/ValueSymbolTable.h index 9e86751dae6f..26cbbfabfc0c 100644 --- a/contrib/llvm/include/llvm/IR/ValueSymbolTable.h +++ b/contrib/llvm/include/llvm/IR/ValueSymbolTable.h @@ -49,13 +49,13 @@ class ValueSymbolTable { /// @{ public: /// @brief A mapping of names to values. - typedef StringMap<Value*> ValueMap; + using ValueMap = StringMap<Value*>; /// @brief An iterator over a ValueMap. - typedef ValueMap::iterator iterator; + using iterator = ValueMap::iterator; /// @brief A const_iterator over a ValueMap. - typedef ValueMap::const_iterator const_iterator; + using const_iterator = ValueMap::const_iterator; /// @} /// @name Constructors diff --git a/contrib/llvm/include/llvm/IR/Verifier.h b/contrib/llvm/include/llvm/IR/Verifier.h index 71f727c3d4fc..15e52d9e0742 100644 --- a/contrib/llvm/include/llvm/IR/Verifier.h +++ b/contrib/llvm/include/llvm/IR/Verifier.h @@ -21,13 +21,17 @@ #ifndef LLVM_IR_VERIFIER_H #define LLVM_IR_VERIFIER_H +#include "llvm/ADT/DenseMap.h" #include "llvm/IR/PassManager.h" +#include <utility> namespace llvm { +class APInt; class Function; class FunctionPass; -class ModulePass; +class Instruction; +class MDNode; class Module; class raw_ostream; struct VerifierSupport; @@ -47,7 +51,7 @@ class TBAAVerifier { /// the offset of the access. If zero, only a zero offset is allowed. /// /// \c BitWidth has no meaning if \c IsInvalid is true. - typedef std::pair<bool, unsigned> TBAABaseNodeSummary; + using TBAABaseNodeSummary = std::pair<bool, unsigned>; DenseMap<const MDNode *, TBAABaseNodeSummary> TBAABaseNodes; /// Maps an alleged scalar TBAA node to a boolean that is true if the said @@ -101,12 +105,14 @@ FunctionPass *createVerifierPass(bool FatalErrors = true); /// and debug info errors. class VerifierAnalysis : public AnalysisInfoMixin<VerifierAnalysis> { friend AnalysisInfoMixin<VerifierAnalysis>; + static AnalysisKey Key; public: struct Result { bool IRBroken, DebugInfoBroken; }; + Result run(Module &M, ModuleAnalysisManager &); Result run(Function &F, FunctionAnalysisManager &); }; @@ -136,7 +142,6 @@ public: PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); }; +} // end namespace llvm -} // End llvm namespace - -#endif +#endif // LLVM_IR_VERIFIER_H diff --git a/contrib/llvm/include/llvm/InitializePasses.h b/contrib/llvm/include/llvm/InitializePasses.h index 44ff4c1a581b..cf314e19d1ca 100644 --- a/contrib/llvm/include/llvm/InitializePasses.h +++ b/contrib/llvm/include/llvm/InitializePasses.h @@ -130,6 +130,7 @@ void initializeEfficiencySanitizerPass(PassRegistry&); void initializeEliminateAvailableExternallyLegacyPassPass(PassRegistry&); void initializeExpandISelPseudosPass(PassRegistry&); void initializeExpandPostRAPass(PassRegistry&); +void initializeExpandReductionsPass(PassRegistry&); void initializeExternalAAWrapperPassPass(PassRegistry&); void initializeFEntryInserterPass(PassRegistry&); void initializeFinalizeMachineBundlesPass(PassRegistry&); @@ -186,6 +187,7 @@ void initializeLintPass(PassRegistry&); void initializeLiveDebugValuesPass(PassRegistry&); void initializeLiveDebugVariablesPass(PassRegistry&); void initializeLiveIntervalsPass(PassRegistry&); +void initializeLiveRangeShrinkPass(PassRegistry&); void initializeLiveRegMatrixPass(PassRegistry&); void initializeLiveStacksPass(PassRegistry&); void initializeLiveVariablesPass(PassRegistry&); @@ -319,11 +321,12 @@ void initializeSCCPLegacyPassPass(PassRegistry&); void initializeSCEVAAWrapperPassPass(PassRegistry&); void initializeSLPVectorizerPass(PassRegistry&); void initializeSROALegacyPassPass(PassRegistry&); -void initializeSafeStackPass(PassRegistry&); +void initializeSafeStackLegacyPassPass(PassRegistry&); void initializeSampleProfileLoaderLegacyPassPass(PassRegistry&); void initializeSanitizerCoverageModulePass(PassRegistry&); void initializeScalarEvolutionWrapperPassPass(PassRegistry&); void initializeScalarizerPass(PassRegistry&); +void initializeScalarizeMaskedMemIntrinPass(PassRegistry&); void initializeScopedNoAliasAAWrapperPassPass(PassRegistry&); void initializeSeparateConstOffsetFromGEPPass(PassRegistry&); void initializeShadowStackGCLoweringPass(PassRegistry&); diff --git a/contrib/llvm/include/llvm/LinkAllPasses.h b/contrib/llvm/include/llvm/LinkAllPasses.h index 39a86e838bde..5c398b2ab567 100644 --- a/contrib/llvm/include/llvm/LinkAllPasses.h +++ b/contrib/llvm/include/llvm/LinkAllPasses.h @@ -206,6 +206,7 @@ namespace { (void) llvm::createMemDerefPrinter(); (void) llvm::createFloat2IntPass(); (void) llvm::createEliminateAvailableExternallyPass(); + (void) llvm::createScalarizeMaskedMemIntrinPass(); (void)new llvm::IntervalPartition(); (void)new llvm::ScalarEvolutionWrapperPass(); diff --git a/contrib/llvm/include/llvm/Object/Wasm.h b/contrib/llvm/include/llvm/Object/Wasm.h index 4bc39d98b7af..d200d4a148e3 100644 --- a/contrib/llvm/include/llvm/Object/Wasm.h +++ b/contrib/llvm/include/llvm/Object/Wasm.h @@ -67,7 +67,8 @@ public: WasmObjectFile(MemoryBufferRef Object, Error &Err); const wasm::WasmObjectHeader &getHeader() const; - const WasmSymbol &getWasmSymbol(DataRefImpl Symb) const; + const WasmSymbol &getWasmSymbol(const DataRefImpl &Symb) const; + const WasmSymbol &getWasmSymbol(const SymbolRef &Symbol) const; const WasmSection &getWasmSection(const SectionRef &Section) const; const wasm::WasmRelocation &getWasmRelocation(const RelocationRef& Ref) const; @@ -81,6 +82,10 @@ public: const std::vector<wasm::WasmGlobal>& globals() const { return Globals; } const std::vector<wasm::WasmExport>& exports() const { return Exports; } + uint32_t getNumberOfSymbols() const { + return Symbols.size(); + } + const std::vector<wasm::WasmElemSegment>& elements() const { return ElemSegments; } diff --git a/contrib/llvm/include/llvm/ObjectYAML/WasmYAML.h b/contrib/llvm/include/llvm/ObjectYAML/WasmYAML.h index bd7d72be4dbc..7b70c9537827 100644 --- a/contrib/llvm/include/llvm/ObjectYAML/WasmYAML.h +++ b/contrib/llvm/include/llvm/ObjectYAML/WasmYAML.h @@ -34,17 +34,6 @@ struct FileHeader { yaml::Hex32 Version; }; -struct Import { - StringRef Module; - StringRef Field; - ExportKind Kind; - union { - uint32_t SigIndex; - ValueType GlobalType; - }; - bool GlobalMutable; -}; - struct Limits { yaml::Hex32 Flags; yaml::Hex32 Initial; @@ -74,6 +63,18 @@ struct Global { wasm::WasmInitExpr InitExpr; }; +struct Import { + StringRef Module; + StringRef Field; + ExportKind Kind; + union { + uint32_t SigIndex; + Global GlobalImport; + Table TableImport; + Limits Memory; + }; +}; + struct LocalDecl { ValueType Type; uint32_t Count; diff --git a/contrib/llvm/include/llvm/ProfileData/SampleProfWriter.h b/contrib/llvm/include/llvm/ProfileData/SampleProfWriter.h index 9d69af32dd46..86af1038d74e 100644 --- a/contrib/llvm/include/llvm/ProfileData/SampleProfWriter.h +++ b/contrib/llvm/include/llvm/ProfileData/SampleProfWriter.h @@ -43,16 +43,7 @@ public: /// Write all the sample profiles in the given map of samples. /// /// \returns status code of the file update operation. - std::error_code write(const StringMap<FunctionSamples> &ProfileMap) { - if (std::error_code EC = writeHeader(ProfileMap)) - return EC; - for (const auto &I : ProfileMap) { - const FunctionSamples &Profile = I.second; - if (std::error_code EC = write(Profile)) - return EC; - } - return sampleprof_error::success; - } + std::error_code write(const StringMap<FunctionSamples> &ProfileMap); raw_ostream &getOutputStream() { return *OutputStream; } diff --git a/contrib/llvm/include/llvm/Support/BinaryStreamArray.h b/contrib/llvm/include/llvm/Support/BinaryStreamArray.h index bad31cd38d6a..77c99ffff919 100644 --- a/contrib/llvm/include/llvm/Support/BinaryStreamArray.h +++ b/contrib/llvm/include/llvm/Support/BinaryStreamArray.h @@ -139,6 +139,7 @@ public: } uint32_t offset() const { return AbsOffset; } + uint32_t getRecordLength() const { return ThisLen; } private: void moveToEnd() { @@ -294,6 +295,8 @@ template <typename T> class FixedStreamArray { friend class FixedStreamArrayIterator<T>; public: + typedef FixedStreamArrayIterator<T> Iterator; + FixedStreamArray() = default; explicit FixedStreamArray(BinaryStreamRef Stream) : Stream(Stream) { assert(Stream.getLength() % sizeof(T) == 0); @@ -371,7 +374,7 @@ public: } FixedStreamArrayIterator<T> &operator-=(std::ptrdiff_t N) { - assert(Index >= N); + assert(std::ptrdiff_t(Index) >= N); Index -= N; return *this; } diff --git a/contrib/llvm/include/llvm/Support/Compiler.h b/contrib/llvm/include/llvm/Support/Compiler.h index a56bc93e111b..be9e46540016 100644 --- a/contrib/llvm/include/llvm/Support/Compiler.h +++ b/contrib/llvm/include/llvm/Support/Compiler.h @@ -111,12 +111,6 @@ #define LLVM_PREFETCH(addr, rw, locality) #endif -#if __has_attribute(sentinel) || LLVM_GNUC_PREREQ(3, 0, 0) -#define LLVM_END_WITH_NULL __attribute__((sentinel)) -#else -#define LLVM_END_WITH_NULL -#endif - #if __has_attribute(used) || LLVM_GNUC_PREREQ(3, 1, 0) #define LLVM_ATTRIBUTE_USED __attribute__((__used__)) #else @@ -233,6 +227,8 @@ /// LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements. #if __cplusplus > 201402L && __has_cpp_attribute(fallthrough) #define LLVM_FALLTHROUGH [[fallthrough]] +#elif __has_cpp_attribute(gnu::fallthrough) +#define LLVM_FALLTHROUGH [[gnu::fallthrough]] #elif !__cplusplus // Workaround for llvm.org/PR23435, since clang 3.6 and below emit a spurious // error when __has_cpp_attribute is given a scoped attribute in C mode. diff --git a/contrib/llvm/include/llvm/Support/KnownBits.h b/contrib/llvm/include/llvm/Support/KnownBits.h index 3d38cf878538..2c77d40559b9 100644 --- a/contrib/llvm/include/llvm/Support/KnownBits.h +++ b/contrib/llvm/include/llvm/Support/KnownBits.h @@ -133,6 +133,66 @@ public: KnownBits zextOrTrunc(unsigned BitWidth) { return KnownBits(Zero.zextOrTrunc(BitWidth), One.zextOrTrunc(BitWidth)); } + + /// Returns the minimum number of trailing zero bits. + unsigned countMinTrailingZeros() const { + return Zero.countTrailingOnes(); + } + + /// Returns the minimum number of trailing one bits. + unsigned countMinTrailingOnes() const { + return One.countTrailingOnes(); + } + + /// Returns the minimum number of leading zero bits. + unsigned countMinLeadingZeros() const { + return Zero.countLeadingOnes(); + } + + /// Returns the minimum number of leading one bits. + unsigned countMinLeadingOnes() const { + return One.countLeadingOnes(); + } + + /// Returns the number of times the sign bit is replicated into the other + /// bits. + unsigned countMinSignBits() const { + if (isNonNegative()) + return countMinLeadingZeros(); + if (isNegative()) + return countMinLeadingOnes(); + return 0; + } + + /// Returns the maximum number of trailing zero bits possible. + unsigned countMaxTrailingZeros() const { + return One.countTrailingZeros(); + } + + /// Returns the maximum number of trailing one bits possible. + unsigned countMaxTrailingOnes() const { + return Zero.countTrailingZeros(); + } + + /// Returns the maximum number of leading zero bits possible. + unsigned countMaxLeadingZeros() const { + return One.countLeadingZeros(); + } + + /// Returns the maximum number of leading one bits possible. + unsigned countMaxLeadingOnes() const { + return Zero.countLeadingZeros(); + } + + /// Returns the number of bits known to be one. + unsigned countMinPopulation() const { + return One.countPopulation(); + } + + /// Returns the maximum number of bits that could be one. + unsigned countMaxPopulation() const { + return getBitWidth() - Zero.countPopulation(); + } }; } // end namespace llvm diff --git a/contrib/llvm/include/llvm/Support/Parallel.h b/contrib/llvm/include/llvm/Support/Parallel.h new file mode 100644 index 000000000000..e36e0cc29e14 --- /dev/null +++ b/contrib/llvm/include/llvm/Support/Parallel.h @@ -0,0 +1,249 @@ +//===- llvm/Support/Parallel.h - Parallel algorithms ----------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_PARALLEL_H +#define LLVM_SUPPORT_PARALLEL_H + +#include "llvm/ADT/STLExtras.h" +#include "llvm/Config/llvm-config.h" +#include "llvm/Support/MathExtras.h" + +#include <algorithm> +#include <condition_variable> +#include <functional> +#include <mutex> + +#if defined(_MSC_VER) && LLVM_ENABLE_THREADS +#pragma warning(push) +#pragma warning(disable : 4530) +#include <concrt.h> +#include <ppl.h> +#pragma warning(pop) +#endif + +namespace llvm { + +namespace parallel { +struct sequential_execution_policy {}; +struct parallel_execution_policy {}; + +template <typename T> +struct is_execution_policy + : public std::integral_constant< + bool, llvm::is_one_of<T, sequential_execution_policy, + parallel_execution_policy>::value> {}; + +constexpr sequential_execution_policy seq{}; +constexpr parallel_execution_policy par{}; + +namespace detail { + +#if LLVM_ENABLE_THREADS + +class Latch { + uint32_t Count; + mutable std::mutex Mutex; + mutable std::condition_variable Cond; + +public: + explicit Latch(uint32_t Count = 0) : Count(Count) {} + ~Latch() { sync(); } + + void inc() { + std::unique_lock<std::mutex> lock(Mutex); + ++Count; + } + + void dec() { + std::unique_lock<std::mutex> lock(Mutex); + if (--Count == 0) + Cond.notify_all(); + } + + void sync() const { + std::unique_lock<std::mutex> lock(Mutex); + Cond.wait(lock, [&] { return Count == 0; }); + } +}; + +class TaskGroup { + Latch L; + +public: + void spawn(std::function<void()> f); + + void sync() const { L.sync(); } +}; + +#if defined(_MSC_VER) +template <class RandomAccessIterator, class Comparator> +void parallel_sort(RandomAccessIterator Start, RandomAccessIterator End, + const Comparator &Comp) { + concurrency::parallel_sort(Start, End, Comp); +} +template <class IterTy, class FuncTy> +void parallel_for_each(IterTy Begin, IterTy End, FuncTy Fn) { + concurrency::parallel_for_each(Begin, End, Fn); +} + +template <class IndexTy, class FuncTy> +void parallel_for_each_n(IndexTy Begin, IndexTy End, FuncTy Fn) { + concurrency::parallel_for(Begin, End, Fn); +} + +#else +const ptrdiff_t MinParallelSize = 1024; + +/// \brief Inclusive median. +template <class RandomAccessIterator, class Comparator> +RandomAccessIterator medianOf3(RandomAccessIterator Start, + RandomAccessIterator End, + const Comparator &Comp) { + RandomAccessIterator Mid = Start + (std::distance(Start, End) / 2); + return Comp(*Start, *(End - 1)) + ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start) + : End - 1) + : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid : End - 1) + : Start); +} + +template <class RandomAccessIterator, class Comparator> +void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIterator End, + const Comparator &Comp, TaskGroup &TG, size_t Depth) { + // Do a sequential sort for small inputs. + if (std::distance(Start, End) < detail::MinParallelSize || Depth == 0) { + std::sort(Start, End, Comp); + return; + } + + // Partition. + auto Pivot = medianOf3(Start, End, Comp); + // Move Pivot to End. + std::swap(*(End - 1), *Pivot); + Pivot = std::partition(Start, End - 1, [&Comp, End](decltype(*Start) V) { + return Comp(V, *(End - 1)); + }); + // Move Pivot to middle of partition. + std::swap(*Pivot, *(End - 1)); + + // Recurse. + TG.spawn([=, &Comp, &TG] { + parallel_quick_sort(Start, Pivot, Comp, TG, Depth - 1); + }); + parallel_quick_sort(Pivot + 1, End, Comp, TG, Depth - 1); +} + +template <class RandomAccessIterator, class Comparator> +void parallel_sort(RandomAccessIterator Start, RandomAccessIterator End, + const Comparator &Comp) { + TaskGroup TG; + parallel_quick_sort(Start, End, Comp, TG, + llvm::Log2_64(std::distance(Start, End)) + 1); +} + +template <class IterTy, class FuncTy> +void parallel_for_each(IterTy Begin, IterTy End, FuncTy Fn) { + // TaskGroup has a relatively high overhead, so we want to reduce + // the number of spawn() calls. We'll create up to 1024 tasks here. + // (Note that 1024 is an arbitrary number. This code probably needs + // improving to take the number of available cores into account.) + ptrdiff_t TaskSize = std::distance(Begin, End) / 1024; + if (TaskSize == 0) + TaskSize = 1; + + TaskGroup TG; + while (TaskSize <= std::distance(Begin, End)) { + TG.spawn([=, &Fn] { std::for_each(Begin, Begin + TaskSize, Fn); }); + Begin += TaskSize; + } + TG.spawn([=, &Fn] { std::for_each(Begin, End, Fn); }); +} + +template <class IndexTy, class FuncTy> +void parallel_for_each_n(IndexTy Begin, IndexTy End, FuncTy Fn) { + ptrdiff_t TaskSize = (End - Begin) / 1024; + if (TaskSize == 0) + TaskSize = 1; + + TaskGroup TG; + IndexTy I = Begin; + for (; I + TaskSize < End; I += TaskSize) { + TG.spawn([=, &Fn] { + for (IndexTy J = I, E = I + TaskSize; J != E; ++J) + Fn(J); + }); + } + TG.spawn([=, &Fn] { + for (IndexTy J = I; J < End; ++J) + Fn(J); + }); +} + +#endif + +#endif + +template <typename Iter> +using DefComparator = + std::less<typename std::iterator_traits<Iter>::value_type>; + +} // namespace detail + +// sequential algorithm implementations. +template <class Policy, class RandomAccessIterator, + class Comparator = detail::DefComparator<RandomAccessIterator>> +void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, + const Comparator &Comp = Comparator()) { + static_assert(is_execution_policy<Policy>::value, + "Invalid execution policy!"); + std::sort(Start, End, Comp); +} + +template <class Policy, class IterTy, class FuncTy> +void for_each(Policy policy, IterTy Begin, IterTy End, FuncTy Fn) { + static_assert(is_execution_policy<Policy>::value, + "Invalid execution policy!"); + std::for_each(Begin, End, Fn); +} + +template <class Policy, class IndexTy, class FuncTy> +void for_each_n(Policy policy, IndexTy Begin, IndexTy End, FuncTy Fn) { + static_assert(is_execution_policy<Policy>::value, + "Invalid execution policy!"); + for (IndexTy I = Begin; I != End; ++I) + Fn(I); +} + +// Parallel algorithm implementations, only available when LLVM_ENABLE_THREADS +// is true. +#if LLVM_ENABLE_THREADS +template <class RandomAccessIterator, + class Comparator = detail::DefComparator<RandomAccessIterator>> +void sort(parallel_execution_policy policy, RandomAccessIterator Start, + RandomAccessIterator End, const Comparator &Comp = Comparator()) { + detail::parallel_sort(Start, End, Comp); +} + +template <class IterTy, class FuncTy> +void for_each(parallel_execution_policy policy, IterTy Begin, IterTy End, + FuncTy Fn) { + detail::parallel_for_each(Begin, End, Fn); +} + +template <class IndexTy, class FuncTy> +void for_each_n(parallel_execution_policy policy, IndexTy Begin, IndexTy End, + FuncTy Fn) { + detail::parallel_for_each_n(Begin, End, Fn); +} +#endif + +} // namespace parallel +} // namespace llvm + +#endif // LLVM_SUPPORT_PARALLEL_H diff --git a/contrib/llvm/include/llvm/Support/Wasm.h b/contrib/llvm/include/llvm/Support/Wasm.h index a48dfe10b3bb..e3831827062c 100644 --- a/contrib/llvm/include/llvm/Support/Wasm.h +++ b/contrib/llvm/include/llvm/Support/Wasm.h @@ -37,17 +37,6 @@ struct WasmSignature { int32_t ReturnType; }; -struct WasmImport { - StringRef Module; - StringRef Field; - uint32_t Kind; - union { - uint32_t SigIndex; - int32_t GlobalType; - }; - bool GlobalMutable; -}; - struct WasmExport { StringRef Name; uint32_t Kind; @@ -82,6 +71,18 @@ struct WasmGlobal { WasmInitExpr InitExpr; }; +struct WasmImport { + StringRef Module; + StringRef Field; + uint32_t Kind; + union { + uint32_t SigIndex; + WasmGlobal Global; + WasmTable Table; + WasmLimits Memory; + }; +}; + struct WasmLocalDecl { int32_t Type; uint32_t Count; diff --git a/contrib/llvm/include/llvm/Target/Target.td b/contrib/llvm/include/llvm/Target/Target.td index fc35b4527bc3..6f44292c47ed 100644 --- a/contrib/llvm/include/llvm/Target/Target.td +++ b/contrib/llvm/include/llvm/Target/Target.td @@ -680,6 +680,11 @@ class RegisterOperand<RegisterClass regclass, string pm = "printOperand"> // this type. The method normally will just use an alt-name index to look // up the name to print. Default to the generic printOperand(). string PrintMethod = pm; + + // EncoderMethod - The target method name to call to encode this register + // operand. + string EncoderMethod = ""; + // ParserMatchClass - The "match class" that operands of this type fit // in. Match classes are used to define the order in which instructions are // match, to ensure that which instructions gets matched is deterministic. diff --git a/contrib/llvm/include/llvm/Target/TargetInstrInfo.h b/contrib/llvm/include/llvm/Target/TargetInstrInfo.h index 82a682cf1f7e..97a6f0c6e3ae 100644 --- a/contrib/llvm/include/llvm/Target/TargetInstrInfo.h +++ b/contrib/llvm/include/llvm/Target/TargetInstrInfo.h @@ -172,11 +172,22 @@ public: /// inalloca arguments. This function reports only the size of the frame part /// that is set up between the frame setup and destroy pseudo instructions. int64_t getFrameSize(const MachineInstr &I) const { - assert(isFrameInstr(I)); + assert(isFrameInstr(I) && "Not a frame instruction"); assert(I.getOperand(0).getImm() >= 0); return I.getOperand(0).getImm(); } + /// Returns the total frame size, which is made up of the space set up inside + /// the pair of frame start-stop instructions and the space that is set up + /// prior to the pair. + int64_t getFrameTotalSize(const MachineInstr &I) const { + if (isFrameSetup(I)) { + assert(I.getOperand(1).getImm() >= 0 && "Frame size must not be negative"); + return getFrameSize(I) + I.getOperand(1).getImm(); + } + return getFrameSize(I); + } + unsigned getCatchReturnOpcode() const { return CatchRetOpcode; } unsigned getReturnOpcode() const { return ReturnOpcode; } diff --git a/contrib/llvm/include/llvm/Target/TargetLowering.h b/contrib/llvm/include/llvm/Target/TargetLowering.h index ced183852146..1ca32d4c3589 100644 --- a/contrib/llvm/include/llvm/Target/TargetLowering.h +++ b/contrib/llvm/include/llvm/Target/TargetLowering.h @@ -1396,7 +1396,10 @@ public: /// It is called by AtomicExpandPass before expanding an /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad /// if shouldInsertFencesForAtomic returns true. - /// RMW and CmpXchg set both IsStore and IsLoad to true. + /// + /// Inst is the original atomic instruction, prior to other expansions that + /// may be performed. + /// /// This function should either return a nullptr, or a pointer to an IR-level /// Instruction*. Even complex fence sequences can be represented by a /// single Instruction* through an intrinsic to be lowered later. @@ -1422,18 +1425,17 @@ public: /// seq_cst. But if they are lowered to monotonic accesses, no amount of /// IR-level fences can prevent it. /// @{ - virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { - if (isReleaseOrStronger(Ord) && IsStore) + virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst, + AtomicOrdering Ord) const { + if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore()) return Builder.CreateFence(Ord); else return nullptr; } virtual Instruction *emitTrailingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { + Instruction *Inst, + AtomicOrdering Ord) const { if (isAcquireOrStronger(Ord)) return Builder.CreateFence(Ord); else @@ -2061,14 +2063,6 @@ public: return false; } - // Return true if the instruction that performs a << b actually performs - // a << (b % (sizeof(a) * 8)). - virtual bool supportsModuloShift(ISD::NodeType Inst, EVT ReturnType) const { - assert((Inst == ISD::SHL || Inst == ISD::SRA || Inst == ISD::SRL) && - "Expect a shift instruction"); - return false; - } - //===--------------------------------------------------------------------===// // Runtime Library hooks // diff --git a/contrib/llvm/include/llvm/Target/TargetSchedule.td b/contrib/llvm/include/llvm/Target/TargetSchedule.td index d342e4fe2613..7b00c9420e35 100644 --- a/contrib/llvm/include/llvm/Target/TargetSchedule.td +++ b/contrib/llvm/include/llvm/Target/TargetSchedule.td @@ -334,7 +334,7 @@ class ReadAdvance<SchedRead read, int cycles, list<SchedWrite> writes = []> } // Directly associate a new SchedRead type with a delay and optional -// pipeline bypess. For use with InstRW or ItinRW. +// pipeline bypass. For use with InstRW or ItinRW. class SchedReadAdvance<int cycles, list<SchedWrite> writes = []> : SchedRead, ProcReadAdvance<cycles, writes>; diff --git a/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td b/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td index 45a842f77a21..9ed614ccee17 100644 --- a/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td +++ b/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td @@ -281,7 +281,7 @@ def SDTConvertOp : SDTypeProfile<1, 5, [ //cvtss, su, us, uu, ff, fs, fu, sf, su ]>; class SDCallSeqStart<list<SDTypeConstraint> constraints> : - SDTypeProfile<0, 1, constraints>; + SDTypeProfile<0, 2, constraints>; class SDCallSeqEnd<list<SDTypeConstraint> constraints> : SDTypeProfile<0, 2, constraints>; diff --git a/contrib/llvm/include/llvm/LibDriver/LibDriver.h b/contrib/llvm/include/llvm/ToolDrivers/llvm-lib/LibDriver.h index 95feb60be403..a4806ac4ad69 100644 --- a/contrib/llvm/include/llvm/LibDriver/LibDriver.h +++ b/contrib/llvm/include/llvm/ToolDrivers/llvm-lib/LibDriver.h @@ -1,4 +1,4 @@ -//===- llvm/LibDriver/LibDriver.h - lib.exe-compatible driver ---*- C++ -*-===// +//===- llvm-lib/LibDriver.h - lib.exe-compatible driver ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -12,8 +12,8 @@ // //===----------------------------------------------------------------------===// -#ifndef LLVM_LIBDRIVER_LIBDRIVER_H -#define LLVM_LIBDRIVER_LIBDRIVER_H +#ifndef LLVM_TOOLDRIVERS_LLVM_LIB_LIBDRIVER_H +#define LLVM_TOOLDRIVERS_LLVM_LIB_LIBDRIVER_H namespace llvm { template <typename T> class ArrayRef; diff --git a/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h b/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h index 0a8903a6ed7b..91c9d255302f 100644 --- a/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h +++ b/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h @@ -43,6 +43,7 @@ class InvokeInst; class Loop; class LoopInfo; class Module; +class ProfileSummaryInfo; class ReturnInst; /// Return an exact copy of the specified module @@ -175,15 +176,17 @@ public: explicit InlineFunctionInfo(CallGraph *cg = nullptr, std::function<AssumptionCache &(Function &)> *GetAssumptionCache = nullptr, + ProfileSummaryInfo *PSI = nullptr, BlockFrequencyInfo *CallerBFI = nullptr, BlockFrequencyInfo *CalleeBFI = nullptr) - : CG(cg), GetAssumptionCache(GetAssumptionCache), CallerBFI(CallerBFI), - CalleeBFI(CalleeBFI) {} + : CG(cg), GetAssumptionCache(GetAssumptionCache), PSI(PSI), + CallerBFI(CallerBFI), CalleeBFI(CalleeBFI) {} /// CG - If non-null, InlineFunction will update the callgraph to reflect the /// changes it makes. CallGraph *CG; std::function<AssumptionCache &(Function &)> *GetAssumptionCache; + ProfileSummaryInfo *PSI; BlockFrequencyInfo *CallerBFI, *CalleeBFI; /// StaticAllocas - InlineFunction fills this in with all static allocas that diff --git a/contrib/llvm/include/llvm/Transforms/Utils/LoopUtils.h b/contrib/llvm/include/llvm/Transforms/Utils/LoopUtils.h index a1cf41d6f931..561f94880624 100644 --- a/contrib/llvm/include/llvm/Transforms/Utils/LoopUtils.h +++ b/contrib/llvm/include/llvm/Transforms/Utils/LoopUtils.h @@ -21,6 +21,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/EHPersonalities.h" +#include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstrTypes.h" @@ -42,6 +43,7 @@ class PredIteratorCache; class ScalarEvolution; class SCEV; class TargetLibraryInfo; +class TargetTransformInfo; /// \brief Captures loop safety information. /// It keep information for loop & its header may throw exception. @@ -489,6 +491,36 @@ bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE = nullptr); +/// Generates a vector reduction using shufflevectors to reduce the value. +Value *getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, + RecurrenceDescriptor::MinMaxRecurrenceKind + MinMaxKind = RecurrenceDescriptor::MRK_Invalid, + ArrayRef<Value *> RedOps = ArrayRef<Value *>()); + +/// Create a target reduction of the given vector. The reduction operation +/// is described by the \p Opcode parameter. min/max reductions require +/// additional information supplied in \p Flags. +/// The target is queried to determine if intrinsics or shuffle sequences are +/// required to implement the reduction. +Value * +createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, + unsigned Opcode, Value *Src, + TargetTransformInfo::ReductionFlags Flags = + TargetTransformInfo::ReductionFlags(), + ArrayRef<Value *> RedOps = ArrayRef<Value *>()); + +/// Create a generic target reduction using a recurrence descriptor \p Desc +/// The target is queried to determine if intrinsics or shuffle sequences are +/// required to implement the reduction. +Value *createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, + RecurrenceDescriptor &Desc, Value *Src, + bool NoNaN = false); + +/// Get the intersection (logical and) of all of the potential IR flags +/// of each scalar operation (VL) that will be converted into a vector (I). +/// Flag set: NSW, NUW, exact, and all of fast-math. +void propagateIRFlags(Value *I, ArrayRef<Value *> VL); + } // end namespace llvm #endif // LLVM_TRANSFORMS_UTILS_LOOPUTILS_H diff --git a/contrib/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h b/contrib/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h index 10338f7937e8..c514db41623c 100644 --- a/contrib/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h +++ b/contrib/llvm/include/llvm/Transforms/Vectorize/SLPVectorizer.h @@ -24,6 +24,7 @@ #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/DemandedBits.h" #include "llvm/Analysis/LoopInfo.h" +#include "llvm/Analysis/OptimizationDiagnosticInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Function.h" @@ -59,7 +60,8 @@ public: // Glue for old PM. bool runImpl(Function &F, ScalarEvolution *SE_, TargetTransformInfo *TTI_, TargetLibraryInfo *TLI_, AliasAnalysis *AA_, LoopInfo *LI_, - DominatorTree *DT_, AssumptionCache *AC_, DemandedBits *DB_); + DominatorTree *DT_, AssumptionCache *AC_, DemandedBits *DB_, + OptimizationRemarkEmitter *ORE_); private: /// \brief Collect store and getelementptr instructions and organize them diff --git a/contrib/llvm/include/llvm/module.modulemap b/contrib/llvm/include/llvm/module.modulemap index 59b1f1621039..5e15e8d49802 100644 --- a/contrib/llvm/include/llvm/module.modulemap +++ b/contrib/llvm/include/llvm/module.modulemap @@ -148,6 +148,7 @@ module LLVM_intrinsic_gen { module IR_Attributes { header "IR/Attributes.h" export * } module IR_CallSite { header "IR/CallSite.h" export * } module IR_ConstantFolder { header "IR/ConstantFolder.h" export * } + module IR_GlobalVariable { header "IR/GlobalVariable.h" export * } module IR_NoFolder { header "IR/NoFolder.h" export * } module IR_Module { header "IR/Module.h" export * } module IR_ModuleSummaryIndex { header "IR/ModuleSummaryIndex.h" export * } diff --git a/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp b/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp index 537823020301..a33c01a0e461 100644 --- a/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp +++ b/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp @@ -17,13 +17,13 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AliasAnalysis.h" +#include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/CFG.h" #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/Analysis/ValueTracking.h" -#include "llvm/Analysis/AssumptionCache.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" @@ -36,6 +36,7 @@ #include "llvm/IR/Operator.h" #include "llvm/Pass.h" #include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/KnownBits.h" #include <algorithm> #define DEBUG_TYPE "basicaa" @@ -1283,9 +1284,9 @@ AliasResult BasicAAResult::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size, // give up if we can't determine conditions that hold for every cycle: const Value *V = DecompGEP1.VarIndices[i].V; - bool SignKnownZero, SignKnownOne; - ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, DL, - 0, &AC, nullptr, DT); + KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, DT); + bool SignKnownZero = Known.isNonNegative(); + bool SignKnownOne = Known.isNegative(); // Zero-extension widens the variable, and so forces the sign // bit to zero. diff --git a/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp b/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp index 0dc4475ca0e2..db87b17c1567 100644 --- a/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp +++ b/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp @@ -301,6 +301,8 @@ bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) { WeightSum += Weights[i]; } } + assert(WeightSum <= UINT32_MAX && + "Expected weights to scale down to 32 bits"); if (WeightSum == 0 || ReachableIdxs.size() == 0) { for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) @@ -328,21 +330,14 @@ bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) { // the difference between reachable blocks. if (ToDistribute > BranchProbability::getZero()) { BranchProbability PerEdge = ToDistribute / ReachableIdxs.size(); - for (auto i : ReachableIdxs) { + for (auto i : ReachableIdxs) BP[i] += PerEdge; - ToDistribute -= PerEdge; - } - // Tail goes to the first reachable edge. - BP[ReachableIdxs[0]] += ToDistribute; } } for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) setEdgeProbability(BB, i, BP[i]); - assert(WeightSum <= UINT32_MAX && - "Expected weights to scale down to 32 bits"); - return true; } diff --git a/contrib/llvm/lib/Analysis/CallGraph.cpp b/contrib/llvm/lib/Analysis/CallGraph.cpp index 6942176ae6ae..ff5242f69a1b 100644 --- a/contrib/llvm/lib/Analysis/CallGraph.cpp +++ b/contrib/llvm/lib/Analysis/CallGraph.cpp @@ -21,23 +21,18 @@ using namespace llvm; // CallGraph::CallGraph(Module &M) - : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)), + : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)), CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) { // Add every function to the call graph. for (Function &F : M) addToCallGraph(&F); - - // If we didn't find a main function, use the external call graph node - if (!Root) - Root = ExternalCallingNode; } CallGraph::CallGraph(CallGraph &&Arg) - : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), Root(Arg.Root), + : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), ExternalCallingNode(Arg.ExternalCallingNode), CallsExternalNode(std::move(Arg.CallsExternalNode)) { Arg.FunctionMap.clear(); - Arg.Root = nullptr; Arg.ExternalCallingNode = nullptr; } @@ -57,21 +52,9 @@ CallGraph::~CallGraph() { void CallGraph::addToCallGraph(Function *F) { CallGraphNode *Node = getOrInsertFunction(F); - // If this function has external linkage, anything could call it. - if (!F->hasLocalLinkage()) { - ExternalCallingNode->addCalledFunction(CallSite(), Node); - - // Found the entry point? - if (F->getName() == "main") { - if (Root) // Found multiple external mains? Don't pick one. - Root = ExternalCallingNode; - else - Root = Node; // Found a main, keep track of it! - } - } - - // If this function has its address taken, anything could call it. - if (F->hasAddressTaken()) + // If this function has external linkage or has its address taken, anything + // could call it. + if (!F->hasLocalLinkage() || F->hasAddressTaken()) ExternalCallingNode->addCalledFunction(CallSite(), Node); // If this function is not defined in this translation unit, it could call @@ -96,13 +79,6 @@ void CallGraph::addToCallGraph(Function *F) { } void CallGraph::print(raw_ostream &OS) const { - OS << "CallGraph Root is: "; - if (Function *F = Root->getFunction()) - OS << F->getName() << "\n"; - else { - OS << "<<null function: 0x" << Root << ">>\n"; - } - // Print in a deterministic order by sorting CallGraphNodes by name. We do // this here to avoid slowing down the non-printing fast path. diff --git a/contrib/llvm/lib/Analysis/ConstantFolding.cpp b/contrib/llvm/lib/Analysis/ConstantFolding.cpp index 130e917e49d7..0ca712bbfe70 100644 --- a/contrib/llvm/lib/Analysis/ConstantFolding.cpp +++ b/contrib/llvm/lib/Analysis/ConstantFolding.cpp @@ -1438,6 +1438,36 @@ bool llvm::canConstantFoldCallTo(const Function *F) { Name == "sinf" || Name == "sinhf" || Name == "sqrtf"; case 't': return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf"; + case '_': + + // Check for various function names that get used for the math functions + // when the header files are preprocessed with the macro + // __FINITE_MATH_ONLY__ enabled. + // The '12' here is the length of the shortest name that can match. + // We need to check the size before looking at Name[1] and Name[2] + // so we may as well check a limit that will eliminate mismatches. + if (Name.size() < 12 || Name[1] != '_') + return false; + switch (Name[2]) { + default: + return false; + case 'a': + return Name == "__acos_finite" || Name == "__acosf_finite" || + Name == "__asin_finite" || Name == "__asinf_finite" || + Name == "__atan2_finite" || Name == "__atan2f_finite"; + case 'c': + return Name == "__cosh_finite" || Name == "__coshf_finite"; + case 'e': + return Name == "__exp_finite" || Name == "__expf_finite" || + Name == "__exp2_finite" || Name == "__exp2f_finite"; + case 'l': + return Name == "__log_finite" || Name == "__logf_finite" || + Name == "__log10_finite" || Name == "__log10f_finite"; + case 'p': + return Name == "__pow_finite" || Name == "__powf_finite"; + case 's': + return Name == "__sinh_finite" || Name == "__sinhf_finite"; + } } } @@ -1637,13 +1667,21 @@ Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, if (!TLI) return nullptr; - switch (Name[0]) { + char NameKeyChar = Name[0]; + if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_') + NameKeyChar = Name[2]; + + switch (NameKeyChar) { case 'a': if ((Name == "acos" && TLI->has(LibFunc_acos)) || - (Name == "acosf" && TLI->has(LibFunc_acosf))) + (Name == "acosf" && TLI->has(LibFunc_acosf)) || + (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) || + (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite))) return ConstantFoldFP(acos, V, Ty); else if ((Name == "asin" && TLI->has(LibFunc_asin)) || - (Name == "asinf" && TLI->has(LibFunc_asinf))) + (Name == "asinf" && TLI->has(LibFunc_asinf)) || + (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) || + (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite))) return ConstantFoldFP(asin, V, Ty); else if ((Name == "atan" && TLI->has(LibFunc_atan)) || (Name == "atanf" && TLI->has(LibFunc_atanf))) @@ -1657,15 +1695,21 @@ Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, (Name == "cosf" && TLI->has(LibFunc_cosf))) return ConstantFoldFP(cos, V, Ty); else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) || - (Name == "coshf" && TLI->has(LibFunc_coshf))) + (Name == "coshf" && TLI->has(LibFunc_coshf)) || + (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) || + (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite))) return ConstantFoldFP(cosh, V, Ty); break; case 'e': if ((Name == "exp" && TLI->has(LibFunc_exp)) || - (Name == "expf" && TLI->has(LibFunc_expf))) + (Name == "expf" && TLI->has(LibFunc_expf)) || + (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) || + (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite))) return ConstantFoldFP(exp, V, Ty); if ((Name == "exp2" && TLI->has(LibFunc_exp2)) || - (Name == "exp2f" && TLI->has(LibFunc_exp2f))) + (Name == "exp2f" && TLI->has(LibFunc_exp2f)) || + (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) || + (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite))) // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a // C99 library. return ConstantFoldBinaryFP(pow, 2.0, V, Ty); @@ -1680,10 +1724,18 @@ Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, break; case 'l': if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) || - (Name == "logf" && V > 0 && TLI->has(LibFunc_logf))) + (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) || + (Name == "__log_finite" && V > 0 && + TLI->has(LibFunc_log_finite)) || + (Name == "__logf_finite" && V > 0 && + TLI->has(LibFunc_logf_finite))) return ConstantFoldFP(log, V, Ty); else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) || - (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f))) + (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) || + (Name == "__log10_finite" && V > 0 && + TLI->has(LibFunc_log10_finite)) || + (Name == "__log10f_finite" && V > 0 && + TLI->has(LibFunc_log10f_finite))) return ConstantFoldFP(log10, V, Ty); break; case 'r': @@ -1695,7 +1747,9 @@ Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, (Name == "sinf" && TLI->has(LibFunc_sinf))) return ConstantFoldFP(sin, V, Ty); else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) || - (Name == "sinhf" && TLI->has(LibFunc_sinhf))) + (Name == "sinhf" && TLI->has(LibFunc_sinhf)) || + (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) || + (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite))) return ConstantFoldFP(sinh, V, Ty); else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) || (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf))) @@ -1813,13 +1867,17 @@ Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, if (!TLI) return nullptr; if ((Name == "pow" && TLI->has(LibFunc_pow)) || - (Name == "powf" && TLI->has(LibFunc_powf))) + (Name == "powf" && TLI->has(LibFunc_powf)) || + (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) || + (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite))) return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); if ((Name == "fmod" && TLI->has(LibFunc_fmod)) || (Name == "fmodf" && TLI->has(LibFunc_fmodf))) return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty); if ((Name == "atan2" && TLI->has(LibFunc_atan2)) || - (Name == "atan2f" && TLI->has(LibFunc_atan2f))) + (Name == "atan2f" && TLI->has(LibFunc_atan2f)) || + (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) || + (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite))) return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty); } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) { if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy()) diff --git a/contrib/llvm/lib/Analysis/DemandedBits.cpp b/contrib/llvm/lib/Analysis/DemandedBits.cpp index 9f5dc5318239..8f808f3e7871 100644 --- a/contrib/llvm/lib/Analysis/DemandedBits.cpp +++ b/contrib/llvm/lib/Analysis/DemandedBits.cpp @@ -86,13 +86,11 @@ void DemandedBits::determineLiveOperandBits( [&](unsigned BitWidth, const Value *V1, const Value *V2) { const DataLayout &DL = I->getModule()->getDataLayout(); Known = KnownBits(BitWidth); - computeKnownBits(const_cast<Value *>(V1), Known, DL, 0, - &AC, UserI, &DT); + computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT); if (V2) { Known2 = KnownBits(BitWidth); - computeKnownBits(const_cast<Value *>(V2), Known2, DL, - 0, &AC, UserI, &DT); + computeKnownBits(V2, Known2, DL, 0, &AC, UserI, &DT); } }; @@ -118,7 +116,7 @@ void DemandedBits::determineLiveOperandBits( // known to be one. ComputeKnownBits(BitWidth, I, nullptr); AB = APInt::getHighBitsSet(BitWidth, - std::min(BitWidth, Known.One.countLeadingZeros()+1)); + std::min(BitWidth, Known.countMaxLeadingZeros()+1)); } break; case Intrinsic::cttz: @@ -128,7 +126,7 @@ void DemandedBits::determineLiveOperandBits( // known to be one. ComputeKnownBits(BitWidth, I, nullptr); AB = APInt::getLowBitsSet(BitWidth, - std::min(BitWidth, Known.One.countTrailingZeros()+1)); + std::min(BitWidth, Known.countMaxTrailingZeros()+1)); } break; } diff --git a/contrib/llvm/lib/Analysis/InlineCost.cpp b/contrib/llvm/lib/Analysis/InlineCost.cpp index 100a591e452c..44c14cb17c22 100644 --- a/contrib/llvm/lib/Analysis/InlineCost.cpp +++ b/contrib/llvm/lib/Analysis/InlineCost.cpp @@ -63,7 +63,7 @@ static cl::opt<bool> // PGO before we actually hook up inliner with analysis passes such as BPI and // BFI. static cl::opt<int> ColdThreshold( - "inlinecold-threshold", cl::Hidden, cl::init(225), + "inlinecold-threshold", cl::Hidden, cl::init(45), cl::desc("Threshold for inlining functions with cold attribute")); static cl::opt<int> diff --git a/contrib/llvm/lib/Analysis/InstructionSimplify.cpp b/contrib/llvm/lib/Analysis/InstructionSimplify.cpp index 4a713f441ce8..5728887cc1e9 100644 --- a/contrib/llvm/lib/Analysis/InstructionSimplify.cpp +++ b/contrib/llvm/lib/Analysis/InstructionSimplify.cpp @@ -1317,7 +1317,7 @@ static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0, // If all valid bits in the shift amount are known zero, the first operand is // unchanged. unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth); - if (Known.Zero.countTrailingOnes() >= NumValidShiftBits) + if (Known.countMinTrailingZeros() >= NumValidShiftBits) return Op0; return nullptr; @@ -1536,7 +1536,7 @@ static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0); auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1); - // For and-of-comapares, check if the intersection is empty: + // For and-of-compares, check if the intersection is empty: // (icmp X, C0) && (icmp X, C1) --> empty set --> false if (IsAnd && Range0.intersectWith(Range1).isEmptySet()) return getFalse(Cmp0->getType()); @@ -1870,6 +1870,24 @@ static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) return Op0; + // (A & B) | (~A ^ B) -> (~A ^ B) + // (B & A) | (~A ^ B) -> (~A ^ B) + // (A & B) | (B ^ ~A) -> (B ^ ~A) + // (B & A) | (B ^ ~A) -> (B ^ ~A) + if (match(Op0, m_And(m_Value(A), m_Value(B))) && + (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || + match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) + return Op1; + + // (~A ^ B) | (A & B) -> (~A ^ B) + // (~A ^ B) | (B & A) -> (~A ^ B) + // (B ^ ~A) | (A & B) -> (B ^ ~A) + // (B ^ ~A) | (B & A) -> (B ^ ~A) + if (match(Op1, m_And(m_Value(A), m_Value(B))) && + (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || + match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) + return Op0; + if (Value *V = simplifyAndOrOfICmps(Op0, Op1, false)) return V; @@ -2286,7 +2304,6 @@ static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, return nullptr; Type *ITy = GetCompareTy(LHS); // The return type. - bool LHSKnownNonNegative, LHSKnownNegative; switch (Pred) { default: llvm_unreachable("Unknown ICmp predicate!"); @@ -2304,39 +2321,41 @@ static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) return getTrue(ITy); break; - case ICmpInst::ICMP_SLT: - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (LHSKnownNegative) + case ICmpInst::ICMP_SLT: { + KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (LHSKnown.isNegative()) return getTrue(ITy); - if (LHSKnownNonNegative) + if (LHSKnown.isNonNegative()) return getFalse(ITy); break; - case ICmpInst::ICMP_SLE: - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (LHSKnownNegative) + } + case ICmpInst::ICMP_SLE: { + KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (LHSKnown.isNegative()) return getTrue(ITy); - if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) + if (LHSKnown.isNonNegative() && + isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) return getFalse(ITy); break; - case ICmpInst::ICMP_SGE: - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (LHSKnownNegative) + } + case ICmpInst::ICMP_SGE: { + KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (LHSKnown.isNegative()) return getFalse(ITy); - if (LHSKnownNonNegative) + if (LHSKnown.isNonNegative()) return getTrue(ITy); break; - case ICmpInst::ICMP_SGT: - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (LHSKnownNegative) + } + case ICmpInst::ICMP_SGT: { + KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (LHSKnown.isNegative()) return getFalse(ITy); - if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) + if (LHSKnown.isNonNegative() && + isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) return getTrue(ITy); break; } + } return nullptr; } @@ -2535,6 +2554,9 @@ static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, return nullptr; } +/// TODO: A large part of this logic is duplicated in InstCombine's +/// foldICmpBinOp(). We should be able to share that and avoid the code +/// duplication. static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q, unsigned MaxRecurse) { @@ -2616,15 +2638,11 @@ static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, return getTrue(ITy); if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { - bool RHSKnownNonNegative, RHSKnownNegative; - bool YKnownNonNegative, YKnownNegative; - ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0, - Q.AC, Q.CxtI, Q.DT); - ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (RHSKnownNonNegative && YKnownNegative) + KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (RHSKnown.isNonNegative() && YKnown.isNegative()) return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); - if (RHSKnownNegative || YKnownNonNegative) + if (RHSKnown.isNegative() || YKnown.isNonNegative()) return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); } } @@ -2636,15 +2654,11 @@ static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, return getFalse(ITy); if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) { - bool LHSKnownNonNegative, LHSKnownNegative; - bool YKnownNonNegative, YKnownNegative; - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, - Q.AC, Q.CxtI, Q.DT); - ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (LHSKnownNonNegative && YKnownNegative) + KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (LHSKnown.isNonNegative() && YKnown.isNegative()) return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy); - if (LHSKnownNegative || YKnownNonNegative) + if (LHSKnown.isNegative() || YKnown.isNonNegative()) return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy); } } @@ -2691,28 +2705,27 @@ static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, // icmp pred (urem X, Y), Y if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { - bool KnownNonNegative, KnownNegative; switch (Pred) { default: break; case ICmpInst::ICMP_SGT: - case ICmpInst::ICMP_SGE: - ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (!KnownNonNegative) + case ICmpInst::ICMP_SGE: { + KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (!Known.isNonNegative()) break; LLVM_FALLTHROUGH; + } case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_UGE: return getFalse(ITy); case ICmpInst::ICMP_SLT: - case ICmpInst::ICMP_SLE: - ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (!KnownNonNegative) + case ICmpInst::ICMP_SLE: { + KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (!Known.isNonNegative()) break; LLVM_FALLTHROUGH; + } case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: @@ -2722,28 +2735,27 @@ static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, // icmp pred X, (urem Y, X) if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { - bool KnownNonNegative, KnownNegative; switch (Pred) { default: break; case ICmpInst::ICMP_SGT: - case ICmpInst::ICMP_SGE: - ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (!KnownNonNegative) + case ICmpInst::ICMP_SGE: { + KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (!Known.isNonNegative()) break; LLVM_FALLTHROUGH; + } case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_UGE: return getTrue(ITy); case ICmpInst::ICMP_SLT: - case ICmpInst::ICMP_SLE: - ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC, - Q.CxtI, Q.DT); - if (!KnownNonNegative) + case ICmpInst::ICMP_SLE: { + KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); + if (!Known.isNonNegative()) break; LLVM_FALLTHROUGH; + } case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: @@ -2815,10 +2827,19 @@ static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, break; case Instruction::UDiv: case Instruction::LShr: - if (ICmpInst::isSigned(Pred)) + if (ICmpInst::isSigned(Pred) || !LBO->isExact() || !RBO->isExact()) break; - LLVM_FALLTHROUGH; + if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), + RBO->getOperand(0), Q, MaxRecurse - 1)) + return V; + break; case Instruction::SDiv: + if (!ICmpInst::isEquality(Pred) || !LBO->isExact() || !RBO->isExact()) + break; + if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), + RBO->getOperand(0), Q, MaxRecurse - 1)) + return V; + break; case Instruction::AShr: if (!LBO->isExact() || !RBO->isExact()) break; @@ -4034,24 +4055,21 @@ Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, /// match a root vector source operand that contains that element in the same /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, - Constant *Mask, Value *RootVec, int RootElt, + int MaskVal, Value *RootVec, unsigned MaxRecurse) { if (!MaxRecurse--) return nullptr; // Bail out if any mask value is undefined. That kind of shuffle may be // simplified further based on demanded bits or other folds. - int MaskVal = ShuffleVectorInst::getMaskValue(Mask, RootElt); if (MaskVal == -1) return nullptr; // The mask value chooses which source operand we need to look at next. - Value *SourceOp; int InVecNumElts = Op0->getType()->getVectorNumElements(); - if (MaskVal < InVecNumElts) { - RootElt = MaskVal; - SourceOp = Op0; - } else { + int RootElt = MaskVal; + Value *SourceOp = Op0; + if (MaskVal >= InVecNumElts) { RootElt = MaskVal - InVecNumElts; SourceOp = Op1; } @@ -4061,7 +4079,7 @@ static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { return foldIdentityShuffles( DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), - SourceShuf->getMask(), RootVec, RootElt, MaxRecurse); + SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); } // TODO: Look through bitcasts? What if the bitcast changes the vector element @@ -4126,17 +4144,7 @@ static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, // second one. if (Op0Const && !Op1Const) { std::swap(Op0, Op1); - for (int &Idx : Indices) { - if (Idx == -1) - continue; - Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; - assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 && - "shufflevector mask index out of range"); - } - Mask = ConstantDataVector::get( - Mask->getContext(), - makeArrayRef(reinterpret_cast<uint32_t *>(Indices.data()), - MaskNumElts)); + ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts); } // A shuffle of a splat is always the splat itself. Legal if the shuffle's @@ -4160,7 +4168,8 @@ static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, for (unsigned i = 0; i != MaskNumElts; ++i) { // Note that recursion is limited for each vector element, so if any element // exceeds the limit, this will fail to simplify. - RootVec = foldIdentityShuffles(i, Op0, Op1, Mask, RootVec, i, MaxRecurse); + RootVec = + foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); // We can't replace a widening/narrowing shuffle with one of its operands. if (!RootVec || RootVec->getType() != RetTy) diff --git a/contrib/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp b/contrib/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp index 99f900ae3932..26706f5509ba 100644 --- a/contrib/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp +++ b/contrib/llvm/lib/Analysis/ModuleSummaryAnalysis.cpp @@ -232,7 +232,7 @@ computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M, } // We should have named any anonymous globals assert(CalledFunction->hasName()); - auto ScaledCount = ProfileSummaryInfo::getProfileCount(&I, BFI); + auto ScaledCount = PSI->getProfileCount(&I, BFI); auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI) : CalleeInfo::HotnessType::Unknown; @@ -330,6 +330,7 @@ ModuleSummaryIndex llvm::buildModuleSummaryIndex( const Module &M, std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI) { + assert(PSI); ModuleSummaryIndex Index; // Identify the local values in the llvm.used and llvm.compiler.used sets, diff --git a/contrib/llvm/lib/Analysis/OptimizationDiagnosticInfo.cpp b/contrib/llvm/lib/Analysis/OptimizationDiagnosticInfo.cpp index 73245981b022..e38e530c052d 100644 --- a/contrib/llvm/lib/Analysis/OptimizationDiagnosticInfo.cpp +++ b/contrib/llvm/lib/Analysis/OptimizationDiagnosticInfo.cpp @@ -101,7 +101,7 @@ void MappingTraits<DiagnosticInfoOptimizationBase *>::mapping( // These are read-only for now. DiagnosticLocation DL = OptDiag->getLocation(); StringRef FN = - GlobalValue::getRealLinkageName(OptDiag->getFunction().getName()); + GlobalValue::dropLLVMManglingEscape(OptDiag->getFunction().getName()); StringRef PassName(OptDiag->PassName); io.mapRequired("Pass", PassName); diff --git a/contrib/llvm/lib/Analysis/ProfileSummaryInfo.cpp b/contrib/llvm/lib/Analysis/ProfileSummaryInfo.cpp index 1a53a8ed4283..502f4205b689 100644 --- a/contrib/llvm/lib/Analysis/ProfileSummaryInfo.cpp +++ b/contrib/llvm/lib/Analysis/ProfileSummaryInfo.cpp @@ -75,11 +75,14 @@ ProfileSummaryInfo::getProfileCount(const Instruction *Inst, return None; assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) && "We can only get profile count for call/invoke instruction."); - // Check if there is a profile metadata on the instruction. If it is present, - // determine hotness solely based on that. - uint64_t TotalCount; - if (Inst->extractProfTotalWeight(TotalCount)) - return TotalCount; + if (computeSummary() && Summary->getKind() == ProfileSummary::PSK_Sample) { + // In sample PGO mode, check if there is a profile metadata on the + // instruction. If it is present, determine hotness solely based on that, + // since the sampled entry count may not be accurate. + uint64_t TotalCount; + if (Inst->extractProfTotalWeight(TotalCount)) + return TotalCount; + } if (BFI) return BFI->getBlockProfileCount(Inst->getParent()); return None; diff --git a/contrib/llvm/lib/Analysis/ScalarEvolution.cpp b/contrib/llvm/lib/Analysis/ScalarEvolution.cpp index 01dca0793145..800354d2f5b4 100644 --- a/contrib/llvm/lib/Analysis/ScalarEvolution.cpp +++ b/contrib/llvm/lib/Analysis/ScalarEvolution.cpp @@ -584,7 +584,7 @@ CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, static int CompareSCEVComplexity( SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV, const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, - unsigned Depth = 0) { + DominatorTree &DT, unsigned Depth = 0) { // Fast-path: SCEVs are uniqued so we can do a quick equality check. if (LHS == RHS) return 0; @@ -629,9 +629,16 @@ static int CompareSCEVComplexity( const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); - // Compare addrec loop depths. + // If there is a dominance relationship between the loops, sort by the + // dominance. Otherwise, sort by depth. We require such order in getAddExpr. const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); if (LLoop != RLoop) { + const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); + assert(LHead != RHead && "Two loops share the same header?"); + if (DT.dominates(LHead, RHead)) + return 1; + else if (DT.dominates(RHead, LHead)) + return -1; unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); if (LDepth != RDepth) return (int)LDepth - (int)RDepth; @@ -645,7 +652,7 @@ static int CompareSCEVComplexity( // Lexicographically compare. for (unsigned i = 0; i != LNumOps; ++i) { int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i), - RA->getOperand(i), Depth + 1); + RA->getOperand(i), DT, Depth + 1); if (X != 0) return X; } @@ -669,7 +676,7 @@ static int CompareSCEVComplexity( if (i >= RNumOps) return 1; int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i), - RC->getOperand(i), Depth + 1); + RC->getOperand(i), DT, Depth + 1); if (X != 0) return X; } @@ -683,10 +690,10 @@ static int CompareSCEVComplexity( // Lexicographically compare udiv expressions. int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(), - Depth + 1); + DT, Depth + 1); if (X != 0) return X; - X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), + X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT, Depth + 1); if (X == 0) EqCacheSCEV.insert({LHS, RHS}); @@ -701,7 +708,7 @@ static int CompareSCEVComplexity( // Compare cast expressions by operand. int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(), - RC->getOperand(), Depth + 1); + RC->getOperand(), DT, Depth + 1); if (X == 0) EqCacheSCEV.insert({LHS, RHS}); return X; @@ -724,7 +731,7 @@ static int CompareSCEVComplexity( /// land in memory. /// static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, - LoopInfo *LI) { + LoopInfo *LI, DominatorTree &DT) { if (Ops.size() < 2) return; // Noop SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache; @@ -732,15 +739,16 @@ static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, // This is the common case, which also happens to be trivially simple. // Special case it. const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; - if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0) + if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0) std::swap(LHS, RHS); return; } // Do the rough sort by complexity. std::stable_sort(Ops.begin(), Ops.end(), - [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) { - return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0; + [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) { + return + CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0; }); // Now that we are sorted by complexity, group elements of the same @@ -2186,7 +2194,7 @@ const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, #endif // Sort by complexity, this groups all similar expression types together. - GroupByComplexity(Ops, &LI); + GroupByComplexity(Ops, &LI, DT); Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); @@ -2492,7 +2500,13 @@ const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, // added together. If so, we can fold them. for (unsigned OtherIdx = Idx+1; OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); - ++OtherIdx) + ++OtherIdx) { + // We expect the AddRecExpr's to be sorted in reverse dominance order, + // so that the 1st found AddRecExpr is dominated by all others. + assert(DT.dominates( + cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), + AddRec->getLoop()->getHeader()) && + "AddRecExprs are not sorted in reverse dominance order?"); if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), @@ -2518,6 +2532,7 @@ const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); } + } // Otherwise couldn't fold anything into this recurrence. Move onto the // next one. @@ -2614,7 +2629,7 @@ const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, #endif // Sort by complexity, this groups all similar expression types together. - GroupByComplexity(Ops, &LI); + GroupByComplexity(Ops, &LI, DT); Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); @@ -3211,7 +3226,7 @@ ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { #endif // Sort by complexity, this groups all similar expression types together. - GroupByComplexity(Ops, &LI); + GroupByComplexity(Ops, &LI, DT); // If there are any constants, fold them together. unsigned Idx = 0; @@ -3312,7 +3327,7 @@ ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { #endif // Sort by complexity, this groups all similar expression types together. - GroupByComplexity(Ops, &LI); + GroupByComplexity(Ops, &LI, DT); // If there are any constants, fold them together. unsigned Idx = 0; @@ -4636,7 +4651,7 @@ uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { KnownBits Known(BitWidth); computeKnownBits(U->getValue(), Known, getDataLayout(), 0, &AC, nullptr, &DT); - return Known.Zero.countTrailingOnes(); + return Known.countMinTrailingZeros(); } // SCEVUDivExpr @@ -5955,6 +5970,30 @@ bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, return false; } +ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) + : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {} + +ScalarEvolution::ExitLimit::ExitLimit( + const SCEV *E, const SCEV *M, bool MaxOrZero, + ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) + : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { + assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || + !isa<SCEVCouldNotCompute>(MaxNotTaken)) && + "Exact is not allowed to be less precise than Max"); + for (auto *PredSet : PredSetList) + for (auto *P : *PredSet) + addPredicate(P); +} + +ScalarEvolution::ExitLimit::ExitLimit( + const SCEV *E, const SCEV *M, bool MaxOrZero, + const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) + : ExitLimit(E, M, MaxOrZero, {&PredSet}) {} + +ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, + bool MaxOrZero) + : ExitLimit(E, M, MaxOrZero, None) {} + /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each /// computable exit into a persistent ExitNotTakenInfo array. ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( @@ -6637,13 +6676,12 @@ ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most // bitwidth(K) iterations. Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); - bool KnownZero, KnownOne; - ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, - Predecessor->getTerminator(), &DT); + KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, + Predecessor->getTerminator(), &DT); auto *Ty = cast<IntegerType>(RHS->getType()); - if (KnownZero) + if (Known.isNonNegative()) StableValue = ConstantInt::get(Ty, 0); - else if (KnownOne) + else if (Known.isNegative()) StableValue = ConstantInt::get(Ty, -1, true); else return getCouldNotCompute(); @@ -7377,48 +7415,49 @@ SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { const APInt &N = NC->getAPInt(); APInt Two(BitWidth, 2); - { - using namespace APIntOps; - const APInt& C = L; - // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C - // The B coefficient is M-N/2 - APInt B(M); - B -= N.sdiv(Two); + // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C - // The A coefficient is N/2 - APInt A(N.sdiv(Two)); + // The A coefficient is N/2 + APInt A = N.sdiv(Two); - // Compute the B^2-4ac term. - APInt SqrtTerm(B); - SqrtTerm *= B; - SqrtTerm -= 4 * (A * C); + // The B coefficient is M-N/2 + APInt B = M; + B -= A; // A is the same as N/2. - if (SqrtTerm.isNegative()) { - // The loop is provably infinite. - return None; - } + // The C coefficient is L. + const APInt& C = L; - // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest - // integer value or else APInt::sqrt() will assert. - APInt SqrtVal(SqrtTerm.sqrt()); + // Compute the B^2-4ac term. + APInt SqrtTerm = B; + SqrtTerm *= B; + SqrtTerm -= 4 * (A * C); - // Compute the two solutions for the quadratic formula. - // The divisions must be performed as signed divisions. - APInt NegB(-B); - APInt TwoA(A << 1); - if (TwoA.isMinValue()) - return None; + if (SqrtTerm.isNegative()) { + // The loop is provably infinite. + return None; + } + + // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest + // integer value or else APInt::sqrt() will assert. + APInt SqrtVal = SqrtTerm.sqrt(); + + // Compute the two solutions for the quadratic formula. + // The divisions must be performed as signed divisions. + APInt NegB = -std::move(B); + APInt TwoA = std::move(A); + TwoA <<= 1; + if (TwoA.isNullValue()) + return None; - LLVMContext &Context = SE.getContext(); + LLVMContext &Context = SE.getContext(); - ConstantInt *Solution1 = - ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); - ConstantInt *Solution2 = - ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); + ConstantInt *Solution1 = + ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); + ConstantInt *Solution2 = + ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); - return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), - cast<SCEVConstant>(SE.getConstant(Solution2))); - } // end APIntOps namespace + return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), + cast<SCEVConstant>(SE.getConstant(Solution2))); } ScalarEvolution::ExitLimit @@ -8976,7 +9015,7 @@ bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, .getSignedMax(); // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! - return (std::move(MaxValue) - std::move(MaxStrideMinusOne)).slt(MaxRHS); + return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); } APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); @@ -8985,7 +9024,7 @@ bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, .getUnsignedMax(); // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! - return (std::move(MaxValue) - std::move(MaxStrideMinusOne)).ult(MaxRHS); + return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); } bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, @@ -9002,7 +9041,7 @@ bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, .getSignedMax(); // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! - return (std::move(MinValue) + std::move(MaxStrideMinusOne)).sgt(MinRHS); + return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); } APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); @@ -9011,7 +9050,7 @@ bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, .getUnsignedMax(); // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! - return (std::move(MinValue) + std::move(MaxStrideMinusOne)).ugt(MinRHS); + return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); } const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, diff --git a/contrib/llvm/lib/Analysis/TargetLibraryInfo.cpp b/contrib/llvm/lib/Analysis/TargetLibraryInfo.cpp index 848e1b4717b5..3cf1bbc5daa5 100644 --- a/contrib/llvm/lib/Analysis/TargetLibraryInfo.cpp +++ b/contrib/llvm/lib/Analysis/TargetLibraryInfo.cpp @@ -241,6 +241,50 @@ static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, TLI.setUnavailable(LibFunc_tanhf); } + // These definitions are due to math-finite.h header on Linux + TLI.setUnavailable(LibFunc_acos_finite); + TLI.setUnavailable(LibFunc_acosf_finite); + TLI.setUnavailable(LibFunc_acosl_finite); + TLI.setUnavailable(LibFunc_acosh_finite); + TLI.setUnavailable(LibFunc_acoshf_finite); + TLI.setUnavailable(LibFunc_acoshl_finite); + TLI.setUnavailable(LibFunc_asin_finite); + TLI.setUnavailable(LibFunc_asinf_finite); + TLI.setUnavailable(LibFunc_asinl_finite); + TLI.setUnavailable(LibFunc_atan2_finite); + TLI.setUnavailable(LibFunc_atan2f_finite); + TLI.setUnavailable(LibFunc_atan2l_finite); + TLI.setUnavailable(LibFunc_atanh_finite); + TLI.setUnavailable(LibFunc_atanhf_finite); + TLI.setUnavailable(LibFunc_atanhl_finite); + TLI.setUnavailable(LibFunc_cosh_finite); + TLI.setUnavailable(LibFunc_coshf_finite); + TLI.setUnavailable(LibFunc_coshl_finite); + TLI.setUnavailable(LibFunc_exp10_finite); + TLI.setUnavailable(LibFunc_exp10f_finite); + TLI.setUnavailable(LibFunc_exp10l_finite); + TLI.setUnavailable(LibFunc_exp2_finite); + TLI.setUnavailable(LibFunc_exp2f_finite); + TLI.setUnavailable(LibFunc_exp2l_finite); + TLI.setUnavailable(LibFunc_exp_finite); + TLI.setUnavailable(LibFunc_expf_finite); + TLI.setUnavailable(LibFunc_expl_finite); + TLI.setUnavailable(LibFunc_log10_finite); + TLI.setUnavailable(LibFunc_log10f_finite); + TLI.setUnavailable(LibFunc_log10l_finite); + TLI.setUnavailable(LibFunc_log2_finite); + TLI.setUnavailable(LibFunc_log2f_finite); + TLI.setUnavailable(LibFunc_log2l_finite); + TLI.setUnavailable(LibFunc_log_finite); + TLI.setUnavailable(LibFunc_logf_finite); + TLI.setUnavailable(LibFunc_logl_finite); + TLI.setUnavailable(LibFunc_pow_finite); + TLI.setUnavailable(LibFunc_powf_finite); + TLI.setUnavailable(LibFunc_powl_finite); + TLI.setUnavailable(LibFunc_sinh_finite); + TLI.setUnavailable(LibFunc_sinhf_finite); + TLI.setUnavailable(LibFunc_sinhl_finite); + // Win32 does *not* provide provide these functions, but they are // generally available on POSIX-compliant systems: TLI.setUnavailable(LibFunc_access); @@ -496,7 +540,7 @@ static StringRef sanitizeFunctionName(StringRef funcName) { // Check for \01 prefix that is used to mangle __asm declarations and // strip it if present. - return GlobalValue::getRealLinkageName(funcName); + return GlobalValue::dropLLVMManglingEscape(funcName); } bool TargetLibraryInfoImpl::getLibFunc(StringRef funcName, @@ -1004,22 +1048,34 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, return (NumParams == 1 && FTy.getParamType(0)->isFloatingPointTy()); case LibFunc_acos: + case LibFunc_acos_finite: case LibFunc_acosf: + case LibFunc_acosf_finite: case LibFunc_acosh: + case LibFunc_acosh_finite: case LibFunc_acoshf: + case LibFunc_acoshf_finite: case LibFunc_acoshl: + case LibFunc_acoshl_finite: case LibFunc_acosl: + case LibFunc_acosl_finite: case LibFunc_asin: + case LibFunc_asin_finite: case LibFunc_asinf: + case LibFunc_asinf_finite: case LibFunc_asinh: case LibFunc_asinhf: case LibFunc_asinhl: case LibFunc_asinl: + case LibFunc_asinl_finite: case LibFunc_atan: case LibFunc_atanf: case LibFunc_atanh: + case LibFunc_atanh_finite: case LibFunc_atanhf: + case LibFunc_atanhf_finite: case LibFunc_atanhl: + case LibFunc_atanhl_finite: case LibFunc_atanl: case LibFunc_cbrt: case LibFunc_cbrtf: @@ -1030,18 +1086,30 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, case LibFunc_cos: case LibFunc_cosf: case LibFunc_cosh: + case LibFunc_cosh_finite: case LibFunc_coshf: + case LibFunc_coshf_finite: case LibFunc_coshl: + case LibFunc_coshl_finite: case LibFunc_cosl: case LibFunc_exp10: + case LibFunc_exp10_finite: case LibFunc_exp10f: + case LibFunc_exp10f_finite: case LibFunc_exp10l: + case LibFunc_exp10l_finite: case LibFunc_exp2: + case LibFunc_exp2_finite: case LibFunc_exp2f: + case LibFunc_exp2f_finite: case LibFunc_exp2l: + case LibFunc_exp2l_finite: case LibFunc_exp: + case LibFunc_exp_finite: case LibFunc_expf: + case LibFunc_expf_finite: case LibFunc_expl: + case LibFunc_expl_finite: case LibFunc_expm1: case LibFunc_expm1f: case LibFunc_expm1l: @@ -1052,20 +1120,29 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, case LibFunc_floorf: case LibFunc_floorl: case LibFunc_log10: + case LibFunc_log10_finite: case LibFunc_log10f: + case LibFunc_log10f_finite: case LibFunc_log10l: + case LibFunc_log10l_finite: case LibFunc_log1p: case LibFunc_log1pf: case LibFunc_log1pl: case LibFunc_log2: + case LibFunc_log2_finite: case LibFunc_log2f: + case LibFunc_log2f_finite: case LibFunc_log2l: + case LibFunc_log2l_finite: case LibFunc_log: + case LibFunc_log_finite: case LibFunc_logb: case LibFunc_logbf: case LibFunc_logbl: case LibFunc_logf: + case LibFunc_logf_finite: case LibFunc_logl: + case LibFunc_logl_finite: case LibFunc_nearbyint: case LibFunc_nearbyintf: case LibFunc_nearbyintl: @@ -1078,8 +1155,11 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, case LibFunc_sin: case LibFunc_sinf: case LibFunc_sinh: + case LibFunc_sinh_finite: case LibFunc_sinhf: + case LibFunc_sinhf_finite: case LibFunc_sinhl: + case LibFunc_sinhl_finite: case LibFunc_sinl: case LibFunc_sqrt: case LibFunc_sqrt_finite: @@ -1100,8 +1180,11 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, FTy.getReturnType() == FTy.getParamType(0)); case LibFunc_atan2: + case LibFunc_atan2_finite: case LibFunc_atan2f: + case LibFunc_atan2f_finite: case LibFunc_atan2l: + case LibFunc_atan2l_finite: case LibFunc_fmin: case LibFunc_fminf: case LibFunc_fminl: @@ -1115,8 +1198,11 @@ bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy, case LibFunc_copysignf: case LibFunc_copysignl: case LibFunc_pow: + case LibFunc_pow_finite: case LibFunc_powf: + case LibFunc_powf_finite: case LibFunc_powl: + case LibFunc_powl_finite: return (NumParams == 2 && FTy.getReturnType()->isFloatingPointTy() && FTy.getReturnType() == FTy.getParamType(0) && FTy.getReturnType() == FTy.getParamType(1)); @@ -1294,6 +1380,14 @@ void TargetLibraryInfoImpl::addVectorizableFunctionsFromVecLib( {"powf", "__svml_powf8", 8}, {"powf", "__svml_powf16", 16}, + { "__pow_finite", "__svml_pow2", 2 }, + { "__pow_finite", "__svml_pow4", 4 }, + { "__pow_finite", "__svml_pow8", 8 }, + + { "__powf_finite", "__svml_powf4", 4 }, + { "__powf_finite", "__svml_powf8", 8 }, + { "__powf_finite", "__svml_powf16", 16 }, + {"llvm.pow.f64", "__svml_pow2", 2}, {"llvm.pow.f64", "__svml_pow4", 4}, {"llvm.pow.f64", "__svml_pow8", 8}, @@ -1310,6 +1404,14 @@ void TargetLibraryInfoImpl::addVectorizableFunctionsFromVecLib( {"expf", "__svml_expf8", 8}, {"expf", "__svml_expf16", 16}, + { "__exp_finite", "__svml_exp2", 2 }, + { "__exp_finite", "__svml_exp4", 4 }, + { "__exp_finite", "__svml_exp8", 8 }, + + { "__expf_finite", "__svml_expf4", 4 }, + { "__expf_finite", "__svml_expf8", 8 }, + { "__expf_finite", "__svml_expf16", 16 }, + {"llvm.exp.f64", "__svml_exp2", 2}, {"llvm.exp.f64", "__svml_exp4", 4}, {"llvm.exp.f64", "__svml_exp8", 8}, @@ -1326,6 +1428,14 @@ void TargetLibraryInfoImpl::addVectorizableFunctionsFromVecLib( {"logf", "__svml_logf8", 8}, {"logf", "__svml_logf16", 16}, + { "__log_finite", "__svml_log2", 2 }, + { "__log_finite", "__svml_log4", 4 }, + { "__log_finite", "__svml_log8", 8 }, + + { "__logf_finite", "__svml_logf4", 4 }, + { "__logf_finite", "__svml_logf8", 8 }, + { "__logf_finite", "__svml_logf16", 16 }, + {"llvm.log.f64", "__svml_log2", 2}, {"llvm.log.f64", "__svml_log4", 4}, {"llvm.log.f64", "__svml_log8", 8}, diff --git a/contrib/llvm/lib/Analysis/TargetTransformInfo.cpp b/contrib/llvm/lib/Analysis/TargetTransformInfo.cpp index 26d606cce9bb..8a5d10473662 100644 --- a/contrib/llvm/lib/Analysis/TargetTransformInfo.cpp +++ b/contrib/llvm/lib/Analysis/TargetTransformInfo.cpp @@ -279,6 +279,10 @@ unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const { return TTIImpl->getRegisterBitWidth(Vector); } +unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const { + return TTIImpl->getMinVectorRegisterBitWidth(); +} + bool TargetTransformInfo::shouldConsiderAddressTypePromotion( const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const { return TTIImpl->shouldConsiderAddressTypePromotion( @@ -500,6 +504,15 @@ unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF, return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); } +bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, + Type *Ty, ReductionFlags Flags) const { + return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags); +} + +bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const { + return TTIImpl->shouldExpandReduction(II); +} + TargetTransformInfo::Concept::~Concept() {} TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} diff --git a/contrib/llvm/lib/Analysis/ValueTracking.cpp b/contrib/llvm/lib/Analysis/ValueTracking.cpp index a7f3ff672aef..cba7363a0afa 100644 --- a/contrib/llvm/lib/Analysis/ValueTracking.cpp +++ b/contrib/llvm/lib/Analysis/ValueTracking.cpp @@ -88,9 +88,8 @@ struct Query { /// classic case of this is assume(x = y), which will attempt to determine /// bits in x from bits in y, which will attempt to determine bits in y from /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call - /// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and - /// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so - /// on. + /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo + /// (all of which can call computeKnownBits), and so on. std::array<const Value *, MaxDepth> Excluded; unsigned NumExcluded; @@ -143,6 +142,16 @@ void llvm::computeKnownBits(const Value *V, KnownBits &Known, Query(DL, AC, safeCxtI(V, CxtI), DT, ORE)); } +static KnownBits computeKnownBits(const Value *V, unsigned Depth, + const Query &Q); + +KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL, + unsigned Depth, AssumptionCache *AC, + const Instruction *CxtI, + const DominatorTree *DT) { + return ::computeKnownBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT)); +} + bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, @@ -159,16 +168,6 @@ bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS, return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue(); } -static void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, - unsigned Depth, const Query &Q); - -void llvm::ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, - const DataLayout &DL, unsigned Depth, - AssumptionCache *AC, const Instruction *CxtI, - const DominatorTree *DT) { - ::ComputeSignBit(V, KnownZero, KnownOne, Depth, - Query(DL, AC, safeCxtI(V, CxtI), DT)); -} static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth, const Query &Q); @@ -194,9 +193,8 @@ bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) { - bool NonNegative, Negative; - ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT); - return NonNegative; + KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT); + return Known.isNonNegative(); } bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth, @@ -214,9 +212,8 @@ bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth, bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) { - bool NonNegative, Negative; - ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT); - return Negative; + KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT); + return Known.isNegative(); } static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q); @@ -342,10 +339,10 @@ static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, // Also compute a conservative estimate for high known-0 bits. // More trickiness is possible, but this is sufficient for the // interesting case of alignment computation. - unsigned TrailZ = Known.Zero.countTrailingOnes() + - Known2.Zero.countTrailingOnes(); - unsigned LeadZ = std::max(Known.Zero.countLeadingOnes() + - Known2.Zero.countLeadingOnes(), + unsigned TrailZ = Known.countMinTrailingZeros() + + Known2.countMinTrailingZeros(); + unsigned LeadZ = std::max(Known.countMinLeadingZeros() + + Known2.countMinLeadingZeros(), BitWidth) - BitWidth; TrailZ = std::min(TrailZ, BitWidth); @@ -750,8 +747,8 @@ static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known, computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I)); // Whatever high bits in c are zero are known to be zero. - Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes()); - // assume(v <_u c) + Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros()); + // assume(v <_u c) } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q.CxtI, Q.DT)) { @@ -761,9 +758,9 @@ static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known, // Whatever high bits in c are zero are known to be zero (if c is a power // of 2, then one more). if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I))) - Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes()+1); + Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1); else - Known.Zero.setHighBits(RHSKnown.Zero.countLeadingOnes()); + Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros()); } } @@ -916,7 +913,7 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, m_Value(Y))))) { Known2.resetAll(); computeKnownBits(Y, Known2, Depth + 1, Q); - if (Known2.One.countTrailingOnes() > 0) + if (Known2.countMinTrailingOnes() > 0) Known.Zero.setBit(0); } break; @@ -953,14 +950,13 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, // treat a udiv as a logical right shift by the power of 2 known to // be less than the denominator. computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); - unsigned LeadZ = Known2.Zero.countLeadingOnes(); + unsigned LeadZ = Known2.countMinLeadingZeros(); Known2.resetAll(); computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); - unsigned RHSUnknownLeadingOnes = Known2.One.countLeadingZeros(); - if (RHSUnknownLeadingOnes != BitWidth) - LeadZ = std::min(BitWidth, - LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); + unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros(); + if (RHSMaxLeadingZeros != BitWidth) + LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1); Known.Zero.setHighBits(LeadZ); break; @@ -983,8 +979,8 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, if (Known.isNegative() && Known2.isNegative()) // We can derive a lower bound on the result by taking the max of the // leading one bits. - MaxHighOnes = std::max(Known.One.countLeadingOnes(), - Known2.One.countLeadingOnes()); + MaxHighOnes = + std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes()); // If either side is non-negative, the result is non-negative. else if (Known.isNonNegative() || Known2.isNonNegative()) MaxHighZeros = 1; @@ -993,8 +989,8 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, if (Known.isNonNegative() && Known2.isNonNegative()) // We can derive an upper bound on the result by taking the max of the // leading zero bits. - MaxHighZeros = std::max(Known.Zero.countLeadingOnes(), - Known2.Zero.countLeadingOnes()); + MaxHighZeros = std::max(Known.countMinLeadingZeros(), + Known2.countMinLeadingZeros()); // If either side is negative, the result is negative. else if (Known.isNegative() || Known2.isNegative()) MaxHighOnes = 1; @@ -1002,12 +998,12 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, // We can derive a lower bound on the result by taking the max of the // leading one bits. MaxHighOnes = - std::max(Known.One.countLeadingOnes(), Known2.One.countLeadingOnes()); + std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes()); } else if (SPF == SPF_UMIN) { // We can derive an upper bound on the result by taking the max of the // leading zero bits. MaxHighZeros = - std::max(Known.Zero.countLeadingOnes(), Known2.Zero.countLeadingOnes()); + std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros()); } // Only known if known in both the LHS and RHS. @@ -1185,8 +1181,8 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); - unsigned Leaders = std::max(Known.Zero.countLeadingOnes(), - Known2.Zero.countLeadingOnes()); + unsigned Leaders = + std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros()); Known.resetAll(); Known.Zero.setHighBits(Leaders); break; @@ -1207,7 +1203,7 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, // to determine if we can prove known low zero bits. KnownBits LocalKnown(BitWidth); computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q); - unsigned TrailZ = LocalKnown.Zero.countTrailingOnes(); + unsigned TrailZ = LocalKnown.countMinTrailingZeros(); gep_type_iterator GTI = gep_type_begin(I); for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) { @@ -1241,7 +1237,7 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, computeKnownBits(Index, LocalKnown, Depth + 1, Q); TrailZ = std::min(TrailZ, unsigned(countTrailingZeros(TypeSize) + - LocalKnown.Zero.countTrailingOnes())); + LocalKnown.countMinTrailingZeros())); } } @@ -1286,8 +1282,8 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, KnownBits Known3(Known); computeKnownBits(L, Known3, Depth + 1, Q); - Known.Zero.setLowBits(std::min(Known2.Zero.countTrailingOnes(), - Known3.Zero.countTrailingOnes())); + Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(), + Known3.countMinTrailingZeros())); if (DontImproveNonNegativePhiBits) break; @@ -1386,12 +1382,25 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, Known.Zero |= Known2.Zero.byteSwap(); Known.One |= Known2.One.byteSwap(); break; - case Intrinsic::ctlz: + case Intrinsic::ctlz: { + computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); + // If we have a known 1, its position is our upper bound. + unsigned PossibleLZ = Known2.One.countLeadingZeros(); + // If this call is undefined for 0, the result will be less than 2^n. + if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) + PossibleLZ = std::min(PossibleLZ, BitWidth - 1); + unsigned LowBits = Log2_32(PossibleLZ)+1; + Known.Zero.setBitsFrom(LowBits); + break; + } case Intrinsic::cttz: { - unsigned LowBits = Log2_32(BitWidth)+1; + computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); + // If we have a known 1, its position is our upper bound. + unsigned PossibleTZ = Known2.One.countTrailingZeros(); // If this call is undefined for 0, the result will be less than 2^n. if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) - LowBits -= 1; + PossibleTZ = std::min(PossibleTZ, BitWidth - 1); + unsigned LowBits = Log2_32(PossibleTZ)+1; Known.Zero.setBitsFrom(LowBits); break; } @@ -1399,7 +1408,7 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); // We can bound the space the count needs. Also, bits known to be zero // can't contribute to the population. - unsigned BitsPossiblySet = BitWidth - Known2.Zero.countPopulation(); + unsigned BitsPossiblySet = Known2.countMaxPopulation(); unsigned LowBits = Log2_32(BitsPossiblySet)+1; Known.Zero.setBitsFrom(LowBits); // TODO: we could bound KnownOne using the lower bound on the number @@ -1450,6 +1459,14 @@ static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known, } /// Determine which bits of V are known to be either zero or one and return +/// them. +KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) { + KnownBits Known(getBitWidth(V->getType(), Q.DL)); + computeKnownBits(V, Known, Depth, Q); + return Known; +} + +/// Determine which bits of V are known to be either zero or one and return /// them in the Known bit set. /// /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that @@ -1568,16 +1585,6 @@ void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?"); } -/// Determine whether the sign bit is known to be zero or one. -/// Convenience wrapper around computeKnownBits. -void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, - unsigned Depth, const Query &Q) { - KnownBits Bits(getBitWidth(V->getType(), Q.DL)); - computeKnownBits(V, Bits, Depth, Q); - KnownOne = Bits.isNegative(); - KnownZero = Bits.isNonNegative(); -} - /// Return true if the given value is known to have exactly one /// bit set when defined. For vectors return true if every element is known to /// be a power of two when defined. Supports values with integer or pointer @@ -1842,24 +1849,20 @@ bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) { if (BO->isExact()) return isKnownNonZero(X, Depth, Q); - bool XKnownNonNegative, XKnownNegative; - ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q); - if (XKnownNegative) + KnownBits Known = computeKnownBits(X, Depth, Q); + if (Known.isNegative()) return true; // If the shifter operand is a constant, and all of the bits shifted // out are known to be zero, and X is known non-zero then at least one // non-zero bit must remain. if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) { - KnownBits Known(BitWidth); - computeKnownBits(X, Known, Depth, Q); - auto ShiftVal = Shift->getLimitedValue(BitWidth - 1); // Is there a known one in the portion not shifted out? - if (Known.One.countLeadingZeros() < BitWidth - ShiftVal) + if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal) return true; // Are all the bits to be shifted out known zero? - if (Known.Zero.countTrailingOnes() >= ShiftVal) + if (Known.countMinTrailingZeros() >= ShiftVal) return isKnownNonZero(X, Depth, Q); } } @@ -1869,39 +1872,34 @@ bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) { } // X + Y. else if (match(V, m_Add(m_Value(X), m_Value(Y)))) { - bool XKnownNonNegative, XKnownNegative; - bool YKnownNonNegative, YKnownNegative; - ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q); - ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q); + KnownBits XKnown = computeKnownBits(X, Depth, Q); + KnownBits YKnown = computeKnownBits(Y, Depth, Q); // If X and Y are both non-negative (as signed values) then their sum is not // zero unless both X and Y are zero. - if (XKnownNonNegative && YKnownNonNegative) + if (XKnown.isNonNegative() && YKnown.isNonNegative()) if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q)) return true; // If X and Y are both negative (as signed values) then their sum is not // zero unless both X and Y equal INT_MIN. - if (XKnownNegative && YKnownNegative) { - KnownBits Known(BitWidth); + if (XKnown.isNegative() && YKnown.isNegative()) { APInt Mask = APInt::getSignedMaxValue(BitWidth); // The sign bit of X is set. If some other bit is set then X is not equal // to INT_MIN. - computeKnownBits(X, Known, Depth, Q); - if (Known.One.intersects(Mask)) + if (XKnown.One.intersects(Mask)) return true; // The sign bit of Y is set. If some other bit is set then Y is not equal // to INT_MIN. - computeKnownBits(Y, Known, Depth, Q); - if (Known.One.intersects(Mask)) + if (YKnown.One.intersects(Mask)) return true; } // The sum of a non-negative number and a power of two is not zero. - if (XKnownNonNegative && + if (XKnown.isNonNegative() && isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q)) return true; - if (YKnownNonNegative && + if (YKnown.isNonNegative() && isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q)) return true; } @@ -2276,14 +2274,7 @@ static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth, // If we know that the sign bit is either zero or one, determine the number of // identical bits in the top of the input value. - if (Known.isNonNegative()) - return std::max(FirstAnswer, Known.Zero.countLeadingOnes()); - - if (Known.isNegative()) - return std::max(FirstAnswer, Known.One.countLeadingOnes()); - - // computeKnownBits gave us no extra information about the top bits. - return FirstAnswer; + return std::max(FirstAnswer, Known.countMinSignBits()); } /// This function computes the integer multiple of Base that equals V. @@ -3441,8 +3432,8 @@ OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS, computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT); // Note that underestimating the number of zero bits gives a more // conservative answer. - unsigned ZeroBits = LHSKnown.Zero.countLeadingOnes() + - RHSKnown.Zero.countLeadingOnes(); + unsigned ZeroBits = LHSKnown.countMinLeadingZeros() + + RHSKnown.countMinLeadingZeros(); // First handle the easy case: if we have enough zero bits there's // definitely no overflow. if (ZeroBits >= BitWidth) @@ -3475,21 +3466,17 @@ OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) { - bool LHSKnownNonNegative, LHSKnownNegative; - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0, - AC, CxtI, DT); - if (LHSKnownNonNegative || LHSKnownNegative) { - bool RHSKnownNonNegative, RHSKnownNegative; - ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0, - AC, CxtI, DT); - - if (LHSKnownNegative && RHSKnownNegative) { + KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT); + if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) { + KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT); + + if (LHSKnown.isNegative() && RHSKnown.isNegative()) { // The sign bit is set in both cases: this MUST overflow. // Create a simple add instruction, and insert it into the struct. return OverflowResult::AlwaysOverflows; } - if (LHSKnownNonNegative && RHSKnownNonNegative) { + if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) { // The sign bit is clear in both cases: this CANNOT overflow. // Create a simple add instruction, and insert it into the struct. return OverflowResult::NeverOverflows; @@ -3499,6 +3486,51 @@ OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS, return OverflowResult::MayOverflow; } +/// \brief Return true if we can prove that adding the two values of the +/// knownbits will not overflow. +/// Otherwise return false. +static bool checkRippleForSignedAdd(const KnownBits &LHSKnown, + const KnownBits &RHSKnown) { + // Addition of two 2's complement numbers having opposite signs will never + // overflow. + if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) || + (LHSKnown.isNonNegative() && RHSKnown.isNegative())) + return true; + + // If either of the values is known to be non-negative, adding them can only + // overflow if the second is also non-negative, so we can assume that. + // Two non-negative numbers will only overflow if there is a carry to the + // sign bit, so we can check if even when the values are as big as possible + // there is no overflow to the sign bit. + if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) { + APInt MaxLHS = ~LHSKnown.Zero; + MaxLHS.clearSignBit(); + APInt MaxRHS = ~RHSKnown.Zero; + MaxRHS.clearSignBit(); + APInt Result = std::move(MaxLHS) + std::move(MaxRHS); + return Result.isSignBitClear(); + } + + // If either of the values is known to be negative, adding them can only + // overflow if the second is also negative, so we can assume that. + // Two negative number will only overflow if there is no carry to the sign + // bit, so we can check if even when the values are as small as possible + // there is overflow to the sign bit. + if (LHSKnown.isNegative() || RHSKnown.isNegative()) { + APInt MinLHS = LHSKnown.One; + MinLHS.clearSignBit(); + APInt MinRHS = RHSKnown.One; + MinRHS.clearSignBit(); + APInt Result = std::move(MinLHS) + std::move(MinRHS); + return Result.isSignBitSet(); + } + + // If we reached here it means that we know nothing about the sign bits. + // In this case we can't know if there will be an overflow, since by + // changing the sign bits any two values can be made to overflow. + return false; +} + static OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const AddOperator *Add, @@ -3510,18 +3542,29 @@ static OverflowResult computeOverflowForSignedAdd(const Value *LHS, return OverflowResult::NeverOverflows; } - bool LHSKnownNonNegative, LHSKnownNegative; - bool RHSKnownNonNegative, RHSKnownNegative; - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0, - AC, CxtI, DT); - ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0, - AC, CxtI, DT); + // If LHS and RHS each have at least two sign bits, the addition will look + // like + // + // XX..... + + // YY..... + // + // If the carry into the most significant position is 0, X and Y can't both + // be 1 and therefore the carry out of the addition is also 0. + // + // If the carry into the most significant position is 1, X and Y can't both + // be 0 and therefore the carry out of the addition is also 1. + // + // Since the carry into the most significant position is always equal to + // the carry out of the addition, there is no signed overflow. + if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 && + ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1) + return OverflowResult::NeverOverflows; + + KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT); + KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT); - if ((LHSKnownNonNegative && RHSKnownNegative) || - (LHSKnownNegative && RHSKnownNonNegative)) { - // The sign bits are opposite: this CANNOT overflow. + if (checkRippleForSignedAdd(LHSKnown, RHSKnown)) return OverflowResult::NeverOverflows; - } // The remaining code needs Add to be available. Early returns if not so. if (!Add) @@ -3532,14 +3575,13 @@ static OverflowResult computeOverflowForSignedAdd(const Value *LHS, // @llvm.assume'ed non-negative rather than proved so from analyzing its // operands. bool LHSOrRHSKnownNonNegative = - (LHSKnownNonNegative || RHSKnownNonNegative); - bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative); + (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()); + bool LHSOrRHSKnownNegative = + (LHSKnown.isNegative() || RHSKnown.isNegative()); if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) { - bool AddKnownNonNegative, AddKnownNegative; - ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL, - /*Depth=*/0, AC, CxtI, DT); - if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) || - (AddKnownNegative && LHSOrRHSKnownNegative)) { + KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT); + if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) || + (AddKnown.isNegative() && LHSOrRHSKnownNegative)) { return OverflowResult::NeverOverflows; } } diff --git a/contrib/llvm/lib/Analysis/VectorUtils.cpp b/contrib/llvm/lib/Analysis/VectorUtils.cpp index 722f17a8067e..2d2249da4e13 100644 --- a/contrib/llvm/lib/Analysis/VectorUtils.cpp +++ b/contrib/llvm/lib/Analysis/VectorUtils.cpp @@ -23,6 +23,7 @@ #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Value.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/IRBuilder.h" using namespace llvm; using namespace llvm::PatternMatch; diff --git a/contrib/llvm/lib/AsmParser/LLParser.cpp b/contrib/llvm/lib/AsmParser/LLParser.cpp index 97a567565b47..d7602c83435c 100644 --- a/contrib/llvm/lib/AsmParser/LLParser.cpp +++ b/contrib/llvm/lib/AsmParser/LLParser.cpp @@ -162,6 +162,10 @@ bool LLParser::ValidateEndOfModule() { AS = AS.addAttributes(Context, AttributeList::FunctionIndex, AttributeSet::get(Context, FnAttrs)); II->setAttributes(AS); + } else if (auto *GV = dyn_cast<GlobalVariable>(V)) { + AttrBuilder Attrs(GV->getAttributes()); + Attrs.merge(B); + GV->setAttributes(AttributeSet::get(Context,Attrs)); } else { llvm_unreachable("invalid object with forward attribute group reference"); } @@ -832,10 +836,10 @@ bool LLParser::parseIndirectSymbol( /// ParseGlobal /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace -/// OptionalExternallyInitialized GlobalType Type Const +/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace -/// OptionalExternallyInitialized GlobalType Type Const +/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs /// /// Everything up to and including OptionalUnnamedAddr has been parsed /// already. @@ -950,6 +954,16 @@ bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, } } + AttrBuilder Attrs; + LocTy BuiltinLoc; + std::vector<unsigned> FwdRefAttrGrps; + if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc)) + return true; + if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { + GV->setAttributes(AttributeSet::get(Context, Attrs)); + ForwardRefAttrGroups[GV] = FwdRefAttrGrps; + } + return false; } diff --git a/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp index 580261a3b5e0..76298121566a 100644 --- a/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp +++ b/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp @@ -93,13 +93,6 @@ static cl::opt<bool> PrintSummaryGUIDs( cl::desc( "Print the global id for each value when reading the module summary")); -// FIXME: This flag should either be removed or moved to clang as a driver flag. -static llvm::cl::opt<bool> IgnoreEmptyThinLTOIndexFile( - "ignore-empty-index-file", llvm::cl::ZeroOrMore, - llvm::cl::desc( - "Ignore an empty index file and perform non-ThinLTO compilation"), - llvm::cl::init(false)); - namespace { enum { @@ -2750,7 +2743,7 @@ Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { // v1: [pointer type, isconst, initid, linkage, alignment, section, // visibility, threadlocal, unnamed_addr, externally_initialized, - // dllstorageclass, comdat] (name in VST) + // dllstorageclass, comdat, attributes] (name in VST) // v2: [strtab_offset, strtab_size, v1] StringRef Name; std::tie(Name, Record) = readNameFromStrtab(Record); @@ -2830,6 +2823,11 @@ Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { } else if (hasImplicitComdat(RawLinkage)) { NewGV->setComdat(reinterpret_cast<Comdat *>(1)); } + + if (Record.size() > 12) { + auto AS = getAttributes(Record[12]).getFnAttributes(); + NewGV->setAttributes(AS); + } return Error::success(); } @@ -5658,7 +5656,8 @@ Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) { } Expected<std::unique_ptr<ModuleSummaryIndex>> -llvm::getModuleSummaryIndexForFile(StringRef Path) { +llvm::getModuleSummaryIndexForFile(StringRef Path, + bool IgnoreEmptyThinLTOIndexFile) { ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = MemoryBuffer::getFileOrSTDIN(Path); if (!FileOrErr) diff --git a/contrib/llvm/lib/Bitcode/Reader/MetadataLoader.cpp b/contrib/llvm/lib/Bitcode/Reader/MetadataLoader.cpp index 42135e5949ce..d80e1da911ca 100644 --- a/contrib/llvm/lib/Bitcode/Reader/MetadataLoader.cpp +++ b/contrib/llvm/lib/Bitcode/Reader/MetadataLoader.cpp @@ -500,7 +500,7 @@ class MetadataLoader::MetadataLoaderImpl { // Upgrade variables attached to globals. for (auto &GV : TheModule.globals()) { - SmallVector<MDNode *, 1> MDs, NewMDs; + SmallVector<MDNode *, 1> MDs; GV.getMetadata(LLVMContext::MD_dbg, MDs); GV.eraseMetadata(LLVMContext::MD_dbg); for (auto *MD : MDs) diff --git a/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp index 1b8d81a60201..1f8b50342c2d 100644 --- a/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp +++ b/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp @@ -1109,7 +1109,7 @@ void ModuleBitcodeWriter::writeModuleInfo() { // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid, // linkage, alignment, section, visibility, threadlocal, // unnamed_addr, externally_initialized, dllstorageclass, - // comdat] + // comdat, attributes] Vals.push_back(StrtabBuilder.add(GV.getName())); Vals.push_back(GV.getName().size()); Vals.push_back(VE.getTypeID(GV.getValueType())); @@ -1124,13 +1124,17 @@ void ModuleBitcodeWriter::writeModuleInfo() { GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None || GV.isExternallyInitialized() || GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass || - GV.hasComdat()) { + GV.hasComdat() || + GV.hasAttributes()) { Vals.push_back(getEncodedVisibility(GV)); Vals.push_back(getEncodedThreadLocalMode(GV)); Vals.push_back(getEncodedUnnamedAddr(GV)); Vals.push_back(GV.isExternallyInitialized()); Vals.push_back(getEncodedDLLStorageClass(GV)); Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0); + + auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex); + Vals.push_back(VE.getAttributeListID(AL)); } else { AbbrevToUse = SimpleGVarAbbrev; } diff --git a/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp b/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp index 861150766986..fd76400331d9 100644 --- a/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp +++ b/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp @@ -314,10 +314,13 @@ ValueEnumerator::ValueEnumerator(const Module &M, // Remember what is the cutoff between globalvalue's and other constants. unsigned FirstConstant = Values.size(); - // Enumerate the global variable initializers. - for (const GlobalVariable &GV : M.globals()) + // Enumerate the global variable initializers and attributes. + for (const GlobalVariable &GV : M.globals()) { if (GV.hasInitializer()) EnumerateValue(GV.getInitializer()); + if (GV.hasAttributes()) + EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex)); + } // Enumerate the aliasees. for (const GlobalAlias &GA : M.aliases()) diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp index 87b45c001de4..98163bffb60b 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp @@ -767,7 +767,7 @@ void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, // If our DISubprogram name is empty, use the mangled name. if (FuncName.empty()) - FuncName = GlobalValue::getRealLinkageName(GV->getName()); + FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName()); // Emit a symbol subsection, required by VS2012+ to find function boundaries. OS.AddComment("Symbol subsection for " + Twine(FuncName)); @@ -888,13 +888,21 @@ void CodeViewDebug::collectVariableInfoFromMFTable( if (!Scope) continue; + // If the variable has an attached offset expression, extract it. + // FIXME: Try to handle DW_OP_deref as well. + int64_t ExprOffset = 0; + if (VI.Expr) + if (!VI.Expr->extractIfOffset(ExprOffset)) + continue; + // Get the frame register used and the offset. unsigned FrameReg = 0; int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); // Calculate the label ranges. - LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset); + LocalVarDefRange DefRange = + createDefRangeMem(CVReg, FrameOffset + ExprOffset); for (const InsnRange &Range : Scope->getRanges()) { const MCSymbol *Begin = getLabelBeforeInsn(Range.first); const MCSymbol *End = getLabelAfterInsn(Range.second); @@ -2194,7 +2202,7 @@ void CodeViewDebug::emitDebugInfoForGlobals() { if (GV->hasComdat()) { MCSymbol *GVSym = Asm->getSymbol(GV); OS.AddComment("Symbol subsection for " + - Twine(GlobalValue::getRealLinkageName(GV->getName()))); + Twine(GlobalValue::dropLLVMManglingEscape(GV->getName()))); switchToDebugSectionForSymbol(GVSym); EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols); // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp index 1d63e33a4d33..826162ad47c4 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp @@ -129,10 +129,9 @@ bool hasDebugInfo(const MachineModuleInfo *MMI, const MachineFunction *MF) { } void DebugHandlerBase::beginFunction(const MachineFunction *MF) { - assert(Asm); PrevInstBB = nullptr; - if (!hasDebugInfo(MMI, MF)) { + if (!Asm || !hasDebugInfo(MMI, MF)) { skippedNonDebugFunction(); return; } diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp index 738e062cb93f..e172712cf889 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp @@ -440,7 +440,7 @@ DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) { auto *InlinedSP = getDISubprogram(DS); // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram // was inlined from another compile unit. - DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP]; + DIE *OriginDIE = getAbstractSPDies()[InlinedSP]; assert(OriginDIE && "Unable to find original DIE for an inlined subprogram."); auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine); @@ -634,7 +634,7 @@ DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope, void DwarfCompileUnit::constructAbstractSubprogramScopeDIE( LexicalScope *Scope) { - DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()]; + DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()]; if (AbsDef) return; @@ -696,7 +696,7 @@ DIE *DwarfCompileUnit::constructImportedEntityDIE( void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { DIE *D = getDIE(SP); - if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) { + if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) { if (D) // If this subprogram has an abstract definition, reference that addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE); @@ -708,6 +708,42 @@ void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) { } } +void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) { + DbgVariable *AbsVar = getExistingAbstractVariable( + InlinedVariable(Var.getVariable(), Var.getInlinedAt())); + auto *VariableDie = Var.getDIE(); + if (AbsVar && AbsVar->getDIE()) { + addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, + *AbsVar->getDIE()); + } else + applyVariableAttributes(Var, *VariableDie); +} + +DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) { + const DILocalVariable *Cleansed; + return getExistingAbstractVariable(IV, Cleansed); +} + +// Find abstract variable, if any, associated with Var. +DbgVariable *DwarfCompileUnit::getExistingAbstractVariable( + InlinedVariable IV, const DILocalVariable *&Cleansed) { + // More then one inlined variable corresponds to one abstract variable. + Cleansed = IV.first; + auto &AbstractVariables = getAbstractVariables(); + auto I = AbstractVariables.find(Cleansed); + if (I != AbstractVariables.end()) + return I->second.get(); + return nullptr; +} + +void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var, + LexicalScope *Scope) { + assert(Scope && Scope->isAbstractScope()); + auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr); + DU->addScopeVariable(Scope, AbsDbgVariable.get()); + getAbstractVariables()[Var] = std::move(AbsDbgVariable); +} + void DwarfCompileUnit::emitHeader(bool UseOffsets) { // Don't bother labeling the .dwo unit, as its offset isn't used. if (!Skeleton) { diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h index 20a415150b4d..77e9e671529f 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h @@ -68,6 +68,9 @@ class DwarfCompileUnit final : public DwarfUnit { // ranges/locs. const MCSymbol *BaseAddress; + DenseMap<const MDNode *, DIE *> AbstractSPDies; + DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables; + /// \brief Construct a DIE for the given DbgVariable without initializing the /// DbgVariable's DIE reference. DIE *constructVariableDIEImpl(const DbgVariable &DV, bool Abstract); @@ -76,6 +79,18 @@ class DwarfCompileUnit final : public DwarfUnit { bool includeMinimalInlineScopes() const; + DenseMap<const MDNode *, DIE *> &getAbstractSPDies() { + if (isDwoUnit() && !DD->shareAcrossDWOCUs()) + return AbstractSPDies; + return DU->getAbstractSPDies(); + } + + DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> &getAbstractVariables() { + if (isDwoUnit() && !DD->shareAcrossDWOCUs()) + return AbstractVariables; + return DU->getAbstractVariables(); + } + public: DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU); @@ -189,6 +204,13 @@ public: DIE *constructImportedEntityDIE(const DIImportedEntity *Module); void finishSubprogramDefinition(const DISubprogram *SP); + void finishVariableDefinition(const DbgVariable &Var); + /// Find abstract variable associated with Var. + typedef DbgValueHistoryMap::InlinedVariable InlinedVariable; + DbgVariable *getExistingAbstractVariable(InlinedVariable IV, + const DILocalVariable *&Cleansed); + DbgVariable *getExistingAbstractVariable(InlinedVariable IV); + void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope); /// Set the skeleton unit associated with this unit. void setSkeleton(DwarfCompileUnit &Skel) { Skeleton = &Skel; } diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp index 6f442f5c3172..3410b98d7776 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp @@ -71,6 +71,10 @@ static cl::opt<bool> GenerateARangeSection("generate-arange-section", cl::desc("Generate dwarf aranges"), cl::init(false)); +static cl::opt<bool> SplitDwarfCrossCuReferences( + "split-dwarf-cross-cu-references", cl::Hidden, + cl::desc("Enable cross-cu references in DWO files"), cl::init(false)); + namespace { enum DefaultOnOff { Default, Enable, Disable }; } @@ -362,21 +366,29 @@ template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) { F(*SkelCU); } -void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) { +bool DwarfDebug::shareAcrossDWOCUs() const { + return SplitDwarfCrossCuReferences; +} + +void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, + LexicalScope *Scope) { assert(Scope && Scope->getScopeNode()); assert(Scope->isAbstractScope()); assert(!Scope->getInlinedAt()); auto *SP = cast<DISubprogram>(Scope->getScopeNode()); - ProcessedSPNodes.insert(SP); - // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram // was inlined from another compile unit. auto &CU = *CUMap.lookup(SP->getUnit()); - forBothCUs(CU, [&](DwarfCompileUnit &CU) { + if (auto *SkelCU = CU.getSkeleton()) { + (shareAcrossDWOCUs() ? CU : SrcCU) + .constructAbstractSubprogramScopeDIE(Scope); + if (CU.getCUNode()->getSplitDebugInlining()) + SkelCU->constructAbstractSubprogramScopeDIE(Scope); + } else { CU.constructAbstractSubprogramScopeDIE(Scope); - }); + } } void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const { @@ -564,13 +576,7 @@ void DwarfDebug::finishVariableDefinitions() { // DIE::getUnit isn't simple - it walks parent pointers, etc. DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie()); assert(Unit); - DbgVariable *AbsVar = getExistingAbstractVariable( - InlinedVariable(Var->getVariable(), Var->getInlinedAt())); - if (AbsVar && AbsVar->getDIE()) { - Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, - *AbsVar->getDIE()); - } else - Unit->applyVariableAttributes(*Var, *VariableDie); + Unit->finishVariableDefinition(*Var); } } @@ -718,58 +724,32 @@ void DwarfDebug::endModule() { } // clean up. - AbstractVariables.clear(); + // FIXME: AbstractVariables.clear(); } -// Find abstract variable, if any, associated with Var. -DbgVariable * -DwarfDebug::getExistingAbstractVariable(InlinedVariable IV, - const DILocalVariable *&Cleansed) { - // More then one inlined variable corresponds to one abstract variable. - Cleansed = IV.first; - auto I = AbstractVariables.find(Cleansed); - if (I != AbstractVariables.end()) - return I->second.get(); - return nullptr; -} - -DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) { - const DILocalVariable *Cleansed; - return getExistingAbstractVariable(IV, Cleansed); -} - -void DwarfDebug::createAbstractVariable(const DILocalVariable *Var, - LexicalScope *Scope) { - assert(Scope && Scope->isAbstractScope()); - auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr); - InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get()); - AbstractVariables[Var] = std::move(AbsDbgVariable); -} - -void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV, +void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV, const MDNode *ScopeNode) { const DILocalVariable *Cleansed = nullptr; - if (getExistingAbstractVariable(IV, Cleansed)) + if (CU.getExistingAbstractVariable(IV, Cleansed)) return; - createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope( + CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope( cast<DILocalScope>(ScopeNode))); } -void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped( +void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable IV, const MDNode *ScopeNode) { const DILocalVariable *Cleansed = nullptr; - if (getExistingAbstractVariable(IV, Cleansed)) + if (CU.getExistingAbstractVariable(IV, Cleansed)) return; if (LexicalScope *Scope = LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode))) - createAbstractVariable(Cleansed, Scope); + CU.createAbstractVariable(Cleansed, Scope); } - // Collect variable information from side table maintained by MF. void DwarfDebug::collectVariableInfoFromMFTable( - DenseSet<InlinedVariable> &Processed) { + DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) { for (const auto &VI : Asm->MF->getVariableDbgInfo()) { if (!VI.Var) continue; @@ -784,7 +764,7 @@ void DwarfDebug::collectVariableInfoFromMFTable( if (!Scope) continue; - ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode()); + ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode()); auto RegVar = make_unique<DbgVariable>(Var.first, Var.second); RegVar->initializeMMI(VI.Expr, VI.Slot); if (InfoHolder.addScopeVariable(Scope, RegVar.get())) @@ -955,9 +935,10 @@ DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc, } } -DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope, +DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU, + LexicalScope &Scope, InlinedVariable IV) { - ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode()); + ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode()); ConcreteVariables.push_back(make_unique<DbgVariable>(IV.first, IV.second)); InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get()); return ConcreteVariables.back().get(); @@ -980,7 +961,7 @@ void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP, DenseSet<InlinedVariable> &Processed) { // Grab the variable info that was squirreled away in the MMI side-table. - collectVariableInfoFromMFTable(Processed); + collectVariableInfoFromMFTable(TheCU, Processed); for (const auto &I : DbgValues) { InlinedVariable IV = I.first; @@ -1002,7 +983,7 @@ void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, continue; Processed.insert(IV); - DbgVariable *RegVar = createConcreteVariable(*Scope, IV); + DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV); const MachineInstr *MInsn = Ranges.front().first; assert(MInsn->isDebugValue() && "History must begin with debug value"); @@ -1038,7 +1019,7 @@ void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, for (const DILocalVariable *DV : SP->getVariables()) { if (Processed.insert(InlinedVariable(DV, nullptr)).second) if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) - createConcreteVariable(*Scope, InlinedVariable(DV, nullptr)); + createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr)); } } @@ -1229,12 +1210,12 @@ void DwarfDebug::endFunctionImpl(const MachineFunction *MF) { for (const DILocalVariable *DV : SP->getVariables()) { if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second) continue; - ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr), + ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr), DV->getScope()); assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes && "ensureAbstractVariableIsCreated inserted abstract scopes"); } - constructAbstractSubprogramScopeDIE(AScope); + constructAbstractSubprogramScopeDIE(TheCU, AScope); } ProcessedSPNodes.insert(SP); diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h index 8a96e7867b6e..b9c5aa9ffb23 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h @@ -210,7 +210,6 @@ class DwarfDebug : public DebugHandlerBase { DenseMap<const MCSymbol *, uint64_t> SymSize; /// Collection of abstract variables. - DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables; SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables; /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists @@ -313,20 +312,16 @@ class DwarfDebug : public DebugHandlerBase { typedef DbgValueHistoryMap::InlinedVariable InlinedVariable; - /// Find abstract variable associated with Var. - DbgVariable *getExistingAbstractVariable(InlinedVariable IV, - const DILocalVariable *&Cleansed); - DbgVariable *getExistingAbstractVariable(InlinedVariable IV); - void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope); - void ensureAbstractVariableIsCreated(InlinedVariable Var, + void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var, const MDNode *Scope); - void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var, + void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var, const MDNode *Scope); - DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV); + DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU, + LexicalScope &Scope, InlinedVariable IV); /// Construct a DIE for this abstract scope. - void constructAbstractSubprogramScopeDIE(LexicalScope *Scope); + void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope); void finishVariableDefinitions(); @@ -446,7 +441,8 @@ class DwarfDebug : public DebugHandlerBase { const DbgValueHistoryMap::InstrRanges &Ranges); /// Collect variable information from the side table maintained by MF. - void collectVariableInfoFromMFTable(DenseSet<InlinedVariable> &P); + void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU, + DenseSet<InlinedVariable> &P); protected: /// Gather pre-function debug information. @@ -518,6 +514,8 @@ public: /// split dwarf proposal support. bool useSplitDwarf() const { return HasSplitDwarf; } + bool shareAcrossDWOCUs() const; + /// Returns the Dwarf Version. uint16_t getDwarfVersion() const; diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h index d4d2ed277274..54924e9806ed 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfFile.h @@ -53,6 +53,7 @@ class DwarfFile { // Collection of abstract subprogram DIEs. DenseMap<const MDNode *, DIE *> AbstractSPDies; + DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables; /// Maps MDNodes for type system with the corresponding DIEs. These DIEs can /// be shared across CUs, that is why we keep the map here instead @@ -105,6 +106,9 @@ public: DenseMap<const MDNode *, DIE *> &getAbstractSPDies() { return AbstractSPDies; } + DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> &getAbstractVariables() { + return AbstractVariables; + } void insertDIE(const MDNode *TypeMD, DIE *Die) { DITypeNodeToDieMap.insert(std::make_pair(TypeMD, Die)); diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp index 8d25def7772c..667afbb450bd 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp @@ -173,7 +173,7 @@ int64_t DwarfUnit::getDefaultLowerBound() const { } /// Check whether the DIE for this MDNode can be shared across CUs. -static bool isShareableAcrossCUs(const DINode *D) { +bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const { // When the MDNode can be part of the type system, the DIE can be shared // across CUs. // Combining type units and cross-CU DIE sharing is lower value (since @@ -181,6 +181,8 @@ static bool isShareableAcrossCUs(const DINode *D) { // level already) but may be implementable for some value in projects // building multiple independent libraries with LTO and then linking those // together. + if (isDwoUnit() && !DD->shareAcrossDWOCUs()) + return false; return (isa<DIType>(D) || (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) && !GenerateDwarfTypeUnits; @@ -645,7 +647,7 @@ void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) { addString(Die, DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name : dwarf::DW_AT_MIPS_linkage_name, - GlobalValue::getRealLinkageName(LinkageName)); + GlobalValue::dropLLVMManglingEscape(LinkageName)); } void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) { diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h index 8fc841703e23..7acad2cbd89f 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h @@ -65,7 +65,7 @@ public: //===----------------------------------------------------------------------===// /// This dwarf writer support class manages information associated with a /// source file. - class DwarfUnit : public DIEUnit { +class DwarfUnit : public DIEUnit { protected: /// MDNode for the compile unit. const DICompileUnit *CUNode; @@ -103,6 +103,9 @@ protected: bool applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie); + bool shareAcrossDWOCUs() const; + bool isShareableAcrossCUs(const DINode *D) const; + public: // Accessors. AsmPrinter* getAsmPrinter() const { return Asm; } diff --git a/contrib/llvm/lib/CodeGen/AsmPrinter/WinException.cpp b/contrib/llvm/lib/CodeGen/AsmPrinter/WinException.cpp index 704f0ac2f191..815658bfb637 100644 --- a/contrib/llvm/lib/CodeGen/AsmPrinter/WinException.cpp +++ b/contrib/llvm/lib/CodeGen/AsmPrinter/WinException.cpp @@ -101,7 +101,7 @@ void WinException::beginFunction(const MachineFunction *MF) { // functions may still refer to it. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo(); StringRef FLinkageName = - GlobalValue::getRealLinkageName(MF->getFunction()->getName()); + GlobalValue::dropLLVMManglingEscape(MF->getFunction()->getName()); emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName); } shouldEmitLSDA = hasEHFunclets; @@ -174,7 +174,7 @@ static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm, // their funclet entry block's number. const MachineFunction *MF = MBB->getParent(); const Function *F = MF->getFunction(); - StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName()); + StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName()); MCContext &Ctx = MF->getContext(); StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch"; return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" + @@ -252,7 +252,7 @@ void WinException::endFunclet() { !CurrentFuncletEntry->isCleanupFuncletEntry()) { // If this is a C++ catch funclet (or the parent function), // emit a reference to the LSDA for the parent function. - StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName()); + StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName()); MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol( Twine("$cppxdata$", FuncLinkageName)); Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4); @@ -536,7 +536,7 @@ void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) { // Emit a label assignment with the SEH frame offset so we can use it for // llvm.x86.seh.recoverfp. StringRef FLinkageName = - GlobalValue::getRealLinkageName(MF->getFunction()->getName()); + GlobalValue::dropLLVMManglingEscape(MF->getFunction()->getName()); MCSymbol *ParentFrameOffset = Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName); const MCExpr *MCOffset = @@ -635,7 +635,7 @@ void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) { auto &OS = *Asm->OutStreamer; const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo(); - StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName()); + StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName()); SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable; MCSymbol *FuncInfoXData = nullptr; @@ -942,7 +942,7 @@ void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo, void WinException::emitExceptHandlerTable(const MachineFunction *MF) { MCStreamer &OS = *Asm->OutStreamer; const Function *F = MF->getFunction(); - StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName()); + StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F->getName()); bool VerboseAsm = OS.isVerboseAsm(); auto AddComment = [&](const Twine &Comment) { diff --git a/contrib/llvm/lib/CodeGen/AtomicExpandPass.cpp b/contrib/llvm/lib/CodeGen/AtomicExpandPass.cpp index 9c19a4fd3c3e..17e6be05eb42 100644 --- a/contrib/llvm/lib/CodeGen/AtomicExpandPass.cpp +++ b/contrib/llvm/lib/CodeGen/AtomicExpandPass.cpp @@ -47,8 +47,7 @@ namespace { bool runOnFunction(Function &F) override; private: - bool bracketInstWithFences(Instruction *I, AtomicOrdering Order, - bool IsStore, bool IsLoad); + bool bracketInstWithFences(Instruction *I, AtomicOrdering Order); IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL); LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI); bool tryExpandAtomicLoad(LoadInst *LI); @@ -224,22 +223,16 @@ bool AtomicExpand::runOnFunction(Function &F) { if (TLI->shouldInsertFencesForAtomic(I)) { auto FenceOrdering = AtomicOrdering::Monotonic; - bool IsStore, IsLoad; if (LI && isAcquireOrStronger(LI->getOrdering())) { FenceOrdering = LI->getOrdering(); LI->setOrdering(AtomicOrdering::Monotonic); - IsStore = false; - IsLoad = true; } else if (SI && isReleaseOrStronger(SI->getOrdering())) { FenceOrdering = SI->getOrdering(); SI->setOrdering(AtomicOrdering::Monotonic); - IsStore = true; - IsLoad = false; } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) || isAcquireOrStronger(RMWI->getOrdering()))) { FenceOrdering = RMWI->getOrdering(); RMWI->setOrdering(AtomicOrdering::Monotonic); - IsStore = IsLoad = true; } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) && (isReleaseOrStronger(CASI->getSuccessOrdering()) || isAcquireOrStronger(CASI->getSuccessOrdering()))) { @@ -250,11 +243,10 @@ bool AtomicExpand::runOnFunction(Function &F) { FenceOrdering = CASI->getSuccessOrdering(); CASI->setSuccessOrdering(AtomicOrdering::Monotonic); CASI->setFailureOrdering(AtomicOrdering::Monotonic); - IsStore = IsLoad = true; } if (FenceOrdering != AtomicOrdering::Monotonic) { - MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad); + MadeChange |= bracketInstWithFences(I, FenceOrdering); } } @@ -320,13 +312,12 @@ bool AtomicExpand::runOnFunction(Function &F) { return MadeChange; } -bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order, - bool IsStore, bool IsLoad) { +bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) { IRBuilder<> Builder(I); - auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad); + auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order); - auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad); + auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order); // The trailing fence is emitted before the instruction instead of after // because there is no easy way of setting Builder insertion point after // an instruction. So we must erase it from the BB, and insert it back @@ -1048,8 +1039,7 @@ bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) { std::prev(BB->end())->eraseFromParent(); Builder.SetInsertPoint(BB); if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier) - TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true, - /*IsLoad=*/true); + TLI->emitLeadingFence(Builder, CI, SuccessOrder); Builder.CreateBr(StartBB); // Start the main loop block now that we've taken care of the preliminaries. @@ -1064,8 +1054,7 @@ bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) { Builder.SetInsertPoint(ReleasingStoreBB); if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier) - TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true, - /*IsLoad=*/true); + TLI->emitLeadingFence(Builder, CI, SuccessOrder); Builder.CreateBr(TryStoreBB); Builder.SetInsertPoint(TryStoreBB); @@ -1094,8 +1083,7 @@ bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) { // necessary. Builder.SetInsertPoint(SuccessBB); if (ShouldInsertFencesForAtomic) - TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true, - /*IsLoad=*/true); + TLI->emitTrailingFence(Builder, CI, SuccessOrder); Builder.CreateBr(ExitBB); Builder.SetInsertPoint(NoStoreBB); @@ -1107,8 +1095,7 @@ bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) { Builder.SetInsertPoint(FailureBB); if (ShouldInsertFencesForAtomic) - TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true, - /*IsLoad=*/true); + TLI->emitTrailingFence(Builder, CI, FailureOrder); Builder.CreateBr(ExitBB); // Finally, we have control-flow based knowledge of whether the cmpxchg diff --git a/contrib/llvm/lib/CodeGen/CodeGen.cpp b/contrib/llvm/lib/CodeGen/CodeGen.cpp index 3fc12ccc3b60..4d30c6574b12 100644 --- a/contrib/llvm/lib/CodeGen/CodeGen.cpp +++ b/contrib/llvm/lib/CodeGen/CodeGen.cpp @@ -43,6 +43,7 @@ void llvm::initializeCodeGen(PassRegistry &Registry) { initializeLiveDebugValuesPass(Registry); initializeLiveDebugVariablesPass(Registry); initializeLiveIntervalsPass(Registry); + initializeLiveRangeShrinkPass(Registry); initializeLiveStacksPass(Registry); initializeLiveVariablesPass(Registry); initializeLocalStackSlotPassPass(Registry); @@ -79,7 +80,8 @@ void llvm::initializeCodeGen(PassRegistry &Registry) { initializeRAGreedyPass(Registry); initializeRegisterCoalescerPass(Registry); initializeRenameIndependentSubregsPass(Registry); - initializeSafeStackPass(Registry); + initializeSafeStackLegacyPassPass(Registry); + initializeScalarizeMaskedMemIntrinPass(Registry); initializeShrinkWrapPass(Registry); initializeSlotIndexesPass(Registry); initializeStackColoringPass(Registry); diff --git a/contrib/llvm/lib/CodeGen/CodeGenPrepare.cpp b/contrib/llvm/lib/CodeGen/CodeGenPrepare.cpp index c6c93811a0f9..f2e024c5e3bd 100644 --- a/contrib/llvm/lib/CodeGen/CodeGenPrepare.cpp +++ b/contrib/llvm/lib/CodeGen/CodeGenPrepare.cpp @@ -295,7 +295,7 @@ bool CodeGenPrepare::runOnFunction(Function &F) { if (PSI->isFunctionHotInCallGraph(&F)) F.setSectionPrefix(".hot"); else if (PSI->isFunctionColdInCallGraph(&F)) - F.setSectionPrefix(".cold"); + F.setSectionPrefix(".unlikely"); } /// This optimization identifies DIV instructions that can be @@ -1549,519 +1549,6 @@ static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, return MadeChange; } -// Translate a masked load intrinsic like -// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, -// <16 x i1> %mask, <16 x i32> %passthru) -// to a chain of basic blocks, with loading element one-by-one if -// the appropriate mask bit is set -// -// %1 = bitcast i8* %addr to i32* -// %2 = extractelement <16 x i1> %mask, i32 0 -// %3 = icmp eq i1 %2, true -// br i1 %3, label %cond.load, label %else -// -//cond.load: ; preds = %0 -// %4 = getelementptr i32* %1, i32 0 -// %5 = load i32* %4 -// %6 = insertelement <16 x i32> undef, i32 %5, i32 0 -// br label %else -// -//else: ; preds = %0, %cond.load -// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] -// %7 = extractelement <16 x i1> %mask, i32 1 -// %8 = icmp eq i1 %7, true -// br i1 %8, label %cond.load1, label %else2 -// -//cond.load1: ; preds = %else -// %9 = getelementptr i32* %1, i32 1 -// %10 = load i32* %9 -// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 -// br label %else2 -// -//else2: ; preds = %else, %cond.load1 -// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] -// %12 = extractelement <16 x i1> %mask, i32 2 -// %13 = icmp eq i1 %12, true -// br i1 %13, label %cond.load4, label %else5 -// -static void scalarizeMaskedLoad(CallInst *CI) { - Value *Ptr = CI->getArgOperand(0); - Value *Alignment = CI->getArgOperand(1); - Value *Mask = CI->getArgOperand(2); - Value *Src0 = CI->getArgOperand(3); - - unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); - VectorType *VecType = dyn_cast<VectorType>(CI->getType()); - assert(VecType && "Unexpected return type of masked load intrinsic"); - - Type *EltTy = CI->getType()->getVectorElementType(); - - IRBuilder<> Builder(CI->getContext()); - Instruction *InsertPt = CI; - BasicBlock *IfBlock = CI->getParent(); - BasicBlock *CondBlock = nullptr; - BasicBlock *PrevIfBlock = CI->getParent(); - - Builder.SetInsertPoint(InsertPt); - Builder.SetCurrentDebugLocation(CI->getDebugLoc()); - - // Short-cut if the mask is all-true. - bool IsAllOnesMask = isa<Constant>(Mask) && - cast<Constant>(Mask)->isAllOnesValue(); - - if (IsAllOnesMask) { - Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); - CI->replaceAllUsesWith(NewI); - CI->eraseFromParent(); - return; - } - - // Adjust alignment for the scalar instruction. - AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); - // Bitcast %addr fron i8* to EltTy* - Type *NewPtrType = - EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); - Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); - unsigned VectorWidth = VecType->getNumElements(); - - Value *UndefVal = UndefValue::get(VecType); - - // The result vector - Value *VResult = UndefVal; - - if (isa<ConstantVector>(Mask)) { - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) - continue; - Value *Gep = - Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); - LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); - VResult = Builder.CreateInsertElement(VResult, Load, - Builder.getInt32(Idx)); - } - Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); - CI->replaceAllUsesWith(NewI); - CI->eraseFromParent(); - return; - } - - PHINode *Phi = nullptr; - Value *PrevPhi = UndefVal; - - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - - // Fill the "else" block, created in the previous iteration - // - // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] - // %mask_1 = extractelement <16 x i1> %mask, i32 Idx - // %to_load = icmp eq i1 %mask_1, true - // br i1 %to_load, label %cond.load, label %else - // - if (Idx > 0) { - Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); - Phi->addIncoming(VResult, CondBlock); - Phi->addIncoming(PrevPhi, PrevIfBlock); - PrevPhi = Phi; - VResult = Phi; - } - - Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); - Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, - ConstantInt::get(Predicate->getType(), 1)); - - // Create "cond" block - // - // %EltAddr = getelementptr i32* %1, i32 0 - // %Elt = load i32* %EltAddr - // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx - // - CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); - Builder.SetInsertPoint(InsertPt); - - Value *Gep = - Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); - LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); - VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); - - // Create "else" block, fill it in the next iteration - BasicBlock *NewIfBlock = - CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); - Builder.SetInsertPoint(InsertPt); - Instruction *OldBr = IfBlock->getTerminator(); - BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); - OldBr->eraseFromParent(); - PrevIfBlock = IfBlock; - IfBlock = NewIfBlock; - } - - Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); - Phi->addIncoming(VResult, CondBlock); - Phi->addIncoming(PrevPhi, PrevIfBlock); - Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); - CI->replaceAllUsesWith(NewI); - CI->eraseFromParent(); -} - -// Translate a masked store intrinsic, like -// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, -// <16 x i1> %mask) -// to a chain of basic blocks, that stores element one-by-one if -// the appropriate mask bit is set -// -// %1 = bitcast i8* %addr to i32* -// %2 = extractelement <16 x i1> %mask, i32 0 -// %3 = icmp eq i1 %2, true -// br i1 %3, label %cond.store, label %else -// -// cond.store: ; preds = %0 -// %4 = extractelement <16 x i32> %val, i32 0 -// %5 = getelementptr i32* %1, i32 0 -// store i32 %4, i32* %5 -// br label %else -// -// else: ; preds = %0, %cond.store -// %6 = extractelement <16 x i1> %mask, i32 1 -// %7 = icmp eq i1 %6, true -// br i1 %7, label %cond.store1, label %else2 -// -// cond.store1: ; preds = %else -// %8 = extractelement <16 x i32> %val, i32 1 -// %9 = getelementptr i32* %1, i32 1 -// store i32 %8, i32* %9 -// br label %else2 -// . . . -static void scalarizeMaskedStore(CallInst *CI) { - Value *Src = CI->getArgOperand(0); - Value *Ptr = CI->getArgOperand(1); - Value *Alignment = CI->getArgOperand(2); - Value *Mask = CI->getArgOperand(3); - - unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); - VectorType *VecType = dyn_cast<VectorType>(Src->getType()); - assert(VecType && "Unexpected data type in masked store intrinsic"); - - Type *EltTy = VecType->getElementType(); - - IRBuilder<> Builder(CI->getContext()); - Instruction *InsertPt = CI; - BasicBlock *IfBlock = CI->getParent(); - Builder.SetInsertPoint(InsertPt); - Builder.SetCurrentDebugLocation(CI->getDebugLoc()); - - // Short-cut if the mask is all-true. - bool IsAllOnesMask = isa<Constant>(Mask) && - cast<Constant>(Mask)->isAllOnesValue(); - - if (IsAllOnesMask) { - Builder.CreateAlignedStore(Src, Ptr, AlignVal); - CI->eraseFromParent(); - return; - } - - // Adjust alignment for the scalar instruction. - AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); - // Bitcast %addr fron i8* to EltTy* - Type *NewPtrType = - EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); - Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); - unsigned VectorWidth = VecType->getNumElements(); - - if (isa<ConstantVector>(Mask)) { - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) - continue; - Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); - Value *Gep = - Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); - Builder.CreateAlignedStore(OneElt, Gep, AlignVal); - } - CI->eraseFromParent(); - return; - } - - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - - // Fill the "else" block, created in the previous iteration - // - // %mask_1 = extractelement <16 x i1> %mask, i32 Idx - // %to_store = icmp eq i1 %mask_1, true - // br i1 %to_store, label %cond.store, label %else - // - Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); - Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, - ConstantInt::get(Predicate->getType(), 1)); - - // Create "cond" block - // - // %OneElt = extractelement <16 x i32> %Src, i32 Idx - // %EltAddr = getelementptr i32* %1, i32 0 - // %store i32 %OneElt, i32* %EltAddr - // - BasicBlock *CondBlock = - IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); - Builder.SetInsertPoint(InsertPt); - - Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); - Value *Gep = - Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); - Builder.CreateAlignedStore(OneElt, Gep, AlignVal); - - // Create "else" block, fill it in the next iteration - BasicBlock *NewIfBlock = - CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); - Builder.SetInsertPoint(InsertPt); - Instruction *OldBr = IfBlock->getTerminator(); - BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); - OldBr->eraseFromParent(); - IfBlock = NewIfBlock; - } - CI->eraseFromParent(); -} - -// Translate a masked gather intrinsic like -// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, -// <16 x i1> %Mask, <16 x i32> %Src) -// to a chain of basic blocks, with loading element one-by-one if -// the appropriate mask bit is set -// -// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind -// % Mask0 = extractelement <16 x i1> %Mask, i32 0 -// % ToLoad0 = icmp eq i1 % Mask0, true -// br i1 % ToLoad0, label %cond.load, label %else -// -// cond.load: -// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 -// % Load0 = load i32, i32* % Ptr0, align 4 -// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 -// br label %else -// -// else: -// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] -// % Mask1 = extractelement <16 x i1> %Mask, i32 1 -// % ToLoad1 = icmp eq i1 % Mask1, true -// br i1 % ToLoad1, label %cond.load1, label %else2 -// -// cond.load1: -// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 -// % Load1 = load i32, i32* % Ptr1, align 4 -// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 -// br label %else2 -// . . . -// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src -// ret <16 x i32> %Result -static void scalarizeMaskedGather(CallInst *CI) { - Value *Ptrs = CI->getArgOperand(0); - Value *Alignment = CI->getArgOperand(1); - Value *Mask = CI->getArgOperand(2); - Value *Src0 = CI->getArgOperand(3); - - VectorType *VecType = dyn_cast<VectorType>(CI->getType()); - - assert(VecType && "Unexpected return type of masked load intrinsic"); - - IRBuilder<> Builder(CI->getContext()); - Instruction *InsertPt = CI; - BasicBlock *IfBlock = CI->getParent(); - BasicBlock *CondBlock = nullptr; - BasicBlock *PrevIfBlock = CI->getParent(); - Builder.SetInsertPoint(InsertPt); - unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); - - Builder.SetCurrentDebugLocation(CI->getDebugLoc()); - - Value *UndefVal = UndefValue::get(VecType); - - // The result vector - Value *VResult = UndefVal; - unsigned VectorWidth = VecType->getNumElements(); - - // Shorten the way if the mask is a vector of constants. - bool IsConstMask = isa<ConstantVector>(Mask); - - if (IsConstMask) { - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) - continue; - Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), - "Ptr" + Twine(Idx)); - LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, - "Load" + Twine(Idx)); - VResult = Builder.CreateInsertElement(VResult, Load, - Builder.getInt32(Idx), - "Res" + Twine(Idx)); - } - Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); - CI->replaceAllUsesWith(NewI); - CI->eraseFromParent(); - return; - } - - PHINode *Phi = nullptr; - Value *PrevPhi = UndefVal; - - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - - // Fill the "else" block, created in the previous iteration - // - // %Mask1 = extractelement <16 x i1> %Mask, i32 1 - // %ToLoad1 = icmp eq i1 %Mask1, true - // br i1 %ToLoad1, label %cond.load, label %else - // - if (Idx > 0) { - Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); - Phi->addIncoming(VResult, CondBlock); - Phi->addIncoming(PrevPhi, PrevIfBlock); - PrevPhi = Phi; - VResult = Phi; - } - - Value *Predicate = Builder.CreateExtractElement(Mask, - Builder.getInt32(Idx), - "Mask" + Twine(Idx)); - Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, - ConstantInt::get(Predicate->getType(), 1), - "ToLoad" + Twine(Idx)); - - // Create "cond" block - // - // %EltAddr = getelementptr i32* %1, i32 0 - // %Elt = load i32* %EltAddr - // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx - // - CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); - Builder.SetInsertPoint(InsertPt); - - Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), - "Ptr" + Twine(Idx)); - LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, - "Load" + Twine(Idx)); - VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), - "Res" + Twine(Idx)); - - // Create "else" block, fill it in the next iteration - BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); - Builder.SetInsertPoint(InsertPt); - Instruction *OldBr = IfBlock->getTerminator(); - BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); - OldBr->eraseFromParent(); - PrevIfBlock = IfBlock; - IfBlock = NewIfBlock; - } - - Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); - Phi->addIncoming(VResult, CondBlock); - Phi->addIncoming(PrevPhi, PrevIfBlock); - Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); - CI->replaceAllUsesWith(NewI); - CI->eraseFromParent(); -} - -// Translate a masked scatter intrinsic, like -// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, -// <16 x i1> %Mask) -// to a chain of basic blocks, that stores element one-by-one if -// the appropriate mask bit is set. -// -// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind -// % Mask0 = extractelement <16 x i1> % Mask, i32 0 -// % ToStore0 = icmp eq i1 % Mask0, true -// br i1 %ToStore0, label %cond.store, label %else -// -// cond.store: -// % Elt0 = extractelement <16 x i32> %Src, i32 0 -// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 -// store i32 %Elt0, i32* % Ptr0, align 4 -// br label %else -// -// else: -// % Mask1 = extractelement <16 x i1> % Mask, i32 1 -// % ToStore1 = icmp eq i1 % Mask1, true -// br i1 % ToStore1, label %cond.store1, label %else2 -// -// cond.store1: -// % Elt1 = extractelement <16 x i32> %Src, i32 1 -// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 -// store i32 % Elt1, i32* % Ptr1, align 4 -// br label %else2 -// . . . -static void scalarizeMaskedScatter(CallInst *CI) { - Value *Src = CI->getArgOperand(0); - Value *Ptrs = CI->getArgOperand(1); - Value *Alignment = CI->getArgOperand(2); - Value *Mask = CI->getArgOperand(3); - - assert(isa<VectorType>(Src->getType()) && - "Unexpected data type in masked scatter intrinsic"); - assert(isa<VectorType>(Ptrs->getType()) && - isa<PointerType>(Ptrs->getType()->getVectorElementType()) && - "Vector of pointers is expected in masked scatter intrinsic"); - - IRBuilder<> Builder(CI->getContext()); - Instruction *InsertPt = CI; - BasicBlock *IfBlock = CI->getParent(); - Builder.SetInsertPoint(InsertPt); - Builder.SetCurrentDebugLocation(CI->getDebugLoc()); - - unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); - unsigned VectorWidth = Src->getType()->getVectorNumElements(); - - // Shorten the way if the mask is a vector of constants. - bool IsConstMask = isa<ConstantVector>(Mask); - - if (IsConstMask) { - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) - continue; - Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), - "Elt" + Twine(Idx)); - Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), - "Ptr" + Twine(Idx)); - Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); - } - CI->eraseFromParent(); - return; - } - for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { - // Fill the "else" block, created in the previous iteration - // - // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx - // % ToStore = icmp eq i1 % Mask1, true - // br i1 % ToStore, label %cond.store, label %else - // - Value *Predicate = Builder.CreateExtractElement(Mask, - Builder.getInt32(Idx), - "Mask" + Twine(Idx)); - Value *Cmp = - Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, - ConstantInt::get(Predicate->getType(), 1), - "ToStore" + Twine(Idx)); - - // Create "cond" block - // - // % Elt1 = extractelement <16 x i32> %Src, i32 1 - // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 - // %store i32 % Elt1, i32* % Ptr1 - // - BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); - Builder.SetInsertPoint(InsertPt); - - Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), - "Elt" + Twine(Idx)); - Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), - "Ptr" + Twine(Idx)); - Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); - - // Create "else" block, fill it in the next iteration - BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); - Builder.SetInsertPoint(InsertPt); - Instruction *OldBr = IfBlock->getTerminator(); - BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); - OldBr->eraseFromParent(); - IfBlock = NewIfBlock; - } - CI->eraseFromParent(); -} - /// If counting leading or trailing zeros is an expensive operation and a zero /// input is defined, add a check for zero to avoid calling the intrinsic. /// @@ -2242,39 +1729,6 @@ bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { } return true; } - case Intrinsic::masked_load: { - // Scalarize unsupported vector masked load - if (!TTI->isLegalMaskedLoad(CI->getType())) { - scalarizeMaskedLoad(CI); - ModifiedDT = true; - return true; - } - return false; - } - case Intrinsic::masked_store: { - if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { - scalarizeMaskedStore(CI); - ModifiedDT = true; - return true; - } - return false; - } - case Intrinsic::masked_gather: { - if (!TTI->isLegalMaskedGather(CI->getType())) { - scalarizeMaskedGather(CI); - ModifiedDT = true; - return true; - } - return false; - } - case Intrinsic::masked_scatter: { - if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { - scalarizeMaskedScatter(CI); - ModifiedDT = true; - return true; - } - return false; - } case Intrinsic::aarch64_stlxr: case Intrinsic::aarch64_stxr: { ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); diff --git a/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp b/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp index ab2382e2db6d..e860906043dd 100644 --- a/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp +++ b/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp @@ -142,8 +142,9 @@ bool ExpandPostRA::LowerCopy(MachineInstr *MI) { MachineOperand &DstMO = MI->getOperand(0); MachineOperand &SrcMO = MI->getOperand(1); - if (SrcMO.getReg() == DstMO.getReg()) { - DEBUG(dbgs() << "identity copy: " << *MI); + bool IdentityCopy = (SrcMO.getReg() == DstMO.getReg()); + if (IdentityCopy || SrcMO.isUndef()) { + DEBUG(dbgs() << (IdentityCopy ? "identity copy: " : "undef copy: ") << *MI); // No need to insert an identity copy instruction, but replace with a KILL // if liveness is changed. if (SrcMO.isUndef() || MI->getNumOperands() > 2) { diff --git a/contrib/llvm/lib/CodeGen/ExpandReductions.cpp b/contrib/llvm/lib/CodeGen/ExpandReductions.cpp new file mode 100644 index 000000000000..a40ea28056dd --- /dev/null +++ b/contrib/llvm/lib/CodeGen/ExpandReductions.cpp @@ -0,0 +1,167 @@ +//===--- ExpandReductions.cpp - Expand experimental reduction intrinsics --===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass implements IR expansion for reduction intrinsics, allowing targets +// to enable the experimental intrinsics until just before codegen. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/CodeGen/ExpandReductions.h" +#include "llvm/CodeGen/Passes.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InstIterator.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Module.h" +#include "llvm/Transforms/Utils/LoopUtils.h" +#include "llvm/Pass.h" + +using namespace llvm; + +namespace { + +unsigned getOpcode(Intrinsic::ID ID) { + switch (ID) { + case Intrinsic::experimental_vector_reduce_fadd: + return Instruction::FAdd; + case Intrinsic::experimental_vector_reduce_fmul: + return Instruction::FMul; + case Intrinsic::experimental_vector_reduce_add: + return Instruction::Add; + case Intrinsic::experimental_vector_reduce_mul: + return Instruction::Mul; + case Intrinsic::experimental_vector_reduce_and: + return Instruction::And; + case Intrinsic::experimental_vector_reduce_or: + return Instruction::Or; + case Intrinsic::experimental_vector_reduce_xor: + return Instruction::Xor; + case Intrinsic::experimental_vector_reduce_smax: + case Intrinsic::experimental_vector_reduce_smin: + case Intrinsic::experimental_vector_reduce_umax: + case Intrinsic::experimental_vector_reduce_umin: + return Instruction::ICmp; + case Intrinsic::experimental_vector_reduce_fmax: + case Intrinsic::experimental_vector_reduce_fmin: + return Instruction::FCmp; + default: + llvm_unreachable("Unexpected ID"); + } +} + +RecurrenceDescriptor::MinMaxRecurrenceKind getMRK(Intrinsic::ID ID) { + switch (ID) { + case Intrinsic::experimental_vector_reduce_smax: + return RecurrenceDescriptor::MRK_SIntMax; + case Intrinsic::experimental_vector_reduce_smin: + return RecurrenceDescriptor::MRK_SIntMin; + case Intrinsic::experimental_vector_reduce_umax: + return RecurrenceDescriptor::MRK_UIntMax; + case Intrinsic::experimental_vector_reduce_umin: + return RecurrenceDescriptor::MRK_UIntMin; + case Intrinsic::experimental_vector_reduce_fmax: + return RecurrenceDescriptor::MRK_FloatMax; + case Intrinsic::experimental_vector_reduce_fmin: + return RecurrenceDescriptor::MRK_FloatMin; + default: + return RecurrenceDescriptor::MRK_Invalid; + } +} + +bool expandReductions(Function &F, const TargetTransformInfo *TTI) { + bool Changed = false; + SmallVector<IntrinsicInst*, 4> Worklist; + for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) + if (auto II = dyn_cast<IntrinsicInst>(&*I)) + Worklist.push_back(II); + + for (auto *II : Worklist) { + IRBuilder<> Builder(II); + Value *Vec = nullptr; + auto ID = II->getIntrinsicID(); + auto MRK = RecurrenceDescriptor::MRK_Invalid; + switch (ID) { + case Intrinsic::experimental_vector_reduce_fadd: + case Intrinsic::experimental_vector_reduce_fmul: + // FMFs must be attached to the call, otherwise it's an ordered reduction + // and it can't be handled by generating this shuffle sequence. + // TODO: Implement scalarization of ordered reductions here for targets + // without native support. + if (!II->getFastMathFlags().unsafeAlgebra()) + continue; + Vec = II->getArgOperand(1); + break; + case Intrinsic::experimental_vector_reduce_add: + case Intrinsic::experimental_vector_reduce_mul: + case Intrinsic::experimental_vector_reduce_and: + case Intrinsic::experimental_vector_reduce_or: + case Intrinsic::experimental_vector_reduce_xor: + case Intrinsic::experimental_vector_reduce_smax: + case Intrinsic::experimental_vector_reduce_smin: + case Intrinsic::experimental_vector_reduce_umax: + case Intrinsic::experimental_vector_reduce_umin: + case Intrinsic::experimental_vector_reduce_fmax: + case Intrinsic::experimental_vector_reduce_fmin: + Vec = II->getArgOperand(0); + MRK = getMRK(ID); + break; + default: + continue; + } + if (!TTI->shouldExpandReduction(II)) + continue; + auto Rdx = getShuffleReduction(Builder, Vec, getOpcode(ID), MRK); + II->replaceAllUsesWith(Rdx); + II->eraseFromParent(); + Changed = true; + } + return Changed; +} + +class ExpandReductions : public FunctionPass { +public: + static char ID; + ExpandReductions() : FunctionPass(ID) { + initializeExpandReductionsPass(*PassRegistry::getPassRegistry()); + } + + bool runOnFunction(Function &F) override { + const auto *TTI =&getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); + return expandReductions(F, TTI); + } + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired<TargetTransformInfoWrapperPass>(); + AU.setPreservesCFG(); + } +}; +} + +char ExpandReductions::ID; +INITIALIZE_PASS_BEGIN(ExpandReductions, "expand-reductions", + "Expand reduction intrinsics", false, false) +INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) +INITIALIZE_PASS_END(ExpandReductions, "expand-reductions", + "Expand reduction intrinsics", false, false) + +FunctionPass *llvm::createExpandReductionsPass() { + return new ExpandReductions(); +} + +PreservedAnalyses ExpandReductionsPass::run(Function &F, + FunctionAnalysisManager &AM) { + const auto &TTI = AM.getResult<TargetIRAnalysis>(F); + if (!expandReductions(F, &TTI)) + return PreservedAnalyses::all(); + PreservedAnalyses PA; + PA.preserveSet<CFGAnalyses>(); + return PA; +} diff --git a/contrib/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp b/contrib/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp index eaf4056e47ea..4d4591042296 100644 --- a/contrib/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp +++ b/contrib/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp @@ -162,7 +162,7 @@ bool LegalizerInfo::isLegal(const MachineInstr &MI, return std::get<0>(getAction(MI, MRI)) == Legal; } -LLT LegalizerInfo::findLegalType(const InstrAspect &Aspect, +Optional<LLT> LegalizerInfo::findLegalType(const InstrAspect &Aspect, LegalizeAction Action) const { switch(Action) { default: @@ -174,20 +174,20 @@ LLT LegalizerInfo::findLegalType(const InstrAspect &Aspect, return Aspect.Type; case NarrowScalar: { return findLegalType(Aspect, - [&](LLT Ty) -> LLT { return Ty.halfScalarSize(); }); + [](LLT Ty) -> LLT { return Ty.halfScalarSize(); }); } case WidenScalar: { - return findLegalType(Aspect, [&](LLT Ty) -> LLT { + return findLegalType(Aspect, [](LLT Ty) -> LLT { return Ty.getSizeInBits() < 8 ? LLT::scalar(8) : Ty.doubleScalarSize(); }); } case FewerElements: { return findLegalType(Aspect, - [&](LLT Ty) -> LLT { return Ty.halfElements(); }); + [](LLT Ty) -> LLT { return Ty.halfElements(); }); } case MoreElements: { return findLegalType(Aspect, - [&](LLT Ty) -> LLT { return Ty.doubleElements(); }); + [](LLT Ty) -> LLT { return Ty.doubleElements(); }); } } } diff --git a/contrib/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp b/contrib/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp index 7248f50945d0..2eb3cdee694d 100644 --- a/contrib/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp +++ b/contrib/llvm/lib/CodeGen/GlobalISel/RegBankSelect.cpp @@ -204,12 +204,8 @@ uint64_t RegBankSelect::getRepairCost( // TODO: use a dedicated constant for ImpossibleCost. if (Cost != UINT_MAX) return Cost; - assert(!TPC->isGlobalISelAbortEnabled() && - "Legalization not available yet"); // Return the legalization cost of that repairing. } - assert(!TPC->isGlobalISelAbortEnabled() && - "Complex repairing not implemented yet"); return UINT_MAX; } @@ -452,6 +448,11 @@ RegBankSelect::MappingCost RegBankSelect::computeMapping( // Sums up the repairing cost of MO at each insertion point. uint64_t RepairCost = getRepairCost(MO, ValMapping); + + // This is an impossible to repair cost. + if (RepairCost == UINT_MAX) + continue; + // Bias used for splitting: 5%. const uint64_t PercentageForBias = 5; uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100; diff --git a/contrib/llvm/lib/CodeGen/GlobalISel/Utils.cpp b/contrib/llvm/lib/CodeGen/GlobalISel/Utils.cpp index 3c93f8123b0d..254bdf10d804 100644 --- a/contrib/llvm/lib/CodeGen/GlobalISel/Utils.cpp +++ b/contrib/llvm/lib/CodeGen/GlobalISel/Utils.cpp @@ -110,3 +110,11 @@ Optional<int64_t> llvm::getConstantVRegVal(unsigned VReg, return None; } + +const llvm::ConstantFP* llvm::getConstantFPVRegVal(unsigned VReg, + const MachineRegisterInfo &MRI) { + MachineInstr *MI = MRI.getVRegDef(VReg); + if (TargetOpcode::G_FCONSTANT != MI->getOpcode()) + return nullptr; + return MI->getOperand(1).getFPImm(); +} diff --git a/contrib/llvm/lib/CodeGen/IfConversion.cpp b/contrib/llvm/lib/CodeGen/IfConversion.cpp index 37fe41582333..628d599a3cc7 100644 --- a/contrib/llvm/lib/CodeGen/IfConversion.cpp +++ b/contrib/llvm/lib/CodeGen/IfConversion.cpp @@ -1318,7 +1318,8 @@ static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) { return false; PI = I++; } - return true; + // Finally see if the last I is indeed a successor to PI. + return PI->isSuccessor(&*I); } /// Invalidate predecessor BB info so it would be re-analyzed to determine if it @@ -1587,22 +1588,32 @@ bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB); } + // To be able to insert code freely at the end of BBI we sometimes remove + // the branch from BBI to NextMBB temporarily. Remember if this happened. + bool RemovedBranchToNextMBB = false; if (CvtMBB.pred_size() > 1) { BBI.NonPredSize -= TII->removeBranch(*BBI.BB); // Copy instructions in the true block, predicate them, and add them to // the entry block. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true); - // RemoveExtraEdges won't work if the block has an unanalyzable branch, so - // explicitly remove CvtBBI as a successor. + // Keep the CFG updated. BBI.BB->removeSuccessor(&CvtMBB, true); } else { // Predicate the 'true' block after removing its branch. CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB); PredicateBlock(*CvtBBI, CvtMBB.end(), Cond); - // Now merge the entry of the triangle with the true block. + // Remove the branch from the entry of the triangle to NextBB to be able to + // do the merge below. Keep the CFG updated, but remember we removed the + // branch since we do want to execute NextMBB, either by introducing a + // branch to it again, or merging it into the entry block. + // How it's handled is decided further down. BBI.NonPredSize -= TII->removeBranch(*BBI.BB); + BBI.BB->removeSuccessor(&NextMBB, true); + RemovedBranchToNextMBB = true; + + // Now merge the entry of the triangle with the true block. MergeBlocks(BBI, *CvtBBI, false); } @@ -1640,12 +1651,19 @@ bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { // block. By not merging them, we make it possible to iteratively // ifcvt the blocks. if (!HasEarlyExit && - NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough && + // We might have removed BBI from NextMBB's predecessor list above but + // we want it to be there, so consider that too. + (NextMBB.pred_size() == (RemovedBranchToNextMBB ? 0 : 1)) && + !NextBBI->HasFallThrough && !NextMBB.hasAddressTaken()) { + // We will merge NextBBI into BBI, and thus remove the current + // fallthrough from BBI into CvtBBI. + BBI.BB->removeSuccessor(&CvtMBB, true); MergeBlocks(BBI, *NextBBI); FalseBBDead = true; } else { InsertUncondBranch(*BBI.BB, NextMBB, TII); + BBI.BB->addSuccessor(&NextMBB); BBI.HasFallThrough = false; } // Mixed predicated and unpredicated code. This cannot be iteratively @@ -1653,8 +1671,6 @@ bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) { IterIfcvt = false; } - RemoveExtraEdges(BBI); - // Update block info. BB can be iteratively if-converted. if (!IterIfcvt) BBI.IsDone = true; diff --git a/contrib/llvm/lib/CodeGen/LiveRangeShrink.cpp b/contrib/llvm/lib/CodeGen/LiveRangeShrink.cpp new file mode 100644 index 000000000000..00182e2c779f --- /dev/null +++ b/contrib/llvm/lib/CodeGen/LiveRangeShrink.cpp @@ -0,0 +1,211 @@ +//===-- LiveRangeShrink.cpp - Move instructions to shrink live range ------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +///===---------------------------------------------------------------------===// +/// +/// \file +/// This pass moves instructions close to the definition of its operands to +/// shrink live range of the def instruction. The code motion is limited within +/// the basic block. The moved instruction should have 1 def, and more than one +/// uses, all of which are the only use of the def. +/// +///===---------------------------------------------------------------------===// +#include "llvm/CodeGen/MachineFunctionPass.h" +#include "llvm/CodeGen/MachineRegisterInfo.h" +#include "llvm/CodeGen/Passes.h" +#include "llvm/ADT/Statistic.h" +#include "llvm/Support/Debug.h" + +#define DEBUG_TYPE "lrshrink" + +STATISTIC(NumInstrsHoistedToShrinkLiveRange, + "Number of insructions hoisted to shrink live range."); + +using namespace llvm; + +namespace { +class LiveRangeShrink : public MachineFunctionPass { +public: + static char ID; + + LiveRangeShrink() : MachineFunctionPass(ID) { + initializeLiveRangeShrinkPass(*PassRegistry::getPassRegistry()); + } + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.setPreservesCFG(); + MachineFunctionPass::getAnalysisUsage(AU); + } + + StringRef getPassName() const override { return "Live Range Shrink"; } + + bool runOnMachineFunction(MachineFunction &MF) override; +}; +} // End anonymous namespace. + +char LiveRangeShrink::ID = 0; +char &llvm::LiveRangeShrinkID = LiveRangeShrink::ID; + +INITIALIZE_PASS(LiveRangeShrink, "lrshrink", "Live Range Shrink Pass", false, + false) +namespace { +typedef DenseMap<MachineInstr *, unsigned> InstOrderMap; + +/// Returns \p New if it's dominated by \p Old, otherwise return \p Old. +/// \p M maintains a map from instruction to its dominating order that satisfies +/// M[A] > M[B] guarantees that A is dominated by B. +/// If \p New is not in \p M, return \p Old. Otherwise if \p Old is null, return +/// \p New. +MachineInstr *FindDominatedInstruction(MachineInstr &New, MachineInstr *Old, + const InstOrderMap &M) { + auto NewIter = M.find(&New); + if (NewIter == M.end()) + return Old; + if (Old == nullptr) + return &New; + unsigned OrderOld = M.find(Old)->second; + unsigned OrderNew = NewIter->second; + if (OrderOld != OrderNew) + return OrderOld < OrderNew ? &New : Old; + // OrderOld == OrderNew, we need to iterate down from Old to see if it + // can reach New, if yes, New is dominated by Old. + for (MachineInstr *I = Old->getNextNode(); M.find(I)->second == OrderNew; + I = I->getNextNode()) + if (I == &New) + return &New; + return Old; +} + +/// Builds Instruction to its dominating order number map \p M by traversing +/// from instruction \p Start. +void BuildInstOrderMap(MachineBasicBlock::iterator Start, InstOrderMap &M) { + M.clear(); + unsigned i = 0; + for (MachineInstr &I : make_range(Start, Start->getParent()->end())) + M[&I] = i++; +} +} // end anonymous namespace + +bool LiveRangeShrink::runOnMachineFunction(MachineFunction &MF) { + if (skipFunction(*MF.getFunction())) + return false; + + MachineRegisterInfo &MRI = MF.getRegInfo(); + + DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n'); + + InstOrderMap IOM; + // Map from register to instruction order (value of IOM) where the + // register is used last. When moving instructions up, we need to + // make sure all its defs (including dead def) will not cross its + // last use when moving up. + DenseMap<unsigned, unsigned> UseMap; + + for (MachineBasicBlock &MBB : MF) { + if (MBB.empty()) + continue; + bool SawStore = false; + BuildInstOrderMap(MBB.begin(), IOM); + UseMap.clear(); + + for (MachineBasicBlock::iterator Next = MBB.begin(); Next != MBB.end();) { + MachineInstr &MI = *Next; + ++Next; + if (MI.isPHI() || MI.isDebugValue()) + continue; + if (MI.mayStore()) + SawStore = true; + + unsigned CurrentOrder = IOM[&MI]; + unsigned Barrier = 0; + for (const MachineOperand &MO : MI.operands()) { + if (!MO.isReg() || MO.isDebug()) + continue; + if (MO.isUse()) + UseMap[MO.getReg()] = CurrentOrder; + else if (MO.isDead() && UseMap.count(MO.getReg())) + // Barrier is the last instruction where MO get used. MI should not + // be moved above Barrier. + Barrier = std::max(Barrier, UseMap[MO.getReg()]); + } + + if (!MI.isSafeToMove(nullptr, SawStore)) { + // If MI has side effects, it should become a barrier for code motion. + // IOM is rebuild from the next instruction to prevent later + // instructions from being moved before this MI. + if (MI.hasUnmodeledSideEffects() && Next != MBB.end()) { + BuildInstOrderMap(Next, IOM); + SawStore = false; + } + continue; + } + + const MachineOperand *DefMO = nullptr; + MachineInstr *Insert = nullptr; + + // Number of live-ranges that will be shortened. We do not count + // live-ranges that are defined by a COPY as it could be coalesced later. + unsigned NumEligibleUse = 0; + + for (const MachineOperand &MO : MI.operands()) { + if (!MO.isReg() || MO.isDead() || MO.isDebug()) + continue; + unsigned Reg = MO.getReg(); + // Do not move the instruction if it def/uses a physical register, + // unless it is a constant physical register. + if (TargetRegisterInfo::isPhysicalRegister(Reg) && + !MRI.isConstantPhysReg(Reg)) { + Insert = nullptr; + break; + } + if (MO.isDef()) { + // Do not move if there is more than one def. + if (DefMO) { + Insert = nullptr; + break; + } + DefMO = &MO; + } else if (MRI.hasOneNonDBGUse(Reg) && MRI.hasOneDef(Reg)) { + MachineInstr &DefInstr = *MRI.def_instr_begin(Reg); + if (!DefInstr.isCopy()) + NumEligibleUse++; + Insert = FindDominatedInstruction(DefInstr, Insert, IOM); + } else { + Insert = nullptr; + break; + } + } + // Move the instruction when # of shrunk live range > 1. + if (DefMO && Insert && NumEligibleUse > 1 && Barrier <= IOM[Insert]) { + MachineBasicBlock::iterator I = std::next(Insert->getIterator()); + // Skip all the PHI and debug instructions. + while (I != MBB.end() && (I->isPHI() || I->isDebugValue())) + I = std::next(I); + if (I == MI.getIterator()) + continue; + + // Update the dominator order to be the same as the insertion point. + // We do this to maintain a non-decreasing order without need to update + // all instruction orders after the insertion point. + unsigned NewOrder = IOM[&*I]; + IOM[&MI] = NewOrder; + NumInstrsHoistedToShrinkLiveRange++; + + // Find MI's debug value following MI. + MachineBasicBlock::iterator EndIter = std::next(MI.getIterator()); + if (MI.getOperand(0).isReg()) + for (; EndIter != MBB.end() && EndIter->isDebugValue() && + EndIter->getOperand(0).isReg() && + EndIter->getOperand(0).getReg() == MI.getOperand(0).getReg(); + ++EndIter, ++Next) + IOM[&*EndIter] = NewOrder; + MBB.splice(I, &MBB, MI.getIterator(), EndIter); + } + } + } + return false; +} diff --git a/contrib/llvm/lib/CodeGen/LiveVariables.cpp b/contrib/llvm/lib/CodeGen/LiveVariables.cpp index 3568b0294ad9..a9aec926115a 100644 --- a/contrib/llvm/lib/CodeGen/LiveVariables.cpp +++ b/contrib/llvm/lib/CodeGen/LiveVariables.cpp @@ -767,7 +767,7 @@ void LiveVariables::addNewBlock(MachineBasicBlock *BB, MachineBasicBlock *SuccBB) { const unsigned NumNew = BB->getNumber(); - SmallSet<unsigned, 16> Defs, Kills; + DenseSet<unsigned> Defs, Kills; MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end(); for (; BBI != BBE && BBI->isPHI(); ++BBI) { diff --git a/contrib/llvm/lib/CodeGen/MachineBlockPlacement.cpp b/contrib/llvm/lib/CodeGen/MachineBlockPlacement.cpp index 4cfc128a8c1d..5003115a770f 100644 --- a/contrib/llvm/lib/CodeGen/MachineBlockPlacement.cpp +++ b/contrib/llvm/lib/CodeGen/MachineBlockPlacement.cpp @@ -133,6 +133,14 @@ static cl::opt<unsigned> TailDupPlacementThreshold( "that won't conflict."), cl::init(2), cl::Hidden); +// Heuristic for aggressive tail duplication. +static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( + "tail-dup-placement-aggressive-threshold", + cl::desc("Instruction cutoff for aggressive tail duplication during " + "layout. Used at -O3. Tail merging during layout is forced to " + "have a threshold that won't conflict."), cl::init(3), + cl::Hidden); + // Heuristic for tail duplication. static cl::opt<unsigned> TailDupPlacementPenalty( "tail-dup-placement-penalty", @@ -2646,9 +2654,26 @@ bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { assert(BlockToChain.empty()); assert(ComputedEdges.empty()); + unsigned TailDupSize = TailDupPlacementThreshold; + // If only the aggressive threshold is explicitly set, use it. + if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && + TailDupPlacementThreshold.getNumOccurrences() == 0) + TailDupSize = TailDupPlacementAggressiveThreshold; + + TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); + // For agressive optimization, we can adjust some thresholds to be less + // conservative. + if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { + // At O3 we should be more willing to copy blocks for tail duplication. This + // increases size pressure, so we only do it at O3 + // Do this unless only the regular threshold is explicitly set. + if (TailDupPlacementThreshold.getNumOccurrences() == 0 || + TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) + TailDupSize = TailDupPlacementAggressiveThreshold; + } + if (TailDupPlacement) { MPDT = &getAnalysis<MachinePostDominatorTree>(); - unsigned TailDupSize = TailDupPlacementThreshold; if (MF.getFunction()->optForSize()) TailDupSize = 1; TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize); @@ -2658,7 +2683,6 @@ bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { buildCFGChains(); // Changing the layout can create new tail merging opportunities. - TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); // TailMerge can create jump into if branches that make CFG irreducible for // HW that requires structured CFG. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && @@ -2666,7 +2690,7 @@ bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { BranchFoldPlacement; // No tail merging opportunities if the block number is less than four. if (MF.size() > 3 && EnableTailMerge) { - unsigned TailMergeSize = TailDupPlacementThreshold + 1; + unsigned TailMergeSize = TailDupSize + 1; BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI, *MBPI, TailMergeSize); diff --git a/contrib/llvm/lib/CodeGen/MachineVerifier.cpp b/contrib/llvm/lib/CodeGen/MachineVerifier.cpp index bfb2cde030dc..ab433273b189 100644 --- a/contrib/llvm/lib/CodeGen/MachineVerifier.cpp +++ b/contrib/llvm/lib/CodeGen/MachineVerifier.cpp @@ -2063,12 +2063,12 @@ void MachineVerifier::verifyStackFrame() { if (I.getOpcode() == FrameSetupOpcode) { if (BBState.ExitIsSetup) report("FrameSetup is after another FrameSetup", &I); - BBState.ExitValue -= TII->getFrameSize(I); + BBState.ExitValue -= TII->getFrameTotalSize(I); BBState.ExitIsSetup = true; } if (I.getOpcode() == FrameDestroyOpcode) { - int Size = TII->getFrameSize(I); + int Size = TII->getFrameTotalSize(I); if (!BBState.ExitIsSetup) report("FrameDestroy is not after a FrameSetup", &I); int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue : diff --git a/contrib/llvm/lib/CodeGen/PHIElimination.cpp b/contrib/llvm/lib/CodeGen/PHIElimination.cpp index c67a25b888bf..db2264b2439d 100644 --- a/contrib/llvm/lib/CodeGen/PHIElimination.cpp +++ b/contrib/llvm/lib/CodeGen/PHIElimination.cpp @@ -34,7 +34,7 @@ #include <algorithm> using namespace llvm; -#define DEBUG_TYPE "phielim" +#define DEBUG_TYPE "phi-node-elimination" static cl::opt<bool> DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), diff --git a/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp b/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp index bf44ee8453b6..1803ea2b9249 100644 --- a/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp +++ b/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp @@ -3214,7 +3214,7 @@ RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) { CurrList(WorkList.begin() + PrevSize, WorkList.end()); if (copyCoalesceWorkList(CurrList)) WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(), - (MachineInstr*)nullptr), WorkList.end()); + nullptr), WorkList.end()); } void RegisterCoalescer::coalesceLocals() { diff --git a/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp b/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp index 35db30f89976..0635e5c0a63c 100644 --- a/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp +++ b/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp @@ -62,10 +62,9 @@ void RegScavenger::init(MachineBasicBlock &MBB) { } this->MBB = &MBB; - for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(), - IE = Scavenged.end(); I != IE; ++I) { - I->Reg = 0; - I->Restore = nullptr; + for (ScavengedInfo &SI : Scavenged) { + SI.Reg = 0; + SI.Restore = nullptr; } Tracking = false; diff --git a/contrib/llvm/lib/CodeGen/SafeStack.cpp b/contrib/llvm/lib/CodeGen/SafeStack.cpp index 7fa379d80c6c..08b3d345f689 100644 --- a/contrib/llvm/lib/CodeGen/SafeStack.cpp +++ b/contrib/llvm/lib/CodeGen/SafeStack.cpp @@ -19,6 +19,7 @@ #include "SafeStackLayout.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/Triple.h" +#include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" @@ -92,11 +93,11 @@ public: /// determined statically), and the unsafe stack, which contains all /// local variables that are accessed in ways that we can't prove to /// be safe. -class SafeStack : public FunctionPass { - const TargetMachine *TM; - const TargetLoweringBase *TL; - const DataLayout *DL; - ScalarEvolution *SE; +class SafeStack { + Function &F; + const TargetLoweringBase &TL; + const DataLayout &DL; + ScalarEvolution &SE; Type *StackPtrTy; Type *IntPtrTy; @@ -171,33 +172,21 @@ class SafeStack : public FunctionPass { uint64_t AllocaSize); public: - static char ID; // Pass identification, replacement for typeid. - SafeStack(const TargetMachine *TM) - : FunctionPass(ID), TM(TM), TL(nullptr), DL(nullptr) { - initializeSafeStackPass(*PassRegistry::getPassRegistry()); - } - SafeStack() : SafeStack(nullptr) {} - - void getAnalysisUsage(AnalysisUsage &AU) const override { - AU.addRequired<ScalarEvolutionWrapperPass>(); - } - - bool doInitialization(Module &M) override { - DL = &M.getDataLayout(); - - StackPtrTy = Type::getInt8PtrTy(M.getContext()); - IntPtrTy = DL->getIntPtrType(M.getContext()); - Int32Ty = Type::getInt32Ty(M.getContext()); - Int8Ty = Type::getInt8Ty(M.getContext()); - - return false; - } - - bool runOnFunction(Function &F) override; -}; // class SafeStack + SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL, + ScalarEvolution &SE) + : F(F), TL(TL), DL(DL), SE(SE), + StackPtrTy(Type::getInt8PtrTy(F.getContext())), + IntPtrTy(DL.getIntPtrType(F.getContext())), + Int32Ty(Type::getInt32Ty(F.getContext())), + Int8Ty(Type::getInt8Ty(F.getContext())) {} + + // Run the transformation on the associated function. + // Returns whether the function was changed. + bool run(); +}; uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) { - uint64_t Size = DL->getTypeAllocSize(AI->getAllocatedType()); + uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType()); if (AI->isArrayAllocation()) { auto C = dyn_cast<ConstantInt>(AI->getArraySize()); if (!C) @@ -209,11 +198,11 @@ uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) { bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize, const Value *AllocaPtr, uint64_t AllocaSize) { - AllocaOffsetRewriter Rewriter(*SE, AllocaPtr); - const SCEV *Expr = Rewriter.visit(SE->getSCEV(Addr)); + AllocaOffsetRewriter Rewriter(SE, AllocaPtr); + const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr)); - uint64_t BitWidth = SE->getTypeSizeInBits(Expr->getType()); - ConstantRange AccessStartRange = SE->getUnsignedRange(Expr); + uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType()); + ConstantRange AccessStartRange = SE.getUnsignedRange(Expr); ConstantRange SizeRange = ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize)); ConstantRange AccessRange = AccessStartRange.add(SizeRange); @@ -226,8 +215,8 @@ bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize, << *AllocaPtr << "\n" << " Access " << *Addr << "\n" << " SCEV " << *Expr - << " U: " << SE->getUnsignedRange(Expr) - << ", S: " << SE->getSignedRange(Expr) << "\n" + << " U: " << SE.getUnsignedRange(Expr) + << ", S: " << SE.getSignedRange(Expr) << "\n" << " Range " << AccessRange << "\n" << " AllocaRange " << AllocaRange << "\n" << " " << (Safe ? "safe" : "unsafe") << "\n"); @@ -266,7 +255,7 @@ bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) { switch (I->getOpcode()) { case Instruction::Load: { - if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getType()), AllocaPtr, + if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr, AllocaSize)) return false; break; @@ -282,7 +271,7 @@ bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) { return false; } - if (!IsAccessSafe(UI, DL->getTypeStoreSize(I->getOperand(0)->getType()), + if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()), AllocaPtr, AllocaSize)) return false; break; @@ -343,7 +332,7 @@ bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) { } Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) { - Value *StackGuardVar = TL->getIRStackGuard(IRB); + Value *StackGuardVar = TL.getIRStackGuard(IRB); if (!StackGuardVar) StackGuardVar = F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy); @@ -390,7 +379,7 @@ void SafeStack::findInsts(Function &F, if (!Arg.hasByValAttr()) continue; uint64_t Size = - DL->getTypeStoreSize(Arg.getType()->getPointerElementType()); + DL.getTypeStoreSize(Arg.getType()->getPointerElementType()); if (IsSafeStackAlloca(&Arg, Size)) continue; @@ -476,19 +465,19 @@ Value *SafeStack::moveStaticAllocasToUnsafeStack( if (StackGuardSlot) { Type *Ty = StackGuardSlot->getAllocatedType(); unsigned Align = - std::max(DL->getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment()); + std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment()); SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot), Align, SSC.getFullLiveRange()); } for (Argument *Arg : ByValArguments) { Type *Ty = Arg->getType()->getPointerElementType(); - uint64_t Size = DL->getTypeStoreSize(Ty); + uint64_t Size = DL.getTypeStoreSize(Ty); if (Size == 0) Size = 1; // Don't create zero-sized stack objects. // Ensure the object is properly aligned. - unsigned Align = std::max((unsigned)DL->getPrefTypeAlignment(Ty), + unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty), Arg->getParamAlignment()); SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange()); } @@ -501,7 +490,7 @@ Value *SafeStack::moveStaticAllocasToUnsafeStack( // Ensure the object is properly aligned. unsigned Align = - std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()); + std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()); SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI)); } @@ -539,7 +528,7 @@ Value *SafeStack::moveStaticAllocasToUnsafeStack( unsigned Offset = SSL.getObjectOffset(Arg); Type *Ty = Arg->getType()->getPointerElementType(); - uint64_t Size = DL->getTypeStoreSize(Ty); + uint64_t Size = DL.getTypeStoreSize(Ty); if (Size == 0) Size = 1; // Don't create zero-sized stack objects. @@ -630,7 +619,7 @@ void SafeStack::moveDynamicAllocasToUnsafeStack( ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false); Type *Ty = AI->getAllocatedType(); - uint64_t TySize = DL->getTypeAllocSize(Ty); + uint64_t TySize = DL.getTypeAllocSize(Ty); Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize)); Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy); @@ -638,7 +627,7 @@ void SafeStack::moveDynamicAllocasToUnsafeStack( // Align the SP value to satisfy the AllocaInst, type and stack alignments. unsigned Align = std::max( - std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()), + std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()), (unsigned)StackAlignment); assert(isPowerOf2_32(Align)); @@ -685,25 +674,10 @@ void SafeStack::moveDynamicAllocasToUnsafeStack( } } -bool SafeStack::runOnFunction(Function &F) { - DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); - - if (!F.hasFnAttribute(Attribute::SafeStack)) { - DEBUG(dbgs() << "[SafeStack] safestack is not requested" - " for this function\n"); - return false; - } - - if (F.isDeclaration()) { - DEBUG(dbgs() << "[SafeStack] function definition" - " is not available\n"); - return false; - } - - if (!TM) - report_fatal_error("Target machine is required"); - TL = TM->getSubtargetImpl(F)->getTargetLowering(); - SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); +bool SafeStack::run() { + assert(F.hasFnAttribute(Attribute::SafeStack) && + "Can't run SafeStack on a function without the attribute"); + assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration"); ++NumFunctions; @@ -736,7 +710,7 @@ bool SafeStack::runOnFunction(Function &F) { ++NumUnsafeStackRestorePointsFunctions; IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt()); - UnsafeStackPtr = TL->getSafeStackPointerLocation(IRB); + UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB); // Load the current stack pointer (we'll also use it as a base pointer). // FIXME: use a dedicated register for it ? @@ -788,14 +762,70 @@ bool SafeStack::runOnFunction(Function &F) { return true; } +class SafeStackLegacyPass : public FunctionPass { + const TargetMachine *TM; + +public: + static char ID; // Pass identification, replacement for typeid.. + SafeStackLegacyPass(const TargetMachine *TM) : FunctionPass(ID), TM(TM) { + initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry()); + } + + SafeStackLegacyPass() : SafeStackLegacyPass(nullptr) {} + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired<TargetLibraryInfoWrapperPass>(); + AU.addRequired<AssumptionCacheTracker>(); + } + + bool runOnFunction(Function &F) override { + DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); + + if (!F.hasFnAttribute(Attribute::SafeStack)) { + DEBUG(dbgs() << "[SafeStack] safestack is not requested" + " for this function\n"); + return false; + } + + if (F.isDeclaration()) { + DEBUG(dbgs() << "[SafeStack] function definition" + " is not available\n"); + return false; + } + + if (!TM) + report_fatal_error("Target machine is required"); + auto *TL = TM->getSubtargetImpl(F)->getTargetLowering(); + if (!TL) + report_fatal_error("TargetLowering instance is required"); + + auto *DL = &F.getParent()->getDataLayout(); + auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); + auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); + + // Compute DT and LI only for functions that have the attribute. + // This is only useful because the legacy pass manager doesn't let us + // compute analyzes lazily. + // In the backend pipeline, nothing preserves DT before SafeStack, so we + // would otherwise always compute it wastefully, even if there is no + // function with the safestack attribute. + DominatorTree DT(F); + LoopInfo LI(DT); + + ScalarEvolution SE(F, TLI, ACT, DT, LI); + + return SafeStack(F, *TL, *DL, SE).run(); + } +}; + } // anonymous namespace -char SafeStack::ID = 0; -INITIALIZE_TM_PASS_BEGIN(SafeStack, "safe-stack", +char SafeStackLegacyPass::ID = 0; +INITIALIZE_TM_PASS_BEGIN(SafeStackLegacyPass, "safe-stack", "Safe Stack instrumentation pass", false, false) -INITIALIZE_TM_PASS_END(SafeStack, "safe-stack", +INITIALIZE_TM_PASS_END(SafeStackLegacyPass, "safe-stack", "Safe Stack instrumentation pass", false, false) FunctionPass *llvm::createSafeStackPass(const llvm::TargetMachine *TM) { - return new SafeStack(TM); + return new SafeStackLegacyPass(TM); } diff --git a/contrib/llvm/lib/CodeGen/ScalarizeMaskedMemIntrin.cpp b/contrib/llvm/lib/CodeGen/ScalarizeMaskedMemIntrin.cpp new file mode 100644 index 000000000000..dab5b91f50ad --- /dev/null +++ b/contrib/llvm/lib/CodeGen/ScalarizeMaskedMemIntrin.cpp @@ -0,0 +1,660 @@ +//=== ScalarizeMaskedMemIntrin.cpp - Scalarize unsupported masked mem ===// +//=== instrinsics ===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass replaces masked memory intrinsics - when unsupported by the target +// - with a chain of basic blocks, that deal with the elements one-by-one if the +// appropriate mask bit is set. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/Target/TargetSubtargetInfo.h" + +using namespace llvm; + +#define DEBUG_TYPE "scalarize-masked-mem-intrin" + +namespace { + +class ScalarizeMaskedMemIntrin : public FunctionPass { + const TargetTransformInfo *TTI; + +public: + static char ID; // Pass identification, replacement for typeid + explicit ScalarizeMaskedMemIntrin() : FunctionPass(ID), TTI(nullptr) { + initializeScalarizeMaskedMemIntrinPass(*PassRegistry::getPassRegistry()); + } + bool runOnFunction(Function &F) override; + + StringRef getPassName() const override { + return "Scalarize Masked Memory Intrinsics"; + } + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired<TargetTransformInfoWrapperPass>(); + } + +private: + bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); + bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); +}; +} // namespace + +char ScalarizeMaskedMemIntrin::ID = 0; +INITIALIZE_PASS_BEGIN(ScalarizeMaskedMemIntrin, "scalarize-masked-mem-intrin", + "Scalarize unsupported masked memory intrinsics", false, + false) +INITIALIZE_PASS_END(ScalarizeMaskedMemIntrin, "scalarize-masked-mem-intrin", + "Scalarize unsupported masked memory intrinsics", false, + false) + +FunctionPass *llvm::createScalarizeMaskedMemIntrinPass() { + return new ScalarizeMaskedMemIntrin(); +} + +// Translate a masked load intrinsic like +// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, +// <16 x i1> %mask, <16 x i32> %passthru) +// to a chain of basic blocks, with loading element one-by-one if +// the appropriate mask bit is set +// +// %1 = bitcast i8* %addr to i32* +// %2 = extractelement <16 x i1> %mask, i32 0 +// %3 = icmp eq i1 %2, true +// br i1 %3, label %cond.load, label %else +// +// cond.load: ; preds = %0 +// %4 = getelementptr i32* %1, i32 0 +// %5 = load i32* %4 +// %6 = insertelement <16 x i32> undef, i32 %5, i32 0 +// br label %else +// +// else: ; preds = %0, %cond.load +// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] +// %7 = extractelement <16 x i1> %mask, i32 1 +// %8 = icmp eq i1 %7, true +// br i1 %8, label %cond.load1, label %else2 +// +// cond.load1: ; preds = %else +// %9 = getelementptr i32* %1, i32 1 +// %10 = load i32* %9 +// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 +// br label %else2 +// +// else2: ; preds = %else, %cond.load1 +// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] +// %12 = extractelement <16 x i1> %mask, i32 2 +// %13 = icmp eq i1 %12, true +// br i1 %13, label %cond.load4, label %else5 +// +static void scalarizeMaskedLoad(CallInst *CI) { + Value *Ptr = CI->getArgOperand(0); + Value *Alignment = CI->getArgOperand(1); + Value *Mask = CI->getArgOperand(2); + Value *Src0 = CI->getArgOperand(3); + + unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); + VectorType *VecType = dyn_cast<VectorType>(CI->getType()); + assert(VecType && "Unexpected return type of masked load intrinsic"); + + Type *EltTy = CI->getType()->getVectorElementType(); + + IRBuilder<> Builder(CI->getContext()); + Instruction *InsertPt = CI; + BasicBlock *IfBlock = CI->getParent(); + BasicBlock *CondBlock = nullptr; + BasicBlock *PrevIfBlock = CI->getParent(); + + Builder.SetInsertPoint(InsertPt); + Builder.SetCurrentDebugLocation(CI->getDebugLoc()); + + // Short-cut if the mask is all-true. + bool IsAllOnesMask = + isa<Constant>(Mask) && cast<Constant>(Mask)->isAllOnesValue(); + + if (IsAllOnesMask) { + Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); + CI->replaceAllUsesWith(NewI); + CI->eraseFromParent(); + return; + } + + // Adjust alignment for the scalar instruction. + AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits() / 8); + // Bitcast %addr fron i8* to EltTy* + Type *NewPtrType = + EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); + Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); + unsigned VectorWidth = VecType->getNumElements(); + + Value *UndefVal = UndefValue::get(VecType); + + // The result vector + Value *VResult = UndefVal; + + if (isa<ConstantVector>(Mask)) { + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) + continue; + Value *Gep = + Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); + LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); + VResult = + Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); + } + Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); + CI->replaceAllUsesWith(NewI); + CI->eraseFromParent(); + return; + } + + PHINode *Phi = nullptr; + Value *PrevPhi = UndefVal; + + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + + // Fill the "else" block, created in the previous iteration + // + // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] + // %mask_1 = extractelement <16 x i1> %mask, i32 Idx + // %to_load = icmp eq i1 %mask_1, true + // br i1 %to_load, label %cond.load, label %else + // + if (Idx > 0) { + Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); + Phi->addIncoming(VResult, CondBlock); + Phi->addIncoming(PrevPhi, PrevIfBlock); + PrevPhi = Phi; + VResult = Phi; + } + + Value *Predicate = + Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); + Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, + ConstantInt::get(Predicate->getType(), 1)); + + // Create "cond" block + // + // %EltAddr = getelementptr i32* %1, i32 0 + // %Elt = load i32* %EltAddr + // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx + // + CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); + Builder.SetInsertPoint(InsertPt); + + Value *Gep = + Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); + LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); + VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); + + // Create "else" block, fill it in the next iteration + BasicBlock *NewIfBlock = + CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); + Builder.SetInsertPoint(InsertPt); + Instruction *OldBr = IfBlock->getTerminator(); + BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); + OldBr->eraseFromParent(); + PrevIfBlock = IfBlock; + IfBlock = NewIfBlock; + } + + Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); + Phi->addIncoming(VResult, CondBlock); + Phi->addIncoming(PrevPhi, PrevIfBlock); + Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); + CI->replaceAllUsesWith(NewI); + CI->eraseFromParent(); +} + +// Translate a masked store intrinsic, like +// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, +// <16 x i1> %mask) +// to a chain of basic blocks, that stores element one-by-one if +// the appropriate mask bit is set +// +// %1 = bitcast i8* %addr to i32* +// %2 = extractelement <16 x i1> %mask, i32 0 +// %3 = icmp eq i1 %2, true +// br i1 %3, label %cond.store, label %else +// +// cond.store: ; preds = %0 +// %4 = extractelement <16 x i32> %val, i32 0 +// %5 = getelementptr i32* %1, i32 0 +// store i32 %4, i32* %5 +// br label %else +// +// else: ; preds = %0, %cond.store +// %6 = extractelement <16 x i1> %mask, i32 1 +// %7 = icmp eq i1 %6, true +// br i1 %7, label %cond.store1, label %else2 +// +// cond.store1: ; preds = %else +// %8 = extractelement <16 x i32> %val, i32 1 +// %9 = getelementptr i32* %1, i32 1 +// store i32 %8, i32* %9 +// br label %else2 +// . . . +static void scalarizeMaskedStore(CallInst *CI) { + Value *Src = CI->getArgOperand(0); + Value *Ptr = CI->getArgOperand(1); + Value *Alignment = CI->getArgOperand(2); + Value *Mask = CI->getArgOperand(3); + + unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); + VectorType *VecType = dyn_cast<VectorType>(Src->getType()); + assert(VecType && "Unexpected data type in masked store intrinsic"); + + Type *EltTy = VecType->getElementType(); + + IRBuilder<> Builder(CI->getContext()); + Instruction *InsertPt = CI; + BasicBlock *IfBlock = CI->getParent(); + Builder.SetInsertPoint(InsertPt); + Builder.SetCurrentDebugLocation(CI->getDebugLoc()); + + // Short-cut if the mask is all-true. + bool IsAllOnesMask = + isa<Constant>(Mask) && cast<Constant>(Mask)->isAllOnesValue(); + + if (IsAllOnesMask) { + Builder.CreateAlignedStore(Src, Ptr, AlignVal); + CI->eraseFromParent(); + return; + } + + // Adjust alignment for the scalar instruction. + AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits() / 8); + // Bitcast %addr fron i8* to EltTy* + Type *NewPtrType = + EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); + Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); + unsigned VectorWidth = VecType->getNumElements(); + + if (isa<ConstantVector>(Mask)) { + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) + continue; + Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); + Value *Gep = + Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); + Builder.CreateAlignedStore(OneElt, Gep, AlignVal); + } + CI->eraseFromParent(); + return; + } + + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + + // Fill the "else" block, created in the previous iteration + // + // %mask_1 = extractelement <16 x i1> %mask, i32 Idx + // %to_store = icmp eq i1 %mask_1, true + // br i1 %to_store, label %cond.store, label %else + // + Value *Predicate = + Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); + Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, + ConstantInt::get(Predicate->getType(), 1)); + + // Create "cond" block + // + // %OneElt = extractelement <16 x i32> %Src, i32 Idx + // %EltAddr = getelementptr i32* %1, i32 0 + // %store i32 %OneElt, i32* %EltAddr + // + BasicBlock *CondBlock = + IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); + Builder.SetInsertPoint(InsertPt); + + Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); + Value *Gep = + Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); + Builder.CreateAlignedStore(OneElt, Gep, AlignVal); + + // Create "else" block, fill it in the next iteration + BasicBlock *NewIfBlock = + CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); + Builder.SetInsertPoint(InsertPt); + Instruction *OldBr = IfBlock->getTerminator(); + BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); + OldBr->eraseFromParent(); + IfBlock = NewIfBlock; + } + CI->eraseFromParent(); +} + +// Translate a masked gather intrinsic like +// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, +// <16 x i1> %Mask, <16 x i32> %Src) +// to a chain of basic blocks, with loading element one-by-one if +// the appropriate mask bit is set +// +// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind +// % Mask0 = extractelement <16 x i1> %Mask, i32 0 +// % ToLoad0 = icmp eq i1 % Mask0, true +// br i1 % ToLoad0, label %cond.load, label %else +// +// cond.load: +// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 +// % Load0 = load i32, i32* % Ptr0, align 4 +// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 +// br label %else +// +// else: +// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] +// % Mask1 = extractelement <16 x i1> %Mask, i32 1 +// % ToLoad1 = icmp eq i1 % Mask1, true +// br i1 % ToLoad1, label %cond.load1, label %else2 +// +// cond.load1: +// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 +// % Load1 = load i32, i32* % Ptr1, align 4 +// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 +// br label %else2 +// . . . +// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src +// ret <16 x i32> %Result +static void scalarizeMaskedGather(CallInst *CI) { + Value *Ptrs = CI->getArgOperand(0); + Value *Alignment = CI->getArgOperand(1); + Value *Mask = CI->getArgOperand(2); + Value *Src0 = CI->getArgOperand(3); + + VectorType *VecType = dyn_cast<VectorType>(CI->getType()); + + assert(VecType && "Unexpected return type of masked load intrinsic"); + + IRBuilder<> Builder(CI->getContext()); + Instruction *InsertPt = CI; + BasicBlock *IfBlock = CI->getParent(); + BasicBlock *CondBlock = nullptr; + BasicBlock *PrevIfBlock = CI->getParent(); + Builder.SetInsertPoint(InsertPt); + unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); + + Builder.SetCurrentDebugLocation(CI->getDebugLoc()); + + Value *UndefVal = UndefValue::get(VecType); + + // The result vector + Value *VResult = UndefVal; + unsigned VectorWidth = VecType->getNumElements(); + + // Shorten the way if the mask is a vector of constants. + bool IsConstMask = isa<ConstantVector>(Mask); + + if (IsConstMask) { + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) + continue; + Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), + "Ptr" + Twine(Idx)); + LoadInst *Load = + Builder.CreateAlignedLoad(Ptr, AlignVal, "Load" + Twine(Idx)); + VResult = Builder.CreateInsertElement( + VResult, Load, Builder.getInt32(Idx), "Res" + Twine(Idx)); + } + Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); + CI->replaceAllUsesWith(NewI); + CI->eraseFromParent(); + return; + } + + PHINode *Phi = nullptr; + Value *PrevPhi = UndefVal; + + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + + // Fill the "else" block, created in the previous iteration + // + // %Mask1 = extractelement <16 x i1> %Mask, i32 1 + // %ToLoad1 = icmp eq i1 %Mask1, true + // br i1 %ToLoad1, label %cond.load, label %else + // + if (Idx > 0) { + Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); + Phi->addIncoming(VResult, CondBlock); + Phi->addIncoming(PrevPhi, PrevIfBlock); + PrevPhi = Phi; + VResult = Phi; + } + + Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx), + "Mask" + Twine(Idx)); + Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, + ConstantInt::get(Predicate->getType(), 1), + "ToLoad" + Twine(Idx)); + + // Create "cond" block + // + // %EltAddr = getelementptr i32* %1, i32 0 + // %Elt = load i32* %EltAddr + // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx + // + CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); + Builder.SetInsertPoint(InsertPt); + + Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), + "Ptr" + Twine(Idx)); + LoadInst *Load = + Builder.CreateAlignedLoad(Ptr, AlignVal, "Load" + Twine(Idx)); + VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), + "Res" + Twine(Idx)); + + // Create "else" block, fill it in the next iteration + BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); + Builder.SetInsertPoint(InsertPt); + Instruction *OldBr = IfBlock->getTerminator(); + BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); + OldBr->eraseFromParent(); + PrevIfBlock = IfBlock; + IfBlock = NewIfBlock; + } + + Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); + Phi->addIncoming(VResult, CondBlock); + Phi->addIncoming(PrevPhi, PrevIfBlock); + Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); + CI->replaceAllUsesWith(NewI); + CI->eraseFromParent(); +} + +// Translate a masked scatter intrinsic, like +// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, +// <16 x i1> %Mask) +// to a chain of basic blocks, that stores element one-by-one if +// the appropriate mask bit is set. +// +// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind +// % Mask0 = extractelement <16 x i1> % Mask, i32 0 +// % ToStore0 = icmp eq i1 % Mask0, true +// br i1 %ToStore0, label %cond.store, label %else +// +// cond.store: +// % Elt0 = extractelement <16 x i32> %Src, i32 0 +// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 +// store i32 %Elt0, i32* % Ptr0, align 4 +// br label %else +// +// else: +// % Mask1 = extractelement <16 x i1> % Mask, i32 1 +// % ToStore1 = icmp eq i1 % Mask1, true +// br i1 % ToStore1, label %cond.store1, label %else2 +// +// cond.store1: +// % Elt1 = extractelement <16 x i32> %Src, i32 1 +// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 +// store i32 % Elt1, i32* % Ptr1, align 4 +// br label %else2 +// . . . +static void scalarizeMaskedScatter(CallInst *CI) { + Value *Src = CI->getArgOperand(0); + Value *Ptrs = CI->getArgOperand(1); + Value *Alignment = CI->getArgOperand(2); + Value *Mask = CI->getArgOperand(3); + + assert(isa<VectorType>(Src->getType()) && + "Unexpected data type in masked scatter intrinsic"); + assert(isa<VectorType>(Ptrs->getType()) && + isa<PointerType>(Ptrs->getType()->getVectorElementType()) && + "Vector of pointers is expected in masked scatter intrinsic"); + + IRBuilder<> Builder(CI->getContext()); + Instruction *InsertPt = CI; + BasicBlock *IfBlock = CI->getParent(); + Builder.SetInsertPoint(InsertPt); + Builder.SetCurrentDebugLocation(CI->getDebugLoc()); + + unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); + unsigned VectorWidth = Src->getType()->getVectorNumElements(); + + // Shorten the way if the mask is a vector of constants. + bool IsConstMask = isa<ConstantVector>(Mask); + + if (IsConstMask) { + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) + continue; + Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), + "Elt" + Twine(Idx)); + Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), + "Ptr" + Twine(Idx)); + Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); + } + CI->eraseFromParent(); + return; + } + for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { + // Fill the "else" block, created in the previous iteration + // + // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx + // % ToStore = icmp eq i1 % Mask1, true + // br i1 % ToStore, label %cond.store, label %else + // + Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx), + "Mask" + Twine(Idx)); + Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, + ConstantInt::get(Predicate->getType(), 1), + "ToStore" + Twine(Idx)); + + // Create "cond" block + // + // % Elt1 = extractelement <16 x i32> %Src, i32 1 + // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 + // %store i32 % Elt1, i32* % Ptr1 + // + BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); + Builder.SetInsertPoint(InsertPt); + + Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), + "Elt" + Twine(Idx)); + Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), + "Ptr" + Twine(Idx)); + Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); + + // Create "else" block, fill it in the next iteration + BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); + Builder.SetInsertPoint(InsertPt); + Instruction *OldBr = IfBlock->getTerminator(); + BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); + OldBr->eraseFromParent(); + IfBlock = NewIfBlock; + } + CI->eraseFromParent(); +} + +bool ScalarizeMaskedMemIntrin::runOnFunction(Function &F) { + if (skipFunction(F)) + return false; + + bool EverMadeChange = false; + + TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); + + bool MadeChange = true; + while (MadeChange) { + MadeChange = false; + for (Function::iterator I = F.begin(); I != F.end();) { + BasicBlock *BB = &*I++; + bool ModifiedDTOnIteration = false; + MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); + + // Restart BB iteration if the dominator tree of the Function was changed + if (ModifiedDTOnIteration) + break; + } + + EverMadeChange |= MadeChange; + } + + return EverMadeChange; +} + +bool ScalarizeMaskedMemIntrin::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { + bool MadeChange = false; + + BasicBlock::iterator CurInstIterator = BB.begin(); + while (CurInstIterator != BB.end()) { + if (CallInst *CI = dyn_cast<CallInst>(&*CurInstIterator++)) + MadeChange |= optimizeCallInst(CI, ModifiedDT); + if (ModifiedDT) + return true; + } + + return MadeChange; +} + +bool ScalarizeMaskedMemIntrin::optimizeCallInst(CallInst *CI, + bool &ModifiedDT) { + + IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); + if (II) { + switch (II->getIntrinsicID()) { + default: + break; + case Intrinsic::masked_load: { + // Scalarize unsupported vector masked load + if (!TTI->isLegalMaskedLoad(CI->getType())) { + scalarizeMaskedLoad(CI); + ModifiedDT = true; + return true; + } + return false; + } + case Intrinsic::masked_store: { + if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { + scalarizeMaskedStore(CI); + ModifiedDT = true; + return true; + } + return false; + } + case Intrinsic::masked_gather: { + if (!TTI->isLegalMaskedGather(CI->getType())) { + scalarizeMaskedGather(CI); + ModifiedDT = true; + return true; + } + return false; + } + case Intrinsic::masked_scatter: { + if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { + scalarizeMaskedScatter(CI); + ModifiedDT = true; + return true; + } + return false; + } + } + } + + return false; +} diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp index c77046fdfaf5..caf5cb497a71 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp @@ -114,7 +114,7 @@ namespace { SmallPtrSet<SDNode *, 32> CombinedNodes; // AA - Used for DAG load/store alias analysis. - AliasAnalysis &AA; + AliasAnalysis *AA; /// When an instruction is simplified, add all users of the instruction to /// the work lists because they might get more simplified now. @@ -496,9 +496,9 @@ namespace { SDValue distributeTruncateThroughAnd(SDNode *N); public: - DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) + DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), - OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { + OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) { ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); MaximumLegalStoreInBits = 0; @@ -1729,10 +1729,9 @@ SDValue DAGCombiner::visitTokenFactor(SDNode *N) { NumLeftToConsider--; } - SDValue Result; - // If we've changed things around then replace token factor. if (Changed) { + SDValue Result; if (Ops.empty()) { // The entry token is the only possible outcome. Result = DAG.getEntryNode(); @@ -1749,13 +1748,9 @@ SDValue DAGCombiner::visitTokenFactor(SDNode *N) { Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); } } - - // Add users to worklist, since we may introduce a lot of new - // chained token factors while removing memory deps. - return CombineTo(N, Result, true /*add to worklist*/); + return Result; } - - return Result; + return SDValue(); } /// MERGE_VALUES can always be eliminated. @@ -2131,17 +2126,17 @@ SDValue DAGCombiner::visitADDCARRY(SDNode *N) { SDValue N0 = N->getOperand(0); SDValue N1 = N->getOperand(1); SDValue CarryIn = N->getOperand(2); + SDLoc DL(N); // canonicalize constant to RHS ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); if (N0C && !N1C) - return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), - N1, N0, CarryIn); + return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); // fold (addcarry x, y, false) -> (uaddo x, y) if (isNullConstant(CarryIn)) - return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), N0, N1); + return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) return Combined; @@ -5313,17 +5308,6 @@ SDValue DAGCombiner::visitSHL(SDNode *N) { } } - // If the target supports masking y in (shl, y), - // fold (shl x, (and y, ((1 << numbits(x)) - 1))) -> (shl x, y) - if (TLI.isOperationLegal(ISD::SHL, VT) && - TLI.supportsModuloShift(ISD::SHL, VT) && N1->getOpcode() == ISD::AND) { - if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { - if (Mask->getZExtValue() == OpSizeInBits - 1) { - return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1->getOperand(0)); - } - } - } - ConstantSDNode *N1C = isConstOrConstSplat(N1); // fold (shl c1, c2) -> c1<<c2 @@ -5331,7 +5315,7 @@ SDValue DAGCombiner::visitSHL(SDNode *N) { if (N0C && N1C && !N1C->isOpaque()) return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); // fold (shl 0, x) -> 0 - if (isNullConstant(N0)) + if (isNullConstantOrNullSplatConstant(N0)) return N0; // fold (shl x, c >= size(x)) -> undef if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) @@ -5522,18 +5506,9 @@ SDValue DAGCombiner::visitSRA(SDNode *N) { EVT VT = N0.getValueType(); unsigned OpSizeInBits = VT.getScalarSizeInBits(); - // If the target supports masking y in (sra, y), - // fold (sra x, (and y, ((1 << numbits(x)) - 1))) -> (sra x, y) - if (TLI.isOperationLegal(ISD::SRA, VT) && - TLI.supportsModuloShift(ISD::SRA, VT) && N1->getOpcode() == ISD::AND) { - if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { - if (Mask->getZExtValue() == OpSizeInBits - 1) { - return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, N1->getOperand(0)); - } - } - } - // Arithmetic shifting an all-sign-bit value is a no-op. + // fold (sra 0, x) -> 0 + // fold (sra -1, x) -> -1 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) return N0; @@ -5548,12 +5523,6 @@ SDValue DAGCombiner::visitSRA(SDNode *N) { ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); if (N0C && N1C && !N1C->isOpaque()) return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); - // fold (sra 0, x) -> 0 - if (isNullConstant(N0)) - return N0; - // fold (sra -1, x) -> -1 - if (isAllOnesConstant(N0)) - return N0; // fold (sra x, c >= size(x)) -> undef if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) return DAG.getUNDEF(VT); @@ -5691,17 +5660,6 @@ SDValue DAGCombiner::visitSRL(SDNode *N) { EVT VT = N0.getValueType(); unsigned OpSizeInBits = VT.getScalarSizeInBits(); - // If the target supports masking y in (srl, y), - // fold (srl x, (and y, ((1 << numbits(x)) - 1))) -> (srl x, y) - if (TLI.isOperationLegal(ISD::SRL, VT) && - TLI.supportsModuloShift(ISD::SRL, VT) && N1->getOpcode() == ISD::AND) { - if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { - if (Mask->getZExtValue() == OpSizeInBits - 1) { - return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1->getOperand(0)); - } - } - } - // fold vector ops if (VT.isVector()) if (SDValue FoldedVOp = SimplifyVBinOp(N)) @@ -5714,7 +5672,7 @@ SDValue DAGCombiner::visitSRL(SDNode *N) { if (N0C && N1C && !N1C->isOpaque()) return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); // fold (srl 0, x) -> 0 - if (isNullConstant(N0)) + if (isNullConstantOrNullSplatConstant(N0)) return N0; // fold (srl x, c >= size(x)) -> undef if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) @@ -7365,14 +7323,8 @@ SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { N0.getValueSizeInBits(), std::min(Op.getValueSizeInBits(), VT.getSizeInBits())); - if (TruncatedBits.isSubsetOf(Known.Zero)) { - if (VT.bitsGT(Op.getValueType())) - return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); - if (VT.bitsLT(Op.getValueType())) - return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); - - return Op; - } + if (TruncatedBits.isSubsetOf(Known.Zero)) + return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); } // fold (zext (truncate (load x))) -> (zext (smaller load x)) @@ -7419,14 +7371,8 @@ SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { } if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { - SDValue Op = N0.getOperand(0); - if (SrcVT.bitsLT(VT)) { - Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); - AddToWorklist(Op.getNode()); - } else if (SrcVT.bitsGT(VT)) { - Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); - AddToWorklist(Op.getNode()); - } + SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); + AddToWorklist(Op.getNode()); return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); } } @@ -7440,11 +7386,7 @@ SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { N0.getValueType()) || !TLI.isZExtFree(N0.getValueType(), VT))) { SDValue X = N0.getOperand(0).getOperand(0); - if (X.getValueType().bitsLT(VT)) { - X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); - } else if (X.getValueType().bitsGT(VT)) { - X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); - } + X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); Mask = Mask.zext(VT.getSizeInBits()); SDLoc DL(N); @@ -7669,14 +7611,8 @@ SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { } // fold (aext (truncate x)) - if (N0.getOpcode() == ISD::TRUNCATE) { - SDValue TruncOp = N0.getOperand(0); - if (TruncOp.getValueType() == VT) - return TruncOp; // x iff x size == zext size. - if (TruncOp.getValueType().bitsGT(VT)) - return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); - return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); - } + if (N0.getOpcode() == ISD::TRUNCATE) + return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); // Fold (aext (and (trunc x), cst)) -> (and x, cst) // if the trunc is not free. @@ -7687,11 +7623,7 @@ SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { N0.getValueType())) { SDLoc DL(N); SDValue X = N0.getOperand(0).getOperand(0); - if (X.getValueType().bitsLT(VT)) { - X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); - } else if (X.getValueType().bitsGT(VT)) { - X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); - } + X = DAG.getAnyExtOrTrunc(X, DL, VT); APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); Mask = Mask.zext(VT.getSizeInBits()); return DAG.getNode(ISD::AND, DL, VT, @@ -14868,6 +14800,55 @@ SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { return SDValue(); } +// Combine shuffles of splat-shuffles of the form: +// shuffle (shuffle V, undef, splat-mask), undef, M +// If splat-mask contains undef elements, we need to be careful about +// introducing undef's in the folded mask which are not the result of composing +// the masks of the shuffles. +static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, + ShuffleVectorSDNode *Splat, + SelectionDAG &DAG) { + ArrayRef<int> SplatMask = Splat->getMask(); + assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); + + // Prefer simplifying to the splat-shuffle, if possible. This is legal if + // every undef mask element in the splat-shuffle has a corresponding undef + // element in the user-shuffle's mask or if the composition of mask elements + // would result in undef. + // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): + // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] + // In this case it is not legal to simplify to the splat-shuffle because we + // may be exposing the users of the shuffle an undef element at index 1 + // which was not there before the combine. + // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] + // In this case the composition of masks yields SplatMask, so it's ok to + // simplify to the splat-shuffle. + // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] + // In this case the composed mask includes all undef elements of SplatMask + // and in addition sets element zero to undef. It is safe to simplify to + // the splat-shuffle. + auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, + ArrayRef<int> SplatMask) { + for (unsigned i = 0, e = UserMask.size(); i != e; ++i) + if (UserMask[i] != -1 && SplatMask[i] == -1 && + SplatMask[UserMask[i]] != -1) + return false; + return true; + }; + if (CanSimplifyToExistingSplat(UserMask, SplatMask)) + return SDValue(Splat, 0); + + // Create a new shuffle with a mask that is composed of the two shuffles' + // masks. + SmallVector<int, 32> NewMask; + for (int Idx : UserMask) + NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); + + return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), + Splat->getOperand(0), Splat->getOperand(1), + NewMask); +} + SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { EVT VT = N->getValueType(0); unsigned NumElts = VT.getVectorNumElements(); @@ -14914,6 +14895,11 @@ SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); } + // A shuffle of a single vector that is a splat can always be folded. + if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) + if (N1->isUndef() && N0Shuf->isSplat()) + return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); + // If it is a splat, check if the argument vector is another splat or a // build_vector. if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { @@ -16381,17 +16367,17 @@ bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { UseAA = false; #endif - if (UseAA && + if (UseAA && AA && Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { // Use alias analysis information. int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; AliasResult AAResult = - AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, - UseTBAA ? Op0->getAAInfo() : AAMDNodes()), - MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, - UseTBAA ? Op1->getAAInfo() : AAMDNodes())); + AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, + UseTBAA ? Op0->getAAInfo() : AAMDNodes()), + MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, + UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); if (AAResult == NoAlias) return false; } @@ -16605,7 +16591,7 @@ bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { } /// This is the entry point for the file. -void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, +void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, CodeGenOpt::Level OptLevel) { /// This is the main entry point to this class. DAGCombiner(*this, AA, OptLevel).Run(Level); diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp index 8c98e3740f6d..5003b79974eb 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp @@ -622,7 +622,7 @@ bool FastISel::selectStackmap(const CallInst *I) { // have to worry about calling conventions and target-specific lowering code. // Instead we perform the call lowering right here. // - // CALLSEQ_START(0...) + // CALLSEQ_START(0, 0...) // STACKMAP(id, nbytes, ...) // CALLSEQ_END(0, 0) // @@ -1150,16 +1150,16 @@ bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) { return true; } - unsigned Offset = 0; + // Byval arguments with frame indices were already handled after argument + // lowering and before isel. + const auto *Arg = + dyn_cast<Argument>(Address->stripInBoundsConstantOffsets()); + if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX) + return true; + Optional<MachineOperand> Op; - if (const auto *Arg = dyn_cast<Argument>(Address)) - // Some arguments' frame index is recorded during argument lowering. - Offset = FuncInfo.getArgumentFrameIndex(Arg); - if (Offset) - Op = MachineOperand::CreateFI(Offset); - if (!Op) - if (unsigned Reg = lookUpRegForValue(Address)) - Op = MachineOperand::CreateReg(Reg, false); + if (unsigned Reg = lookUpRegForValue(Address)) + Op = MachineOperand::CreateReg(Reg, false); // If we have a VLA that has a "use" in a metadata node that's then used // here but it has no other uses, then we have a problem. E.g., diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp index cdf4d3a8b4e5..606b8952f3c1 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp @@ -85,7 +85,6 @@ void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf, MF = &mf; TLI = MF->getSubtarget().getTargetLowering(); RegInfo = &MF->getRegInfo(); - MachineModuleInfo &MMI = MF->getMMI(); const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); unsigned StackAlign = TFI->getStackAlignment(); @@ -214,33 +213,6 @@ void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf, if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I))) InitializeRegForValue(&I); - // Collect llvm.dbg.declare information. This is done now instead of - // during the initial isel pass through the IR so that it is done - // in a predictable order. - if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I)) { - assert(DI->getVariable() && "Missing variable"); - assert(DI->getDebugLoc() && "Missing location"); - if (MMI.hasDebugInfo()) { - // Don't handle byval struct arguments or VLAs, for example. - // Non-byval arguments are handled here (they refer to the stack - // temporary alloca at this point). - const Value *Address = DI->getAddress(); - if (Address) { - if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) - Address = BCI->getOperand(0); - if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { - DenseMap<const AllocaInst *, int>::iterator SI = - StaticAllocaMap.find(AI); - if (SI != StaticAllocaMap.end()) { // Check for VLAs. - int FI = SI->second; - MF->setVariableDbgInfo(DI->getVariable(), DI->getExpression(), - FI, DI->getDebugLoc()); - } - } - } - } - } - // Decide the preferred extend type for a value. PreferredExtendType[&I] = getPreferredExtendForValue(&I); } @@ -510,12 +482,11 @@ void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A, /// If the argument does not have any assigned frame index then 0 is /// returned. int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) { - DenseMap<const Argument *, int>::iterator I = - ByValArgFrameIndexMap.find(A); + auto I = ByValArgFrameIndexMap.find(A); if (I != ByValArgFrameIndexMap.end()) return I->second; DEBUG(dbgs() << "Argument does not have assigned frame index!\n"); - return 0; + return INT_MAX; } unsigned FunctionLoweringInfo::getCatchPadExceptionPointerVReg( diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp index 2654b3ad7a62..9a47a914df91 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp @@ -1493,7 +1493,7 @@ void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, // Chain the dynamic stack allocation so that it doesn't modify the stack // pointer when other instructions are using the stack. - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); SDValue Size = Tmp2.getOperand(1); SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); @@ -4187,6 +4187,7 @@ void SelectionDAGLegalize::PromoteNode(SDNode *Node) { ReplacedNode(Node); break; } + case ISD::MUL: case ISD::SDIV: case ISD::SREM: case ISD::UDIV: diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h index cde4331cc42d..4c3b514856b7 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h @@ -675,6 +675,7 @@ private: // Vector Operand Splitting: <128 x ty> -> 2 x <64 x ty>. bool SplitVectorOperand(SDNode *N, unsigned OpNo); SDValue SplitVecOp_VSELECT(SDNode *N, unsigned OpNo); + SDValue SplitVecOp_VECREDUCE(SDNode *N, unsigned OpNo); SDValue SplitVecOp_UnaryOp(SDNode *N); SDValue SplitVecOp_TruncateHelper(SDNode *N); diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp index 97a7fab6efd0..ff0e609803d8 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp @@ -1513,6 +1513,22 @@ bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) { case ISD::ZERO_EXTEND_VECTOR_INREG: Res = SplitVecOp_ExtVecInRegOp(N); break; + + case ISD::VECREDUCE_FADD: + case ISD::VECREDUCE_FMUL: + case ISD::VECREDUCE_ADD: + case ISD::VECREDUCE_MUL: + case ISD::VECREDUCE_AND: + case ISD::VECREDUCE_OR: + case ISD::VECREDUCE_XOR: + case ISD::VECREDUCE_SMAX: + case ISD::VECREDUCE_SMIN: + case ISD::VECREDUCE_UMAX: + case ISD::VECREDUCE_UMIN: + case ISD::VECREDUCE_FMAX: + case ISD::VECREDUCE_FMIN: + Res = SplitVecOp_VECREDUCE(N, OpNo); + break; } } @@ -1565,6 +1581,48 @@ SDValue DAGTypeLegalizer::SplitVecOp_VSELECT(SDNode *N, unsigned OpNo) { return DAG.getNode(ISD::CONCAT_VECTORS, DL, Src0VT, LoSelect, HiSelect); } +SDValue DAGTypeLegalizer::SplitVecOp_VECREDUCE(SDNode *N, unsigned OpNo) { + EVT ResVT = N->getValueType(0); + SDValue Lo, Hi; + SDLoc dl(N); + + SDValue VecOp = N->getOperand(OpNo); + EVT VecVT = VecOp.getValueType(); + assert(VecVT.isVector() && "Can only split reduce vector operand"); + GetSplitVector(VecOp, Lo, Hi); + EVT LoOpVT, HiOpVT; + std::tie(LoOpVT, HiOpVT) = DAG.GetSplitDestVTs(VecVT); + + bool NoNaN = N->getFlags().hasNoNaNs(); + unsigned CombineOpc = 0; + switch (N->getOpcode()) { + case ISD::VECREDUCE_FADD: CombineOpc = ISD::FADD; break; + case ISD::VECREDUCE_FMUL: CombineOpc = ISD::FMUL; break; + case ISD::VECREDUCE_ADD: CombineOpc = ISD::ADD; break; + case ISD::VECREDUCE_MUL: CombineOpc = ISD::MUL; break; + case ISD::VECREDUCE_AND: CombineOpc = ISD::AND; break; + case ISD::VECREDUCE_OR: CombineOpc = ISD::OR; break; + case ISD::VECREDUCE_XOR: CombineOpc = ISD::XOR; break; + case ISD::VECREDUCE_SMAX: CombineOpc = ISD::SMAX; break; + case ISD::VECREDUCE_SMIN: CombineOpc = ISD::SMIN; break; + case ISD::VECREDUCE_UMAX: CombineOpc = ISD::UMAX; break; + case ISD::VECREDUCE_UMIN: CombineOpc = ISD::UMIN; break; + case ISD::VECREDUCE_FMAX: + CombineOpc = NoNaN ? ISD::FMAXNUM : ISD::FMAXNAN; + break; + case ISD::VECREDUCE_FMIN: + CombineOpc = NoNaN ? ISD::FMINNUM : ISD::FMINNAN; + break; + default: + llvm_unreachable("Unexpected reduce ISD node"); + } + + // Use the appropriate scalar instruction on the split subvectors before + // reducing the now partially reduced smaller vector. + SDValue Partial = DAG.getNode(CombineOpc, dl, LoOpVT, Lo, Hi); + return DAG.getNode(N->getOpcode(), dl, ResVT, Partial); +} + SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) { // The result has a legal vector type, but the input needs splitting. EVT ResVT = N->getValueType(0); diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp index d605a1dc1c20..057badcd6b74 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp @@ -2217,10 +2217,10 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // Also compute a conservative estimate for high known-0 bits. // More trickiness is possible, but this is sufficient for the // interesting case of alignment computation. - unsigned TrailZ = Known.Zero.countTrailingOnes() + - Known2.Zero.countTrailingOnes(); - unsigned LeadZ = std::max(Known.Zero.countLeadingOnes() + - Known2.Zero.countLeadingOnes(), + unsigned TrailZ = Known.countMinTrailingZeros() + + Known2.countMinTrailingZeros(); + unsigned LeadZ = std::max(Known.countMinLeadingZeros() + + Known2.countMinLeadingZeros(), BitWidth) - BitWidth; Known.resetAll(); @@ -2233,13 +2233,12 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // treat a udiv as a logical right shift by the power of 2 known to // be less than the denominator. computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); - unsigned LeadZ = Known2.Zero.countLeadingOnes(); + unsigned LeadZ = Known2.countMinLeadingZeros(); computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1); - unsigned RHSUnknownLeadingOnes = Known2.One.countLeadingZeros(); - if (RHSUnknownLeadingOnes != BitWidth) - LeadZ = std::min(BitWidth, - LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); + unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros(); + if (RHSMaxLeadingZeros != BitWidth) + LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1); Known.Zero.setHighBits(LeadZ); break; @@ -2359,7 +2358,7 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, case ISD::CTTZ_ZERO_UNDEF: { computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); // If we have a known 1, its position is our upper bound. - unsigned PossibleTZ = Known2.One.countTrailingZeros(); + unsigned PossibleTZ = Known2.countMaxTrailingZeros(); unsigned LowBits = Log2_32(PossibleTZ) + 1; Known.Zero.setBitsFrom(LowBits); break; @@ -2368,7 +2367,7 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, case ISD::CTLZ_ZERO_UNDEF: { computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); // If we have a known 1, its position is our upper bound. - unsigned PossibleLZ = Known2.One.countLeadingZeros(); + unsigned PossibleLZ = Known2.countMaxLeadingZeros(); unsigned LowBits = Log2_32(PossibleLZ) + 1; Known.Zero.setBitsFrom(LowBits); break; @@ -2376,7 +2375,7 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, case ISD::CTPOP: { computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); // If we know some of the bits are zero, they can't be one. - unsigned PossibleOnes = BitWidth - Known2.Zero.countPopulation(); + unsigned PossibleOnes = Known2.countMaxPopulation(); Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); break; } @@ -2493,13 +2492,12 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // going to be 0 in the result. Both addition and complement operations // preserve the low zero bits. computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); - unsigned KnownZeroLow = Known2.Zero.countTrailingOnes(); + unsigned KnownZeroLow = Known2.countMinTrailingZeros(); if (KnownZeroLow == 0) break; computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1); - KnownZeroLow = std::min(KnownZeroLow, - Known2.Zero.countTrailingOnes()); + KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros()); Known.Zero.setLowBits(KnownZeroLow); break; } @@ -2526,15 +2524,13 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // and the other has the top 8 bits clear, we know the top 7 bits of the // output must be clear. computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1); - unsigned KnownZeroHigh = Known2.Zero.countLeadingOnes(); - unsigned KnownZeroLow = Known2.Zero.countTrailingOnes(); + unsigned KnownZeroHigh = Known2.countMinLeadingZeros(); + unsigned KnownZeroLow = Known2.countMinTrailingZeros(); computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1); - KnownZeroHigh = std::min(KnownZeroHigh, - Known2.Zero.countLeadingOnes()); - KnownZeroLow = std::min(KnownZeroLow, - Known2.Zero.countTrailingOnes()); + KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros()); + KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros()); if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) { // With ADDE and ADDCARRY, a carry bit may be added in, so we can only @@ -2594,8 +2590,8 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1); computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1); - uint32_t Leaders = std::max(Known.Zero.countLeadingOnes(), - Known2.Zero.countLeadingOnes()); + uint32_t Leaders = + std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros()); Known.resetAll(); Known.Zero.setHighBits(Leaders); break; @@ -2711,8 +2707,8 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // UMIN - we know that the result will have the maximum of the // known zero leading bits of the inputs. - unsigned LeadZero = Known.Zero.countLeadingOnes(); - LeadZero = std::max(LeadZero, Known2.Zero.countLeadingOnes()); + unsigned LeadZero = Known.countMinLeadingZeros(); + LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros()); Known.Zero &= Known2.Zero; Known.One &= Known2.One; @@ -2726,8 +2722,8 @@ void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known, // UMAX - we know that the result will have the maximum of the // known one leading bits of the inputs. - unsigned LeadOne = Known.One.countLeadingOnes(); - LeadOne = std::max(LeadOne, Known2.One.countLeadingOnes()); + unsigned LeadOne = Known.countMinLeadingOnes(); + LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes()); Known.Zero &= Known2.Zero; Known.One &= Known2.One; @@ -2843,8 +2839,7 @@ bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { // Fall back to computeKnownBits to catch other known cases. KnownBits Known; computeKnownBits(Val, Known); - return (Known.Zero.countPopulation() == BitWidth - 1) && - (Known.One.countPopulation() == 1); + return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); } unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { @@ -2860,6 +2855,7 @@ unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, EVT VT = Op.getValueType(); assert(VT.isInteger() && "Invalid VT!"); unsigned VTBits = VT.getScalarSizeInBits(); + unsigned NumElts = DemandedElts.getBitWidth(); unsigned Tmp, Tmp2; unsigned FirstAnswer = 1; @@ -2903,6 +2899,39 @@ unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, } return Tmp; + case ISD::VECTOR_SHUFFLE: { + // Collect the minimum number of sign bits that are shared by every vector + // element referenced by the shuffle. + APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); + const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); + assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); + for (unsigned i = 0; i != NumElts; ++i) { + int M = SVN->getMaskElt(i); + if (!DemandedElts[i]) + continue; + // For UNDEF elements, we don't know anything about the common state of + // the shuffle result. + if (M < 0) + return 1; + if ((unsigned)M < NumElts) + DemandedLHS.setBit((unsigned)M % NumElts); + else + DemandedRHS.setBit((unsigned)M % NumElts); + } + Tmp = UINT_MAX; + if (!!DemandedLHS) + Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); + if (!!DemandedRHS) { + Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); + Tmp = std::min(Tmp, Tmp2); + } + // If we don't know anything, early out and try computeKnownBits fall-back. + if (Tmp == 1) + break; + assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); + return Tmp; + } + case ISD::SIGN_EXTEND: case ISD::SIGN_EXTEND_VECTOR_INREG: Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); @@ -3142,14 +3171,36 @@ unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); } - case ISD::EXTRACT_SUBVECTOR: - return ComputeNumSignBits(Op.getOperand(0), Depth + 1); + case ISD::EXTRACT_SUBVECTOR: { + // If we know the element index, just demand that subvector elements, + // otherwise demand them all. + SDValue Src = Op.getOperand(0); + ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1)); + unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); + if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) { + // Offset the demanded elts by the subvector index. + uint64_t Idx = SubIdx->getZExtValue(); + APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx); + return ComputeNumSignBits(Src, DemandedSrc, Depth + 1); + } + return ComputeNumSignBits(Src, Depth + 1); + } case ISD::CONCAT_VECTORS: - // Determine the minimum number of sign bits across all input vectors. - // Early out if the result is already 1. - Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1); - for (unsigned i = 1, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) - Tmp = std::min(Tmp, ComputeNumSignBits(Op.getOperand(i), Depth + 1)); + // Determine the minimum number of sign bits across all demanded + // elts of the input vectors. Early out if the result is already 1. + Tmp = UINT_MAX; + EVT SubVectorVT = Op.getOperand(0).getValueType(); + unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); + unsigned NumSubVectors = Op.getNumOperands(); + for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { + APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); + DemandedSub = DemandedSub.trunc(NumSubVectorElts); + if (!DemandedSub) + continue; + Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); + Tmp = std::min(Tmp, Tmp2); + } + assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); return Tmp; } @@ -3543,7 +3594,7 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, assert(Operand.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!"); if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) - return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); + return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); else if (OpOpcode == ISD::UNDEF) // sext(undef) = 0, because the top bits will all be the same. return getConstant(0, DL, VT); @@ -3559,8 +3610,7 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, assert(Operand.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!"); if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) - return getNode(ISD::ZERO_EXTEND, DL, VT, - Operand.getNode()->getOperand(0)); + return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); else if (OpOpcode == ISD::UNDEF) // zext(undef) = 0, because the top bits will be zero. return getConstant(0, DL, VT); @@ -3579,13 +3629,13 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ANY_EXTEND) // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) - return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); + return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); else if (OpOpcode == ISD::UNDEF) return getUNDEF(VT); // (ext (trunx x)) -> x if (OpOpcode == ISD::TRUNCATE) { - SDValue OpOp = Operand.getNode()->getOperand(0); + SDValue OpOp = Operand.getOperand(0); if (OpOp.getValueType() == VT) return OpOp; } @@ -3601,16 +3651,16 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, assert(Operand.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!"); if (OpOpcode == ISD::TRUNCATE) - return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); + return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ANY_EXTEND) { // If the source is smaller than the dest, we still need an extend. - if (Operand.getNode()->getOperand(0).getValueType().getScalarType() + if (Operand.getOperand(0).getValueType().getScalarType() .bitsLT(VT.getScalarType())) - return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); - if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) - return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); - return Operand.getNode()->getOperand(0); + return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); + if (Operand.getOperand(0).getValueType().bitsGT(VT)) + return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); + return Operand.getOperand(0); } if (OpOpcode == ISD::UNDEF) return getUNDEF(VT); @@ -3665,15 +3715,14 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags? - return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), - Operand.getNode()->getOperand(0), - Operand.getNode()->getFlags()); + return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1), + Operand.getOperand(0), Operand.getNode()->getFlags()); if (OpOpcode == ISD::FNEG) // --X -> X - return Operand.getNode()->getOperand(0); + return Operand.getOperand(0); break; case ISD::FABS: if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) - return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); + return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); break; } @@ -5970,7 +6019,7 @@ SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, unsigned NumOps = Ops.size(); switch (NumOps) { case 0: return getNode(Opcode, DL, VT); - case 1: return getNode(Opcode, DL, VT, Ops[0]); + case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); default: break; @@ -7520,9 +7569,8 @@ unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); KnownBits Known(PtrWidth); - llvm::computeKnownBits(const_cast<GlobalValue *>(GV), Known, - getDataLayout()); - unsigned AlignBits = Known.Zero.countTrailingOnes(); + llvm::computeKnownBits(GV, Known, getDataLayout()); + unsigned AlignBits = Known.countMinTrailingZeros(); unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; if (Align) return MinAlign(Align, GVOffset); @@ -7621,7 +7669,7 @@ bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, return false; // FIXME: The widths are based on this node's type, but build vectors can - // truncate their operands. + // truncate their operands. SplatValue = APInt(VecWidth, 0); SplatUndef = APInt(VecWidth, 0); diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp index 50313e2da884..57d340c41c39 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp @@ -661,7 +661,7 @@ SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, unsigned RegSize = RegisterVT.getSizeInBits(); unsigned NumSignBits = LOI->NumSignBits; - unsigned NumZeroBits = LOI->Known.Zero.countLeadingOnes(); + unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); if (NumZeroBits == RegSize) { // The current value is a zero. @@ -811,9 +811,9 @@ void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, } } -void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, +void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, const TargetLibraryInfo *li) { - AA = &aa; + AA = aa; GFI = gfi; LibInfo = li; DL = &DAG.getDataLayout(); @@ -3423,7 +3423,7 @@ void SelectionDAGBuilder::visitLoad(const LoadInst &I) { if (isVolatile || NumValues > MaxParallelChains) // Serialize volatile loads with other side effects. Root = getRoot(); - else if (AA->pointsToConstantMemory(MemoryLocation( + else if (AA && AA->pointsToConstantMemory(MemoryLocation( SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { // Do not serialize (non-volatile) loads of constant memory with anything. Root = DAG.getEntryNode(); @@ -3535,8 +3535,8 @@ void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { Type *Ty = I.getType(); AAMDNodes AAInfo; I.getAAMetadata(AAInfo); - assert(!AA->pointsToConstantMemory(MemoryLocation( - SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo)) && + assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( + SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && "load_from_swift_error should not be constant memory"); SmallVector<EVT, 4> ValueVTs; @@ -3817,7 +3817,7 @@ void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); // Do not serialize masked loads of constant memory with anything. - bool AddToChain = !AA->pointsToConstantMemory(MemoryLocation( + bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); @@ -3861,7 +3861,7 @@ void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { bool UniformBase = getUniformBase(BasePtr, Base, Index, this); bool ConstantMemory = false; if (UniformBase && - AA->pointsToConstantMemory(MemoryLocation( + AA && AA->pointsToConstantMemory(MemoryLocation( BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo))) { // Do not serialize (non-volatile) loads of constant memory with anything. @@ -4676,7 +4676,8 @@ bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( bool IsIndirect = false; Optional<MachineOperand> Op; // Some arguments' frame index is recorded during argument lowering. - if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) + int FI = FuncInfo.getArgumentFrameIndex(Arg); + if (FI != INT_MAX) Op = MachineOperand::CreateFI(FI); if (!Op && N.getNode()) { @@ -4927,6 +4928,13 @@ SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { return nullptr; } + // Byval arguments with frame indices were already handled after argument + // lowering and before isel. + const auto *Arg = + dyn_cast<Argument>(Address->stripInBoundsConstantOffsets()); + if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX) + return nullptr; + SDValue &N = NodeMap[Address]; if (!N.getNode() && isa<Argument>(Address)) // Check unused arguments map. @@ -4957,20 +4965,6 @@ SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { // virtual register info from the FuncInfo.ValueMap. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, true, N)) { - // If variable is pinned by a alloca in dominating bb then - // use StaticAllocaMap. - if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { - if (AI->getParent() != DI.getParent()) { - DenseMap<const AllocaInst*, int>::iterator SI = - FuncInfo.StaticAllocaMap.find(AI); - if (SI != FuncInfo.StaticAllocaMap.end()) { - SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, - 0, dl, SDNodeOrder); - DAG.AddDbgValue(SDV, nullptr, false); - return nullptr; - } - } - } DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); } } @@ -5651,7 +5645,7 @@ SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { int FI = FuncInfo.StaticAllocaMap[Slot]; MCSymbol *FrameAllocSym = MF.getMMI().getContext().getOrCreateFrameAllocSymbol( - GlobalValue::getRealLinkageName(MF.getName()), Idx); + GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, TII->get(TargetOpcode::LOCAL_ESCAPE)) .addSym(FrameAllocSym) @@ -5672,7 +5666,7 @@ SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX)); MCSymbol *FrameAllocSym = MF.getMMI().getContext().getOrCreateFrameAllocSymbol( - GlobalValue::getRealLinkageName(Fn->getName()), IdxVal); + GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); // Create a MCSymbol for the label to avoid any target lowering // that would make this PC relative. @@ -5737,6 +5731,24 @@ SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { case Intrinsic::experimental_deoptimize: LowerDeoptimizeCall(&I); return nullptr; + + case Intrinsic::experimental_vector_reduce_fadd: + case Intrinsic::experimental_vector_reduce_fmul: + case Intrinsic::experimental_vector_reduce_add: + case Intrinsic::experimental_vector_reduce_mul: + case Intrinsic::experimental_vector_reduce_and: + case Intrinsic::experimental_vector_reduce_or: + case Intrinsic::experimental_vector_reduce_xor: + case Intrinsic::experimental_vector_reduce_smax: + case Intrinsic::experimental_vector_reduce_smin: + case Intrinsic::experimental_vector_reduce_umax: + case Intrinsic::experimental_vector_reduce_umin: + case Intrinsic::experimental_vector_reduce_fmax: + case Intrinsic::experimental_vector_reduce_fmin: { + visitVectorReduce(I, Intrinsic); + return nullptr; + } + } } @@ -5982,7 +5994,7 @@ static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, bool ConstantMemory = false; // Do not serialize (non-volatile) loads of constant memory with anything. - if (Builder.AA->pointsToConstantMemory(PtrVal)) { + if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { Root = Builder.DAG.getEntryNode(); ConstantMemory = true; } else { @@ -7422,11 +7434,11 @@ void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { // have to worry about calling conventions and target specific lowering code. // Instead we perform the call lowering right here. // - // chain, flag = CALLSEQ_START(chain, 0) + // chain, flag = CALLSEQ_START(chain, 0, 0) // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) // chain, flag = CALLSEQ_END(chain, 0, 0, flag) // - Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL); + Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); InFlag = Chain.getValue(1); // Add the <id> and <numBytes> constants. @@ -7616,6 +7628,76 @@ void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, FuncInfo.MF->getFrameInfo().setHasPatchPoint(); } +void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, + unsigned Intrinsic) { + const TargetLowering &TLI = DAG.getTargetLoweringInfo(); + SDValue Op1 = getValue(I.getArgOperand(0)); + SDValue Op2; + if (I.getNumArgOperands() > 1) + Op2 = getValue(I.getArgOperand(1)); + SDLoc dl = getCurSDLoc(); + EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); + SDValue Res; + FastMathFlags FMF; + if (isa<FPMathOperator>(I)) + FMF = I.getFastMathFlags(); + SDNodeFlags SDFlags; + SDFlags.setNoNaNs(FMF.noNaNs()); + + switch (Intrinsic) { + case Intrinsic::experimental_vector_reduce_fadd: + if (FMF.unsafeAlgebra()) + Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); + else + Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); + break; + case Intrinsic::experimental_vector_reduce_fmul: + if (FMF.unsafeAlgebra()) + Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); + else + Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); + break; + case Intrinsic::experimental_vector_reduce_add: + Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_mul: + Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_and: + Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_or: + Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_xor: + Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_smax: + Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_smin: + Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_umax: + Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_umin: + Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); + break; + case Intrinsic::experimental_vector_reduce_fmax: { + Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); + break; + } + case Intrinsic::experimental_vector_reduce_fmin: { + Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); + break; + } + default: + llvm_unreachable("Unhandled vector reduce intrinsic"); + } + setValue(&I, Res); +} + /// Returns an AttributeList representing the attributes applied to the return /// value of the given call. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h index 9e9989058ae5..bdaee858da61 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h @@ -604,11 +604,11 @@ public: SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo, CodeGenOpt::Level ol) : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()), - DAG(dag), FuncInfo(funcinfo), + DAG(dag), DL(nullptr), AA(nullptr), FuncInfo(funcinfo), HasTailCall(false) { } - void init(GCFunctionInfo *gfi, AliasAnalysis &aa, + void init(GCFunctionInfo *gfi, AliasAnalysis *AA, const TargetLibraryInfo *li); /// Clear out the current SelectionDAG and the associated state and prepare @@ -909,6 +909,8 @@ private: void visitGCRelocate(const GCRelocateInst &I); void visitGCResult(const GCResultInst &I); + void visitVectorReduce(const CallInst &I, unsigned Intrinsic); + void visitUserOp1(const Instruction &I) { llvm_unreachable("UserOp1 should not exist at instruction selection time!"); } diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp index 26dd45ef933f..c37d7080f2c5 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp @@ -346,6 +346,19 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const { case ISD::SETFALSE: return "setfalse"; case ISD::SETFALSE2: return "setfalse2"; } + case ISD::VECREDUCE_FADD: return "vecreduce_fadd"; + case ISD::VECREDUCE_FMUL: return "vecreduce_fmul"; + case ISD::VECREDUCE_ADD: return "vecreduce_add"; + case ISD::VECREDUCE_MUL: return "vecreduce_mul"; + case ISD::VECREDUCE_AND: return "vecreduce_and"; + case ISD::VECREDUCE_OR: return "vecreduce_or"; + case ISD::VECREDUCE_XOR: return "vecreduce_xor"; + case ISD::VECREDUCE_SMAX: return "vecreduce_smax"; + case ISD::VECREDUCE_SMIN: return "vecreduce_smin"; + case ISD::VECREDUCE_UMAX: return "vecreduce_umax"; + case ISD::VECREDUCE_UMIN: return "vecreduce_umin"; + case ISD::VECREDUCE_FMAX: return "vecreduce_fmax"; + case ISD::VECREDUCE_FMIN: return "vecreduce_fmin"; } } diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp index 3aabdaeaa094..5e0feccb6b4c 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp @@ -38,6 +38,7 @@ #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineMemOperand.h" +#include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachinePassRegistry.h" #include "llvm/CodeGen/MachineRegisterInfo.h" @@ -299,7 +300,7 @@ SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, FuncInfo(new FunctionLoweringInfo()), CurDAG(new SelectionDAG(tm, OL)), SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)), - GFI(), + AA(), GFI(), OptLevel(OL), DAGSize(0) { initializeGCModuleInfoPass(*PassRegistry::getPassRegistry()); @@ -317,7 +318,8 @@ SelectionDAGISel::~SelectionDAGISel() { } void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { - AU.addRequired<AAResultsWrapperPass>(); + if (OptLevel != CodeGenOpt::None) + AU.addRequired<AAResultsWrapperPass>(); AU.addRequired<GCModuleInfo>(); AU.addRequired<StackProtector>(); AU.addPreserved<StackProtector>(); @@ -394,7 +396,6 @@ bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { TII = MF->getSubtarget().getInstrInfo(); TLI = MF->getSubtarget().getTargetLowering(); RegInfo = &MF->getRegInfo(); - AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr; ORE = make_unique<OptimizationRemarkEmitter>(&Fn); @@ -406,12 +407,22 @@ bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { CurDAG->init(*MF, *ORE); FuncInfo->set(Fn, *MF, CurDAG); + // Now get the optional analyzes if we want to. + // This is based on the possibly changed OptLevel (after optnone is taken + // into account). That's unfortunate but OK because it just means we won't + // ask for passes that have been required anyway. + if (UseMBPI && OptLevel != CodeGenOpt::None) FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); else FuncInfo->BPI = nullptr; - SDB->init(GFI, *AA, LibInfo); + if (OptLevel != CodeGenOpt::None) + AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); + else + AA = nullptr; + + SDB->init(GFI, AA, LibInfo); MF->setHasInlineAsm(false); @@ -715,7 +726,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { { NamedRegionTimer T("combine1", "DAG Combining 1", GroupName, GroupDescription, TimePassesIsEnabled); - CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel); + CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel); } DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber @@ -747,7 +758,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { { NamedRegionTimer T("combine_lt", "DAG Combining after legalize types", GroupName, GroupDescription, TimePassesIsEnabled); - CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel); + CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel); } DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber @@ -781,7 +792,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { { NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors", GroupName, GroupDescription, TimePassesIsEnabled); - CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel); + CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel); } DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#" @@ -807,7 +818,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() { { NamedRegionTimer T("combine2", "DAG Combining 2", GroupName, GroupDescription, TimePassesIsEnabled); - CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel); + CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel); } DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber @@ -1145,6 +1156,51 @@ static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo, } } +/// Collect llvm.dbg.declare information. This is done after argument lowering +/// in case the declarations refer to arguments. +static void processDbgDeclares(FunctionLoweringInfo *FuncInfo) { + MachineFunction *MF = FuncInfo->MF; + const DataLayout &DL = MF->getDataLayout(); + for (const BasicBlock &BB : *FuncInfo->Fn) { + for (const Instruction &I : BB) { + const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I); + if (!DI) + continue; + + assert(DI->getVariable() && "Missing variable"); + assert(DI->getDebugLoc() && "Missing location"); + const Value *Address = DI->getAddress(); + if (!Address) + continue; + + // Look through casts and constant offset GEPs. These mostly come from + // inalloca. + APInt Offset(DL.getPointerSizeInBits(0), 0); + Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset); + + // Check if the variable is a static alloca or a byval or inalloca + // argument passed in memory. If it is not, then we will ignore this + // intrinsic and handle this during isel like dbg.value. + int FI = INT_MAX; + if (const auto *AI = dyn_cast<AllocaInst>(Address)) { + auto SI = FuncInfo->StaticAllocaMap.find(AI); + if (SI != FuncInfo->StaticAllocaMap.end()) + FI = SI->second; + } else if (const auto *Arg = dyn_cast<Argument>(Address)) + FI = FuncInfo->getArgumentFrameIndex(Arg); + + if (FI == INT_MAX) + continue; + + DIExpression *Expr = DI->getExpression(); + if (Offset.getBoolValue()) + Expr = DIExpression::prepend(Expr, DIExpression::NoDeref, + Offset.getZExtValue()); + MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc()); + } + } +} + /// Propagate swifterror values through the machine function CFG. static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) { auto *TLI = FuncInfo->TLI; @@ -1317,6 +1373,8 @@ void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { } createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB); + processDbgDeclares(FuncInfo); + // Iterate over all basic blocks in the function. for (const BasicBlock *LLVMBB : RPOT) { if (OptLevel != CodeGenOpt::None) { diff --git a/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp index 23f597db140c..befbd80d7965 100644 --- a/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp +++ b/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp @@ -417,11 +417,10 @@ bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && TLI.isZExtFree(SmallVT, Op.getValueType())) { // We found a type with free casts. - SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT, - DAG.getNode(ISD::TRUNCATE, dl, SmallVT, - Op.getNode()->getOperand(0)), - DAG.getNode(ISD::TRUNCATE, dl, SmallVT, - Op.getNode()->getOperand(1))); + SDValue X = DAG.getNode( + Op.getOpcode(), dl, SmallVT, + DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), + DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); bool NeedZext = DemandedSize > SmallVTBits; SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, dl, Op.getValueType(), X); @@ -817,7 +816,7 @@ bool TargetLowering::SimplifyDemandedBits(SDValue Op, // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits // are not demanded. This will likely allow the anyext to be folded away. if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) { - SDValue InnerOp = InOp.getNode()->getOperand(0); + SDValue InnerOp = InOp.getOperand(0); EVT InnerVT = InnerOp.getValueType(); unsigned InnerBits = InnerVT.getSizeInBits(); if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits && diff --git a/contrib/llvm/lib/CodeGen/ShrinkWrap.cpp b/contrib/llvm/lib/CodeGen/ShrinkWrap.cpp index 4837495777da..2638702da152 100644 --- a/contrib/llvm/lib/CodeGen/ShrinkWrap.cpp +++ b/contrib/llvm/lib/CodeGen/ShrinkWrap.cpp @@ -282,8 +282,14 @@ void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB, if (!Restore) Restore = &MBB; - else + else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it + // means the block never returns. If that's the + // case, we don't want to call + // `findNearestCommonDominator`, which will + // return `Restore`. Restore = MPDT->findNearestCommonDominator(Restore, &MBB); + else + Restore = nullptr; // Abort, we can't find a restore point in this case. // Make sure we would be able to insert the restore code before the // terminator. @@ -293,7 +299,7 @@ void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB, continue; // One of the terminator needs to happen before the restore point. if (MBB.succ_empty()) { - Restore = nullptr; + Restore = nullptr; // Abort, we can't find a restore point in this case. break; } // Look for a restore point that post-dominates all the successors. @@ -419,7 +425,7 @@ static bool isIrreducibleCFG(const MachineFunction &MF, } bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) { - if (MF.empty() || !isShrinkWrapEnabled(MF)) + if (skipFunction(*MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF)) return false; DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n'); diff --git a/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp b/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp index ab578df4069d..e9eff4d0acb2 100644 --- a/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp +++ b/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp @@ -93,8 +93,8 @@ bool SjLjEHPrepare::doInitialization(Module &M) { doubleUnderDataTy, // __data VoidPtrTy, // __personality VoidPtrTy, // __lsda - doubleUnderJBufTy, // __jbuf - nullptr); + doubleUnderJBufTy // __jbuf + ); return true; } diff --git a/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp b/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp index 34892680aceb..1d232c71d824 100644 --- a/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp +++ b/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp @@ -232,7 +232,11 @@ static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO, if (!MD) return nullptr; - auto *VM = dyn_cast<ValueAsMetadata>(MD->getOperand(0)); + const MDOperand &Op = MD->getOperand(0); + if (!Op.get()) + return nullptr; + + auto *VM = dyn_cast<ValueAsMetadata>(Op); if (!VM) report_fatal_error("MD_associated operand is not ValueAsMetadata"); diff --git a/contrib/llvm/lib/CodeGen/TargetPassConfig.cpp b/contrib/llvm/lib/CodeGen/TargetPassConfig.cpp index 150195f5f85b..e6c5d8753b83 100644 --- a/contrib/llvm/lib/CodeGen/TargetPassConfig.cpp +++ b/contrib/llvm/lib/CodeGen/TargetPassConfig.cpp @@ -487,6 +487,14 @@ void TargetPassConfig::addIRPasses() { // Insert calls to mcount-like functions. addPass(createCountingFunctionInserterPass()); + + // Add scalarization of target's unsupported masked memory intrinsics pass. + // the unsupported intrinsic will be replaced with a chain of basic blocks, + // that stores/loads element one-by-one if the appropriate mask bit is set. + addPass(createScalarizeMaskedMemIntrinPass()); + + // Expand reduction intrinsics into shuffle sequences if the target wants to. + addPass(createExpandReductionsPass()); } /// Turn exception handling constructs into something the code generators can @@ -607,6 +615,9 @@ void TargetPassConfig::addMachinePasses() { addPass(&LocalStackSlotAllocationID, false); } + if (getOptLevel() != CodeGenOpt::None) + addPass(&LiveRangeShrinkID); + // Run pre-ra passes. addPreRegAlloc(); diff --git a/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp b/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp index 75359fe3c0ea..7392c8327148 100644 --- a/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp +++ b/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp @@ -155,7 +155,7 @@ public: void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); - AU.addRequired<AAResultsWrapperPass>(); + AU.addUsedIfAvailable<AAResultsWrapperPass>(); AU.addUsedIfAvailable<LiveVariables>(); AU.addPreserved<LiveVariables>(); AU.addPreserved<SlotIndexes>(); @@ -1627,7 +1627,10 @@ bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) { InstrItins = MF->getSubtarget().getInstrItineraryData(); LV = getAnalysisIfAvailable<LiveVariables>(); LIS = getAnalysisIfAvailable<LiveIntervals>(); - AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); + if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>()) + AA = &AAPass->getAAResults(); + else + AA = nullptr; OptLevel = TM.getOptLevel(); bool MadeChange = false; diff --git a/contrib/llvm/lib/CodeGen/UnreachableBlockElim.cpp b/contrib/llvm/lib/CodeGen/UnreachableBlockElim.cpp index f085132b6a94..407fd9b162e9 100644 --- a/contrib/llvm/lib/CodeGen/UnreachableBlockElim.cpp +++ b/contrib/llvm/lib/CodeGen/UnreachableBlockElim.cpp @@ -206,11 +206,12 @@ bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { if (InputReg != OutputReg) { MachineRegisterInfo &MRI = F.getRegInfo(); unsigned InputSub = Input.getSubReg(); - if (InputSub == 0) { - MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)); + if (InputSub == 0 && + MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg))) { MRI.replaceRegWith(OutputReg, InputReg); } else { - // The input register to the PHI has a subregister: + // The input register to the PHI has a subregister or it can't be + // constrained to the proper register class: // insert a COPY instead of simply replacing the output // with the input. const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo(); diff --git a/contrib/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp b/contrib/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp index 0069ee3cc904..b6ed0453d9c4 100644 --- a/contrib/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp +++ b/contrib/llvm/lib/DebugInfo/CodeView/CVTypeVisitor.cpp @@ -26,8 +26,7 @@ CVTypeVisitor::CVTypeVisitor(TypeVisitorCallbacks &Callbacks) : Callbacks(Callbacks) {} template <typename T> -static Error visitKnownRecord(CVTypeVisitor &Visitor, CVType &Record, - TypeVisitorCallbacks &Callbacks) { +static Error visitKnownRecord(CVType &Record, TypeVisitorCallbacks &Callbacks) { TypeRecordKind RK = static_cast<TypeRecordKind>(Record.Type); T KnownRecord(RK); if (auto EC = Callbacks.visitKnownRecord(Record, KnownRecord)) @@ -76,7 +75,7 @@ void CVTypeVisitor::addTypeServerHandler(TypeServerHandler &Handler) { Handlers.push_back(&Handler); } -Error CVTypeVisitor::visitTypeRecord(CVType &Record) { +Expected<bool> CVTypeVisitor::handleTypeServer(CVType &Record) { if (Record.Type == TypeLeafKind::LF_TYPESERVER2 && !Handlers.empty()) { auto TS = deserializeTypeServerRecord(Record); if (!TS) @@ -90,16 +89,16 @@ Error CVTypeVisitor::visitTypeRecord(CVType &Record) { // If the handler processed the record, return success. if (*ExpectedResult) - return Error::success(); + return true; // Otherwise keep searching for a handler, eventually falling out and // using the default record handler. } } + return false; +} - if (auto EC = Callbacks.visitTypeBegin(Record)) - return EC; - +Error CVTypeVisitor::finishVisitation(CVType &Record) { switch (Record.Type) { default: if (auto EC = Callbacks.visitUnknownType(Record)) @@ -107,7 +106,7 @@ Error CVTypeVisitor::visitTypeRecord(CVType &Record) { break; #define TYPE_RECORD(EnumName, EnumVal, Name) \ case EnumName: { \ - if (auto EC = visitKnownRecord<Name##Record>(*this, Record, Callbacks)) \ + if (auto EC = visitKnownRecord<Name##Record>(Record, Callbacks)) \ return EC; \ break; \ } @@ -124,6 +123,32 @@ Error CVTypeVisitor::visitTypeRecord(CVType &Record) { return Error::success(); } +Error CVTypeVisitor::visitTypeRecord(CVType &Record, TypeIndex Index) { + auto ExpectedResult = handleTypeServer(Record); + if (!ExpectedResult) + return ExpectedResult.takeError(); + if (*ExpectedResult) + return Error::success(); + + if (auto EC = Callbacks.visitTypeBegin(Record, Index)) + return EC; + + return finishVisitation(Record); +} + +Error CVTypeVisitor::visitTypeRecord(CVType &Record) { + auto ExpectedResult = handleTypeServer(Record); + if (!ExpectedResult) + return ExpectedResult.takeError(); + if (*ExpectedResult) + return Error::success(); + + if (auto EC = Callbacks.visitTypeBegin(Record)) + return EC; + + return finishVisitation(Record); +} + static Error visitMemberRecord(CVMemberRecord &Record, TypeVisitorCallbacks &Callbacks) { if (auto EC = Callbacks.visitMemberBegin(Record)) diff --git a/contrib/llvm/lib/DebugInfo/CodeView/ModuleDebugUnknownFragment.cpp b/contrib/llvm/lib/DebugInfo/CodeView/ModuleDebugUnknownFragment.cpp deleted file mode 100644 index 9fd2cb8ed3e8..000000000000 --- a/contrib/llvm/lib/DebugInfo/CodeView/ModuleDebugUnknownFragment.cpp +++ /dev/null @@ -1,10 +0,0 @@ -//===- ModuleDebugUnknownFragment.cpp ---------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "llvm/DebugInfo/CodeView/ModuleDebugUnknownFragment.h"
\ No newline at end of file diff --git a/contrib/llvm/lib/DebugInfo/CodeView/RandomAccessTypeVisitor.cpp b/contrib/llvm/lib/DebugInfo/CodeView/RandomAccessTypeVisitor.cpp new file mode 100644 index 000000000000..4cb9acbe07d9 --- /dev/null +++ b/contrib/llvm/lib/DebugInfo/CodeView/RandomAccessTypeVisitor.cpp @@ -0,0 +1,91 @@ +//===- RandomAccessTypeVisitor.cpp ---------------------------- *- C++ --*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "llvm/DebugInfo/CodeView/RandomAccessTypeVisitor.h" + +#include "llvm/DebugInfo/CodeView/TypeDatabase.h" +#include "llvm/DebugInfo/CodeView/TypeServerHandler.h" +#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h" + +using namespace llvm; +using namespace llvm::codeview; + +RandomAccessTypeVisitor::RandomAccessTypeVisitor( + const CVTypeArray &Types, uint32_t NumRecords, + PartialOffsetArray PartialOffsets) + : Database(NumRecords), Types(Types), DatabaseVisitor(Database), + InternalVisitor(Pipeline), PartialOffsets(PartialOffsets) { + Pipeline.addCallbackToPipeline(Deserializer); + Pipeline.addCallbackToPipeline(DatabaseVisitor); + + KnownOffsets.resize(Database.capacity()); +} + +Error RandomAccessTypeVisitor::visitTypeIndex(TypeIndex TI, + TypeVisitorCallbacks &Callbacks) { + assert(TI.toArrayIndex() < Database.capacity()); + + if (!Database.contains(TI)) { + if (auto EC = visitRangeForType(TI)) + return EC; + } + + assert(Database.contains(TI)); + auto &Record = Database.getTypeRecord(TI); + CVTypeVisitor V(Callbacks); + return V.visitTypeRecord(Record, TI); +} + +Error RandomAccessTypeVisitor::visitRangeForType(TypeIndex TI) { + if (PartialOffsets.empty()) { + TypeIndex TIB(TypeIndex::FirstNonSimpleIndex); + TypeIndex TIE = TIB + Database.capacity(); + return visitRange(TIB, 0, TIE); + } + + auto Next = std::upper_bound(PartialOffsets.begin(), PartialOffsets.end(), TI, + [](TypeIndex Value, const TypeIndexOffset &IO) { + return Value < IO.Type; + }); + + assert(Next != PartialOffsets.begin()); + auto Prev = std::prev(Next); + + TypeIndex TIB = Prev->Type; + TypeIndex TIE; + if (Next == PartialOffsets.end()) { + TIE = TypeIndex::fromArrayIndex(Database.capacity()); + } else { + TIE = Next->Type; + } + + if (auto EC = visitRange(TIB, Prev->Offset, TIE)) + return EC; + return Error::success(); +} + +Error RandomAccessTypeVisitor::visitRange(TypeIndex Begin, uint32_t BeginOffset, + TypeIndex End) { + + auto RI = Types.at(BeginOffset); + assert(RI != Types.end()); + + while (Begin != End) { + assert(!Database.contains(Begin)); + if (auto EC = InternalVisitor.visitTypeRecord(*RI, Begin)) + return EC; + KnownOffsets[Begin.toArrayIndex()] = BeginOffset; + + BeginOffset += RI.getRecordLength(); + ++Begin; + ++RI; + } + + return Error::success(); +} diff --git a/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabase.cpp b/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabase.cpp index 5b8841041f88..7924440e5e29 100644 --- a/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabase.cpp +++ b/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabase.cpp @@ -65,20 +65,32 @@ static const SimpleTypeEntry SimpleTypeNames[] = { {"__bool64*", SimpleTypeKind::Boolean64}, }; -TypeDatabase::TypeDatabase(uint32_t ExpectedSize) : TypeNameStorage(Allocator) { - CVUDTNames.reserve(ExpectedSize); - TypeRecords.reserve(ExpectedSize); +TypeDatabase::TypeDatabase(uint32_t Capacity) : TypeNameStorage(Allocator) { + CVUDTNames.resize(Capacity); + TypeRecords.resize(Capacity); + ValidRecords.resize(Capacity); } -/// Gets the type index for the next type record. -TypeIndex TypeDatabase::getNextTypeIndex() const { - return TypeIndex(TypeIndex::FirstNonSimpleIndex + CVUDTNames.size()); +TypeIndex TypeDatabase::appendType(StringRef Name, const CVType &Data) { + TypeIndex TI; + TI = getAppendIndex(); + if (TI.toArrayIndex() >= capacity()) + grow(); + recordType(Name, TI, Data); + return TI; } -/// Records the name of a type, and reserves its type index. -void TypeDatabase::recordType(StringRef Name, const CVType &Data) { - CVUDTNames.push_back(Name); - TypeRecords.push_back(Data); +void TypeDatabase::recordType(StringRef Name, TypeIndex Index, + const CVType &Data) { + uint32_t AI = Index.toArrayIndex(); + + assert(!contains(Index)); + assert(AI < capacity()); + + CVUDTNames[AI] = Name; + TypeRecords[AI] = Data; + ValidRecords.set(AI); + ++Count; } /// Saves the name in a StringSet and creates a stable StringRef. @@ -104,24 +116,47 @@ StringRef TypeDatabase::getTypeName(TypeIndex Index) const { return "<unknown simple type>"; } - uint32_t I = Index.getIndex() - TypeIndex::FirstNonSimpleIndex; - if (I < CVUDTNames.size()) - return CVUDTNames[I]; + if (contains(Index)) + return CVUDTNames[Index.toArrayIndex()]; return "<unknown UDT>"; } const CVType &TypeDatabase::getTypeRecord(TypeIndex Index) const { - return TypeRecords[Index.getIndex() - TypeIndex::FirstNonSimpleIndex]; + assert(contains(Index)); + return TypeRecords[Index.toArrayIndex()]; } CVType &TypeDatabase::getTypeRecord(TypeIndex Index) { - return TypeRecords[Index.getIndex() - TypeIndex::FirstNonSimpleIndex]; + assert(contains(Index)); + return TypeRecords[Index.toArrayIndex()]; +} + +bool TypeDatabase::contains(TypeIndex Index) const { + uint32_t AI = Index.toArrayIndex(); + if (AI >= capacity()) + return false; + + return ValidRecords.test(AI); } -bool TypeDatabase::containsTypeIndex(TypeIndex Index) const { - uint32_t I = Index.getIndex() - TypeIndex::FirstNonSimpleIndex; - return I < CVUDTNames.size(); +uint32_t TypeDatabase::size() const { return Count; } + +uint32_t TypeDatabase::capacity() const { return TypeRecords.size(); } + +void TypeDatabase::grow() { + TypeRecords.emplace_back(); + CVUDTNames.emplace_back(); + ValidRecords.resize(ValidRecords.size() + 1); } -uint32_t TypeDatabase::size() const { return CVUDTNames.size(); } +bool TypeDatabase::empty() const { return size() == 0; } + +TypeIndex TypeDatabase::getAppendIndex() const { + if (empty()) + return TypeIndex::fromArrayIndex(0); + + int Index = ValidRecords.find_last(); + assert(Index != -1); + return TypeIndex::fromArrayIndex(Index) + 1; +} diff --git a/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabaseVisitor.cpp b/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabaseVisitor.cpp index c234afd2288b..8d97f8b1cb40 100644 --- a/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabaseVisitor.cpp +++ b/contrib/llvm/lib/DebugInfo/CodeView/TypeDatabaseVisitor.cpp @@ -15,7 +15,7 @@ using namespace llvm; using namespace llvm::codeview; -Error TypeDatabaseVisitor::visitTypeBegin(CVRecord<TypeLeafKind> &Record) { +Error TypeDatabaseVisitor::visitTypeBegin(CVType &Record) { assert(!IsInFieldList); // Reset Name to the empty string. If the visitor sets it, we know it. Name = ""; @@ -28,6 +28,22 @@ Error TypeDatabaseVisitor::visitTypeBegin(CVRecord<TypeLeafKind> &Record) { return Error::success(); } +Error TypeDatabaseVisitor::visitTypeBegin(CVType &Record, TypeIndex Index) { + if (auto EC = visitTypeBegin(Record)) + return EC; + + CurrentTypeIndex = Index; + return Error::success(); +} + +StringRef TypeDatabaseVisitor::getTypeName(TypeIndex Index) const { + return TypeDB->getTypeName(Index); +} + +StringRef TypeDatabaseVisitor::saveTypeName(StringRef Name) { + return TypeDB->saveTypeName(Name); +} + Error TypeDatabaseVisitor::visitTypeEnd(CVType &CVR) { if (CVR.Type == LF_FIELDLIST) { assert(IsInFieldList); @@ -39,7 +55,12 @@ Error TypeDatabaseVisitor::visitTypeEnd(CVType &CVR) { // CVUDTNames is indexed by type index, and must have one entry for every // type. Field list members are not recorded, and are only referenced by // their containing field list record. - TypeDB.recordType(Name, CVR); + if (CurrentTypeIndex) + TypeDB->recordType(Name, *CurrentTypeIndex, CVR); + else + TypeDB->appendType(Name, CVR); + + CurrentTypeIndex.reset(); return Error::success(); } @@ -73,13 +94,13 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, ArgListRecord &Args) { uint32_t Size = Indices.size(); SmallString<256> TypeName("("); for (uint32_t I = 0; I < Size; ++I) { - StringRef ArgTypeName = TypeDB.getTypeName(Indices[I]); + StringRef ArgTypeName = getTypeName(Indices[I]); TypeName.append(ArgTypeName); if (I + 1 != Size) TypeName.append(", "); } TypeName.push_back(')'); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); return Error::success(); } @@ -89,13 +110,13 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, uint32_t Size = Indices.size(); SmallString<256> TypeName("\""); for (uint32_t I = 0; I < Size; ++I) { - StringRef ArgTypeName = TypeDB.getTypeName(Indices[I]); + StringRef ArgTypeName = getTypeName(Indices[I]); TypeName.append(ArgTypeName); if (I + 1 != Size) TypeName.append("\" \""); } TypeName.push_back('\"'); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); return Error::success(); } @@ -132,26 +153,26 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, ProcedureRecord &Proc) { - StringRef ReturnTypeName = TypeDB.getTypeName(Proc.getReturnType()); - StringRef ArgListTypeName = TypeDB.getTypeName(Proc.getArgumentList()); + StringRef ReturnTypeName = getTypeName(Proc.getReturnType()); + StringRef ArgListTypeName = getTypeName(Proc.getArgumentList()); SmallString<256> TypeName(ReturnTypeName); TypeName.push_back(' '); TypeName.append(ArgListTypeName); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); return Error::success(); } Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, MemberFunctionRecord &MF) { - StringRef ReturnTypeName = TypeDB.getTypeName(MF.getReturnType()); - StringRef ClassTypeName = TypeDB.getTypeName(MF.getClassType()); - StringRef ArgListTypeName = TypeDB.getTypeName(MF.getArgumentList()); + StringRef ReturnTypeName = getTypeName(MF.getReturnType()); + StringRef ClassTypeName = getTypeName(MF.getClassType()); + StringRef ArgListTypeName = getTypeName(MF.getArgumentList()); SmallString<256> TypeName(ReturnTypeName); TypeName.push_back(' '); TypeName.append(ClassTypeName); TypeName.append("::"); TypeName.append(ArgListTypeName); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); return Error::success(); } @@ -171,13 +192,13 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, PointerRecord &Ptr) { if (Ptr.isPointerToMember()) { const MemberPointerInfo &MI = Ptr.getMemberInfo(); - StringRef PointeeName = TypeDB.getTypeName(Ptr.getReferentType()); - StringRef ClassName = TypeDB.getTypeName(MI.getContainingType()); + StringRef PointeeName = getTypeName(Ptr.getReferentType()); + StringRef ClassName = getTypeName(MI.getContainingType()); SmallString<256> TypeName(PointeeName); TypeName.push_back(' '); TypeName.append(ClassName); TypeName.append("::*"); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); } else { SmallString<256> TypeName; if (Ptr.isConst()) @@ -187,7 +208,7 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, PointerRecord &Ptr) { if (Ptr.isUnaligned()) TypeName.append("__unaligned "); - TypeName.append(TypeDB.getTypeName(Ptr.getReferentType())); + TypeName.append(getTypeName(Ptr.getReferentType())); if (Ptr.getMode() == PointerMode::LValueReference) TypeName.append("&"); @@ -197,7 +218,7 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, PointerRecord &Ptr) { TypeName.append("*"); if (!TypeName.empty()) - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); } return Error::success(); } @@ -205,7 +226,7 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, PointerRecord &Ptr) { Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, ModifierRecord &Mod) { uint16_t Mods = static_cast<uint16_t>(Mod.getModifiers()); - StringRef ModifiedName = TypeDB.getTypeName(Mod.getModifiedType()); + StringRef ModifiedName = getTypeName(Mod.getModifiedType()); SmallString<256> TypeName; if (Mods & uint16_t(ModifierOptions::Const)) TypeName.append("const "); @@ -214,14 +235,14 @@ Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, ModifierRecord &Mod) { if (Mods & uint16_t(ModifierOptions::Unaligned)) TypeName.append("__unaligned "); TypeName.append(ModifiedName); - Name = TypeDB.saveTypeName(TypeName); + Name = saveTypeName(TypeName); return Error::success(); } Error TypeDatabaseVisitor::visitKnownRecord(CVType &CVR, VFTableShapeRecord &Shape) { - Name = TypeDB.saveTypeName("<vftable " + utostr(Shape.getEntryCount()) + - " methods>"); + Name = + saveTypeName("<vftable " + utostr(Shape.getEntryCount()) + " methods>"); return Error::success(); } diff --git a/contrib/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp b/contrib/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp index 870d95221e7d..27a6e0987886 100644 --- a/contrib/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp +++ b/contrib/llvm/lib/DebugInfo/CodeView/TypeDumpVisitor.cpp @@ -173,10 +173,13 @@ void TypeDumpVisitor::printItemIndex(StringRef FieldName, TypeIndex TI) const { } Error TypeDumpVisitor::visitTypeBegin(CVType &Record) { + TypeIndex TI = getSourceDB().getAppendIndex(); + return visitTypeBegin(Record, TI); +} + +Error TypeDumpVisitor::visitTypeBegin(CVType &Record, TypeIndex Index) { W->startLine() << getLeafTypeName(Record.Type); - W->getOStream() << " (" - << HexNumber(getSourceDB().getNextTypeIndex().getIndex()) - << ")"; + W->getOStream() << " (" << HexNumber(Index.getIndex()) << ")"; W->getOStream() << " {\n"; W->indent(); W->printEnum("TypeLeafKind", unsigned(Record.Type), diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp index 246899ac12b9..59a060d143ff 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp @@ -66,7 +66,7 @@ uint64_t llvm::getRelocatedValue(const DataExtractor &Data, uint32_t Size, RelocAddrMap::const_iterator AI = Relocs->find(*Off); if (AI == Relocs->end()) return Data.getUnsigned(Off, Size); - return Data.getUnsigned(Off, Size) + AI->second.second; + return Data.getUnsigned(Off, Size) + AI->second.Value; } static void dumpAccelSection(raw_ostream &OS, StringRef Name, @@ -905,16 +905,23 @@ static Error createError(const Twine &Reason, llvm::Error E) { /// Returns the address of symbol relocation used against. Used for futher /// relocations computation. Symbol's section load address is taken in account if /// LoadedObjectInfo interface is provided. -static Expected<uint64_t> getSymbolAddress(const object::ObjectFile &Obj, - const RelocationRef &Reloc, - const LoadedObjectInfo *L) { +static Expected<uint64_t> +getSymbolAddress(const object::ObjectFile &Obj, const RelocationRef &Reloc, + const LoadedObjectInfo *L, + std::map<SymbolRef, uint64_t> &Cache) { uint64_t Ret = 0; object::section_iterator RSec = Obj.section_end(); object::symbol_iterator Sym = Reloc.getSymbol(); + std::map<SymbolRef, uint64_t>::iterator CacheIt = Cache.end(); // First calculate the address of the symbol or section as it appears // in the object file if (Sym != Obj.symbol_end()) { + bool New; + std::tie(CacheIt, New) = Cache.insert({*Sym, 0}); + if (!New) + return CacheIt->second; + Expected<uint64_t> SymAddrOrErr = Sym->getAddress(); if (!SymAddrOrErr) return createError("error: failed to compute symbol address: ", @@ -943,6 +950,10 @@ static Expected<uint64_t> getSymbolAddress(const object::ObjectFile &Obj, if (L && RSec != Obj.section_end()) if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec)) Ret += SectionLoadAddress - RSec->getAddress(); + + if (CacheIt != Cache.end()) + CacheIt->second = Ret; + return Ret; } @@ -1075,6 +1086,7 @@ DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj, continue; } + std::map<SymbolRef, uint64_t> AddrCache; if (Section.relocation_begin() != Section.relocation_end()) { uint64_t SectionSize = RelocatedSection->getSize(); for (const RelocationRef &Reloc : Section.relocations()) { @@ -1083,7 +1095,8 @@ DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj, if (isRelocScattered(Obj, Reloc)) continue; - Expected<uint64_t> SymAddrOrErr = getSymbolAddress(Obj, Reloc, L); + Expected<uint64_t> SymAddrOrErr = + getSymbolAddress(Obj, Reloc, L, AddrCache); if (!SymAddrOrErr) { errs() << toString(SymAddrOrErr.takeError()) << '\n'; continue; @@ -1114,7 +1127,7 @@ DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj, << " at " << format("%p", Address) << " with width " << format("%d", R.Width) << "\n"); - Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value))); + Map->insert({Address, {(uint8_t)R.Width, R.Value}}); } } } diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp index 0cf71f530446..6601393d7459 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp @@ -54,9 +54,8 @@ void DWARFDebugAranges::generate(DWARFContext *CTX) { if (ParsedCUOffsets.insert(CUOffset).second) { DWARFAddressRangesVector CURanges; CU->collectAddressRanges(CURanges); - for (const auto &R : CURanges) { - appendRange(CUOffset, R.first, R.second); - } + for (const auto &R : CURanges) + appendRange(CUOffset, R.LowPC, R.HighPC); } } diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp index 9380fe8fe85d..8da797750abd 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp @@ -69,8 +69,8 @@ DWARFDebugRangeList::getAbsoluteRanges(uint64_t BaseAddress) const { if (RLE.isBaseAddressSelectionEntry(AddressSize)) { BaseAddress = RLE.EndAddress; } else { - Res.push_back(std::make_pair(BaseAddress + RLE.StartAddress, - BaseAddress + RLE.EndAddress)); + Res.push_back( + {BaseAddress + RLE.StartAddress, BaseAddress + RLE.EndAddress}); } } return Res; diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp index 24039eb35209..e3bd759ba94b 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFDie.cpp @@ -60,8 +60,8 @@ static void dumpRanges(raw_ostream &OS, const DWARFAddressRangesVector& Ranges, OS << '\n'; OS.indent(Indent); OS << format("[0x%0*" PRIx64 " - 0x%0*" PRIx64 ")", - AddressSize*2, Range.first, - AddressSize*2, Range.second); + AddressSize*2, Range.LowPC, + AddressSize*2, Range.HighPC); } } @@ -229,9 +229,9 @@ DWARFDie::getAddressRanges() const { return DWARFAddressRangesVector(); // Single range specified by low/high PC. uint64_t LowPC, HighPC; - if (getLowAndHighPC(LowPC, HighPC)) { - return DWARFAddressRangesVector(1, std::make_pair(LowPC, HighPC)); - } + if (getLowAndHighPC(LowPC, HighPC)) + return {{LowPC, HighPC}}; + // Multiple ranges from .debug_ranges section. auto RangesOffset = toSectionOffset(find(DW_AT_ranges)); if (RangesOffset) { @@ -257,7 +257,7 @@ DWARFDie::collectChildrenAddressRanges(DWARFAddressRangesVector& Ranges) const { bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const { for (const auto& R : getAddressRanges()) { - if (R.first <= Address && Address < R.second) + if (R.LowPC <= Address && Address < R.HighPC) return true; } return false; diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp index e0f819383289..25824f6eb83b 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp @@ -24,7 +24,11 @@ bool DWARFTypeUnit::extractImpl(DataExtractor debug_info, return false; TypeHash = debug_info.getU64(offset_ptr); TypeOffset = debug_info.getU32(offset_ptr); - return TypeOffset < getLength(); + // TypeOffset is relative to the beginning of the header, + // so we have to account for the leading length field. + // FIXME: The size of the length field is 12 in DWARF64. + unsigned SizeOfLength = 4; + return TypeOffset < getLength() + SizeOfLength; } void DWARFTypeUnit::dump(raw_ostream &OS, bool SummarizeTypes) { diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp index f50487fc3ba3..3835d4da9ae9 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp @@ -349,18 +349,18 @@ void DWARFUnit::updateAddressDieMap(DWARFDie Die) { if (Die.isSubroutineDIE()) { for (const auto &R : Die.getAddressRanges()) { // Ignore 0-sized ranges. - if (R.first == R.second) + if (R.LowPC == R.HighPC) continue; - auto B = AddrDieMap.upper_bound(R.first); - if (B != AddrDieMap.begin() && R.first < (--B)->second.first) { + auto B = AddrDieMap.upper_bound(R.LowPC); + if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) { // The range is a sub-range of existing ranges, we need to split the // existing range. - if (R.second < B->second.first) - AddrDieMap[R.second] = B->second; - if (R.first > B->first) - AddrDieMap[B->first].first = R.first; + if (R.HighPC < B->second.first) + AddrDieMap[R.HighPC] = B->second; + if (R.LowPC > B->first) + AddrDieMap[B->first].first = R.LowPC; } - AddrDieMap[R.first] = std::make_pair(R.second, Die); + AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die); } } // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to diff --git a/contrib/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp b/contrib/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp index 9494e876da15..8a544296f65c 100644 --- a/contrib/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp +++ b/contrib/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp @@ -23,7 +23,7 @@ using namespace llvm; using namespace dwarf; using namespace object; -void DWARFVerifier::verifyDebugInfoAttribute(DWARFDie &Die, +void DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die, DWARFAttribute &AttrValue) { const auto Attr = AttrValue.Attr; switch (Attr) { @@ -68,7 +68,7 @@ void DWARFVerifier::verifyDebugInfoAttribute(DWARFDie &Die, } } -void DWARFVerifier::verifyDebugInfoForm(DWARFDie &Die, +void DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die, DWARFAttribute &AttrValue) { const auto Form = AttrValue.Value.getForm(); switch (Form) { @@ -136,7 +136,7 @@ void DWARFVerifier::verifyDebugInfoForm(DWARFDie &Die, } } -void DWARFVerifier::veifyDebugInfoReferences() { +void DWARFVerifier::verifyDebugInfoReferences() { // Take all references and make sure they point to an actual DIE by // getting the DIE by offset and emitting an error OS << "Verifying .debug_info references...\n"; @@ -172,7 +172,7 @@ bool DWARFVerifier::handleDebugInfo() { } } } - veifyDebugInfoReferences(); + verifyDebugInfoReferences(); return NumDebugInfoErrors == 0; } diff --git a/contrib/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp b/contrib/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp index 375c35b11145..701a318511b8 100644 --- a/contrib/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp +++ b/contrib/llvm/lib/DebugInfo/PDB/Native/TpiStreamBuilder.cpp @@ -109,7 +109,7 @@ uint32_t TpiStreamBuilder::calculateHashBufferSize() const { } uint32_t TpiStreamBuilder::calculateIndexOffsetSize() const { - return TypeIndexOffsets.size() * sizeof(TypeIndexOffset); + return TypeIndexOffsets.size() * sizeof(codeview::TypeIndexOffset); } Error TpiStreamBuilder::finalizeMsfLayout() { diff --git a/contrib/llvm/lib/ExecutionEngine/Orc/OrcMCJITReplacement.h b/contrib/llvm/lib/ExecutionEngine/Orc/OrcMCJITReplacement.h index a5100a56bcf1..a27573f93b97 100644 --- a/contrib/llvm/lib/ExecutionEngine/Orc/OrcMCJITReplacement.h +++ b/contrib/llvm/lib/ExecutionEngine/Orc/OrcMCJITReplacement.h @@ -94,9 +94,8 @@ class OrcMCJITReplacement : public ExecutionEngine { return ClientMM->registerEHFrames(Addr, LoadAddr, Size); } - void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, - size_t Size) override { - return ClientMM->deregisterEHFrames(Addr, LoadAddr, Size); + void deregisterEHFrames() override { + return ClientMM->deregisterEHFrames(); } void notifyObjectLoaded(RuntimeDyld &RTDyld, diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp index de73fbde8eb7..99e84b7496d4 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp @@ -134,6 +134,18 @@ void RTDyldMemoryManager::deregisterEHFramesInProcess(uint8_t *Addr, #endif +void RTDyldMemoryManager::registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, + size_t Size) { + registerEHFramesInProcess(Addr, Size); + EHFrames.push_back({Addr, Size}); +} + +void RTDyldMemoryManager::deregisterEHFrames() { + for (auto &Frame : EHFrames) + deregisterEHFramesInProcess(Frame.Addr, Frame.Size); + EHFrames.clear(); +} + static int jit_noop() { return 0; } diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp index df9d2ceba329..e9a4b71c903d 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp @@ -73,7 +73,9 @@ namespace llvm { void RuntimeDyldImpl::registerEHFrames() {} -void RuntimeDyldImpl::deregisterEHFrames() {} +void RuntimeDyldImpl::deregisterEHFrames() { + MemMgr.deregisterEHFrames(); +} #ifndef NDEBUG static void dumpSectionMemory(const SectionEntry &S, StringRef State) { diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp index 50f63fb8dd39..660843765b3f 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp @@ -221,22 +221,10 @@ void RuntimeDyldELF::registerEHFrames() { uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress(); size_t EHFrameSize = Sections[EHFrameSID].getSize(); MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize); - RegisteredEHFrameSections.push_back(EHFrameSID); } UnregisteredEHFrameSections.clear(); } -void RuntimeDyldELF::deregisterEHFrames() { - for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) { - SID EHFrameSID = RegisteredEHFrameSections[i]; - uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress(); - uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress(); - size_t EHFrameSize = Sections[EHFrameSID].getSize(); - MemMgr.deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize); - } - RegisteredEHFrameSections.clear(); -} - std::unique_ptr<RuntimeDyldELF> llvm::RuntimeDyldELF::create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, @@ -802,20 +790,35 @@ void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section, writeInt32BE(LocalAddress, Delta / 2); break; } + case ELF::R_390_PC16: { + int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset); + assert(int16_t(Delta) == Delta && "R_390_PC16 overflow"); + writeInt16BE(LocalAddress, Delta); + break; + } case ELF::R_390_PC32: { int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset); assert(int32_t(Delta) == Delta && "R_390_PC32 overflow"); writeInt32BE(LocalAddress, Delta); break; } - case ELF::R_390_64: - writeInt64BE(LocalAddress, Value + Addend); - break; case ELF::R_390_PC64: { int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset); writeInt64BE(LocalAddress, Delta); break; } + case ELF::R_390_8: + *LocalAddress = (uint8_t)(Value + Addend); + break; + case ELF::R_390_16: + writeInt16BE(LocalAddress, Value + Addend); + break; + case ELF::R_390_32: + writeInt32BE(LocalAddress, Value + Addend); + break; + case ELF::R_390_64: + writeInt64BE(LocalAddress, Value + Addend); + break; } } diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h index 84dd810101f3..fb5da6dd8bbb 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.h @@ -152,7 +152,6 @@ private: // in a table until we receive a request to register all unregistered // EH frame sections with the memory manager. SmallVector<SID, 2> UnregisteredEHFrameSections; - SmallVector<SID, 2> RegisteredEHFrameSections; // Map between GOT relocation value and corresponding GOT offset std::map<RelocationValueRef, uint64_t> GOTOffsetMap; @@ -180,7 +179,6 @@ public: StubMap &Stubs) override; bool isCompatibleFile(const object::ObjectFile &Obj) const override; void registerEHFrames() override; - void deregisterEHFrames() override; Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override; }; diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h index f5cc883d98fd..18c23c5a2a5d 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h @@ -515,7 +515,7 @@ public: virtual void registerEHFrames(); - virtual void deregisterEHFrames(); + void deregisterEHFrames(); virtual Error finalizeLoad(const ObjectFile &ObjImg, ObjSectionToIDMap &SectionMap) { diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h index 0398413e1532..6aa1a2bdb926 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFI386.h @@ -217,7 +217,6 @@ public: } void registerEHFrames() override {} - void deregisterEHFrames() override {} }; } diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h index 8c6af0bd9c6d..318afa21a88b 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFThumb.h @@ -316,7 +316,6 @@ public: } void registerEHFrames() override {} - void deregisterEHFrames() override {} }; } diff --git a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h index 109beb36f1ee..26e73989d7ed 100644 --- a/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h +++ b/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h @@ -194,9 +194,6 @@ public: } UnregisteredEHFrameSections.clear(); } - void deregisterEHFrames() override { - // Stub - } Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override { // Look for and record the EH frame section IDs. diff --git a/contrib/llvm/lib/IR/AsmWriter.cpp b/contrib/llvm/lib/IR/AsmWriter.cpp index 4c6e3e3788bd..ec4663018bd4 100644 --- a/contrib/llvm/lib/IR/AsmWriter.cpp +++ b/contrib/llvm/lib/IR/AsmWriter.cpp @@ -805,6 +805,9 @@ void SlotTracker::processModule() { if (!Var.hasName()) CreateModuleSlot(&Var); processGlobalObjectMetadata(Var); + auto Attrs = Var.getAttributes(); + if (Attrs.hasAttributes()) + CreateAttributeSetSlot(Attrs); } for (const GlobalAlias &A : TheModule->aliases()) { @@ -2502,6 +2505,10 @@ void AssemblyWriter::printGlobal(const GlobalVariable *GV) { GV->getAllMetadata(MDs); printMetadataAttachments(MDs, ", "); + auto Attrs = GV->getAttributes(); + if (Attrs.hasAttributes()) + Out << " #" << Machine.getAttributeGroupSlot(Attrs); + printInfoComment(*GV); } diff --git a/contrib/llvm/lib/IR/AttributeImpl.h b/contrib/llvm/lib/IR/AttributeImpl.h index cf2925254695..acfac316e91e 100644 --- a/contrib/llvm/lib/IR/AttributeImpl.h +++ b/contrib/llvm/lib/IR/AttributeImpl.h @@ -1,4 +1,4 @@ -//===-- AttributeImpl.h - Attribute Internals -------------------*- C++ -*-===// +//===- AttributeImpl.h - Attribute Internals --------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -21,9 +21,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/IR/Attributes.h" #include "llvm/Support/TrailingObjects.h" -#include <algorithm> #include <cassert> -#include <climits> #include <cstddef> #include <cstdint> #include <string> @@ -80,11 +78,13 @@ public: else Profile(ID, getKindAsString(), getValueAsString()); } + static void Profile(FoldingSetNodeID &ID, Attribute::AttrKind Kind, uint64_t Val) { ID.AddInteger(Kind); if (Val) ID.AddInteger(Val); } + static void Profile(FoldingSetNodeID &ID, StringRef Kind, StringRef Values) { ID.AddString(Kind); if (!Values.empty()) ID.AddString(Values); @@ -114,9 +114,10 @@ public: }; class IntAttributeImpl : public EnumAttributeImpl { - void anchor() override; uint64_t Val; + void anchor() override; + public: IntAttributeImpl(Attribute::AttrKind Kind, uint64_t Val) : EnumAttributeImpl(IntAttrEntry, Kind), Val(Val) { @@ -188,20 +189,22 @@ public: std::pair<unsigned, Optional<unsigned>> getAllocSizeArgs() const; std::string getAsString(bool InAttrGrp) const; - typedef const Attribute *iterator; + using iterator = const Attribute *; + iterator begin() const { return getTrailingObjects<Attribute>(); } iterator end() const { return begin() + NumAttrs; } void Profile(FoldingSetNodeID &ID) const { Profile(ID, makeArrayRef(begin(), end())); } + static void Profile(FoldingSetNodeID &ID, ArrayRef<Attribute> AttrList) { for (const auto &Attr : AttrList) Attr.Profile(ID); } }; -typedef std::pair<unsigned, AttributeSet> IndexAttrPair; +using IndexAttrPair = std::pair<unsigned, AttributeSet>; //===----------------------------------------------------------------------===// /// \class @@ -265,7 +268,8 @@ public: return AvailableFunctionAttrs & ((uint64_t)1) << Kind; } - typedef AttributeSet::iterator iterator; + using iterator = AttributeSet::iterator; + iterator begin(unsigned Slot) const { return getSlotAttributes(Slot).begin(); } diff --git a/contrib/llvm/lib/IR/Attributes.cpp b/contrib/llvm/lib/IR/Attributes.cpp index 3b1140ab542c..ce60367a6c8b 100644 --- a/contrib/llvm/lib/IR/Attributes.cpp +++ b/contrib/llvm/lib/IR/Attributes.cpp @@ -34,6 +34,8 @@ #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> +#include <climits> +#include <cstddef> #include <cstdint> #include <limits> #include <map> @@ -504,16 +506,74 @@ AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) { return AttributeSet(AttributeSetNode::get(C, Attrs)); } +AttributeSet AttributeSet::addAttribute(LLVMContext &C, + Attribute::AttrKind Kind) const { + if (hasAttribute(Kind)) return *this; + AttrBuilder B; + B.addAttribute(Kind); + return addAttributes(C, AttributeSet::get(C, B)); +} + +AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind, + StringRef Value) const { + AttrBuilder B; + B.addAttribute(Kind, Value); + return addAttributes(C, AttributeSet::get(C, B)); +} + +AttributeSet AttributeSet::addAttributes(LLVMContext &C, + const AttributeSet AS) const { + if (!hasAttributes()) + return AS; + + if (!AS.hasAttributes()) + return *this; + + AttrBuilder B(AS); + for (Attribute I : *this) + B.addAttribute(I); + + return get(C, B); +} + +AttributeSet AttributeSet::removeAttribute(LLVMContext &C, + Attribute::AttrKind Kind) const { + if (!hasAttribute(Kind)) return *this; + AttrBuilder B; + B.addAttribute(Kind); + return removeAttributes(C, B); +} + +AttributeSet AttributeSet::removeAttribute(LLVMContext &C, + StringRef Kind) const { + if (!hasAttribute(Kind)) return *this; + AttrBuilder B; + B.addAttribute(Kind); + return removeAttributes(C, B); +} + +AttributeSet AttributeSet::removeAttributes(LLVMContext &C, + const AttrBuilder &Attrs) const { + + // FIXME it is not obvious how this should work for alignment. + // For now, say we can't pass in alignment, which no current use does. + assert(!Attrs.hasAlignmentAttr() && "Attempt to change alignment!"); + + AttrBuilder B(*this); + B.remove(Attrs); + return get(C, B); +} + unsigned AttributeSet::getNumAttributes() const { return SetNode ? SetNode->getNumAttributes() : 0; } bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const { - return SetNode ? SetNode->hasAttribute(Kind) : 0; + return SetNode ? SetNode->hasAttribute(Kind) : false; } bool AttributeSet::hasAttribute(StringRef Kind) const { - return SetNode ? SetNode->hasAttribute(Kind) : 0; + return SetNode ? SetNode->hasAttribute(Kind) : false; } Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const { @@ -557,6 +617,14 @@ AttributeSet::iterator AttributeSet::end() const { return SetNode ? SetNode->end() : nullptr; } +#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) +LLVM_DUMP_METHOD void AttributeSet::dump() const { + dbgs() << "AS =\n"; + dbgs() << " { "; + dbgs() << getAsString(true) << " }\n"; +} +#endif + //===----------------------------------------------------------------------===// // AttributeSetNode Definition //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/lib/IR/ConstantFold.cpp b/contrib/llvm/lib/IR/ConstantFold.cpp index 80b117015ede..a20f3f811c8d 100644 --- a/contrib/llvm/lib/IR/ConstantFold.cpp +++ b/contrib/llvm/lib/IR/ConstantFold.cpp @@ -2041,9 +2041,6 @@ Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C, Optional<unsigned> InRangeIndex, ArrayRef<Value *> Idxs) { if (Idxs.empty()) return C; - Constant *Idx0 = cast<Constant>(Idxs[0]); - if ((Idxs.size() == 1 && Idx0->isNullValue())) - return C; if (isa<UndefValue>(C)) { Type *GEPTy = GetElementPtrInst::getGEPReturnType( @@ -2051,10 +2048,15 @@ Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C, return UndefValue::get(GEPTy); } + Constant *Idx0 = cast<Constant>(Idxs[0]); + if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0))) + return C; + if (C->isNullValue()) { bool isNull = true; for (unsigned i = 0, e = Idxs.size(); i != e; ++i) - if (!cast<Constant>(Idxs[i])->isNullValue()) { + if (!isa<UndefValue>(Idxs[i]) && + !cast<Constant>(Idxs[i])->isNullValue()) { isNull = false; break; } diff --git a/contrib/llvm/lib/IR/ConstantRange.cpp b/contrib/llvm/lib/IR/ConstantRange.cpp index aeb1257754f3..509caba3acd4 100644 --- a/contrib/llvm/lib/IR/ConstantRange.cpp +++ b/contrib/llvm/lib/IR/ConstantRange.cpp @@ -278,7 +278,7 @@ APInt ConstantRange::getUnsignedMax() const { } APInt ConstantRange::getUnsignedMin() const { - if (isFullSet() || (isWrappedSet() && getUpper() != 0)) + if (isFullSet() || (isWrappedSet() && !getUpper().isNullValue())) return APInt::getMinValue(getBitWidth()); return getLower(); } @@ -442,7 +442,7 @@ ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const { APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower; APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper; - if (L == 0 && U == 0) + if (L.isNullValue() && U.isNullValue()) return ConstantRange(getBitWidth()); return ConstantRange(std::move(L), std::move(U)); @@ -757,7 +757,8 @@ ConstantRange::multiply(const ConstantRange &Other) const { // from one positive number to another which is as good as we can generate. // In this case, skip the extra work of generating signed ranges which aren't // going to be better than this range. - if (!UR.isWrappedSet() && UR.getLower().isNonNegative()) + if (!UR.isWrappedSet() && + (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue())) return UR; // Now the signed range. Because we could be dealing with negative numbers @@ -834,7 +835,7 @@ ConstantRange::umin(const ConstantRange &Other) const { ConstantRange ConstantRange::udiv(const ConstantRange &RHS) const { - if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax() == 0) + if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue()) return ConstantRange(getBitWidth(), /*isFullSet=*/false); if (RHS.isFullSet()) return ConstantRange(getBitWidth(), /*isFullSet=*/true); @@ -842,7 +843,7 @@ ConstantRange::udiv(const ConstantRange &RHS) const { APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax()); APInt RHS_umin = RHS.getUnsignedMin(); - if (RHS_umin == 0) { + if (RHS_umin.isNullValue()) { // We want the lowest value in RHS excluding zero. Usually that would be 1 // except for a range in the form of [X, 1) in which case it would be X. if (RHS.getUpper() == 1) @@ -892,29 +893,33 @@ ConstantRange::shl(const ConstantRange &Other) const { if (isEmptySet() || Other.isEmptySet()) return ConstantRange(getBitWidth(), /*isFullSet=*/false); - APInt min = getUnsignedMin().shl(Other.getUnsignedMin()); - APInt max = getUnsignedMax().shl(Other.getUnsignedMax()); + APInt max = getUnsignedMax(); + APInt Other_umax = Other.getUnsignedMax(); - // there's no overflow! - APInt Zeros(getBitWidth(), getUnsignedMax().countLeadingZeros()); - if (Zeros.ugt(Other.getUnsignedMax())) - return ConstantRange(std::move(min), std::move(max) + 1); + // there's overflow! + if (Other_umax.uge(max.countLeadingZeros())) + return ConstantRange(getBitWidth(), /*isFullSet=*/true); // FIXME: implement the other tricky cases - return ConstantRange(getBitWidth(), /*isFullSet=*/true); + + APInt min = getUnsignedMin(); + min <<= Other.getUnsignedMin(); + max <<= Other_umax; + + return ConstantRange(std::move(min), std::move(max) + 1); } ConstantRange ConstantRange::lshr(const ConstantRange &Other) const { if (isEmptySet() || Other.isEmptySet()) return ConstantRange(getBitWidth(), /*isFullSet=*/false); - - APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()); + + APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1; APInt min = getUnsignedMin().lshr(Other.getUnsignedMax()); - if (min == max + 1) + if (min == max) return ConstantRange(getBitWidth(), /*isFullSet=*/true); - return ConstantRange(std::move(min), std::move(max) + 1); + return ConstantRange(std::move(min), std::move(max)); } ConstantRange ConstantRange::inverse() const { diff --git a/contrib/llvm/lib/IR/Constants.cpp b/contrib/llvm/lib/IR/Constants.cpp index ffc8f2e4303b..4b9d89cda539 100644 --- a/contrib/llvm/lib/IR/Constants.cpp +++ b/contrib/llvm/lib/IR/Constants.cpp @@ -30,7 +30,7 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> -#include <cstdarg> + using namespace llvm; //===----------------------------------------------------------------------===// @@ -966,16 +966,6 @@ Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) { return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V); } -Constant *ConstantStruct::get(StructType *T, ...) { - va_list ap; - SmallVector<Constant*, 8> Values; - va_start(ap, T); - while (Constant *Val = va_arg(ap, llvm::Constant*)) - Values.push_back(Val); - va_end(ap); - return get(T, Values); -} - ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V) : ConstantAggregate(T, ConstantVectorVal, V) { assert(V.size() == T->getNumElements() && @@ -1810,8 +1800,7 @@ Constant *ConstantExpr::getSizeOf(Type* Ty) { Constant *ConstantExpr::getAlignOf(Type* Ty) { // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 // Note that a non-inbounds gep is used, as null isn't within any object. - Type *AligningTy = - StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr); + Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty); Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0)); Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0); Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); diff --git a/contrib/llvm/lib/IR/ConstantsContext.h b/contrib/llvm/lib/IR/ConstantsContext.h index eda751d8af4a..25eb9452d9d0 100644 --- a/contrib/llvm/lib/IR/ConstantsContext.h +++ b/contrib/llvm/lib/IR/ConstantsContext.h @@ -22,6 +22,7 @@ #include "llvm/ADT/None.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" +#include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/InlineAsm.h" @@ -387,31 +388,34 @@ struct ConstantExprKeyType; template <class ConstantClass> struct ConstantInfo; template <> struct ConstantInfo<ConstantExpr> { - typedef ConstantExprKeyType ValType; - typedef Type TypeClass; + using ValType = ConstantExprKeyType; + using TypeClass = Type; }; template <> struct ConstantInfo<InlineAsm> { - typedef InlineAsmKeyType ValType; - typedef PointerType TypeClass; + using ValType = InlineAsmKeyType; + using TypeClass = PointerType; }; template <> struct ConstantInfo<ConstantArray> { - typedef ConstantAggrKeyType<ConstantArray> ValType; - typedef ArrayType TypeClass; + using ValType = ConstantAggrKeyType<ConstantArray>; + using TypeClass = ArrayType; }; template <> struct ConstantInfo<ConstantStruct> { - typedef ConstantAggrKeyType<ConstantStruct> ValType; - typedef StructType TypeClass; + using ValType = ConstantAggrKeyType<ConstantStruct>; + using TypeClass = StructType; }; template <> struct ConstantInfo<ConstantVector> { - typedef ConstantAggrKeyType<ConstantVector> ValType; - typedef VectorType TypeClass; + using ValType = ConstantAggrKeyType<ConstantVector>; + using TypeClass = VectorType; }; template <class ConstantClass> struct ConstantAggrKeyType { ArrayRef<Constant *> Operands; + ConstantAggrKeyType(ArrayRef<Constant *> Operands) : Operands(Operands) {} + ConstantAggrKeyType(ArrayRef<Constant *> Operands, const ConstantClass *) : Operands(Operands) {} + ConstantAggrKeyType(const ConstantClass *C, SmallVectorImpl<Constant *> &Storage) { assert(Storage.empty() && "Expected empty storage"); @@ -437,7 +441,8 @@ template <class ConstantClass> struct ConstantAggrKeyType { return hash_combine_range(Operands.begin(), Operands.end()); } - typedef typename ConstantInfo<ConstantClass>::TypeClass TypeClass; + using TypeClass = typename ConstantInfo<ConstantClass>::TypeClass; + ConstantClass *create(TypeClass *Ty) const { return new (Operands.size()) ConstantClass(Ty, Operands); } @@ -457,6 +462,7 @@ struct InlineAsmKeyType { : AsmString(AsmString), Constraints(Constraints), FTy(FTy), HasSideEffects(HasSideEffects), IsAlignStack(IsAlignStack), AsmDialect(AsmDialect) {} + InlineAsmKeyType(const InlineAsm *Asm, SmallVectorImpl<Constant *> &) : AsmString(Asm->getAsmString()), Constraints(Asm->getConstraintString()), FTy(Asm->getFunctionType()), HasSideEffects(Asm->hasSideEffects()), @@ -483,7 +489,8 @@ struct InlineAsmKeyType { AsmDialect, FTy); } - typedef ConstantInfo<InlineAsm>::TypeClass TypeClass; + using TypeClass = ConstantInfo<InlineAsm>::TypeClass; + InlineAsm *create(TypeClass *Ty) const { assert(PointerType::getUnqual(FTy) == Ty); return new InlineAsm(FTy, AsmString, Constraints, HasSideEffects, @@ -507,11 +514,13 @@ struct ConstantExprKeyType { : Opcode(Opcode), SubclassOptionalData(SubclassOptionalData), SubclassData(SubclassData), Ops(Ops), Indexes(Indexes), ExplicitTy(ExplicitTy) {} + ConstantExprKeyType(ArrayRef<Constant *> Operands, const ConstantExpr *CE) : Opcode(CE->getOpcode()), SubclassOptionalData(CE->getRawSubclassOptionalData()), SubclassData(CE->isCompare() ? CE->getPredicate() : 0), Ops(Operands), Indexes(CE->hasIndices() ? CE->getIndices() : ArrayRef<unsigned>()) {} + ConstantExprKeyType(const ConstantExpr *CE, SmallVectorImpl<Constant *> &Storage) : Opcode(CE->getOpcode()), @@ -553,7 +562,8 @@ struct ConstantExprKeyType { hash_combine_range(Indexes.begin(), Indexes.end())); } - typedef ConstantInfo<ConstantExpr>::TypeClass TypeClass; + using TypeClass = ConstantInfo<ConstantExpr>::TypeClass; + ConstantExpr *create(TypeClass *Ty) const { switch (Opcode) { default: @@ -594,16 +604,17 @@ struct ConstantExprKeyType { template <class ConstantClass> class ConstantUniqueMap { public: - typedef typename ConstantInfo<ConstantClass>::ValType ValType; - typedef typename ConstantInfo<ConstantClass>::TypeClass TypeClass; - typedef std::pair<TypeClass *, ValType> LookupKey; + using ValType = typename ConstantInfo<ConstantClass>::ValType; + using TypeClass = typename ConstantInfo<ConstantClass>::TypeClass; + using LookupKey = std::pair<TypeClass *, ValType>; /// Key and hash together, so that we compute the hash only once and reuse it. - typedef std::pair<unsigned, LookupKey> LookupKeyHashed; + using LookupKeyHashed = std::pair<unsigned, LookupKey>; private: struct MapInfo { - typedef DenseMapInfo<ConstantClass *> ConstantClassInfo; + using ConstantClassInfo = DenseMapInfo<ConstantClass *>; + static inline ConstantClass *getEmptyKey() { return ConstantClassInfo::getEmptyKey(); } @@ -643,7 +654,7 @@ private: }; public: - typedef DenseSet<ConstantClass *, MapInfo> MapTy; + using MapTy = DenseSet<ConstantClass *, MapInfo>; private: MapTy Map; diff --git a/contrib/llvm/lib/IR/DebugInfoMetadata.cpp b/contrib/llvm/lib/IR/DebugInfoMetadata.cpp index cdbe237766a3..e6c49cad0722 100644 --- a/contrib/llvm/lib/IR/DebugInfoMetadata.cpp +++ b/contrib/llvm/lib/IR/DebugInfoMetadata.cpp @@ -672,6 +672,24 @@ void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops, } } +bool DIExpression::extractIfOffset(int64_t &Offset) const { + if (getNumElements() == 0) { + Offset = 0; + return true; + } + if (getNumElements() != 2) + return false; + if (Elements[0] == dwarf::DW_OP_plus) { + Offset = Elements[1]; + return true; + } + if (Elements[0] == dwarf::DW_OP_minus) { + Offset = -Elements[1]; + return true; + } + return false; +} + DIExpression *DIExpression::prepend(const DIExpression *Expr, bool Deref, int64_t Offset, bool StackValue) { SmallVector<uint64_t, 8> Ops; diff --git a/contrib/llvm/lib/IR/DebugLoc.cpp b/contrib/llvm/lib/IR/DebugLoc.cpp index f31074a7ad44..3168ec6944a3 100644 --- a/contrib/llvm/lib/IR/DebugLoc.cpp +++ b/contrib/llvm/lib/IR/DebugLoc.cpp @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "llvm/IR/DebugLoc.h" +#include "llvm/IR/IntrinsicInst.h" #include "LLVMContextImpl.h" #include "llvm/IR/DebugInfo.h" using namespace llvm; @@ -66,6 +67,119 @@ DebugLoc DebugLoc::get(unsigned Line, unsigned Col, const MDNode *Scope, const_cast<MDNode *>(InlinedAt)); } +DebugLoc DebugLoc::appendInlinedAt(DebugLoc DL, DILocation *InlinedAt, + LLVMContext &Ctx, + DenseMap<const MDNode *, MDNode *> &Cache, + bool ReplaceLast) { + SmallVector<DILocation *, 3> InlinedAtLocations; + DILocation *Last = InlinedAt; + DILocation *CurInlinedAt = DL; + + // Gather all the inlined-at nodes. + while (DILocation *IA = CurInlinedAt->getInlinedAt()) { + // Skip any we've already built nodes for. + if (auto *Found = Cache[IA]) { + Last = cast<DILocation>(Found); + break; + } + + if (ReplaceLast && !IA->getInlinedAt()) + break; + InlinedAtLocations.push_back(IA); + CurInlinedAt = IA; + } + + // Starting from the top, rebuild the nodes to point to the new inlined-at + // location (then rebuilding the rest of the chain behind it) and update the + // map of already-constructed inlined-at nodes. + for (const DILocation *MD : reverse(InlinedAtLocations)) + Cache[MD] = Last = DILocation::getDistinct( + Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last); + + return Last; +} + +/// Reparent \c Scope from \c OrigSP to \c NewSP. +static DIScope *reparentScope(LLVMContext &Ctx, DIScope *Scope, + DISubprogram *OrigSP, DISubprogram *NewSP, + DenseMap<const MDNode *, MDNode *> &Cache) { + SmallVector<DIScope *, 3> ScopeChain; + DIScope *Last = NewSP; + DIScope *CurScope = Scope; + do { + if (auto *SP = dyn_cast<DISubprogram>(CurScope)) { + // Don't rewrite this scope chain if it doesn't lead to the replaced SP. + if (SP != OrigSP) + return Scope; + Cache.insert({OrigSP, NewSP}); + break; + } + if (auto *Found = Cache[CurScope]) { + Last = cast<DIScope>(Found); + break; + } + ScopeChain.push_back(CurScope); + } while ((CurScope = CurScope->getScope().resolve())); + + // Starting from the top, rebuild the nodes to point to the new inlined-at + // location (then rebuilding the rest of the chain behind it) and update the + // map of already-constructed inlined-at nodes. + for (const DIScope *MD : reverse(ScopeChain)) { + if (auto *LB = dyn_cast<DILexicalBlock>(MD)) + Cache[MD] = Last = DILexicalBlock::getDistinct( + Ctx, Last, LB->getFile(), LB->getLine(), LB->getColumn()); + else if (auto *LB = dyn_cast<DILexicalBlockFile>(MD)) + Cache[MD] = Last = DILexicalBlockFile::getDistinct( + Ctx, Last, LB->getFile(), LB->getDiscriminator()); + else + llvm_unreachable("illegal parent scope"); + } + return Last; +} + +void DebugLoc::reparentDebugInfo(Instruction &I, DISubprogram *OrigSP, + DISubprogram *NewSP, + DenseMap<const MDNode *, MDNode *> &Cache) { + auto DL = I.getDebugLoc(); + if (!OrigSP || !NewSP || OrigSP == NewSP || !DL) + return; + + // Reparent the debug location. + auto &Ctx = I.getContext(); + DILocation *InlinedAt = DL->getInlinedAt(); + if (InlinedAt) { + while (auto *IA = InlinedAt->getInlinedAt()) + InlinedAt = IA; + auto NewScope = + reparentScope(Ctx, InlinedAt->getScope(), OrigSP, NewSP, Cache); + InlinedAt = + DebugLoc::get(InlinedAt->getLine(), InlinedAt->getColumn(), NewScope); + } + I.setDebugLoc( + DebugLoc::get(DL.getLine(), DL.getCol(), + reparentScope(Ctx, DL->getScope(), OrigSP, NewSP, Cache), + DebugLoc::appendInlinedAt(DL, InlinedAt, Ctx, Cache, + ReplaceLastInlinedAt))); + + // Fix up debug variables to point to NewSP. + auto reparentVar = [&](DILocalVariable *Var) { + return DILocalVariable::getDistinct( + Ctx, + cast<DILocalScope>( + reparentScope(Ctx, Var->getScope(), OrigSP, NewSP, Cache)), + Var->getName(), Var->getFile(), Var->getLine(), Var->getType(), + Var->getArg(), Var->getFlags(), Var->getAlignInBits()); + }; + if (auto *DbgValue = dyn_cast<DbgValueInst>(&I)) { + auto *Var = DbgValue->getVariable(); + I.setOperand(2, MetadataAsValue::get(Ctx, reparentVar(Var))); + } else if (auto *DbgDeclare = dyn_cast<DbgDeclareInst>(&I)) { + auto *Var = DbgDeclare->getVariable(); + I.setOperand(1, MetadataAsValue::get(Ctx, reparentVar(Var))); + } +} + + #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void DebugLoc::dump() const { if (!Loc) diff --git a/contrib/llvm/lib/IR/DiagnosticInfo.cpp b/contrib/llvm/lib/IR/DiagnosticInfo.cpp index 395b6158e0c8..e73f53f3202d 100644 --- a/contrib/llvm/lib/IR/DiagnosticInfo.cpp +++ b/contrib/llvm/lib/IR/DiagnosticInfo.cpp @@ -12,20 +12,31 @@ // Diagnostics reporting is still done as part of the LLVMContext. //===----------------------------------------------------------------------===// -#include "llvm/IR/DiagnosticInfo.h" -#include "LLVMContextImpl.h" +#include "llvm/ADT/iterator_range.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" -#include "llvm/IR/DebugInfo.h" +#include "llvm/IR/DebugInfoMetadata.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" #include "llvm/IR/Instruction.h" +#include "llvm/IR/LLVMContext.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/Support/Regex.h" #include <atomic> +#include <cassert> +#include <memory> #include <string> using namespace llvm; @@ -53,6 +64,8 @@ struct PassRemarksOpt { } }; +} // end anonymous namespace + static PassRemarksOpt PassRemarksOptLoc; static PassRemarksOpt PassRemarksMissedOptLoc; static PassRemarksOpt PassRemarksAnalysisOptLoc; @@ -85,7 +98,6 @@ PassRemarksAnalysis( "the given regular expression"), cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired, cl::ZeroOrMore); -} int llvm::getNextAvailablePluginDiagnosticKind() { static std::atomic<int> PluginKindID(DK_FirstPluginKind); @@ -97,8 +109,7 @@ const char *OptimizationRemarkAnalysis::AlwaysPrint = ""; DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I, const Twine &MsgStr, DiagnosticSeverity Severity) - : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr), - Instr(&I) { + : DiagnosticInfo(DK_InlineAsm, Severity), MsgStr(MsgStr), Instr(&I) { if (const MDNode *SrcLoc = I.getMetadata("srcloc")) { if (SrcLoc->getNumOperands() != 0) if (const auto *CI = @@ -193,7 +204,7 @@ DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Value *V // Only include names that correspond to user variables. FIXME: we should use // debug info if available to get the name of the user variable. if (isa<llvm::Argument>(V) || isa<GlobalValue>(V)) - Val = GlobalValue::getRealLinkageName(V->getName()); + Val = GlobalValue::dropLLVMManglingEscape(V->getName()); else if (isa<Constant>(V)) { raw_string_ostream OS(Val); V->printAsOperand(OS, /*PrintType=*/false); diff --git a/contrib/llvm/lib/IR/Function.cpp b/contrib/llvm/lib/IR/Function.cpp index 58c060550322..16a9e51b8306 100644 --- a/contrib/llvm/lib/IR/Function.cpp +++ b/contrib/llvm/lib/IR/Function.cpp @@ -1,4 +1,4 @@ -//===-- Function.cpp - Implement the Global object classes ----------------===// +//===- Function.cpp - Implement the Global object classes -----------------===// // // The LLVM Compiler Infrastructure // @@ -11,21 +11,51 @@ // //===----------------------------------------------------------------------===// -#include "llvm/IR/Function.h" #include "LLVMContextImpl.h" #include "SymbolTableListTraitsImpl.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/ValueTypes.h" +#include "llvm/IR/Argument.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallSite.h" +#include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" #include "llvm/IR/InstIterator.h" +#include "llvm/IR/Instruction.h" +#include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" +#include "llvm/IR/SymbolTableListTraits.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Use.h" +#include "llvm/IR/User.h" +#include "llvm/IR/Value.h" +#include "llvm/IR/ValueSymbolTable.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/ErrorHandling.h" +#include <algorithm> +#include <cassert> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <string> + using namespace llvm; // Explicit instantiations of SymbolTableListTraits since some of the methods @@ -36,7 +66,7 @@ template class llvm::SymbolTableListTraits<BasicBlock>; // Argument Implementation //===----------------------------------------------------------------------===// -void Argument::anchor() { } +void Argument::anchor() {} Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { @@ -186,7 +216,7 @@ Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name, Module *ParentModule) : GlobalObject(Ty, Value::FunctionVal, OperandTraits<Function>::op_begin(this), 0, Linkage, name), - Arguments(nullptr), NumArgs(Ty->getNumParams()) { + NumArgs(Ty->getNumParams()) { assert(FunctionType::isValidReturnType(getReturnType()) && "invalid return type"); setGlobalObjectSubClassData(0); @@ -386,24 +416,20 @@ void Function::clearGC() { /// Copy all additional attributes (those not needed to create a Function) from /// the Function Src to this one. -void Function::copyAttributesFrom(const GlobalValue *Src) { +void Function::copyAttributesFrom(const Function *Src) { GlobalObject::copyAttributesFrom(Src); - const Function *SrcF = dyn_cast<Function>(Src); - if (!SrcF) - return; - - setCallingConv(SrcF->getCallingConv()); - setAttributes(SrcF->getAttributes()); - if (SrcF->hasGC()) - setGC(SrcF->getGC()); + setCallingConv(Src->getCallingConv()); + setAttributes(Src->getAttributes()); + if (Src->hasGC()) + setGC(Src->getGC()); else clearGC(); - if (SrcF->hasPersonalityFn()) - setPersonalityFn(SrcF->getPersonalityFn()); - if (SrcF->hasPrefixData()) - setPrefixData(SrcF->getPrefixData()); - if (SrcF->hasPrologueData()) - setPrologueData(SrcF->getPrologueData()); + if (Src->hasPersonalityFn()) + setPersonalityFn(Src->getPersonalityFn()); + if (Src->hasPrefixData()) + setPrefixData(Src->getPrefixData()); + if (Src->hasPrologueData()) + setPrologueData(Src->getPrologueData()); } /// Table of string intrinsic names indexed by enum value. @@ -486,10 +512,10 @@ void Function::recalculateIntrinsicID() { static std::string getMangledTypeStr(Type* Ty) { std::string Result; if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { - Result += "p" + llvm::utostr(PTyp->getAddressSpace()) + + Result += "p" + utostr(PTyp->getAddressSpace()) + getMangledTypeStr(PTyp->getElementType()); } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { - Result += "a" + llvm::utostr(ATyp->getNumElements()) + + Result += "a" + utostr(ATyp->getNumElements()) + getMangledTypeStr(ATyp->getElementType()); } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { if (!STyp->isLiteral()) { @@ -534,7 +560,6 @@ std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { return Result; } - /// IIT_Info - These are enumerators that describe the entries returned by the /// getIntrinsicInfoTableEntries function. /// @@ -585,9 +610,10 @@ enum IIT_Info { static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { + using namespace Intrinsic; + IIT_Info Info = IIT_Info(Infos[NextElt++]); unsigned StructElts = 2; - using namespace Intrinsic; switch (Info) { case IIT_Done: @@ -742,7 +768,6 @@ static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, llvm_unreachable("unhandled"); } - #define GET_INTRINSIC_GENERATOR_GLOBAL #include "llvm/IR/Intrinsics.gen" #undef GET_INTRINSIC_GENERATOR_GLOBAL @@ -780,10 +805,10 @@ void Intrinsic::getIntrinsicInfoTableEntries(ID id, DecodeIITType(NextElt, IITEntries, T); } - static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, ArrayRef<Type*> Tys, LLVMContext &Context) { using namespace Intrinsic; + IITDescriptor D = Infos.front(); Infos = Infos.slice(1); @@ -855,12 +880,10 @@ static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, case IITDescriptor::VecOfAnyPtrsToElt: // Return the overloaded type (which determines the pointers address space) return Tys[D.getOverloadArgNumber()]; - } + } llvm_unreachable("unhandled"); } - - FunctionType *Intrinsic::getType(LLVMContext &Context, ID id, ArrayRef<Type*> Tys) { SmallVector<IITDescriptor, 8> Table; diff --git a/contrib/llvm/lib/IR/Globals.cpp b/contrib/llvm/lib/IR/Globals.cpp index 5f338f58d940..17d27b016cf2 100644 --- a/contrib/llvm/lib/IR/Globals.cpp +++ b/contrib/llvm/lib/IR/Globals.cpp @@ -69,6 +69,30 @@ void GlobalValue::copyAttributesFrom(const GlobalValue *Src) { setDLLStorageClass(Src->getDLLStorageClass()); } +void GlobalValue::removeFromParent() { + switch (getValueID()) { +#define HANDLE_GLOBAL_VALUE(NAME) \ + case Value::NAME##Val: \ + return static_cast<NAME *>(this)->removeFromParent(); +#include "llvm/IR/Value.def" + default: + break; + } + llvm_unreachable("not a global"); +} + +void GlobalValue::eraseFromParent() { + switch (getValueID()) { +#define HANDLE_GLOBAL_VALUE(NAME) \ + case Value::NAME##Val: \ + return static_cast<NAME *>(this)->eraseFromParent(); +#include "llvm/IR/Value.def" + default: + break; + } + llvm_unreachable("not a global"); +} + unsigned GlobalValue::getAlignment() const { if (auto *GA = dyn_cast<GlobalAlias>(this)) { // In general we cannot compute this at the IR level, but we try. @@ -93,12 +117,10 @@ void GlobalObject::setAlignment(unsigned Align) { assert(getAlignment() == Align && "Alignment representation error!"); } -void GlobalObject::copyAttributesFrom(const GlobalValue *Src) { +void GlobalObject::copyAttributesFrom(const GlobalObject *Src) { GlobalValue::copyAttributesFrom(Src); - if (const auto *GV = dyn_cast<GlobalObject>(Src)) { - setAlignment(GV->getAlignment()); - setSection(GV->getSection()); - } + setAlignment(Src->getAlignment()); + setSection(Src->getSection()); } std::string GlobalValue::getGlobalIdentifier(StringRef Name, @@ -233,7 +255,7 @@ bool GlobalValue::canIncreaseAlignment() const { const GlobalObject *GlobalValue::getBaseObject() const { if (auto *GO = dyn_cast<GlobalObject>(this)) return GO; - if (auto *GA = dyn_cast<GlobalAlias>(this)) + if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this)) return GA->getBaseObject(); return nullptr; } @@ -333,12 +355,11 @@ void GlobalVariable::setInitializer(Constant *InitVal) { /// Copy all additional attributes (those not needed to create a GlobalVariable) /// from the GlobalVariable Src to this one. -void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) { +void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) { GlobalObject::copyAttributesFrom(Src); - if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) { - setThreadLocalMode(SrcVar->getThreadLocalMode()); - setExternallyInitialized(SrcVar->isExternallyInitialized()); - } + setThreadLocalMode(Src->getThreadLocalMode()); + setExternallyInitialized(Src->isExternallyInitialized()); + setAttributes(Src->getAttributes()); } void GlobalVariable::dropAllReferences() { diff --git a/contrib/llvm/lib/IR/IRBuilder.cpp b/contrib/llvm/lib/IR/IRBuilder.cpp index e265a823687f..3477c087967f 100644 --- a/contrib/llvm/lib/IR/IRBuilder.cpp +++ b/contrib/llvm/lib/IR/IRBuilder.cpp @@ -161,6 +161,94 @@ CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align, return CI; } +static CallInst *getReductionIntrinsic(IRBuilderBase *Builder, Intrinsic::ID ID, + Value *Src) { + Module *M = Builder->GetInsertBlock()->getParent()->getParent(); + Value *Ops[] = {Src}; + Type *Tys[] = { Src->getType()->getVectorElementType(), Src->getType() }; + auto Decl = Intrinsic::getDeclaration(M, ID, Tys); + return createCallHelper(Decl, Ops, Builder); +} + +CallInst *IRBuilderBase::CreateFAddReduce(Value *Acc, Value *Src) { + Module *M = GetInsertBlock()->getParent()->getParent(); + Value *Ops[] = {Acc, Src}; + Type *Tys[] = {Src->getType()->getVectorElementType(), Acc->getType(), + Src->getType()}; + auto Decl = Intrinsic::getDeclaration( + M, Intrinsic::experimental_vector_reduce_fadd, Tys); + return createCallHelper(Decl, Ops, this); +} + +CallInst *IRBuilderBase::CreateFMulReduce(Value *Acc, Value *Src) { + Module *M = GetInsertBlock()->getParent()->getParent(); + Value *Ops[] = {Acc, Src}; + Type *Tys[] = {Src->getType()->getVectorElementType(), Acc->getType(), + Src->getType()}; + auto Decl = Intrinsic::getDeclaration( + M, Intrinsic::experimental_vector_reduce_fmul, Tys); + return createCallHelper(Decl, Ops, this); +} + +CallInst *IRBuilderBase::CreateAddReduce(Value *Src) { + return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_add, + Src); +} + +CallInst *IRBuilderBase::CreateMulReduce(Value *Src) { + return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_mul, + Src); +} + +CallInst *IRBuilderBase::CreateAndReduce(Value *Src) { + return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_and, + Src); +} + +CallInst *IRBuilderBase::CreateOrReduce(Value *Src) { + return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_or, + Src); +} + +CallInst *IRBuilderBase::CreateXorReduce(Value *Src) { + return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_xor, + Src); +} + +CallInst *IRBuilderBase::CreateIntMaxReduce(Value *Src, bool IsSigned) { + auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smax + : Intrinsic::experimental_vector_reduce_umax; + return getReductionIntrinsic(this, ID, Src); +} + +CallInst *IRBuilderBase::CreateIntMinReduce(Value *Src, bool IsSigned) { + auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smin + : Intrinsic::experimental_vector_reduce_umin; + return getReductionIntrinsic(this, ID, Src); +} + +CallInst *IRBuilderBase::CreateFPMaxReduce(Value *Src, bool NoNaN) { + auto Rdx = getReductionIntrinsic( + this, Intrinsic::experimental_vector_reduce_fmax, Src); + if (NoNaN) { + FastMathFlags FMF; + FMF.setNoNaNs(); + Rdx->setFastMathFlags(FMF); + } + return Rdx; +} + +CallInst *IRBuilderBase::CreateFPMinReduce(Value *Src, bool NoNaN) { + auto Rdx = getReductionIntrinsic( + this, Intrinsic::experimental_vector_reduce_fmin, Src); + if (NoNaN) { + FastMathFlags FMF; + FMF.setNoNaNs(); + Rdx->setFastMathFlags(FMF); + } + return Rdx; +} + CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) { assert(isa<PointerType>(Ptr->getType()) && "lifetime.start only applies to pointers."); diff --git a/contrib/llvm/lib/IR/Instruction.cpp b/contrib/llvm/lib/IR/Instruction.cpp index 906a28a5c887..91b9d9232b54 100644 --- a/contrib/llvm/lib/IR/Instruction.cpp +++ b/contrib/llvm/lib/IR/Instruction.cpp @@ -534,6 +534,30 @@ bool Instruction::isAtomic() const { } } +bool Instruction::hasAtomicLoad() const { + assert(isAtomic()); + switch (getOpcode()) { + default: + return false; + case Instruction::AtomicCmpXchg: + case Instruction::AtomicRMW: + case Instruction::Load: + return true; + } +} + +bool Instruction::hasAtomicStore() const { + assert(isAtomic()); + switch (getOpcode()) { + default: + return false; + case Instruction::AtomicCmpXchg: + case Instruction::AtomicRMW: + case Instruction::Store: + return true; + } +} + bool Instruction::mayThrow() const { if (const CallInst *CI = dyn_cast<CallInst>(this)) return !CI->doesNotThrow(); diff --git a/contrib/llvm/lib/IR/Instructions.cpp b/contrib/llvm/lib/IR/Instructions.cpp index a60cc375d568..5a5b9c0d06bb 100644 --- a/contrib/llvm/lib/IR/Instructions.cpp +++ b/contrib/llvm/lib/IR/Instructions.cpp @@ -1,4 +1,4 @@ -//===-- Instructions.cpp - Implement the LLVM instructions ----------------===// +//===- Instructions.cpp - Implement the LLVM instructions -----------------===// // // The LLVM Compiler Infrastructure // @@ -12,18 +12,36 @@ // //===----------------------------------------------------------------------===// -#include "llvm/IR/Instructions.h" #include "LLVMContextImpl.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/Twine.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallSite.h" -#include "llvm/IR/ConstantRange.h" +#include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Value.h" +#include "llvm/Support/AtomicOrdering.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" +#include <algorithm> +#include <cassert> +#include <cstdint> +#include <vector> + using namespace llvm; //===----------------------------------------------------------------------===// @@ -42,7 +60,42 @@ User::op_iterator CallSite::getCallee() const { //===----------------------------------------------------------------------===// // Out of line virtual method, so the vtable, etc has a home. -TerminatorInst::~TerminatorInst() { +TerminatorInst::~TerminatorInst() = default; + +unsigned TerminatorInst::getNumSuccessors() const { + switch (getOpcode()) { +#define HANDLE_TERM_INST(N, OPC, CLASS) \ + case Instruction::OPC: \ + return static_cast<const CLASS *>(this)->getNumSuccessorsV(); +#include "llvm/IR/Instruction.def" + default: + break; + } + llvm_unreachable("not a terminator"); +} + +BasicBlock *TerminatorInst::getSuccessor(unsigned idx) const { + switch (getOpcode()) { +#define HANDLE_TERM_INST(N, OPC, CLASS) \ + case Instruction::OPC: \ + return static_cast<const CLASS *>(this)->getSuccessorV(idx); +#include "llvm/IR/Instruction.def" + default: + break; + } + llvm_unreachable("not a terminator"); +} + +void TerminatorInst::setSuccessor(unsigned idx, BasicBlock *B) { + switch (getOpcode()) { +#define HANDLE_TERM_INST(N, OPC, CLASS) \ + case Instruction::OPC: \ + return static_cast<CLASS *>(this)->setSuccessorV(idx, B); +#include "llvm/IR/Instruction.def" + default: + break; + } + llvm_unreachable("not a terminator"); } //===----------------------------------------------------------------------===// @@ -50,8 +103,7 @@ TerminatorInst::~TerminatorInst() { //===----------------------------------------------------------------------===// // Out of line virtual method, so the vtable, etc has a home. -UnaryInstruction::~UnaryInstruction() { -} +UnaryInstruction::~UnaryInstruction() = default; //===----------------------------------------------------------------------===// // SelectInst Class @@ -82,7 +134,6 @@ const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { return nullptr; } - //===----------------------------------------------------------------------===// // PHINode Class //===----------------------------------------------------------------------===// @@ -242,8 +293,7 @@ void LandingPadInst::addClause(Constant *Val) { // CallInst Implementation //===----------------------------------------------------------------------===// -CallInst::~CallInst() { -} +CallInst::~CallInst() = default; void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { @@ -541,7 +591,6 @@ Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, ArraySize, OpB, MallocF, Name); } - /// CreateMalloc - Generate the IR for a call to malloc: /// 1. Compute the malloc call's argument as the specified type's size, /// possibly multiplied by the array size if the array size is not @@ -692,9 +741,11 @@ InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } + unsigned InvokeInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) { return setSuccessor(idx, B); } @@ -821,6 +872,7 @@ ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) if (retVal) Op<0>() = retVal; } + ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, @@ -828,6 +880,7 @@ ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) if (retVal) Op<0>() = retVal; } + ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { @@ -847,8 +900,7 @@ BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const { llvm_unreachable("ReturnInst has no successors!"); } -ReturnInst::~ReturnInst() { -} +ReturnInst::~ReturnInst() = default; //===----------------------------------------------------------------------===// // ResumeInst Implementation @@ -930,9 +982,11 @@ BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const { assert(Idx == 0); return getUnwindDest(); } + unsigned CleanupReturnInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx == 0); setUnwindDest(B); @@ -973,9 +1027,11 @@ BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const { assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); return getSuccessor(); } + unsigned CatchReturnInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); setSuccessor(B); @@ -1067,9 +1123,11 @@ void CatchSwitchInst::removeHandler(handler_iterator HI) { BasicBlock *CatchSwitchInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } + unsigned CatchSwitchInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void CatchSwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } @@ -1155,6 +1213,7 @@ BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) assert(IfTrue && "Branch destination may not be null!"); Op<-1>() = IfTrue; } + BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, @@ -1189,7 +1248,6 @@ BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, #endif } - BranchInst::BranchInst(const BranchInst &BI) : TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), @@ -1216,14 +1274,15 @@ void BranchInst::swapSuccessors() { BasicBlock *BranchInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } + unsigned BranchInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } - //===----------------------------------------------------------------------===// // AllocaInst Implementation //===----------------------------------------------------------------------===// @@ -1279,8 +1338,7 @@ AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, } // Out of line virtual method, so the vtable, etc has a home. -AllocaInst::~AllocaInst() { -} +AllocaInst::~AllocaInst() = default; void AllocaInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); @@ -1543,8 +1601,7 @@ AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, SynchronizationScope SynchScope, Instruction *InsertBefore) : Instruction( - StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), - nullptr), + StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); @@ -1556,8 +1613,7 @@ AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, SynchronizationScope SynchScope, BasicBlock *InsertAtEnd) : Instruction( - StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), - nullptr), + StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); @@ -1771,14 +1827,12 @@ ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, setName(Name); } - bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) return false; return true; } - //===----------------------------------------------------------------------===// // InsertElementInst Implementation //===----------------------------------------------------------------------===// @@ -1825,7 +1879,6 @@ bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, return true; } - //===----------------------------------------------------------------------===// // ShuffleVectorInst Implementation //===----------------------------------------------------------------------===// @@ -1938,7 +1991,6 @@ void ShuffleVectorInst::getShuffleMask(Constant *Mask, } } - //===----------------------------------------------------------------------===// // InsertValueInst Class //===----------------------------------------------------------------------===// @@ -1951,7 +2003,7 @@ void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, // (other than weirdness with &*IdxBegin being invalid; see // getelementptr's init routine for example). But there's no // present need to support it. - assert(Idxs.size() > 0 && "InsertValueInst must have at least one index"); + assert(!Idxs.empty() && "InsertValueInst must have at least one index"); assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == Val->getType() && "Inserted value must match indexed type!"); @@ -1980,7 +2032,7 @@ void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { // There's no fundamental reason why we require at least one index. // But there's no present need to support it. - assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index"); + assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); Indices.append(Idxs.begin(), Idxs.end()); setName(Name); @@ -2053,7 +2105,6 @@ BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, setName(Name); } - void BinaryOperator::init(BinaryOps iType) { Value *LHS = getOperand(0), *RHS = getOperand(1); (void)LHS; (void)RHS; // Silence warnings. @@ -2213,7 +2264,6 @@ BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, Op->getType(), Name, InsertAtEnd); } - // isConstantAllOnes - Helper function for several functions below static inline bool isConstantAllOnes(const Value *V) { if (const Constant *C = dyn_cast<Constant>(V)) @@ -2279,7 +2329,6 @@ const Value *BinaryOperator::getNotArgument(const Value *BinOp) { return getNotArgument(const_cast<Value*>(BinOp)); } - // Exchange the two operands to this instruction. This instruction is safe to // use on any binary instruction and does not modify the semantics of the // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode @@ -2291,7 +2340,6 @@ bool BinaryOperator::swapOperands() { return false; } - //===----------------------------------------------------------------------===// // FPMathOperator Class //===----------------------------------------------------------------------===// @@ -2305,7 +2353,6 @@ float FPMathOperator::getFPAccuracy() const { return Accuracy->getValueAPF().convertToFloat(); } - //===----------------------------------------------------------------------===// // CastInst Class //===----------------------------------------------------------------------===// @@ -2567,13 +2614,12 @@ unsigned CastInst::isEliminableCastPair( return Instruction::BitCast; return 0; } - case 12: { + case 12: // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) return Instruction::AddrSpaceCast; return Instruction::BitCast; - } case 13: // FIXME: this state can be merged with (1), but the following assert // is useful to check the correcteness of the sequence due to semantic @@ -2594,7 +2640,6 @@ unsigned CastInst::isEliminableCastPair( DstTy->getScalarType()->getPointerElementType()) return Instruction::AddrSpaceCast; return 0; - case 15: // FIXME: this state can be merged with (1), but the following assert // is useful to check the correcteness of the sequence due to semantic @@ -3070,7 +3115,6 @@ CastInst::getCastOpcode( /// of the types involved. bool CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { - // Check for type sanity on the arguments Type *SrcTy = S->getType(); @@ -3419,7 +3463,6 @@ bool CmpInst::isEquality() const { return cast<FCmpInst>(this)->isEquality(); } - CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { switch (pred) { default: llvm_unreachable("Unknown cmp predicate!"); @@ -3743,9 +3786,11 @@ void SwitchInst::growOperands() { BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } + unsigned SwitchInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } @@ -3832,9 +3877,11 @@ void IndirectBrInst::removeDestination(unsigned idx) { BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } + unsigned IndirectBrInst::getNumSuccessorsV() const { return getNumSuccessors(); } + void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } diff --git a/contrib/llvm/lib/IR/LegacyPassManager.cpp b/contrib/llvm/lib/IR/LegacyPassManager.cpp index 628a67bd639c..b2b12289f871 100644 --- a/contrib/llvm/lib/IR/LegacyPassManager.cpp +++ b/contrib/llvm/lib/IR/LegacyPassManager.cpp @@ -12,6 +12,7 @@ //===----------------------------------------------------------------------===// #include "llvm/IR/LegacyPassManager.h" +#include "llvm/ADT/Statistic.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManagers.h" @@ -465,6 +466,11 @@ public: // null. It may be called multiple times. static void createTheTimeInfo(); + // print - Prints out timing information and then resets the timers. + void print() { + TG.print(*CreateInfoOutputFile()); + } + /// getPassTimer - Return the timer for the specified pass if it exists. Timer *getPassTimer(Pass *P) { if (P->getAsPMDataManager()) @@ -1752,6 +1758,13 @@ Timer *llvm::getPassTimer(Pass *P) { return nullptr; } +/// If timing is enabled, report the times collected up to now and then reset +/// them. +void llvm::reportAndResetTimings() { + if (TheTimeInfo) + TheTimeInfo->print(); +} + //===----------------------------------------------------------------------===// // PMStack implementation // diff --git a/contrib/llvm/lib/IR/Module.cpp b/contrib/llvm/lib/IR/Module.cpp index fec9df193685..12c258d95f52 100644 --- a/contrib/llvm/lib/IR/Module.cpp +++ b/contrib/llvm/lib/IR/Module.cpp @@ -1,4 +1,4 @@ -//===-- Module.cpp - Implement the Module class ---------------------------===// +//===- Module.cpp - Implement the Module class ----------------------------===// // // The LLVM Compiler Infrastructure // @@ -11,27 +11,46 @@ // //===----------------------------------------------------------------------===// -#include "llvm/IR/Module.h" #include "SymbolTableListTraitsImpl.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" -#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/Comdat.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/DebugInfoMetadata.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalAlias.h" +#include "llvm/IR/GlobalIFunc.h" +#include "llvm/IR/GlobalValue.h" +#include "llvm/IR/GlobalVariable.h" #include "llvm/IR/GVMaterializer.h" -#include "llvm/IR/InstrTypes.h" #include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Metadata.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/SymbolTableListTraits.h" +#include "llvm/IR/Type.h" #include "llvm/IR/TypeFinder.h" -#include "llvm/Support/Dwarf.h" +#include "llvm/IR/Value.h" +#include "llvm/IR/ValueSymbolTable.h" +#include "llvm/Pass.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/CodeGen.h" #include "llvm/Support/Error.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/RandomNumberGenerator.h" #include <algorithm> -#include <cstdarg> -#include <cstdlib> +#include <cassert> +#include <cstdint> +#include <memory> +#include <utility> +#include <vector> using namespace llvm; diff --git a/contrib/llvm/lib/IR/Type.cpp b/contrib/llvm/lib/IR/Type.cpp index b67b0a307861..c9f957c244f8 100644 --- a/contrib/llvm/lib/IR/Type.cpp +++ b/contrib/llvm/lib/IR/Type.cpp @@ -1,4 +1,4 @@ -//===-- Type.cpp - Implement the Type class -------------------------------===// +//===- Type.cpp - Implement the Type class --------------------------------===// // // The LLVM Compiler Infrastructure // @@ -11,12 +11,25 @@ // //===----------------------------------------------------------------------===// -#include "llvm/IR/Type.h" #include "LLVMContextImpl.h" +#include "llvm/ADT/APInt.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/IR/Constant.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" -#include <algorithm> -#include <cstdarg> +#include "llvm/IR/Type.h" +#include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/MathExtras.h" +#include "llvm/Support/raw_ostream.h" +#include <cassert> +#include <utility> + using namespace llvm; //===----------------------------------------------------------------------===// @@ -220,7 +233,6 @@ PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) { return getInt64Ty(C)->getPointerTo(AS); } - //===----------------------------------------------------------------------===// // IntegerType Implementation //===----------------------------------------------------------------------===// @@ -362,7 +374,8 @@ void StructType::setName(StringRef Name) { if (Name == getName()) return; StringMap<StructType *> &SymbolTable = getContext().pImpl->NamedStructTypes; - typedef StringMap<StructType *>::MapEntryTy EntryTy; + + using EntryTy = StringMap<StructType *>::MapEntryTy; // If this struct already had a name, remove its symbol table entry. Don't // delete the data yet because it may be part of the new name. @@ -419,21 +432,6 @@ StructType *StructType::get(LLVMContext &Context, bool isPacked) { return get(Context, None, isPacked); } -StructType *StructType::get(Type *type, ...) { - assert(type && "Cannot create a struct type with no elements with this"); - LLVMContext &Ctx = type->getContext(); - va_list ap; - SmallVector<llvm::Type*, 8> StructFields; - va_start(ap, type); - while (type) { - StructFields.push_back(type); - type = va_arg(ap, llvm::Type*); - } - auto *Ret = llvm::StructType::get(Ctx, StructFields); - va_end(ap); - return Ret; -} - StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements, StringRef Name, bool isPacked) { StructType *ST = create(Context, Name); @@ -462,21 +460,6 @@ StructType *StructType::create(ArrayRef<Type*> Elements) { return create(Elements[0]->getContext(), Elements, StringRef()); } -StructType *StructType::create(StringRef Name, Type *type, ...) { - assert(type && "Cannot create a struct type with no elements with this"); - LLVMContext &Ctx = type->getContext(); - va_list ap; - SmallVector<llvm::Type*, 8> StructFields; - va_start(ap, type); - while (type) { - StructFields.push_back(type); - type = va_arg(ap, llvm::Type*); - } - auto *Ret = llvm::StructType::create(Ctx, StructFields, Name); - va_end(ap); - return Ret; -} - bool StructType::isSized(SmallPtrSetImpl<Type*> *Visited) const { if ((getSubclassData() & SCDB_IsSized) != 0) return true; @@ -508,19 +491,6 @@ StringRef StructType::getName() const { return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey(); } -void StructType::setBody(Type *type, ...) { - assert(type && "Cannot create a struct type with no elements with this"); - va_list ap; - SmallVector<llvm::Type*, 8> StructFields; - va_start(ap, type); - while (type) { - StructFields.push_back(type); - type = va_arg(ap, llvm::Type*); - } - setBody(StructFields); - va_end(ap); -} - bool StructType::isValidElementType(Type *ElemTy) { return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() && !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy() && @@ -540,7 +510,6 @@ StructType *Module::getTypeByName(StringRef Name) const { return getContext().pImpl->NamedStructTypes.lookup(Name); } - //===----------------------------------------------------------------------===// // CompositeType Implementation //===----------------------------------------------------------------------===// @@ -589,7 +558,6 @@ bool CompositeType::indexValid(unsigned Idx) const { return true; } - //===----------------------------------------------------------------------===// // ArrayType Implementation //===----------------------------------------------------------------------===// @@ -661,7 +629,6 @@ PointerType *PointerType::get(Type *EltTy, unsigned AddressSpace) { return Entry; } - PointerType::PointerType(Type *E, unsigned AddrSpace) : Type(E->getContext(), PointerTyID), PointeeTy(E) { ContainedTys = &PointeeTy; diff --git a/contrib/llvm/lib/IR/Verifier.cpp b/contrib/llvm/lib/IR/Verifier.cpp index 65e124562493..3b68d6365872 100644 --- a/contrib/llvm/lib/IR/Verifier.cpp +++ b/contrib/llvm/lib/IR/Verifier.cpp @@ -267,6 +267,9 @@ class Verifier : public InstVisitor<Verifier>, VerifierSupport { /// \brief Keep track of the metadata nodes that have been checked already. SmallPtrSet<const Metadata *, 32> MDNodes; + /// Keep track which DISubprogram is attached to which function. + DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments; + /// Track all DICompileUnits visited. SmallPtrSet<const Metadata *, 2> CUVisited; @@ -386,7 +389,7 @@ public: verifyCompileUnits(); verifyDeoptimizeCallingConvs(); - + DISubprogramAttachments.clear(); return !Broken; } @@ -2085,13 +2088,19 @@ void Verifier::visitFunction(const Function &F) { switch (I.first) { default: break; - case LLVMContext::MD_dbg: + case LLVMContext::MD_dbg: { ++NumDebugAttachments; AssertDI(NumDebugAttachments == 1, "function must have a single !dbg attachment", &F, I.second); AssertDI(isa<DISubprogram>(I.second), "function !dbg attachment must be a subprogram", &F, I.second); + auto *SP = cast<DISubprogram>(I.second); + const Function *&AttachedTo = DISubprogramAttachments[SP]; + AssertDI(!AttachedTo || AttachedTo == &F, + "DISubprogram attached to more than one function", SP, &F); + AttachedTo = &F; break; + } case LLVMContext::MD_prof: ++NumProfAttachments; Assert(NumProfAttachments == 1, diff --git a/contrib/llvm/lib/LTO/LTO.cpp b/contrib/llvm/lib/LTO/LTO.cpp index 2d2dcdec05fb..c73b6b6b15c1 100644 --- a/contrib/llvm/lib/LTO/LTO.cpp +++ b/contrib/llvm/lib/LTO/LTO.cpp @@ -973,7 +973,7 @@ Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache, // this value. If not, no need to preserve any ThinLTO copies. !Res.second.IRName.empty()) GUIDPreservedSymbols.insert(GlobalValue::getGUID( - GlobalValue::getRealLinkageName(Res.second.IRName))); + GlobalValue::dropLLVMManglingEscape(Res.second.IRName))); } auto DeadSymbols = @@ -993,7 +993,7 @@ Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache, if (Res.second.IRName.empty()) continue; auto GUID = GlobalValue::getGUID( - GlobalValue::getRealLinkageName(Res.second.IRName)); + GlobalValue::dropLLVMManglingEscape(Res.second.IRName)); // Mark exported unless index-based analysis determined it to be dead. if (!DeadSymbols.count(GUID)) ExportedGUIDs.insert(GUID); diff --git a/contrib/llvm/lib/LTO/LTOCodeGenerator.cpp b/contrib/llvm/lib/LTO/LTOCodeGenerator.cpp index 86fba843e980..6a275560dc92 100644 --- a/contrib/llvm/lib/LTO/LTOCodeGenerator.cpp +++ b/contrib/llvm/lib/LTO/LTOCodeGenerator.cpp @@ -495,17 +495,14 @@ void LTOCodeGenerator::verifyMergedModuleOnce() { return; HasVerifiedInput = true; - if (LTOStripInvalidDebugInfo) { - bool BrokenDebugInfo = false; - if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo)) - report_fatal_error("Broken module found, compilation aborted!"); - if (BrokenDebugInfo) { - emitWarning("Invalid debug info found, debug info will be stripped"); - StripDebugInfo(*MergedModule); - } - } - if (verifyModule(*MergedModule, &dbgs())) + bool BrokenDebugInfo = false; + if (verifyModule(*MergedModule, &dbgs(), + LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr)) report_fatal_error("Broken module found, compilation aborted!"); + if (BrokenDebugInfo) { + emitWarning("Invalid debug info found, debug info will be stripped"); + StripDebugInfo(*MergedModule); + } } void LTOCodeGenerator::finishOptimizationRemarks() { @@ -600,6 +597,7 @@ bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) { // If statistics were requested, print them out after codegen. if (llvm::AreStatisticsEnabled()) llvm::PrintStatistics(); + reportAndResetTimings(); finishOptimizationRemarks(); diff --git a/contrib/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/contrib/llvm/lib/LTO/ThinLTOCodeGenerator.cpp index b4ee7c2b2fbc..65a7994325bc 100644 --- a/contrib/llvm/lib/LTO/ThinLTOCodeGenerator.cpp +++ b/contrib/llvm/lib/LTO/ThinLTOCodeGenerator.cpp @@ -446,7 +446,7 @@ ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, { raw_svector_ostream OS(OutputBuffer); ProfileSummaryInfo PSI(TheModule); - auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr); + auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI); WriteBitcodeToFile(&TheModule, OS, true, &Index); } return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer)); @@ -1024,4 +1024,5 @@ void ThinLTOCodeGenerator::run() { // If statistics were requested, print them out now. if (llvm::AreStatisticsEnabled()) llvm::PrintStatistics(); + reportAndResetTimings(); } diff --git a/contrib/llvm/lib/Linker/IRMover.cpp b/contrib/llvm/lib/Linker/IRMover.cpp index 15a46a2d0420..ecef1efda1a2 100644 --- a/contrib/llvm/lib/Linker/IRMover.cpp +++ b/contrib/llvm/lib/Linker/IRMover.cpp @@ -602,6 +602,7 @@ GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), SGVar->getType()->getAddressSpace()); NewDGV->setAlignment(SGVar->getAlignment()); + NewDGV->copyAttributesFrom(SGVar); return NewDGV; } @@ -610,8 +611,11 @@ GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { Function *IRLinker::copyFunctionProto(const Function *SF) { // If there is no linkage to be performed or we are linking from the source, // bring SF over. - return Function::Create(TypeMap.get(SF->getFunctionType()), - GlobalValue::ExternalLinkage, SF->getName(), &DstM); + auto *F = + Function::Create(TypeMap.get(SF->getFunctionType()), + GlobalValue::ExternalLinkage, SF->getName(), &DstM); + F->copyAttributesFrom(SF); + return F; } /// Set up prototypes for any aliases that come over from the source module. @@ -619,9 +623,11 @@ GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) { // If there is no linkage to be performed or we're linking from the source, // bring over SGA. auto *Ty = TypeMap.get(SGA->getValueType()); - return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), - GlobalValue::ExternalLinkage, SGA->getName(), - &DstM); + auto *GA = + GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), + GlobalValue::ExternalLinkage, SGA->getName(), &DstM); + GA->copyAttributesFrom(SGA); + return GA; } GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, @@ -648,8 +654,6 @@ GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, else if (SGV->hasExternalWeakLinkage()) NewGV->setLinkage(GlobalValue::ExternalWeakLinkage); - NewGV->copyAttributesFrom(SGV); - if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { // Metadata for global variables and function declarations is copied eagerly. if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) diff --git a/contrib/llvm/lib/MC/MCObjectStreamer.cpp b/contrib/llvm/lib/MC/MCObjectStreamer.cpp index f7f2253256eb..174397e27396 100644 --- a/contrib/llvm/lib/MC/MCObjectStreamer.cpp +++ b/contrib/llvm/lib/MC/MCObjectStreamer.cpp @@ -133,6 +133,11 @@ void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, // Avoid fixups when possible. int64_t AbsValue; if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) { + if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) { + getContext().reportError( + Loc, "value evaluated as " + Twine(AbsValue) + " is out of range."); + return; + } EmitIntValue(AbsValue, Size); return; } diff --git a/contrib/llvm/lib/MC/MCParser/AsmParser.cpp b/contrib/llvm/lib/MC/MCParser/AsmParser.cpp index 66ba853da2fe..3b213ef4ce09 100644 --- a/contrib/llvm/lib/MC/MCParser/AsmParser.cpp +++ b/contrib/llvm/lib/MC/MCParser/AsmParser.cpp @@ -288,6 +288,7 @@ public: private: bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc); + void altMacroString(StringRef AltMacroStr, std::string &Res); bool parseStatement(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI); bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites); @@ -1209,6 +1210,8 @@ bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) { const char *CharPtr = StrLoc.getPointer(); while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') && (*CharPtr != '\0')){ + if(*CharPtr == '!') + CharPtr++; CharPtr++; } if (*CharPtr == '>') { @@ -1218,6 +1221,15 @@ bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) { return false; } +/// \brief creating a string without the escape characters '!'. +void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) { + for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) { + if (AltMacroStr[Pos] == '!') + Pos++; + Res += AltMacroStr[Pos]; + } +} + /// \brief Parse an expression and return it. /// /// expr ::= expr &&,|| expr -> lowest. @@ -2309,6 +2321,15 @@ bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer)) // Emit an integer value to the buffer. OS << Token.getIntVal(); + // Only Token that was validated as a string and begins with '<' + // is considered altMacroString!!! + else if ((Lexer.IsaAltMacroMode()) && + (*(Token.getString().begin()) == '<') && + Token.is(AsmToken::String)) { + std::string Res; + altMacroString(Token.getStringContents(), Res); + OS << Res; + } // We expect no quotes around the string's contents when // parsing for varargs. else if (Token.isNot(AsmToken::String) || VarargParameter) diff --git a/contrib/llvm/lib/Object/COFFObjectFile.cpp b/contrib/llvm/lib/Object/COFFObjectFile.cpp index b1223e81be43..28531feccfe1 100644 --- a/contrib/llvm/lib/Object/COFFObjectFile.cpp +++ b/contrib/llvm/lib/Object/COFFObjectFile.cpp @@ -1062,7 +1062,7 @@ COFFObjectFile::getSectionContents(const coff_section *Sec, // In COFF, a virtual section won't have any in-file // content, so the file pointer to the content will be zero. if (Sec->PointerToRawData == 0) - return object_error::parse_failed; + return std::error_code(); // The only thing that we need to verify is that the contents is contained // within the file bounds. We don't need to make sure it doesn't cover other // data, as there's nothing that says that is not allowed. @@ -1602,8 +1602,6 @@ ErrorOr<ArrayRef<UTF16>> ResourceSectionRef::getDirStringAtOffset(uint32_t Offse uint16_t Length; RETURN_IF_ERROR(Reader.readInteger(Length)); ArrayRef<UTF16> RawDirString; - // Strings are stored as 2-byte aligned unicode characters but readFixedString - // assumes byte string, so we double length. RETURN_IF_ERROR(Reader.readArray(RawDirString, Length)); return RawDirString; } diff --git a/contrib/llvm/lib/Object/WasmObjectFile.cpp b/contrib/llvm/lib/Object/WasmObjectFile.cpp index 39f8704aacf2..058686e4db9e 100644 --- a/contrib/llvm/lib/Object/WasmObjectFile.cpp +++ b/contrib/llvm/lib/Object/WasmObjectFile.cpp @@ -168,6 +168,13 @@ static wasm::WasmLimits readLimits(const uint8_t *&Ptr) { return Result; } +static wasm::WasmTable readTable(const uint8_t *&Ptr) { + wasm::WasmTable Table; + Table.ElemType = readVarint7(Ptr); + Table.Limits = readLimits(Ptr); + return Table; +} + static Error readSection(WasmSection &Section, const uint8_t *&Ptr, const uint8_t *Start) { // TODO(sbc): Avoid reading past EOF in the case of malformed files. @@ -397,13 +404,22 @@ Error WasmObjectFile::parseImportSection(const uint8_t *Ptr, const uint8_t *End) Sections.size(), i); break; case wasm::WASM_EXTERNAL_GLOBAL: - Im.GlobalType = readVarint7(Ptr); - Im.GlobalMutable = readVaruint1(Ptr); + Im.Global.Type = readVarint7(Ptr); + Im.Global.Mutable = readVaruint1(Ptr); Symbols.emplace_back(Im.Field, WasmSymbol::SymbolType::GLOBAL_IMPORT, Sections.size(), i); break; + case wasm::WASM_EXTERNAL_MEMORY: + Im.Memory = readLimits(Ptr); + break; + case wasm::WASM_EXTERNAL_TABLE: + Im.Table = readTable(Ptr); + if (Im.Table.ElemType != wasm::WASM_TYPE_ANYFUNC) { + return make_error<GenericBinaryError>("Invalid table element type", + object_error::parse_failed); + } + break; default: - // TODO(sbc): Handle other kinds of imports return make_error<GenericBinaryError>( "Unexpected import kind", object_error::parse_failed); } @@ -431,14 +447,11 @@ Error WasmObjectFile::parseTableSection(const uint8_t *Ptr, const uint8_t *End) uint32_t Count = readVaruint32(Ptr); Tables.reserve(Count); while (Count--) { - wasm::WasmTable Table; - Table.ElemType = readVarint7(Ptr); - if (Table.ElemType != wasm::WASM_TYPE_ANYFUNC) { + Tables.push_back(readTable(Ptr)); + if (Tables.back().ElemType != wasm::WASM_TYPE_ANYFUNC) { return make_error<GenericBinaryError>("Invalid table element type", object_error::parse_failed); } - Table.Limits = readLimits(Ptr); - Tables.push_back(Table); } if (Ptr != End) return make_error<GenericBinaryError>("Table section ended prematurely", @@ -493,8 +506,10 @@ Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) Symbols.emplace_back(Ex.Name, WasmSymbol::SymbolType::GLOBAL_EXPORT, Sections.size(), i); break; + case wasm::WASM_EXTERNAL_MEMORY: + case wasm::WASM_EXTERNAL_TABLE: + break; default: - // TODO(sbc): Handle other kinds of exports return make_error<GenericBinaryError>( "Unexpected export kind", object_error::parse_failed); } @@ -507,7 +522,7 @@ Error WasmObjectFile::parseExportSection(const uint8_t *Ptr, const uint8_t *End) Error WasmObjectFile::parseStartSection(const uint8_t *Ptr, const uint8_t *End) { StartFunction = readVaruint32(Ptr); - if (StartFunction < FunctionTypes.size()) + if (StartFunction >= FunctionTypes.size()) return make_error<GenericBinaryError>("Invalid start function", object_error::parse_failed); return Error::success(); @@ -638,10 +653,14 @@ basic_symbol_iterator WasmObjectFile::symbol_end() const { return BasicSymbolRef(Ref, this); } -const WasmSymbol &WasmObjectFile::getWasmSymbol(DataRefImpl Symb) const { +const WasmSymbol &WasmObjectFile::getWasmSymbol(const DataRefImpl &Symb) const { return Symbols[Symb.d.a]; } +const WasmSymbol &WasmObjectFile::getWasmSymbol(const SymbolRef &Symb) const { + return getWasmSymbol(Symb.getRawDataRefImpl()); +} + Expected<StringRef> WasmObjectFile::getSymbolName(DataRefImpl Symb) const { const WasmSymbol &Sym = getWasmSymbol(Symb); return Sym.Name; diff --git a/contrib/llvm/lib/ObjectYAML/WasmYAML.cpp b/contrib/llvm/lib/ObjectYAML/WasmYAML.cpp index c5d1b438ee2a..910d32f16af9 100644 --- a/contrib/llvm/lib/ObjectYAML/WasmYAML.cpp +++ b/contrib/llvm/lib/ObjectYAML/WasmYAML.cpp @@ -265,8 +265,12 @@ void MappingTraits<WasmYAML::Import>::mapping(IO &IO, if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { IO.mapRequired("SigIndex", Import.SigIndex); } else if (Import.Kind == wasm::WASM_EXTERNAL_GLOBAL) { - IO.mapRequired("GlobalType", Import.GlobalType); - IO.mapRequired("GlobalMutable", Import.GlobalMutable); + IO.mapRequired("GlobalType", Import.GlobalImport.Type); + IO.mapRequired("GlobalMutable", Import.GlobalImport.Mutable); + } else if (Import.Kind == wasm::WASM_EXTERNAL_TABLE) { + IO.mapRequired("Table", Import.TableImport); + } else if (Import.Kind == wasm::WASM_EXTERNAL_MEMORY ) { + IO.mapRequired("Memory", Import.Memory); } else { llvm_unreachable("unhandled import type"); } diff --git a/contrib/llvm/lib/ProfileData/SampleProfWriter.cpp b/contrib/llvm/lib/ProfileData/SampleProfWriter.cpp index b91b6fb7c7ad..b05efa7417b9 100644 --- a/contrib/llvm/lib/ProfileData/SampleProfWriter.cpp +++ b/contrib/llvm/lib/ProfileData/SampleProfWriter.cpp @@ -29,6 +29,7 @@ #include <algorithm> #include <cstdint> #include <memory> +#include <set> #include <system_error> #include <utility> #include <vector> @@ -36,6 +37,32 @@ using namespace llvm; using namespace sampleprof; +std::error_code +SampleProfileWriter::write(const StringMap<FunctionSamples> &ProfileMap) { + if (std::error_code EC = writeHeader(ProfileMap)) + return EC; + + // Sort the ProfileMap by total samples. + typedef std::pair<StringRef, const FunctionSamples *> NameFunctionSamples; + std::vector<NameFunctionSamples> V; + for (const auto &I : ProfileMap) + V.push_back(std::make_pair(I.getKey(), &I.second)); + + std::stable_sort( + V.begin(), V.end(), + [](const NameFunctionSamples &A, const NameFunctionSamples &B) { + if (A.second->getTotalSamples() == B.second->getTotalSamples()) + return A.first > B.first; + return A.second->getTotalSamples() > B.second->getTotalSamples(); + }); + + for (const auto &I : V) { + if (std::error_code EC = write(*I.second)) + return EC; + } + return sampleprof_error::success; +} + /// \brief Write samples to a text file. /// /// Note: it may be tempting to implement this in terms of @@ -97,8 +124,7 @@ std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) { } void SampleProfileWriterBinary::addName(StringRef FName) { - auto NextIdx = NameTable.size(); - NameTable.insert(std::make_pair(FName, NextIdx)); + NameTable.insert(std::make_pair(FName, 0)); } void SampleProfileWriterBinary::addNames(const FunctionSamples &S) { @@ -136,10 +162,18 @@ std::error_code SampleProfileWriterBinary::writeHeader( addNames(I.second); } + // Sort the names to make NameTable is deterministic. + std::set<StringRef> V; + for (const auto &I : NameTable) + V.insert(I.first); + int i = 0; + for (const StringRef &N : V) + NameTable[N] = i++; + // Write out the name table. encodeULEB128(NameTable.size(), OS); - for (auto N : NameTable) { - OS << N.first; + for (auto N : V) { + OS << N; encodeULEB128(0, OS); } return sampleprof_error::success; diff --git a/contrib/llvm/lib/Support/APInt.cpp b/contrib/llvm/lib/Support/APInt.cpp index caa0691f9205..17144522db82 100644 --- a/contrib/llvm/lib/Support/APInt.cpp +++ b/contrib/llvm/lib/Support/APInt.cpp @@ -122,35 +122,38 @@ APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix) fromString(numbits, Str, radix); } +void APInt::reallocate(unsigned NewBitWidth) { + // If the number of words is the same we can just change the width and stop. + if (getNumWords() == getNumWords(NewBitWidth)) { + BitWidth = NewBitWidth; + return; + } + + // If we have an allocation, delete it. + if (!isSingleWord()) + delete [] U.pVal; + + // Update BitWidth. + BitWidth = NewBitWidth; + + // If we are supposed to have an allocation, create it. + if (!isSingleWord()) + U.pVal = getMemory(getNumWords()); +} + void APInt::AssignSlowCase(const APInt& RHS) { // Don't do anything for X = X if (this == &RHS) return; - if (BitWidth == RHS.getBitWidth()) { - // assume same bit-width single-word case is already handled - assert(!isSingleWord()); - memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE); - return; - } + // Adjust the bit width and handle allocations as necessary. + reallocate(RHS.getBitWidth()); - if (isSingleWord()) { - // assume case where both are single words is already handled - assert(!RHS.isSingleWord()); - U.pVal = getMemory(RHS.getNumWords()); - memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE); - } else if (getNumWords() == RHS.getNumWords()) - memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE); - else if (RHS.isSingleWord()) { - delete [] U.pVal; + // Copy the data. + if (isSingleWord()) U.VAL = RHS.U.VAL; - } else { - delete [] U.pVal; - U.pVal = getMemory(RHS.getNumWords()); - memcpy(U.pVal, RHS.U.pVal, RHS.getNumWords() * APINT_WORD_SIZE); - } - BitWidth = RHS.BitWidth; - clearUnusedBits(); + else + memcpy(U.pVal, RHS.U.pVal, getNumWords() * APINT_WORD_SIZE); } /// This method 'profiles' an APInt for use with FoldingSet. @@ -1138,10 +1141,13 @@ APInt APInt::multiplicativeInverse(const APInt& modulo) const { return APInt(BitWidth, 0); // The next-to-last t is the multiplicative inverse. However, we are - // interested in a positive inverse. Calcuate a positive one from a negative + // interested in a positive inverse. Calculate a positive one from a negative // one if necessary. A simple addition of the modulo suffices because // abs(t[i]) is known to be less than *this/2 (see the link above). - return t[i].isNegative() ? t[i] + modulo : t[i]; + if (t[i].isNegative()) + t[i] += modulo; + + return std::move(t[i]); } /// Calculate the magic numbers required to implement a signed integer division @@ -1240,7 +1246,7 @@ APInt::mu APInt::magicu(unsigned LeadingZeros) const { /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The /// variables here have the same names as in the algorithm. Comments explain /// the algorithm and any deviation from it. -static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, +static void KnuthDiv(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t* r, unsigned m, unsigned n) { assert(u && "Must provide dividend"); assert(v && "Must provide divisor"); @@ -1266,16 +1272,16 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, // overflow. Note that this can require an extra word in u so that u must // be of length m+n+1. unsigned shift = countLeadingZeros(v[n-1]); - unsigned v_carry = 0; - unsigned u_carry = 0; + uint32_t v_carry = 0; + uint32_t u_carry = 0; if (shift) { for (unsigned i = 0; i < m+n; ++i) { - unsigned u_tmp = u[i] >> (32 - shift); + uint32_t u_tmp = u[i] >> (32 - shift); u[i] = (u[i] << shift) | u_carry; u_carry = u_tmp; } for (unsigned i = 0; i < n; ++i) { - unsigned v_tmp = v[i] >> (32 - shift); + uint32_t v_tmp = v[i] >> (32 - shift); v[i] = (v[i] << shift) | v_carry; v_carry = v_tmp; } @@ -1296,11 +1302,11 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease - // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test + // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test // on v[n-2] determines at high speed most of the cases in which the trial // value qp is one too large, and it eliminates all cases where qp is two // too large. - uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]); + uint64_t dividend = Make_64(u[j+n], u[j+n-1]); DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n'); uint64_t qp = dividend / v[n-1]; uint64_t rp = dividend % v[n-1]; @@ -1323,14 +1329,14 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, int64_t borrow = 0; for (unsigned i = 0; i < n; ++i) { uint64_t p = uint64_t(qp) * uint64_t(v[i]); - int64_t subres = int64_t(u[j+i]) - borrow - (unsigned)p; - u[j+i] = (unsigned)subres; - borrow = (p >> 32) - (subres >> 32); + int64_t subres = int64_t(u[j+i]) - borrow - Lo_32(p); + u[j+i] = Lo_32(subres); + borrow = Hi_32(p) - Hi_32(subres); DEBUG(dbgs() << "KnuthDiv: u[j+i] = " << u[j+i] << ", borrow = " << borrow << '\n'); } bool isNeg = u[j+n] < borrow; - u[j+n] -= (unsigned)borrow; + u[j+n] -= Lo_32(borrow); DEBUG(dbgs() << "KnuthDiv: after subtraction:"); DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]); @@ -1338,7 +1344,7 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was // negative, go to step D6; otherwise go on to step D7. - q[j] = (unsigned)qp; + q[j] = Lo_32(qp); if (isNeg) { // D6. [Add back]. The probability that this step is necessary is very // small, on the order of only 2/b. Make sure that test data accounts for @@ -1349,7 +1355,7 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, // since it cancels with the borrow that occurred in D4. bool carry = false; for (unsigned i = 0; i < n; i++) { - unsigned limit = std::min(u[j+i],v[i]); + uint32_t limit = std::min(u[j+i],v[i]); u[j+i] += v[i] + carry; carry = u[j+i] < limit || (carry && u[j+i] == limit); } @@ -1374,7 +1380,7 @@ static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, // multiplication by d by using a shift left. So, all we have to do is // shift right here. if (shift) { - unsigned carry = 0; + uint32_t carry = 0; DEBUG(dbgs() << "KnuthDiv: remainder:"); for (int i = n-1; i >= 0; i--) { r[i] = (u[i] >> shift) | carry; @@ -1403,17 +1409,16 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, // can't use 64-bit operands here because we don't have native results of // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't // work on large-endian machines. - uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT); unsigned n = rhsWords * 2; unsigned m = (lhsWords * 2) - n; // Allocate space for the temporary values we need either on the stack, if // it will fit, or on the heap if it won't. - unsigned SPACE[128]; - unsigned *U = nullptr; - unsigned *V = nullptr; - unsigned *Q = nullptr; - unsigned *R = nullptr; + uint32_t SPACE[128]; + uint32_t *U = nullptr; + uint32_t *V = nullptr; + uint32_t *Q = nullptr; + uint32_t *R = nullptr; if ((Remainder?4:3)*n+2*m+1 <= 128) { U = &SPACE[0]; V = &SPACE[m+n+1]; @@ -1421,34 +1426,34 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, if (Remainder) R = &SPACE[(m+n+1) + n + (m+n)]; } else { - U = new unsigned[m + n + 1]; - V = new unsigned[n]; - Q = new unsigned[m+n]; + U = new uint32_t[m + n + 1]; + V = new uint32_t[n]; + Q = new uint32_t[m+n]; if (Remainder) - R = new unsigned[n]; + R = new uint32_t[n]; } // Initialize the dividend - memset(U, 0, (m+n+1)*sizeof(unsigned)); + memset(U, 0, (m+n+1)*sizeof(uint32_t)); for (unsigned i = 0; i < lhsWords; ++i) { - uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.U.VAL : LHS.U.pVal[i]); - U[i * 2] = (unsigned)(tmp & mask); - U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT)); + uint64_t tmp = LHS.getRawData()[i]; + U[i * 2] = Lo_32(tmp); + U[i * 2 + 1] = Hi_32(tmp); } U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm. // Initialize the divisor - memset(V, 0, (n)*sizeof(unsigned)); + memset(V, 0, (n)*sizeof(uint32_t)); for (unsigned i = 0; i < rhsWords; ++i) { - uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.U.VAL : RHS.U.pVal[i]); - V[i * 2] = (unsigned)(tmp & mask); - V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT)); + uint64_t tmp = RHS.getRawData()[i]; + V[i * 2] = Lo_32(tmp); + V[i * 2 + 1] = Hi_32(tmp); } // initialize the quotient and remainder - memset(Q, 0, (m+n) * sizeof(unsigned)); + memset(Q, 0, (m+n) * sizeof(uint32_t)); if (Remainder) - memset(R, 0, n * sizeof(unsigned)); + memset(R, 0, n * sizeof(uint32_t)); // Now, adjust m and n for the Knuth division. n is the number of words in // the divisor. m is the number of words by which the dividend exceeds the @@ -1469,22 +1474,22 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, // are using base 2^32 instead of base 10. assert(n != 0 && "Divide by zero?"); if (n == 1) { - unsigned divisor = V[0]; - unsigned remainder = 0; - for (int i = m+n-1; i >= 0; i--) { - uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i]; + uint32_t divisor = V[0]; + uint32_t remainder = 0; + for (int i = m; i >= 0; i--) { + uint64_t partial_dividend = Make_64(remainder, U[i]); if (partial_dividend == 0) { Q[i] = 0; remainder = 0; } else if (partial_dividend < divisor) { Q[i] = 0; - remainder = (unsigned)partial_dividend; + remainder = Lo_32(partial_dividend); } else if (partial_dividend == divisor) { Q[i] = 1; remainder = 0; } else { - Q[i] = (unsigned)(partial_dividend / divisor); - remainder = (unsigned)(partial_dividend - (Q[i] * divisor)); + Q[i] = Lo_32(partial_dividend / divisor); + remainder = Lo_32(partial_dividend - (Q[i] * divisor)); } } if (R) @@ -1498,24 +1503,16 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, // If the caller wants the quotient if (Quotient) { // Set up the Quotient value's memory. - if (Quotient->BitWidth != LHS.BitWidth) { - if (Quotient->isSingleWord()) - Quotient->U.VAL = 0; - else - delete [] Quotient->U.pVal; - Quotient->BitWidth = LHS.BitWidth; - if (!Quotient->isSingleWord()) - Quotient->U.pVal = getClearedMemory(Quotient->getNumWords()); - } else - Quotient->clearAllBits(); + Quotient->reallocate(LHS.BitWidth); + // Clear out any previous bits. + Quotient->clearAllBits(); // The quotient is in Q. Reconstitute the quotient into Quotient's low // order words. // This case is currently dead as all users of divide() handle trivial cases // earlier. if (lhsWords == 1) { - uint64_t tmp = - uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2)); + uint64_t tmp = Make_64(Q[1], Q[0]); if (Quotient->isSingleWord()) Quotient->U.VAL = tmp; else @@ -1523,30 +1520,21 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, } else { assert(!Quotient->isSingleWord() && "Quotient APInt not large enough"); for (unsigned i = 0; i < lhsWords; ++i) - Quotient->U.pVal[i] = - uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2)); + Quotient->U.pVal[i] = Make_64(Q[i*2+1], Q[i*2]); } } // If the caller wants the remainder if (Remainder) { // Set up the Remainder value's memory. - if (Remainder->BitWidth != RHS.BitWidth) { - if (Remainder->isSingleWord()) - Remainder->U.VAL = 0; - else - delete [] Remainder->U.pVal; - Remainder->BitWidth = RHS.BitWidth; - if (!Remainder->isSingleWord()) - Remainder->U.pVal = getClearedMemory(Remainder->getNumWords()); - } else - Remainder->clearAllBits(); + Remainder->reallocate(RHS.BitWidth); + // Clear out any previous bits. + Remainder->clearAllBits(); // The remainder is in R. Reconstitute the remainder into Remainder's low // order words. if (rhsWords == 1) { - uint64_t tmp = - uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2)); + uint64_t tmp = Make_64(R[1], R[0]); if (Remainder->isSingleWord()) Remainder->U.VAL = tmp; else @@ -1554,8 +1542,7 @@ void APInt::divide(const APInt &LHS, unsigned lhsWords, const APInt &RHS, } else { assert(!Remainder->isSingleWord() && "Remainder APInt not large enough"); for (unsigned i = 0; i < rhsWords; ++i) - Remainder->U.pVal[i] = - uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2)); + Remainder->U.pVal[i] = Make_64(R[i*2+1], R[i*2]); } } @@ -1578,29 +1565,30 @@ APInt APInt::udiv(const APInt& RHS) const { } // Get some facts about the LHS and RHS number of bits and words - unsigned rhsBits = RHS.getActiveBits(); - unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); + unsigned lhsWords = getNumWords(getActiveBits()); + unsigned rhsBits = RHS.getActiveBits(); + unsigned rhsWords = getNumWords(rhsBits); assert(rhsWords && "Divided by zero???"); - unsigned lhsBits = this->getActiveBits(); - unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1); // Deal with some degenerate cases if (!lhsWords) // 0 / X ===> 0 return APInt(BitWidth, 0); - else if (lhsWords < rhsWords || this->ult(RHS)) { + if (rhsBits == 1) + // X / 1 ===> X + return *this; + if (lhsWords < rhsWords || this->ult(RHS)) // X / Y ===> 0, iff X < Y return APInt(BitWidth, 0); - } else if (*this == RHS) { + if (*this == RHS) // X / X ===> 1 return APInt(BitWidth, 1); - } else if (lhsWords == 1 && rhsWords == 1) { + if (lhsWords == 1) // rhsWords is 1 if lhsWords is 1. // All high words are zero, just use native divide return APInt(BitWidth, this->U.pVal[0] / RHS.U.pVal[0]); - } // We have to compute it the hard way. Invoke the Knuth divide algorithm. - APInt Quotient(1,0); // to hold result. + APInt Quotient; // to hold result. divide(*this, lhsWords, RHS, rhsWords, &Quotient, nullptr); return Quotient; } @@ -1624,31 +1612,32 @@ APInt APInt::urem(const APInt& RHS) const { } // Get some facts about the LHS - unsigned lhsBits = getActiveBits(); - unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1); + unsigned lhsWords = getNumWords(getActiveBits()); // Get some facts about the RHS unsigned rhsBits = RHS.getActiveBits(); - unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); + unsigned rhsWords = getNumWords(rhsBits); assert(rhsWords && "Performing remainder operation by zero ???"); // Check the degenerate cases - if (lhsWords == 0) { + if (lhsWords == 0) // 0 % Y ===> 0 return APInt(BitWidth, 0); - } else if (lhsWords < rhsWords || this->ult(RHS)) { + if (rhsBits == 1) + // X % 1 ===> 0 + return APInt(BitWidth, 0); + if (lhsWords < rhsWords || this->ult(RHS)) // X % Y ===> X, iff X < Y return *this; - } else if (*this == RHS) { + if (*this == RHS) // X % X == 0; return APInt(BitWidth, 0); - } else if (lhsWords == 1) { + if (lhsWords == 1) // All high words are zero, just use native remainder return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]); - } // We have to compute it the hard way. Invoke the Knuth divide algorithm. - APInt Remainder(1,0); + APInt Remainder; divide(*this, lhsWords, RHS, rhsWords, nullptr, &Remainder); return Remainder; } @@ -1667,22 +1656,23 @@ APInt APInt::srem(const APInt &RHS) const { void APInt::udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder) { assert(LHS.BitWidth == RHS.BitWidth && "Bit widths must be the same"); + unsigned BitWidth = LHS.BitWidth; // First, deal with the easy case if (LHS.isSingleWord()) { assert(RHS.U.VAL != 0 && "Divide by zero?"); uint64_t QuotVal = LHS.U.VAL / RHS.U.VAL; uint64_t RemVal = LHS.U.VAL % RHS.U.VAL; - Quotient = APInt(LHS.BitWidth, QuotVal); - Remainder = APInt(LHS.BitWidth, RemVal); + Quotient = APInt(BitWidth, QuotVal); + Remainder = APInt(BitWidth, RemVal); return; } // Get some size facts about the dividend and divisor - unsigned lhsBits = LHS.getActiveBits(); - unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1); + unsigned lhsWords = getNumWords(LHS.getActiveBits()); unsigned rhsBits = RHS.getActiveBits(); - unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); + unsigned rhsWords = getNumWords(rhsBits); + assert(rhsWords && "Performing divrem operation by zero ???"); // Check the degenerate cases if (lhsWords == 0) { @@ -1691,6 +1681,11 @@ void APInt::udivrem(const APInt &LHS, const APInt &RHS, return; } + if (rhsBits == 1) { + Quotient = LHS; // X / 1 ===> X + Remainder = 0; // X % 1 ===> 0 + } + if (lhsWords < rhsWords || LHS.ult(RHS)) { Remainder = LHS; // X % Y ===> X, iff X < Y Quotient = 0; // X / Y ===> 0, iff X < Y @@ -1703,12 +1698,15 @@ void APInt::udivrem(const APInt &LHS, const APInt &RHS, return; } - if (lhsWords == 1 && rhsWords == 1) { + if (lhsWords == 1) { // rhsWords is 1 if lhsWords is 1. // There is only one word to consider so use the native versions. - uint64_t lhsValue = LHS.isSingleWord() ? LHS.U.VAL : LHS.U.pVal[0]; - uint64_t rhsValue = RHS.isSingleWord() ? RHS.U.VAL : RHS.U.pVal[0]; - Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue); - Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue); + uint64_t lhsValue = LHS.U.pVal[0]; + uint64_t rhsValue = RHS.U.pVal[0]; + // Make sure there is enough space to hold the results. + Quotient.reallocate(BitWidth); + Remainder.reallocate(BitWidth); + Quotient = lhsValue / rhsValue; + Remainder = lhsValue % rhsValue; return; } @@ -1723,12 +1721,12 @@ void APInt::sdivrem(const APInt &LHS, const APInt &RHS, APInt::udivrem(-LHS, -RHS, Quotient, Remainder); else { APInt::udivrem(-LHS, RHS, Quotient, Remainder); - Quotient = -Quotient; + Quotient.negate(); } - Remainder = -Remainder; + Remainder.negate(); } else if (RHS.isNegative()) { APInt::udivrem(LHS, -RHS, Quotient, Remainder); - Quotient = -Quotient; + Quotient.negate(); } else { APInt::udivrem(LHS, RHS, Quotient, Remainder); } @@ -1859,10 +1857,8 @@ void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) { *this += digit; } // If its negative, put it in two's complement form - if (isNeg) { - --(*this); - this->flipAllBits(); - } + if (isNeg) + this->negate(); } void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, @@ -1940,8 +1936,7 @@ void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, // They want to print the signed version and it is a negative value // Flip the bits and add one to turn it into the equivalent positive // value and put a '-' in the result. - Tmp.flipAllBits(); - ++Tmp; + Tmp.negate(); Str.push_back('-'); } @@ -1961,22 +1956,19 @@ void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1)); unsigned MaskAmt = Radix - 1; - while (Tmp != 0) { + while (Tmp.getBoolValue()) { unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt; Str.push_back(Digits[Digit]); Tmp.lshrInPlace(ShiftAmt); } } else { - APInt divisor(Radix == 10? 4 : 8, Radix); - while (Tmp != 0) { - APInt APdigit(1, 0); - APInt tmp2(Tmp.getBitWidth(), 0); - divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, - &APdigit); + APInt divisor(Tmp.getBitWidth(), Radix); + APInt APdigit; + while (Tmp.getBoolValue()) { + udivrem(Tmp, divisor, Tmp, APdigit); unsigned Digit = (unsigned)APdigit.getZExtValue(); assert(Digit < Radix && "divide failed"); Str.push_back(Digits[Digit]); - Tmp = tmp2; } } @@ -2346,13 +2338,11 @@ int APInt::tcMultiply(WordType *dst, const WordType *lhs, return overflow; } -/* DST = LHS * RHS, where DST has width the sum of the widths of the - operands. No overflow occurs. DST must be disjoint from both - operands. Returns the number of parts required to hold the - result. */ -unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs, - const WordType *rhs, unsigned lhsParts, - unsigned rhsParts) { +/// DST = LHS * RHS, where DST has width the sum of the widths of the +/// operands. No overflow occurs. DST must be disjoint from both operands. +void APInt::tcFullMultiply(WordType *dst, const WordType *lhs, + const WordType *rhs, unsigned lhsParts, + unsigned rhsParts) { /* Put the narrower number on the LHS for less loops below. */ if (lhsParts > rhsParts) return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts); @@ -2363,10 +2353,6 @@ unsigned APInt::tcFullMultiply(WordType *dst, const WordType *lhs, for (unsigned i = 0; i < lhsParts; i++) tcMultiplyPart(&dst[i], rhs, lhs[i], 0, rhsParts, rhsParts + 1, true); - - unsigned n = lhsParts + rhsParts; - - return n - (dst[n - 1] == 0); } /* If RHS is zero LHS and REMAINDER are left unchanged, return one. @@ -2400,22 +2386,20 @@ int APInt::tcDivide(WordType *lhs, const WordType *rhs, /* Loop, subtracting SRHS if REMAINDER is greater and adding that to the total. */ for (;;) { - int compare; - - compare = tcCompare(remainder, srhs, parts); - if (compare >= 0) { - tcSubtract(remainder, srhs, 0, parts); - lhs[n] |= mask; - } + int compare = tcCompare(remainder, srhs, parts); + if (compare >= 0) { + tcSubtract(remainder, srhs, 0, parts); + lhs[n] |= mask; + } - if (shiftCount == 0) - break; - shiftCount--; - tcShiftRight(srhs, parts, 1); - if ((mask >>= 1) == 0) { - mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1); - n--; - } + if (shiftCount == 0) + break; + shiftCount--; + tcShiftRight(srhs, parts, 1); + if ((mask >>= 1) == 0) { + mask = (WordType) 1 << (APINT_BITS_PER_WORD - 1); + n--; + } } return false; diff --git a/contrib/llvm/tools/lld/lib/Core/TaskGroup.cpp b/contrib/llvm/lib/Support/Parallel.cpp index d4de48ce3dc4..ab2cfdebf07d 100644 --- a/contrib/llvm/tools/lld/lib/Core/TaskGroup.cpp +++ b/contrib/llvm/lib/Support/Parallel.cpp @@ -1,25 +1,20 @@ -//===- lld/Core/TaskGroup.cpp - Task Group --------------------------------===// +//===- llvm/Support/Parallel.cpp - Parallel algorithms --------------------===// // -// The LLVM Linker +// The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// -#include "lld/Core/TaskGroup.h" +#include "llvm/Support/Parallel.h" #include "llvm/Config/llvm-config.h" #include <atomic> #include <stack> #include <thread> -#if defined(_MSC_VER) && LLVM_ENABLE_THREADS -#include <concrt.h> -#include <ppl.h> -#endif - -using namespace lld; +using namespace llvm; namespace { @@ -122,7 +117,7 @@ private: std::stack<std::function<void()>> WorkStack; std::mutex Mutex; std::condition_variable Cond; - Latch Done; + parallel::detail::Latch Done; }; Executor *Executor::getDefaultExecutor() { @@ -132,10 +127,12 @@ Executor *Executor::getDefaultExecutor() { #endif } -void TaskGroup::spawn(std::function<void()> f) { - _latch.inc(); - Executor::getDefaultExecutor()->add([&, f] { - f(); - _latch.dec(); +#if LLVM_ENABLE_THREADS +void parallel::detail::TaskGroup::spawn(std::function<void()> F) { + L.inc(); + Executor::getDefaultExecutor()->add([&, F] { + F(); + L.dec(); }); } +#endif diff --git a/contrib/llvm/lib/Support/Unix/Path.inc b/contrib/llvm/lib/Support/Unix/Path.inc index fa28ba1b6ab6..cdea09be41e0 100644 --- a/contrib/llvm/lib/Support/Unix/Path.inc +++ b/contrib/llvm/lib/Support/Unix/Path.inc @@ -103,13 +103,16 @@ #define STATVFS_F_FLAG(vfs) (vfs).f_flags #endif +#if defined(__FreeBSD__) || defined(__NetBSD__) +#include <sys/sysctl.h> +#endif + using namespace llvm; namespace llvm { namespace sys { namespace fs { -#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \ - defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \ +#if defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \ defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \ defined(_AIX) static int @@ -164,7 +167,7 @@ getprogpath(char ret[PATH_MAX], const char *bin) free(pv); return nullptr; } -#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__ +#endif // Bitrig || OpenBSD || minix || linux || CYGWIN || DragonFly || AIX /// GetMainExecutable - Return the path to the main executable, given the /// value of argv[0] from program startup. @@ -180,9 +183,24 @@ std::string getMainExecutable(const char *argv0, void *MainAddr) { if (realpath(exe_path, link_path)) return link_path; } -#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \ - defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \ - defined(__FreeBSD_kernel__) || defined(_AIX) +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) + int mib[4]; + mib[0] = CTL_KERN; +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PATHNAME; + mib[3] = -1; +#else + mib[1] = KERN_PROC_ARGS; + mib[2] = -1; + mib[3] = KERN_PROC_PATHNAME; +#endif + char exe_path[PATH_MAX]; + size_t cb = sizeof(exe_path); + if (sysctl(mib, 4, exe_path, &cb, NULL, 0) == 0) + return exe_path; +#elif defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \ + defined(__DragonFly__) || defined(_AIX) char exe_path[PATH_MAX]; if (getprogpath(exe_path, argv0) != NULL) diff --git a/contrib/llvm/lib/Support/Unix/Process.inc b/contrib/llvm/lib/Support/Unix/Process.inc index 16f8f5a98e52..1d0143c6716e 100644 --- a/contrib/llvm/lib/Support/Unix/Process.inc +++ b/contrib/llvm/lib/Support/Unix/Process.inc @@ -347,7 +347,7 @@ static bool terminalHasColors(int fd) { MutexGuard G(*TermColorMutex); int errret = 0; - if (setupterm((char *)nullptr, fd, &errret) != 0) + if (setupterm(nullptr, fd, &errret) != 0) // Regardless of why, if we can't get terminfo, we shouldn't try to print // colors. return false; @@ -369,7 +369,7 @@ static bool terminalHasColors(int fd) { // Now extract the structure allocated by setupterm and free its memory // through a really silly dance. - struct term *termp = set_curterm((struct term *)nullptr); + struct term *termp = set_curterm(nullptr); (void)del_curterm(termp); // Drop any errors here. // Return true if we found a color capabilities for the current terminal. diff --git a/contrib/llvm/lib/Target/AArch64/AArch64.td b/contrib/llvm/lib/Target/AArch64/AArch64.td index 73f2b6a25f66..4af5fef4287c 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64.td +++ b/contrib/llvm/lib/Target/AArch64/AArch64.td @@ -216,6 +216,7 @@ def ProcA72 : SubtargetFeature<"a72", "ARMProcFamily", "CortexA72", FeatureCRC, FeatureCrypto, FeatureFPARMv8, + FeatureFuseAES, FeatureNEON, FeaturePerfMon ]>; diff --git a/contrib/llvm/lib/Target/AArch64/AArch64CallLowering.cpp b/contrib/llvm/lib/Target/AArch64/AArch64CallLowering.cpp index ff3e4c40e2c2..29f6d571d6bd 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64CallLowering.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64CallLowering.cpp @@ -380,7 +380,7 @@ bool AArch64CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, MIRBuilder.buildSequence(OrigRet.Reg, SplitRegs, RegOffsets); } - CallSeqStart.addImm(Handler.StackSize); + CallSeqStart.addImm(Handler.StackSize).addImm(0); MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP) .addImm(Handler.StackSize) .addImm(0); diff --git a/contrib/llvm/lib/Target/AArch64/AArch64FastISel.cpp b/contrib/llvm/lib/Target/AArch64/AArch64FastISel.cpp index 083708001757..9ac7ecb9cdb4 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64FastISel.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64FastISel.cpp @@ -3014,7 +3014,7 @@ bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI, // Issue CALLSEQ_START unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) - .addImm(NumBytes); + .addImm(NumBytes).addImm(0); // Process the args. for (CCValAssign &VA : ArgLocs) { diff --git a/contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp b/contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp index 4b1bb27dce73..4f7c2e122390 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp @@ -2265,7 +2265,7 @@ SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); - StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); + StructType *RetTy = StructType::get(ArgTy, ArgTy); TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(dl) .setChain(DAG.getEntryNode()) @@ -3249,9 +3249,7 @@ AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass if (!IsSibCall) - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, - true), - DL); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy(DAG.getDataLayout())); diff --git a/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp index cb268828455e..c42738da7ab0 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp @@ -3427,6 +3427,10 @@ static bool getFMAPatterns(MachineInstr &Root, Patterns.push_back(MachineCombinerPattern::FMLSv1i32_indexed_OP2); Found = true; } + if (canCombineWithFMUL(MBB, Root.getOperand(1), AArch64::FNMULSrr)) { + Patterns.push_back(MachineCombinerPattern::FNMULSUBS_OP1); + Found = true; + } break; case AArch64::FSUBDrr: if (canCombineWithFMUL(MBB, Root.getOperand(1), AArch64::FMULDrr)) { @@ -3441,6 +3445,10 @@ static bool getFMAPatterns(MachineInstr &Root, Patterns.push_back(MachineCombinerPattern::FMLSv1i64_indexed_OP2); Found = true; } + if (canCombineWithFMUL(MBB, Root.getOperand(1), AArch64::FNMULDrr)) { + Patterns.push_back(MachineCombinerPattern::FNMULSUBD_OP1); + Found = true; + } break; case AArch64::FSUBv2f32: if (canCombineWithFMUL(MBB, Root.getOperand(2), @@ -3495,6 +3503,8 @@ AArch64InstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const { case MachineCombinerPattern::FMULADDD_OP2: case MachineCombinerPattern::FMULSUBD_OP1: case MachineCombinerPattern::FMULSUBD_OP2: + case MachineCombinerPattern::FNMULSUBS_OP1: + case MachineCombinerPattern::FNMULSUBD_OP1: case MachineCombinerPattern::FMLAv1i32_indexed_OP1: case MachineCombinerPattern::FMLAv1i32_indexed_OP2: case MachineCombinerPattern::FMLAv1i64_indexed_OP1: @@ -3996,6 +4006,24 @@ void AArch64InstrInfo::genAlternativeCodeSequence( MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); break; } + + case MachineCombinerPattern::FNMULSUBS_OP1: + case MachineCombinerPattern::FNMULSUBD_OP1: { + // FNMUL I=A,B,0 + // FSUB R,I,C + // ==> FNMADD R,A,B,C // = -A*B - C + // --- Create(FNMADD); + if (Pattern == MachineCombinerPattern::FNMULSUBS_OP1) { + Opc = AArch64::FNMADDSrrr; + RC = &AArch64::FPR32RegClass; + } else { + Opc = AArch64::FNMADDDrrr; + RC = &AArch64::FPR64RegClass; + } + MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); + break; + } + case MachineCombinerPattern::FMULSUBS_OP2: case MachineCombinerPattern::FMULSUBD_OP2: { // FMUL I=A,B,0 @@ -4011,6 +4039,7 @@ void AArch64InstrInfo::genAlternativeCodeSequence( } MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); break; + } case MachineCombinerPattern::FMLSv1i32_indexed_OP2: Opc = AArch64::FMLSv1i32_indexed; @@ -4067,7 +4096,6 @@ void AArch64InstrInfo::genAlternativeCodeSequence( FMAInstKind::Accumulator); } break; - } } // end switch (Pattern) // Record MUL and ADD/SUB for deletion DelInstrs.push_back(MUL); diff --git a/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.td b/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.td index 902b08844216..5ddf66654a67 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.td +++ b/contrib/llvm/lib/Target/AArch64/AArch64InstrInfo.td @@ -156,7 +156,8 @@ def AArch64adrp : SDNode<"AArch64ISD::ADRP", SDTIntUnaryOp, []>; def AArch64addlow : SDNode<"AArch64ISD::ADDlow", SDTIntBinOp, []>; def AArch64LOADgot : SDNode<"AArch64ISD::LOADgot", SDTIntUnaryOp>; def AArch64callseq_start : SDNode<"ISD::CALLSEQ_START", - SDCallSeqStart<[ SDTCisVT<0, i32> ]>, + SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>, [SDNPHasChain, SDNPOutGlue]>; def AArch64callseq_end : SDNode<"ISD::CALLSEQ_END", SDCallSeqEnd<[ SDTCisVT<0, i32>, @@ -328,8 +329,9 @@ include "AArch64InstrFormats.td" let Defs = [SP], Uses = [SP], hasSideEffects = 1, isCodeGenOnly = 1 in { // We set Sched to empty list because we expect these instructions to simply get // removed in most cases. -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt), - [(AArch64callseq_start timm:$amt)]>, Sched<[]>; +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), + [(AArch64callseq_start timm:$amt1, timm:$amt2)]>, + Sched<[]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), [(AArch64callseq_end timm:$amt1, timm:$amt2)]>, Sched<[]>; diff --git a/contrib/llvm/lib/Target/AArch64/AArch64RegisterBankInfo.cpp b/contrib/llvm/lib/Target/AArch64/AArch64RegisterBankInfo.cpp index 5f895903da6f..789270c2a34b 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64RegisterBankInfo.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64RegisterBankInfo.cpp @@ -529,9 +529,34 @@ AArch64RegisterBankInfo::getInstrMapping(const MachineInstr &MI) const { // for the greedy mode the cost of the cross bank copy will // offset this number. // FIXME: Should be derived from the scheduling model. - if (OpRegBankIdx[0] >= PMI_FirstFPR) + if (OpRegBankIdx[0] != PMI_FirstGPR) Cost = 2; + else + // Check if that load feeds fp instructions. + // In that case, we want the default mapping to be on FPR + // instead of blind map every scalar to GPR. + for (const MachineInstr &UseMI : + MRI.use_instructions(MI.getOperand(0).getReg())) + // If we have at least one direct use in a FP instruction, + // assume this was a floating point load in the IR. + // If it was not, we would have had a bitcast before + // reaching that instruction. + if (isPreISelGenericFloatingPointOpcode(UseMI.getOpcode())) { + OpRegBankIdx[0] = PMI_FirstFPR; + break; + } break; + case TargetOpcode::G_STORE: + // Check if that store is fed by fp instructions. + if (OpRegBankIdx[0] == PMI_FirstGPR) { + unsigned VReg = MI.getOperand(0).getReg(); + if (!VReg) + break; + MachineInstr *DefMI = MRI.getVRegDef(VReg); + if (isPreISelGenericFloatingPointOpcode(DefMI->getOpcode())) + OpRegBankIdx[0] = PMI_FirstFPR; + break; + } } // Finally construct the computed mapping. diff --git a/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td b/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td index 8f8eeef8a6cf..a9b4d44a523e 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td +++ b/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorDetails.td @@ -42,11 +42,11 @@ def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^FCVT(N|M|P|Z|A)(S|U)(v1i32|v1 def : InstRW<[FalkorWr_1VXVY_4cyc], (instrs FCVTXNv1i64)>; def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^FCVTZ(S|U)(v2i32|v4i16)(_shift)?$")>; -def : InstRW<[FalkorWr_1VXVY_5cyc], (instregex "^(FMUL|FMULX)(v2f32|v4f16|(v1i16_indexed|v4i16_indexed|v1i32_indexed|v2i32_indexed))$")>; -def : InstRW<[FalkorWr_1VXVY_5cyc], (instrs FMULX16, FMULX32)>; +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc], (instregex "^(FMUL|FMULX)(v2f32|v4f16|(v1i16_indexed|v4i16_indexed|v1i32_indexed|v2i32_indexed))$")>; +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc], (instrs FMULX16, FMULX32)>; -def : InstRW<[FalkorWr_1VXVY_6cyc], (instregex "^(FMUL|FMULX)v1i64_indexed$")>; -def : InstRW<[FalkorWr_1VXVY_6cyc], (instrs FMULX64)>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc], (instregex "^(FMUL|FMULX)v1i64_indexed$")>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc], (instrs FMULX64)>; def : InstRW<[FalkorWr_2VXVY_1cyc], (instregex "^(FABS|FNEG)(v2f64|v4f32|v8f16)$")>; @@ -62,9 +62,9 @@ def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^FCVT(N|M|P|Z|A)(S|U)(v2f64|v4 def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^(FCVTL|FCVTL2)(v2i32|v4i16|v4i32|v8i16)$")>; def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^FCVTZ(S|U)(v2i64|v4i32|v8i16)(_shift)?$")>; -def : InstRW<[FalkorWr_2VXVY_5cyc], (instregex "^(FMUL|FMULX)(v2f64|v4f32|v8f16|v8i16_indexed|v4i32_indexed)$")>; +def : InstRW<[FalkorWr_FMUL32_2VXVY_5cyc], (instregex "^(FMUL|FMULX)(v2f64|v4f32|v8f16|v8i16_indexed|v4i32_indexed)$")>; -def : InstRW<[FalkorWr_2VXVY_6cyc], (instregex "^(FMUL|FMULX)v2i64_indexed$")>; +def : InstRW<[FalkorWr_FMUL64_2VXVY_6cyc], (instregex "^(FMUL|FMULX)v2i64_indexed$")>; def : InstRW<[FalkorWr_3VXVY_4cyc], (instregex "^(FCVTX?N|FCVTX?N2)(v1i32|v1i64|v1f16|v2f32|v4f16)$")>; @@ -72,13 +72,14 @@ def : InstRW<[FalkorWr_3VXVY_5cyc], (instregex "^(FCVTX?N|FCVTX?N2)(v2i32|v4i1 def : InstRW<[FalkorWr_2VX_2VY_2cyc], (instregex "^(FDIV|FSQRT)(v2f64|v4f32|v8f16)$")>; -def : InstRW<[FalkorWr_1VXVY_4cyc, FalkorReadVMA],(instregex "^ML(A|S)(v8i8|v4i16|v2i32)(_indexed)?$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc, FalkorReadVMA],(instregex "^ML(A|S)(v16i8|v8i16|v4i32|v2i64)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc, FalkorReadVMA], (instregex "^ML(A|S)(v8i8|v4i16|v2i32)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc, FalkorReadVMA], (instregex "^ML(A|S)(v16i8|v8i16|v4i32|v2i64)(_indexed)?$")>; + +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc, FalkorReadFMA32], (instregex "^FML(A|S)(v2f32|v4f16|(v1i16_indexed|v4i16_indexed|v1i32_indexed|v2i32_indexed))$")>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc, FalkorReadFMA64], (instregex "^FML(A|S)v1i64_indexed$")>; +def : InstRW<[FalkorWr_FMUL32_2VXVY_5cyc, FalkorReadFMA32], (instregex "^FML(A|S)(v4f32|v8f16|v8i16_indexed|v4i32_indexed)$")>; +def : InstRW<[FalkorWr_FMUL64_2VXVY_6cyc, FalkorReadFMA64], (instregex "^FML(A|S)(v2f64|v2i64_indexed)$")>; -def : InstRW<[FalkorWr_1VXVY_5cyc, FalkorReadFMA],(instregex "^FML(A|S)(v2f32|v4f16|(v1i16_indexed|v4i16_indexed|v1i32_indexed|v2i32_indexed))$")>; -def : InstRW<[FalkorWr_1VXVY_6cyc, FalkorReadFMA],(instregex "^FML(A|S)v1i64_indexed$")>; -def : InstRW<[FalkorWr_2VXVY_5cyc, FalkorReadFMA],(instregex "^FML(A|S)(v2f64|v4f32|v8f16|v8i16_indexed|v4i32_indexed)$")>; -def : InstRW<[FalkorWr_2VXVY_6cyc, FalkorReadFMA],(instregex "^FML(A|S)v2i64_indexed$")>; // SIMD Integer Instructions // ----------------------------------------------------------------------------- def : InstRW<[FalkorWr_1VXVY_1cyc], (instregex "^ADD(v1i64|v2i32|v4i16|v8i8)$")>; @@ -119,10 +120,10 @@ def : InstRW<[FalkorWr_1VXVY_3cyc], (instregex "^SQNEG(v1i8|v1i16|v1i32|v1i64) def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^(S|U)ADDLVv8i8v$")>; def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^(S|U)?(MAX|MIN)V(v8i8v|v8i16v)$")>; def : InstRW<[FalkorWr_1VXVY_4cyc], (instrs ADDVv8i8v)>; -def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^MUL(v2i32|v4i16|v8i8)(_indexed)?$")>; -def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^SQR?DMULH(v8i8|v4i16|v1i32|v2i32|v1i16)(_indexed)?$")>; -def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^SQDMULL(i16|i32)$")>; -def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^SQRDML(A|S)?H(v8i8|v4i16|v1i32|v2i32|v1i16)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc], (instregex "^MUL(v2i32|v4i16|v8i8)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc], (instregex "^SQR?DMULH(v8i8|v4i16|v1i32|v2i32|v1i16)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc], (instregex "^SQDMULL(i16|i32)$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc, FalkorReadVMA], (instregex "^SQRDML(A|S)H(i16|i32|v8i8|v4i16|v1i32|v2i32|v1i16)(_indexed)?$")>; def : InstRW<[FalkorWr_1VXVY_5cyc], (instregex "^(S|U)?(MAX|MIN)Vv16i8v$")>; @@ -169,9 +170,9 @@ def : InstRW<[FalkorWr_2VXVY_3cyc], (instregex "^PMULL2?(v1i64|v2i64)$")>; def : InstRW<[FalkorWr_2VXVY_3cyc], (instregex "^S(L|R)I(v16i8|v8i16|v4i32|v2i64)_shift$")>; def : InstRW<[FalkorWr_2VXVY_3cyc], (instregex "^SQ(ABS|NEG)(v16i8|v8i16|v4i32|v2i64)$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^(MUL|SQR?DMULH)(v16i8|v8i16|v4i32)(_indexed)?$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^SQDMULLv.*$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^SQRDML(A|S)H(v16i8|v8i16|v4i32)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc], (instregex "^(MUL|SQR?DMULH)(v16i8|v8i16|v4i32)(_indexed)?$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc], (instregex "^SQDMULLv.*$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc, FalkorReadVMA], (instregex "^SQRDML(A|S)H(v16i8|v8i16|v4i32)(_indexed)?$")>; def : InstRW<[FalkorWr_3VXVY_3cyc], (instregex "^(S|U)ADDLVv4i32v$")>; @@ -185,8 +186,9 @@ def : InstRW<[FalkorWr_4VXVY_3cyc], (instregex "^(S|U)ABALv.*$")>; def : InstRW<[FalkorWr_4VXVY_4cyc], (instregex "^(S|U)ABA(v16i8|v8i16|v4i32)$")>; -def : InstRW<[FalkorWr_1VXVY_4cyc, FalkorReadVMA],(instregex "^SQD(MLAL|MLSL)(i16|i32)$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc, FalkorReadVMA],(instregex "^SQD(MLAL|MLSL)v.*$")>; +def : InstRW<[FalkorWr_VMUL32_1VXVY_4cyc, FalkorReadVMA], (instregex "^SQD(MLAL|MLSL)(i16|i32|v1i32_indexed|v1i64_indexed)$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc, FalkorReadVMA], (instregex "^SQD(MLAL|MLSL)v[248].*$")>; + // SIMD Load Instructions // ----------------------------------------------------------------------------- def : InstRW<[WriteVLD], (instregex "^LD1(i64|Onev(8b|4h|2s|1d|16b|8h|4s|2d))$")>; @@ -294,9 +296,9 @@ def : InstRW<[FalkorWr_1VXVY_3cyc], (instrs FRECPEv1i32, FRECPEv1i64, FRSQRTEv def : InstRW<[FalkorWr_1VXVY_3cyc], (instrs FRECPXv1i32, FRECPXv1i64)>; def : InstRW<[FalkorWr_1VXVY_3cyc], (instrs URECPEv2i32, URSQRTEv2i32)>; -def : InstRW<[FalkorWr_1VXVY_5cyc], (instrs FRECPS32, FRSQRTS32, FRECPSv2f32, FRSQRTSv2f32)>; +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc], (instrs FRECPS32, FRSQRTS32, FRECPSv2f32, FRSQRTSv2f32)>; -def : InstRW<[FalkorWr_1VXVY_6cyc], (instrs FRECPS64, FRSQRTS64)>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc], (instrs FRECPS64, FRSQRTS64)>; def : InstRW<[FalkorWr_1GTOV_1VXVY_2cyc],(instregex "^INSv(i32|i64)(gpr|lane)$")>; def : InstRW<[FalkorWr_2GTOV_1cyc], (instregex "^DUP(v4i32|v2i64)(gpr|lane)$")>; @@ -311,9 +313,9 @@ def : InstRW<[FalkorWr_2VXVY_3cyc], (instrs URECPEv4i32, URSQRTEv4i32)>; def : InstRW<[FalkorWr_2VXVY_4cyc], (instrs TBLv8i8Two)>; def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^TBX(v8|v16)i8One$")>; -def : InstRW<[FalkorWr_2VXVY_5cyc], (instrs FRECPSv4f32, FRSQRTSv4f32)>; +def : InstRW<[FalkorWr_FMUL32_2VXVY_5cyc], (instrs FRECPSv4f32, FRSQRTSv4f32)>; -def : InstRW<[FalkorWr_2VXVY_6cyc], (instrs FRECPSv2f64, FRSQRTSv2f64)>; +def : InstRW<[FalkorWr_FMUL64_2VXVY_6cyc], (instrs FRECPSv2f64, FRSQRTSv2f64)>; def : InstRW<[FalkorWr_3VXVY_5cyc], (instregex "^TBL(v8i8Three|v16i8Two)$")>; def : InstRW<[FalkorWr_3VXVY_5cyc], (instregex "^TBX(v8i8Two|v16i8Two)$")>; @@ -416,22 +418,25 @@ def : InstRW<[FalkorWr_1VXVY_3cyc], (instrs FCVTSHr, FCVTDHr)>; def : InstRW<[FalkorWr_1VXVY_4cyc], (instrs FCVTSDr, FCVTDSr)>; -def : InstRW<[FalkorWr_1VXVY_5cyc], (instregex "^F(N)?MUL(H|S)rr$")>; +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc], (instregex "^F(N)?MUL(H|S)rr$")>; -def : InstRW<[FalkorWr_1VXVY_6cyc], (instregex "^F(N)?MULDrr$")>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc], (instregex "^F(N)?MULDrr$")>; def : InstRW<[FalkorWr_1VX_1VY_10cyc],(instregex "^FDIV(H|S|D)rr$")>; def : InstRW<[FalkorWr_1VX_1VY_2cyc], (instregex "^FSQRT(H|S|D)r$")>; -def : InstRW<[FalkorWr_1VXVY_5cyc, FalkorReadFMA],(instregex "^F(N)?M(ADD|SUB)(H|S)rrr$")>; -def : InstRW<[FalkorWr_1VXVY_6cyc, FalkorReadFMA],(instregex "^F(N)?M(ADD|SUB)Drrr$")>; +def : InstRW<[FalkorWr_FMUL32_1VXVY_5cyc, ReadDefault, ReadDefault, FalkorReadFMA32], (instregex "^F(N)?M(ADD|SUB)(H|S)rrr$")>; +def : InstRW<[FalkorWr_FMUL64_1VXVY_6cyc, ReadDefault, ReadDefault, FalkorReadFMA64], (instregex "^F(N)?M(ADD|SUB)Drrr$")>; // FP Miscellaneous Instructions // ----------------------------------------------------------------------------- -def : InstRW<[FalkorWr_FMOV], (instregex "^FMOV(HW|HX|SW|DX|DXHigh)r$")>; +def : InstRW<[FalkorWr_FMOV], (instregex "^FMOV(H|S|D)i$")>; +def : InstRW<[FalkorWr_1GTOV_1cyc], (instregex "^FMOV(HW|HX|SW|DX|DXHigh)r$")>; def : InstRW<[FalkorWr_1VTOG_1cyc], (instregex "^FCVTZ(S|U)(S|U)(W|X)(D|S)ri?$")>; def : InstRW<[FalkorWr_1VTOG_1cyc], (instregex "^FMOV(WH|WS|XH|XD|XDHigh)r$")>; -def : InstRW<[FalkorWr_1VXVY_1cyc], (instregex "^FMOV(Hi|Hr|S0|Si|Sr|D0|Di|Dr|v.*_ns)$")>; +def : InstRW<[FalkorWr_1VXVY_1cyc], (instregex "^FMOV(Hr|Sr|Dr|v.*_ns)$")>; +// FIXME: We are currently generating movi v0.2d, #0 for these, which is worse than fmov 0.0 +def : InstRW<[FalkorWr_2VXVY_1cyc], (instrs FMOVD0, FMOVS0)>; def : InstRW<[FalkorWr_1GTOV_4cyc], (instregex "^(S|U)CVTF(S|U)(W|X)(D|S)ri$")>; def : InstRW<[FalkorWr_1VXVY_4cyc], (instregex "^(S|U)CVTF(v1i16|v1i32|v2i32|v1i64|v4i16|v2f32|v4f16|d|s)(_shift)?")>; @@ -475,16 +480,17 @@ def : InstRW<[FalkorWr_2XYZ_2cyc], (instregex "^EXTR(W|X)rri$")>; // Divide and Multiply Instructions // ----------------------------------------------------------------------------- -def : InstRW<[FalkorWr_1X_4cyc], (instregex "^(S|U)M(ADD|SUB)Lrrr$")>; -def : InstRW<[FalkorWr_1X_4cyc], (instregex "^M(ADD|SUB)Wrrr$")>; +def : InstRW<[FalkorWr_IMUL64_1X_4cyc, ReadDefault, ReadDefault, FalkorReadIMA64], (instregex "^(S|U)M(ADD|SUB)Lrrr$")>; +def : InstRW<[FalkorWr_IMUL32_1X_2cyc, ReadDefault, ReadDefault, FalkorReadIMA32], (instregex "^M(ADD|SUB)Wrrr$")>; -def : InstRW<[FalkorWr_1X_5cyc], (instregex "^(S|U)MULHrr$")>; -def : InstRW<[FalkorWr_1X_5cyc], (instregex "^M(ADD|SUB)Xrrr$")>; +def : InstRW<[FalkorWr_IMUL64_1X_5cyc], (instregex "^(S|U)MULHrr$")>; +def : InstRW<[FalkorWr_IMUL64_1X_5cyc, ReadDefault, ReadDefault, FalkorReadIMA64], (instregex "^M(ADD|SUB)Xrrr$")>; def : InstRW<[FalkorWr_1X_1Z_8cyc], (instregex "^(S|U)DIVWr$")>; def : InstRW<[FalkorWr_1X_1Z_16cyc], (instregex "^(S|U)DIVXr$")>; -def : InstRW<[FalkorWr_2VXVY_4cyc], (instregex "^(S|U)(MLAL|MLSL|MULL)v.*$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc], (instregex "^(S|U)MULLv.*$")>; +def : InstRW<[FalkorWr_VMUL32_2VXVY_4cyc, FalkorReadVMA], (instregex "^(S|U)(MLAL|MLSL)v.*$")>; // Move and Shift Instructions // ----------------------------------------------------------------------------- diff --git a/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorWriteRes.td b/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorWriteRes.td index e64b2c441a19..6526cc28e806 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorWriteRes.td +++ b/contrib/llvm/lib/Target/AArch64/AArch64SchedFalkorWriteRes.td @@ -29,8 +29,9 @@ // Define 1 micro-op types def FalkorWr_1X_2cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 2; } -def FalkorWr_1X_4cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 4; } -def FalkorWr_1X_5cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 5; } +def FalkorWr_IMUL32_1X_2cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 4; } +def FalkorWr_IMUL64_1X_4cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 4; } +def FalkorWr_IMUL64_1X_5cyc : SchedWriteRes<[FalkorUnitX]> { let Latency = 5; } def FalkorWr_1Z_0cyc : SchedWriteRes<[FalkorUnitZ]> { let Latency = 0; } def FalkorWr_1ZB_0cyc : SchedWriteRes<[FalkorUnitZB]> { let Latency = 0; } def FalkorWr_1LD_3cyc : SchedWriteRes<[FalkorUnitLD]> { let Latency = 3; } @@ -45,8 +46,10 @@ def FalkorWr_1VXVY_1cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 1; } def FalkorWr_1VXVY_2cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 2; } def FalkorWr_1VXVY_3cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 3; } def FalkorWr_1VXVY_4cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 4; } +def FalkorWr_VMUL32_1VXVY_4cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 4; } def FalkorWr_1VXVY_5cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 5; } -def FalkorWr_1VXVY_6cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 6; } +def FalkorWr_FMUL32_1VXVY_5cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 5; } +def FalkorWr_FMUL64_1VXVY_6cyc : SchedWriteRes<[FalkorUnitVXVY]>{ let Latency = 6; } def FalkorWr_1LD_0cyc : SchedWriteRes<[FalkorUnitLD]> { let Latency = 0; } def FalkorWr_1ST_0cyc : SchedWriteRes<[FalkorUnitST]> { let Latency = 0; } @@ -75,14 +78,26 @@ def FalkorWr_2VXVY_4cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { let Latency = 4; let NumMicroOps = 2; } +def FalkorWr_VMUL32_2VXVY_4cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { + let Latency = 4; + let NumMicroOps = 2; +} def FalkorWr_2VXVY_5cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { let Latency = 5; let NumMicroOps = 2; } +def FalkorWr_FMUL32_2VXVY_5cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { + let Latency = 5; + let NumMicroOps = 2; +} def FalkorWr_2VXVY_6cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { let Latency = 6; let NumMicroOps = 2; } +def FalkorWr_FMUL64_2VXVY_6cyc : SchedWriteRes<[FalkorUnitVXVY, FalkorUnitVXVY]> { + let Latency = 6; + let NumMicroOps = 2; +} def FalkorWr_1LD_1VXVY_4cyc : SchedWriteRes<[FalkorUnitLD, FalkorUnitVXVY]> { let Latency = 4; @@ -350,18 +365,17 @@ def FalkorWr_2LD_2VXVY_1XYZ_2LD_2VXVY_4cyc:SchedWriteRes<[FalkorUnitLD, let NumMicroOps = 9; } -// Forwarding logic is modeled for vector multiply and accumulate +// Forwarding logic is modeled for multiply add/accumulate. // ----------------------------------------------------------------------------- -def FalkorReadVMA : SchedReadAdvance<2, [FalkorWr_1VXVY_4cyc, - FalkorWr_2VXVY_4cyc]>; -def FalkorReadFMA : SchedReadAdvance<3, [FalkorWr_1VXVY_5cyc, - FalkorWr_1VXVY_6cyc, - FalkorWr_2VXVY_5cyc, - FalkorWr_2VXVY_6cyc]>; +def FalkorReadIMA32 : SchedReadAdvance<3, [FalkorWr_IMUL32_1X_2cyc]>; +def FalkorReadIMA64 : SchedReadAdvance<4, [FalkorWr_IMUL64_1X_4cyc, FalkorWr_IMUL64_1X_5cyc]>; +def FalkorReadVMA : SchedReadAdvance<3, [FalkorWr_VMUL32_1VXVY_4cyc, FalkorWr_VMUL32_2VXVY_4cyc]>; +def FalkorReadFMA32 : SchedReadAdvance<1, [FalkorWr_FMUL32_1VXVY_5cyc, FalkorWr_FMUL32_2VXVY_5cyc]>; +def FalkorReadFMA64 : SchedReadAdvance<2, [FalkorWr_FMUL64_1VXVY_6cyc, FalkorWr_FMUL64_2VXVY_6cyc]>; // SchedPredicates and WriteVariants for Immediate Zero and LSLFast // ----------------------------------------------------------------------------- -def FalkorImmZPred : SchedPredicate<[{TII->isGPRZero(*MI)}]>; +def FalkorImmZPred : SchedPredicate<[{MI->getOperand(1).getImm() == 0}]>; def FalkorLSLFastPred : SchedPredicate<[{TII->isFalkorLSLFast(*MI)}]>; def FalkorWr_FMOV : SchedWriteVariant<[ @@ -378,7 +392,6 @@ def FalkorWr_LDR : SchedWriteVariant<[ def FalkorWr_ADD : SchedWriteVariant<[ SchedVar<FalkorLSLFastPred, [FalkorWr_1XYZ_1cyc]>, - SchedVar<FalkorImmZPred, [FalkorWr_1XYZ_1cyc]>, SchedVar<NoSchedPred, [FalkorWr_2XYZ_2cyc]>]>; def FalkorWr_PRFM : SchedWriteVariant<[ diff --git a/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.cpp b/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.cpp index abdeac019a18..1c81d34014fd 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.cpp @@ -91,6 +91,8 @@ void AArch64Subtarget::initializeProperties() { case Falkor: MaxInterleaveFactor = 4; VectorInsertExtractBaseCost = 2; + // FIXME: remove this to enable 64-bit SLP if performance looks good. + MinVectorRegisterBitWidth = 128; break; case Kryo: MaxInterleaveFactor = 4; @@ -99,6 +101,8 @@ void AArch64Subtarget::initializeProperties() { PrefetchDistance = 740; MinPrefetchStride = 1024; MaxPrefetchIterationsAhead = 11; + // FIXME: remove this to enable 64-bit SLP if performance looks good. + MinVectorRegisterBitWidth = 128; break; case ThunderX2T99: CacheLineSize = 64; @@ -108,6 +112,8 @@ void AArch64Subtarget::initializeProperties() { PrefetchDistance = 128; MinPrefetchStride = 1024; MaxPrefetchIterationsAhead = 4; + // FIXME: remove this to enable 64-bit SLP if performance looks good. + MinVectorRegisterBitWidth = 128; break; case ThunderX: case ThunderXT88: @@ -116,6 +122,8 @@ void AArch64Subtarget::initializeProperties() { CacheLineSize = 128; PrefFunctionAlignment = 3; PrefLoopAlignment = 2; + // FIXME: remove this to enable 64-bit SLP if performance looks good. + MinVectorRegisterBitWidth = 128; break; case CortexA35: break; case CortexA53: break; diff --git a/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.h b/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.h index 5b9bee6e41b8..df54bf3f48e1 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.h +++ b/contrib/llvm/lib/Target/AArch64/AArch64Subtarget.h @@ -83,6 +83,9 @@ protected: // NegativeImmediates - transform instructions with negative immediates bool NegativeImmediates = true; + // Enable 64-bit vectorization in SLP. + unsigned MinVectorRegisterBitWidth = 64; + bool UseAA = false; bool PredictableSelectIsExpensive = false; bool BalanceFPOps = false; @@ -106,6 +109,7 @@ protected: unsigned PrefFunctionAlignment = 0; unsigned PrefLoopAlignment = 0; unsigned MaxJumpTableSize = 0; + unsigned WideningBaseCost = 0; // ReserveX18 - X18 is not available as a general purpose register. bool ReserveX18; @@ -190,6 +194,10 @@ public: bool isXRaySupported() const override { return true; } + unsigned getMinVectorRegisterBitWidth() const { + return MinVectorRegisterBitWidth; + } + bool isX18Reserved() const { return ReserveX18; } bool hasFPARMv8() const { return HasFPARMv8; } bool hasNEON() const { return HasNEON; } @@ -228,6 +236,8 @@ public: unsigned getMaximumJumpTableSize() const { return MaxJumpTableSize; } + unsigned getWideningBaseCost() const { return WideningBaseCost; } + /// CPU has TBI (top byte of addresses is ignored during HW address /// translation) and OS enables it. bool supportsAddressTopByteIgnored() const; diff --git a/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp b/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp index 8875f9b72647..12a2e9a867f0 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp @@ -70,3 +70,11 @@ const MCExpr *AArch64_MachoTargetObjectFile::getIndirectSymViaGOTPCRel( const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext()); return MCBinaryExpr::createSub(Res, PC, getContext()); } + +void AArch64_MachoTargetObjectFile::getNameWithPrefix( + SmallVectorImpl<char> &OutName, const GlobalValue *GV, + const TargetMachine &TM) const { + // AArch64 does not use section-relative relocations so any global symbol must + // be accessed via at least a linker-private symbol. + getMangler().getNameWithPrefix(OutName, GV, /* CannotUsePrivateLabel */ true); +} diff --git a/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h b/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h index 05e1dfa9e6c9..47e3bce43f6e 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h +++ b/contrib/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h @@ -40,6 +40,9 @@ public: const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override; + + void getNameWithPrefix(SmallVectorImpl<char> &OutName, const GlobalValue *GV, + const TargetMachine &TM) const override; }; } // end namespace llvm diff --git a/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp b/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp index 4d59da0c646d..7c6f55c06bce 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp +++ b/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp @@ -176,11 +176,95 @@ AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) { return TTI::PSK_Software; } +bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode, + ArrayRef<const Value *> Args) { + + // A helper that returns a vector type from the given type. The number of + // elements in type Ty determine the vector width. + auto toVectorTy = [&](Type *ArgTy) { + return VectorType::get(ArgTy->getScalarType(), + DstTy->getVectorNumElements()); + }; + + // Exit early if DstTy is not a vector type whose elements are at least + // 16-bits wide. + if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16) + return false; + + // Determine if the operation has a widening variant. We consider both the + // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the + // instructions. + // + // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we + // verify that their extending operands are eliminated during code + // generation. + switch (Opcode) { + case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2). + case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2). + break; + default: + return false; + } + + // To be a widening instruction (either the "wide" or "long" versions), the + // second operand must be a sign- or zero extend having a single user. We + // only consider extends having a single user because they may otherwise not + // be eliminated. + if (Args.size() != 2 || + (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) || + !Args[1]->hasOneUse()) + return false; + auto *Extend = cast<CastInst>(Args[1]); + + // Legalize the destination type and ensure it can be used in a widening + // operation. + auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy); + unsigned DstElTySize = DstTyL.second.getScalarSizeInBits(); + if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits()) + return false; + + // Legalize the source type and ensure it can be used in a widening + // operation. + Type *SrcTy = toVectorTy(Extend->getSrcTy()); + auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy); + unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits(); + if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits()) + return false; + + // Get the total number of vector elements in the legalized types. + unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorNumElements(); + unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorNumElements(); + + // Return true if the legalized types have the same number of vector elements + // and the destination element type size is twice that of the source type. + return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize; +} + int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, const Instruction *I) { int ISD = TLI->InstructionOpcodeToISD(Opcode); assert(ISD && "Invalid opcode"); + // If the cast is observable, and it is used by a widening instruction (e.g., + // uaddl, saddw, etc.), it may be free. + if (I && I->hasOneUse()) { + auto *SingleUser = cast<Instruction>(*I->user_begin()); + SmallVector<const Value *, 4> Operands(SingleUser->operand_values()); + if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) { + // If the cast is the second operand, it is free. We will generate either + // a "wide" or "long" version of the widening instruction. + if (I == SingleUser->getOperand(1)) + return 0; + // If the cast is not the second operand, it will be free if it looks the + // same as the second operand. In this case, we will generate a "long" + // version of the widening instruction. + if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1))) + if (I->getOpcode() == Cast->getOpcode() && + cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy()) + return 0; + } + } + EVT SrcTy = TLI->getValueType(DL, Src); EVT DstTy = TLI->getValueType(DL, Dst); @@ -379,6 +463,16 @@ int AArch64TTIImpl::getArithmeticInstrCost( // Legalize the type. std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); + // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.), + // add in the widening overhead specified by the sub-target. Since the + // extends feeding widening instructions are performed automatically, they + // aren't present in the generated code and have a zero cost. By adding a + // widening overhead here, we attach the total cost of the combined operation + // to the widening instruction. + int Cost = 0; + if (isWideningInstruction(Ty, Opcode, Args)) + Cost += ST->getWideningBaseCost(); + int ISD = TLI->InstructionOpcodeToISD(Opcode); if (ISD == ISD::SDIV && @@ -388,9 +482,9 @@ int AArch64TTIImpl::getArithmeticInstrCost( // normally expanded to the sequence ADD + CMP + SELECT + SRA. // The OperandValue properties many not be same as that of previous // operation; conservatively assume OP_None. - int Cost = getArithmeticInstrCost(Instruction::Add, Ty, Opd1Info, Opd2Info, - TargetTransformInfo::OP_None, - TargetTransformInfo::OP_None); + Cost += getArithmeticInstrCost(Instruction::Add, Ty, Opd1Info, Opd2Info, + TargetTransformInfo::OP_None, + TargetTransformInfo::OP_None); Cost += getArithmeticInstrCost(Instruction::Sub, Ty, Opd1Info, Opd2Info, TargetTransformInfo::OP_None, TargetTransformInfo::OP_None); @@ -405,8 +499,8 @@ int AArch64TTIImpl::getArithmeticInstrCost( switch (ISD) { default: - return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, - Opd1PropInfo, Opd2PropInfo); + return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, + Opd1PropInfo, Opd2PropInfo); case ISD::ADD: case ISD::MUL: case ISD::XOR: @@ -414,7 +508,7 @@ int AArch64TTIImpl::getArithmeticInstrCost( case ISD::AND: // These nodes are marked as 'custom' for combining purposes only. // We know that they are legal. See LowerAdd in ISelLowering. - return 1 * LT.first; + return (Cost + 1) * LT.first; } } diff --git a/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h b/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h index e37c003e064c..280d97f3c502 100644 --- a/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h +++ b/contrib/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h @@ -43,6 +43,9 @@ class AArch64TTIImpl : public BasicTTIImplBase<AArch64TTIImpl> { VECTOR_LDST_FOUR_ELEMENTS }; + bool isWideningInstruction(Type *Ty, unsigned Opcode, + ArrayRef<const Value *> Args); + public: explicit AArch64TTIImpl(const AArch64TargetMachine *TM, const Function &F) : BaseT(TM, F.getParent()->getDataLayout()), ST(TM->getSubtargetImpl(F)), @@ -84,6 +87,10 @@ public: return 64; } + unsigned getMinVectorRegisterBitWidth() { + return ST->getMinVectorRegisterBitWidth(); + } + unsigned getMaxInterleaveFactor(unsigned VF); int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, @@ -134,6 +141,10 @@ public: unsigned getMinPrefetchStride(); unsigned getMaxPrefetchIterationsAhead(); + + bool shouldExpandReduction(const IntrinsicInst *II) const { + return false; + } /// @} }; diff --git a/contrib/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp b/contrib/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp index 4dbcc9581a84..449d732a8d44 100644 --- a/contrib/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp +++ b/contrib/llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp @@ -3904,10 +3904,14 @@ bool AArch64AsmParser::parseDirectiveArch(SMLoc L) { return false; } +static SMLoc incrementLoc(SMLoc L, int Offset) { + return SMLoc::getFromPointer(L.getPointer() + Offset); +} + /// parseDirectiveCPU /// ::= .cpu id bool AArch64AsmParser::parseDirectiveCPU(SMLoc L) { - SMLoc CPULoc = getLoc(); + SMLoc CurLoc = getLoc(); StringRef CPU, ExtensionString; std::tie(CPU, ExtensionString) = @@ -3923,15 +3927,19 @@ bool AArch64AsmParser::parseDirectiveCPU(SMLoc L) { // FIXME This is using tablegen data, but should be moved to ARMTargetParser // once that is tablegen'ed if (!getSTI().isCPUStringValid(CPU)) { - Error(CPULoc, "unknown CPU name"); + Error(CurLoc, "unknown CPU name"); return false; } MCSubtargetInfo &STI = copySTI(); STI.setDefaultFeatures(CPU, ""); + CurLoc = incrementLoc(CurLoc, CPU.size()); FeatureBitset Features = STI.getFeatureBits(); for (auto Name : RequestedExtensions) { + // Advance source location past '+'. + CurLoc = incrementLoc(CurLoc, 1); + bool EnableFeature = true; if (Name.startswith_lower("no")) { @@ -3939,6 +3947,7 @@ bool AArch64AsmParser::parseDirectiveCPU(SMLoc L) { Name = Name.substr(2); } + bool FoundExtension = false; for (const auto &Extension : ExtensionMap) { if (Extension.Name != Name) continue; @@ -3952,9 +3961,15 @@ bool AArch64AsmParser::parseDirectiveCPU(SMLoc L) { uint64_t Features = ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures)); setAvailableFeatures(Features); + FoundExtension = true; break; } + + if (!FoundExtension) + Error(CurLoc, "unsupported architectural extension"); + + CurLoc = incrementLoc(CurLoc, Name.size()); } return false; } diff --git a/contrib/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp b/contrib/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp index 94112849f84e..1b28df963b40 100644 --- a/contrib/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp +++ b/contrib/llvm/lib/Target/AArch64/MCTargetDesc/AArch64MCAsmInfo.cpp @@ -32,8 +32,9 @@ static cl::opt<AsmWriterVariantTy> AsmWriterVariant( clEnumValN(Apple, "apple", "Emit Apple-style NEON assembly"))); AArch64MCAsmInfoDarwin::AArch64MCAsmInfoDarwin() { - // We prefer NEON instructions to be printed in the short form. - AssemblerDialect = AsmWriterVariant == Default ? 1 : AsmWriterVariant; + // We prefer NEON instructions to be printed in the short, Apple-specific + // form when targeting Darwin. + AssemblerDialect = AsmWriterVariant == Default ? Apple : AsmWriterVariant; PrivateGlobalPrefix = "L"; PrivateLabelPrefix = "L"; @@ -68,8 +69,9 @@ AArch64MCAsmInfoELF::AArch64MCAsmInfoELF(const Triple &T) { if (T.getArch() == Triple::aarch64_be) IsLittleEndian = false; - // We prefer NEON instructions to be printed in the short form. - AssemblerDialect = AsmWriterVariant == Default ? 0 : AsmWriterVariant; + // We prefer NEON instructions to be printed in the generic form when + // targeting ELF. + AssemblerDialect = AsmWriterVariant == Default ? Generic : AsmWriterVariant; CodePointerSize = 8; diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPU.h b/contrib/llvm/lib/Target/AMDGPU/AMDGPU.h index 8f6e1e7d8846..3f89702bed50 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPU.h +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPU.h @@ -50,6 +50,10 @@ FunctionPass *createSIDebuggerInsertNopsPass(); FunctionPass *createSIInsertWaitsPass(); FunctionPass *createSIInsertWaitcntsPass(); FunctionPass *createAMDGPUCodeGenPreparePass(const GCNTargetMachine *TM = nullptr); +FunctionPass *createAMDGPUMachineCFGStructurizerPass(); + +void initializeAMDGPUMachineCFGStructurizerPass(PassRegistry&); +extern char &AMDGPUMachineCFGStructurizerID; ModulePass *createAMDGPUAnnotateKernelFeaturesPass(const TargetMachine *TM = nullptr); void initializeAMDGPUAnnotateKernelFeaturesPass(PassRegistry &); diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPU.td b/contrib/llvm/lib/Target/AMDGPU/AMDGPU.td index 2e5b78bbf7ef..b279bd61e180 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPU.td +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPU.td @@ -61,6 +61,24 @@ def FeatureFlatAddressSpace : SubtargetFeature<"flat-address-space", "Support flat address space" >; +def FeatureFlatInstOffsets : SubtargetFeature<"flat-inst-offsets", + "FlatInstOffsets", + "true", + "Flat instructions have immediate offset addressing mode" +>; + +def FeatureFlatGlobalInsts : SubtargetFeature<"flat-global-insts", + "FlatGlobalInsts", + "true", + "Have global_* flat memory instructions" +>; + +def FeatureFlatScratchInsts : SubtargetFeature<"flat-scratch-insts", + "FlatScratchInsts", + "true", + "Have scratch_* flat memory instructions" +>; + def FeatureUnalignedBufferAccess : SubtargetFeature<"unaligned-buffer-access", "UnalignedBufferAccess", "true", @@ -407,7 +425,8 @@ def FeatureGFX9 : SubtargetFeatureGeneration<"GFX9", FeatureGCN3Encoding, FeatureCIInsts, Feature16BitInsts, FeatureSMemRealTime, FeatureScalarStores, FeatureInv2PiInlineImm, FeatureApertureRegs, FeatureGFX9Insts, FeatureVOP3P, FeatureVGPRIndexMode, - FeatureFastFMAF32, FeatureDPP + FeatureFastFMAF32, FeatureDPP, + FeatureFlatInstOffsets, FeatureFlatGlobalInsts, FeatureFlatScratchInsts ] >; diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp index ccae36ced1f8..7c99752b881f 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp @@ -136,8 +136,7 @@ private: bool SelectMUBUFIntrinsicVOffset(SDValue Offset, SDValue &SOffset, SDValue &ImmOffset, SDValue &VOffset) const; - bool SelectFlat(SDValue Addr, SDValue &VAddr, - SDValue &SLC, SDValue &TFE) const; + bool SelectFlat(SDValue Addr, SDValue &VAddr, SDValue &SLC) const; bool SelectSMRDOffset(SDValue ByteOffsetNode, SDValue &Offset, bool &Imm) const; @@ -1278,10 +1277,9 @@ bool AMDGPUDAGToDAGISel::SelectMUBUFIntrinsicVOffset(SDValue Offset, bool AMDGPUDAGToDAGISel::SelectFlat(SDValue Addr, SDValue &VAddr, - SDValue &SLC, - SDValue &TFE) const { + SDValue &SLC) const { VAddr = Addr; - TFE = SLC = CurDAG->getTargetConstant(0, SDLoc(), MVT::i1); + SLC = CurDAG->getTargetConstant(0, SDLoc(), MVT::i1); return true; } diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp index 915d1d9e0e68..f80652b87373 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp @@ -567,13 +567,19 @@ static bool hasSourceMods(const SDNode *N) { case AMDGPUISD::INTERP_P1: case AMDGPUISD::INTERP_P2: case AMDGPUISD::DIV_SCALE: + + // TODO: Should really be looking at the users of the bitcast. These are + // problematic because bitcasts are used to legalize all stores to integer + // types. + case ISD::BITCAST: return false; default: return true; } } -static bool allUsesHaveSourceMods(const SDNode *N, unsigned CostThreshold = 4) { +bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N, + unsigned CostThreshold) { // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus // it is truly free to use a source modifier in all cases. If there are // multiple users but for each one will necessitate using VOP3, there will be @@ -2299,7 +2305,7 @@ static bool isU24(SDValue Op, SelectionDAG &DAG) { EVT VT = Op.getValueType(); DAG.computeKnownBits(Op, Known); - return (VT.getSizeInBits() - Known.Zero.countLeadingOnes()) <= 24; + return (VT.getSizeInBits() - Known.countMinLeadingZeros()) <= 24; } static bool isI24(SDValue Op, SelectionDAG &DAG) { diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h index e1a5a2072418..4c588a7bafd0 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.h @@ -132,6 +132,8 @@ public: return false; } + static bool allUsesHaveSourceMods(const SDNode *N, + unsigned CostThreshold = 4); bool isFAbsFree(EVT VT) const override; bool isFNegFree(EVT VT) const override; bool isTruncateFree(EVT Src, EVT Dest) const override; diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp index 8867ed689a31..a7eac080f885 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp @@ -127,9 +127,9 @@ bool AMDGPUInstructionSelector::selectG_STORE(MachineInstr &I) const { .add(I.getOperand(1)) .add(I.getOperand(0)) .addImm(0) - .addImm(0) .addImm(0); + // Now that we selected an opcode, we need to constrain the register // operands to use appropriate classes. bool Ret = constrainSelectedInstRegOperands(*Flat, TII, TRI, RBI); @@ -393,7 +393,6 @@ bool AMDGPUInstructionSelector::selectG_LOAD(MachineInstr &I) const { .add(I.getOperand(0)) .addReg(PtrReg) .addImm(0) - .addImm(0) .addImm(0); bool Ret = constrainSelectedInstRegOperands(*Flat, TII, TRI, RBI); diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp index a2567a549028..9de302994e68 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp @@ -33,6 +33,7 @@ AMDGPULegalizerInfo::AMDGPULegalizerInfo() { const LLT P1 = LLT::pointer(1, 64); const LLT P2 = LLT::pointer(2, 64); + setAction({G_CONSTANT, S32}, Legal); setAction({G_CONSTANT, S64}, Legal); setAction({G_GEP, P1}, Legal); diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp new file mode 100644 index 000000000000..6d2785ba1c60 --- /dev/null +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp @@ -0,0 +1,2881 @@ +//===- AMDGPUMachineCFGStructurizer.cpp - Machine code if conversion pass. ===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file implements the machine instruction level CFG structurizer pass. +// +//===----------------------------------------------------------------------===// + +#include "AMDGPU.h" +#include "SIInstrInfo.h" +#include "AMDGPUSubtarget.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/PostOrderIterator.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Analysis/CFG.h" +#include "llvm/CodeGen/MachineBasicBlock.h" +#include "llvm/CodeGen/MachineFunctionPass.h" +#include "llvm/CodeGen/MachineInstr.h" +#include "llvm/CodeGen/MachineInstrBuilder.h" +#include "llvm/CodeGen/MachineRegionInfo.h" +#include "llvm/CodeGen/MachineRegisterInfo.h" +#include "llvm/CodeGen/Passes.h" +#include "llvm/IR/DebugLoc.h" +#include "llvm/Support/Debug.h" +#include "llvm/Target/TargetInstrInfo.h" +#include "llvm/Target/TargetLowering.h" +#include "llvm/Target/TargetSubtargetInfo.h" +#include <tuple> +using namespace llvm; + +#define DEBUG_TYPE "amdgpucfgstructurizer" + +namespace { +class PHILinearizeDestIterator; + +class PHILinearize { + friend class PHILinearizeDestIterator; + +public: + typedef std::pair<unsigned, MachineBasicBlock *> PHISourceT; + +private: + typedef DenseSet<PHISourceT> PHISourcesT; + typedef struct { + unsigned DestReg; + DebugLoc DL; + PHISourcesT Sources; + } PHIInfoElementT; + typedef SmallPtrSet<PHIInfoElementT *, 2> PHIInfoT; + PHIInfoT PHIInfo; + + static unsigned phiInfoElementGetDest(PHIInfoElementT *Info); + static void phiInfoElementSetDef(PHIInfoElementT *Info, unsigned NewDef); + static PHISourcesT &phiInfoElementGetSources(PHIInfoElementT *Info); + static void phiInfoElementAddSource(PHIInfoElementT *Info, unsigned SourceReg, + MachineBasicBlock *SourceMBB); + static void phiInfoElementRemoveSource(PHIInfoElementT *Info, + unsigned SourceReg, + MachineBasicBlock *SourceMBB); + PHIInfoElementT *findPHIInfoElement(unsigned DestReg); + PHIInfoElementT *findPHIInfoElementFromSource(unsigned SourceReg, + MachineBasicBlock *SourceMBB); + +public: + bool findSourcesFromMBB(MachineBasicBlock *SourceMBB, + SmallVector<unsigned, 4> &Sources); + void addDest(unsigned DestReg, const DebugLoc &DL); + void replaceDef(unsigned OldDestReg, unsigned NewDestReg); + void deleteDef(unsigned DestReg); + void addSource(unsigned DestReg, unsigned SourceReg, + MachineBasicBlock *SourceMBB); + void removeSource(unsigned DestReg, unsigned SourceReg, + MachineBasicBlock *SourceMBB = nullptr); + bool findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB, + unsigned &DestReg); + bool isSource(unsigned Reg, MachineBasicBlock *SourceMBB = nullptr); + unsigned getNumSources(unsigned DestReg); + void dump(MachineRegisterInfo *MRI); + void clear(); + + typedef PHISourcesT::iterator source_iterator; + typedef PHILinearizeDestIterator dest_iterator; + + dest_iterator dests_begin(); + dest_iterator dests_end(); + + source_iterator sources_begin(unsigned Reg); + source_iterator sources_end(unsigned Reg); +}; + +class PHILinearizeDestIterator { +private: + PHILinearize::PHIInfoT::iterator Iter; + +public: + unsigned operator*() { return PHILinearize::phiInfoElementGetDest(*Iter); } + PHILinearizeDestIterator &operator++() { + ++Iter; + return *this; + } + bool operator==(const PHILinearizeDestIterator &I) const { + return I.Iter == Iter; + } + bool operator!=(const PHILinearizeDestIterator &I) const { + return I.Iter != Iter; + } + + PHILinearizeDestIterator(PHILinearize::PHIInfoT::iterator I) : Iter(I) {} +}; + +unsigned PHILinearize::phiInfoElementGetDest(PHIInfoElementT *Info) { + return Info->DestReg; +} + +void PHILinearize::phiInfoElementSetDef(PHIInfoElementT *Info, + unsigned NewDef) { + Info->DestReg = NewDef; +} + +PHILinearize::PHISourcesT & +PHILinearize::phiInfoElementGetSources(PHIInfoElementT *Info) { + return Info->Sources; +} + +void PHILinearize::phiInfoElementAddSource(PHIInfoElementT *Info, + unsigned SourceReg, + MachineBasicBlock *SourceMBB) { + // Assertion ensures we don't use the same SourceMBB for the + // sources, because we cannot have different registers with + // identical predecessors, but we can have the same register for + // multiple predecessors. +#if !defined(NDEBUG) + for (auto SI : phiInfoElementGetSources(Info)) { + assert((SI.second != SourceMBB || SourceReg == SI.first)); + } +#endif + + phiInfoElementGetSources(Info).insert(PHISourceT(SourceReg, SourceMBB)); +} + +void PHILinearize::phiInfoElementRemoveSource(PHIInfoElementT *Info, + unsigned SourceReg, + MachineBasicBlock *SourceMBB) { + auto &Sources = phiInfoElementGetSources(Info); + SmallVector<PHISourceT, 4> ElimiatedSources; + for (auto SI : Sources) { + if (SI.first == SourceReg && + (SI.second == nullptr || SI.second == SourceMBB)) { + ElimiatedSources.push_back(PHISourceT(SI.first, SI.second)); + } + } + + for (auto &Source : ElimiatedSources) { + Sources.erase(Source); + } +} + +PHILinearize::PHIInfoElementT * +PHILinearize::findPHIInfoElement(unsigned DestReg) { + for (auto I : PHIInfo) { + if (phiInfoElementGetDest(I) == DestReg) { + return I; + } + } + return nullptr; +} + +PHILinearize::PHIInfoElementT * +PHILinearize::findPHIInfoElementFromSource(unsigned SourceReg, + MachineBasicBlock *SourceMBB) { + for (auto I : PHIInfo) { + for (auto SI : phiInfoElementGetSources(I)) { + if (SI.first == SourceReg && + (SI.second == nullptr || SI.second == SourceMBB)) { + return I; + } + } + } + return nullptr; +} + +bool PHILinearize::findSourcesFromMBB(MachineBasicBlock *SourceMBB, + SmallVector<unsigned, 4> &Sources) { + bool FoundSource = false; + for (auto I : PHIInfo) { + for (auto SI : phiInfoElementGetSources(I)) { + if (SI.second == SourceMBB) { + FoundSource = true; + Sources.push_back(SI.first); + } + } + } + return FoundSource; +} + +void PHILinearize::addDest(unsigned DestReg, const DebugLoc &DL) { + assert(findPHIInfoElement(DestReg) == nullptr && "Dest already exsists"); + PHISourcesT EmptySet; + PHIInfoElementT *NewElement = new PHIInfoElementT(); + NewElement->DestReg = DestReg; + NewElement->DL = DL; + NewElement->Sources = EmptySet; + PHIInfo.insert(NewElement); +} + +void PHILinearize::replaceDef(unsigned OldDestReg, unsigned NewDestReg) { + phiInfoElementSetDef(findPHIInfoElement(OldDestReg), NewDestReg); +} + +void PHILinearize::deleteDef(unsigned DestReg) { + PHIInfoElementT *InfoElement = findPHIInfoElement(DestReg); + PHIInfo.erase(InfoElement); + delete InfoElement; +} + +void PHILinearize::addSource(unsigned DestReg, unsigned SourceReg, + MachineBasicBlock *SourceMBB) { + phiInfoElementAddSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB); +} + +void PHILinearize::removeSource(unsigned DestReg, unsigned SourceReg, + MachineBasicBlock *SourceMBB) { + phiInfoElementRemoveSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB); +} + +bool PHILinearize::findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB, + unsigned &DestReg) { + PHIInfoElementT *InfoElement = + findPHIInfoElementFromSource(SourceReg, SourceMBB); + if (InfoElement != nullptr) { + DestReg = phiInfoElementGetDest(InfoElement); + return true; + } + return false; +} + +bool PHILinearize::isSource(unsigned Reg, MachineBasicBlock *SourceMBB) { + unsigned DestReg; + return findDest(Reg, SourceMBB, DestReg); +} + +unsigned PHILinearize::getNumSources(unsigned DestReg) { + return phiInfoElementGetSources(findPHIInfoElement(DestReg)).size(); +} + +void PHILinearize::dump(MachineRegisterInfo *MRI) { + const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo(); + dbgs() << "=PHIInfo Start=\n"; + for (auto PII : this->PHIInfo) { + PHIInfoElementT &Element = *PII; + dbgs() << "Dest: " << PrintReg(Element.DestReg, TRI) + << " Sources: {"; + for (auto &SI : Element.Sources) { + dbgs() << PrintReg(SI.first, TRI) << "(BB#" + << SI.second->getNumber() << "),"; + } + dbgs() << "}\n"; + } + dbgs() << "=PHIInfo End=\n"; +} + +void PHILinearize::clear() { PHIInfo = PHIInfoT(); } + +PHILinearize::dest_iterator PHILinearize::dests_begin() { + return PHILinearizeDestIterator(PHIInfo.begin()); +} + +PHILinearize::dest_iterator PHILinearize::dests_end() { + return PHILinearizeDestIterator(PHIInfo.end()); +} + +PHILinearize::source_iterator PHILinearize::sources_begin(unsigned Reg) { + auto InfoElement = findPHIInfoElement(Reg); + return phiInfoElementGetSources(InfoElement).begin(); +} +PHILinearize::source_iterator PHILinearize::sources_end(unsigned Reg) { + auto InfoElement = findPHIInfoElement(Reg); + return phiInfoElementGetSources(InfoElement).end(); +} + +class RegionMRT; +class MBBMRT; + +static unsigned getPHINumInputs(MachineInstr &PHI) { + assert(PHI.isPHI()); + return (PHI.getNumOperands() - 1) / 2; +} + +static MachineBasicBlock *getPHIPred(MachineInstr &PHI, unsigned Index) { + assert(PHI.isPHI()); + return PHI.getOperand(Index * 2 + 2).getMBB(); +} + +static void setPhiPred(MachineInstr &PHI, unsigned Index, + MachineBasicBlock *NewPred) { + PHI.getOperand(Index * 2 + 2).setMBB(NewPred); +} + +static unsigned getPHISourceReg(MachineInstr &PHI, unsigned Index) { + assert(PHI.isPHI()); + return PHI.getOperand(Index * 2 + 1).getReg(); +} + +static unsigned getPHIDestReg(MachineInstr &PHI) { + assert(PHI.isPHI()); + return PHI.getOperand(0).getReg(); +} + +class LinearizedRegion { +protected: + MachineBasicBlock *Entry; + // The exit block is part of the region, and is the last + // merge block before exiting the region. + MachineBasicBlock *Exit; + DenseSet<unsigned> LiveOuts; + SmallPtrSet<MachineBasicBlock *, 1> MBBs; + bool HasLoop; + LinearizedRegion *Parent; + RegionMRT *RMRT; + + void storeLiveOutReg(MachineBasicBlock *MBB, unsigned Reg, + MachineInstr *DefInstr, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo); + + void storeLiveOutRegRegion(RegionMRT *Region, unsigned Reg, + MachineInstr *DefInstr, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo); + + void storeMBBLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo, + RegionMRT *TopRegion); + + void storeLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo); + + void storeLiveOuts(RegionMRT *Region, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo, + RegionMRT *TopRegion = nullptr); + +public: + void setRegionMRT(RegionMRT *Region) { RMRT = Region; } + + RegionMRT *getRegionMRT() { return RMRT; } + + void setParent(LinearizedRegion *P) { Parent = P; } + + LinearizedRegion *getParent() { return Parent; } + + void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr); + + void setBBSelectRegIn(unsigned Reg); + + unsigned getBBSelectRegIn(); + + void setBBSelectRegOut(unsigned Reg, bool IsLiveOut); + + unsigned getBBSelectRegOut(); + + void setHasLoop(bool Value); + + bool getHasLoop(); + + void addLiveOut(unsigned VReg); + + void removeLiveOut(unsigned Reg); + + void replaceLiveOut(unsigned OldReg, unsigned NewReg); + + void replaceRegister(unsigned Register, unsigned NewRegister, + MachineRegisterInfo *MRI, bool ReplaceInside, + bool ReplaceOutside, bool IncludeLoopPHIs); + + void replaceRegisterInsideRegion(unsigned Register, unsigned NewRegister, + bool IncludeLoopPHIs, + MachineRegisterInfo *MRI); + + void replaceRegisterOutsideRegion(unsigned Register, unsigned NewRegister, + bool IncludeLoopPHIs, + MachineRegisterInfo *MRI); + + DenseSet<unsigned> *getLiveOuts(); + + void setEntry(MachineBasicBlock *NewEntry); + + MachineBasicBlock *getEntry(); + + void setExit(MachineBasicBlock *NewExit); + + MachineBasicBlock *getExit(); + + void addMBB(MachineBasicBlock *MBB); + + void addMBBs(LinearizedRegion *InnerRegion); + + bool contains(MachineBasicBlock *MBB); + + bool isLiveOut(unsigned Reg); + + bool hasNoDef(unsigned Reg, MachineRegisterInfo *MRI); + + void removeFalseRegisterKills(MachineRegisterInfo *MRI); + + void initLiveOut(RegionMRT *Region, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo); + + LinearizedRegion(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, PHILinearize &PHIInfo); + + LinearizedRegion(); + + ~LinearizedRegion(); +}; + +class MRT { +protected: + RegionMRT *Parent; + unsigned BBSelectRegIn; + unsigned BBSelectRegOut; + +public: + unsigned getBBSelectRegIn() { return BBSelectRegIn; } + + unsigned getBBSelectRegOut() { return BBSelectRegOut; } + + void setBBSelectRegIn(unsigned Reg) { BBSelectRegIn = Reg; } + + void setBBSelectRegOut(unsigned Reg) { BBSelectRegOut = Reg; } + + virtual RegionMRT *getRegionMRT() { return nullptr; } + + virtual MBBMRT *getMBBMRT() { return nullptr; } + + bool isRegion() { return getRegionMRT() != nullptr; } + + bool isMBB() { return getMBBMRT() != nullptr; } + + bool isRoot() { return Parent == nullptr; } + + void setParent(RegionMRT *Region) { Parent = Region; } + + RegionMRT *getParent() { return Parent; } + + static MachineBasicBlock * + initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo, + DenseMap<MachineRegion *, RegionMRT *> &RegionMap); + + static RegionMRT *buildMRT(MachineFunction &MF, + const MachineRegionInfo *RegionInfo, + const SIInstrInfo *TII, + MachineRegisterInfo *MRI); + + virtual void dump(const TargetRegisterInfo *TRI, int depth = 0) = 0; + + void dumpDepth(int depth) { + for (int i = depth; i > 0; --i) { + dbgs() << " "; + } + } + + virtual ~MRT() {} +}; + +class MBBMRT : public MRT { + MachineBasicBlock *MBB; + +public: + virtual MBBMRT *getMBBMRT() { return this; } + + MachineBasicBlock *getMBB() { return MBB; } + + virtual void dump(const TargetRegisterInfo *TRI, int depth = 0) { + dumpDepth(depth); + dbgs() << "MBB: " << getMBB()->getNumber(); + dbgs() << " In: " << PrintReg(getBBSelectRegIn(), TRI); + dbgs() << ", Out: " << PrintReg(getBBSelectRegOut(), TRI) << "\n"; + } + + MBBMRT(MachineBasicBlock *BB) : MBB(BB) { + setParent(nullptr); + setBBSelectRegOut(0); + setBBSelectRegIn(0); + } +}; + +class RegionMRT : public MRT { +protected: + MachineRegion *Region; + LinearizedRegion *LRegion; + MachineBasicBlock *Succ; + + SetVector<MRT *> Children; + +public: + virtual RegionMRT *getRegionMRT() { return this; } + + void setLinearizedRegion(LinearizedRegion *LinearizeRegion) { + LRegion = LinearizeRegion; + } + + LinearizedRegion *getLinearizedRegion() { return LRegion; } + + MachineRegion *getMachineRegion() { return Region; } + + unsigned getInnerOutputRegister() { + return (*(Children.begin()))->getBBSelectRegOut(); + } + + void addChild(MRT *Tree) { Children.insert(Tree); } + + SetVector<MRT *> *getChildren() { return &Children; } + + virtual void dump(const TargetRegisterInfo *TRI, int depth = 0) { + dumpDepth(depth); + dbgs() << "Region: " << (void *)Region; + dbgs() << " In: " << PrintReg(getBBSelectRegIn(), TRI); + dbgs() << ", Out: " << PrintReg(getBBSelectRegOut(), TRI) << "\n"; + + dumpDepth(depth); + if (getSucc()) + dbgs() << "Succ: " << getSucc()->getNumber() << "\n"; + else + dbgs() << "Succ: none \n"; + for (auto MRTI : Children) { + MRTI->dump(TRI, depth + 1); + } + } + + MRT *getEntryTree() { return Children.back(); } + + MRT *getExitTree() { return Children.front(); } + + MachineBasicBlock *getEntry() { + MRT *Tree = Children.back(); + return (Tree->isRegion()) ? Tree->getRegionMRT()->getEntry() + : Tree->getMBBMRT()->getMBB(); + } + + MachineBasicBlock *getExit() { + MRT *Tree = Children.front(); + return (Tree->isRegion()) ? Tree->getRegionMRT()->getExit() + : Tree->getMBBMRT()->getMBB(); + } + + void setSucc(MachineBasicBlock *MBB) { Succ = MBB; } + + MachineBasicBlock *getSucc() { return Succ; } + + bool contains(MachineBasicBlock *MBB) { + for (auto CI : Children) { + if (CI->isMBB()) { + if (MBB == CI->getMBBMRT()->getMBB()) { + return true; + } + } else { + if (CI->getRegionMRT()->contains(MBB)) { + return true; + } else if (CI->getRegionMRT()->getLinearizedRegion() != nullptr && + CI->getRegionMRT()->getLinearizedRegion()->contains(MBB)) { + return true; + } + } + } + return false; + } + + void replaceLiveOutReg(unsigned Register, unsigned NewRegister) { + LinearizedRegion *LRegion = getLinearizedRegion(); + LRegion->replaceLiveOut(Register, NewRegister); + for (auto &CI : Children) { + if (CI->isRegion()) { + CI->getRegionMRT()->replaceLiveOutReg(Register, NewRegister); + } + } + } + + RegionMRT(MachineRegion *MachineRegion) + : Region(MachineRegion), LRegion(nullptr), Succ(nullptr) { + setParent(nullptr); + setBBSelectRegOut(0); + setBBSelectRegIn(0); + } + + virtual ~RegionMRT() { + if (LRegion) { + delete LRegion; + } + + for (auto CI : Children) { + delete &(*CI); + } + } +}; + +static unsigned createBBSelectReg(const SIInstrInfo *TII, + MachineRegisterInfo *MRI) { + return MRI->createVirtualRegister(TII->getPreferredSelectRegClass(32)); +} + +MachineBasicBlock * +MRT::initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo, + DenseMap<MachineRegion *, RegionMRT *> &RegionMap) { + for (auto &MFI : MF) { + MachineBasicBlock *ExitMBB = &MFI; + if (ExitMBB->succ_size() == 0) { + return ExitMBB; + } + } + llvm_unreachable("CFG has no exit block"); + return nullptr; +} + +RegionMRT *MRT::buildMRT(MachineFunction &MF, + const MachineRegionInfo *RegionInfo, + const SIInstrInfo *TII, MachineRegisterInfo *MRI) { + SmallPtrSet<MachineRegion *, 4> PlacedRegions; + DenseMap<MachineRegion *, RegionMRT *> RegionMap; + MachineRegion *TopLevelRegion = RegionInfo->getTopLevelRegion(); + RegionMRT *Result = new RegionMRT(TopLevelRegion); + RegionMap[TopLevelRegion] = Result; + + // Insert the exit block first, we need it to be the merge node + // for the top level region. + MachineBasicBlock *Exit = initializeMRT(MF, RegionInfo, RegionMap); + + unsigned BBSelectRegIn = createBBSelectReg(TII, MRI); + MBBMRT *ExitMRT = new MBBMRT(Exit); + RegionMap[RegionInfo->getRegionFor(Exit)]->addChild(ExitMRT); + ExitMRT->setBBSelectRegIn(BBSelectRegIn); + + for (auto MBBI : post_order(&(MF.front()))) { + MachineBasicBlock *MBB = &(*MBBI); + + // Skip Exit since we already added it + if (MBB == Exit) { + continue; + } + + DEBUG(dbgs() << "Visiting BB#" << MBB->getNumber() << "\n"); + MBBMRT *NewMBB = new MBBMRT(MBB); + MachineRegion *Region = RegionInfo->getRegionFor(MBB); + + // Ensure we have the MRT region + if (RegionMap.count(Region) == 0) { + RegionMRT *NewMRTRegion = new RegionMRT(Region); + RegionMap[Region] = NewMRTRegion; + + // Ensure all parents are in the RegionMap + MachineRegion *Parent = Region->getParent(); + while (RegionMap.count(Parent) == 0) { + RegionMRT *NewMRTParent = new RegionMRT(Parent); + NewMRTParent->addChild(NewMRTRegion); + NewMRTRegion->setParent(NewMRTParent); + RegionMap[Parent] = NewMRTParent; + NewMRTRegion = NewMRTParent; + Parent = Parent->getParent(); + } + RegionMap[Parent]->addChild(NewMRTRegion); + NewMRTRegion->setParent(RegionMap[Parent]); + } + + // Add MBB to Region MRT + RegionMap[Region]->addChild(NewMBB); + NewMBB->setParent(RegionMap[Region]); + RegionMap[Region]->setSucc(Region->getExit()); + } + return Result; +} + +void LinearizedRegion::storeLiveOutReg(MachineBasicBlock *MBB, unsigned Reg, + MachineInstr *DefInstr, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo) { + if (TRI->isVirtualRegister(Reg)) { + DEBUG(dbgs() << "Considering Register: " << PrintReg(Reg, TRI) << "\n"); + // If this is a source register to a PHI we are chaining, it + // must be live out. + if (PHIInfo.isSource(Reg)) { + DEBUG(dbgs() << "Add LiveOut (PHI): " << PrintReg(Reg, TRI) << "\n"); + addLiveOut(Reg); + } else { + // If this is live out of the MBB + for (auto &UI : MRI->use_operands(Reg)) { + if (UI.getParent()->getParent() != MBB) { + DEBUG(dbgs() << "Add LiveOut (MBB BB#" << MBB->getNumber() + << "): " << PrintReg(Reg, TRI) << "\n"); + addLiveOut(Reg); + } else { + // If the use is in the same MBB we have to make sure + // it is after the def, otherwise it is live out in a loop + MachineInstr *UseInstr = UI.getParent(); + for (MachineBasicBlock::instr_iterator + MII = UseInstr->getIterator(), + MIE = UseInstr->getParent()->instr_end(); + MII != MIE; ++MII) { + if ((&(*MII)) == DefInstr) { + DEBUG(dbgs() << "Add LiveOut (Loop): " << PrintReg(Reg, TRI) + << "\n"); + addLiveOut(Reg); + } + } + } + } + } + } +} + +void LinearizedRegion::storeLiveOutRegRegion(RegionMRT *Region, unsigned Reg, + MachineInstr *DefInstr, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo) { + if (TRI->isVirtualRegister(Reg)) { + DEBUG(dbgs() << "Considering Register: " << PrintReg(Reg, TRI) << "\n"); + for (auto &UI : MRI->use_operands(Reg)) { + if (!Region->contains(UI.getParent()->getParent())) { + DEBUG(dbgs() << "Add LiveOut (Region " << (void *)Region + << "): " << PrintReg(Reg, TRI) << "\n"); + addLiveOut(Reg); + } + } + } +} + +void LinearizedRegion::storeLiveOuts(MachineBasicBlock *MBB, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo) { + DEBUG(dbgs() << "-Store Live Outs Begin (BB#" << MBB->getNumber() << ")-\n"); + for (auto &II : *MBB) { + for (auto &RI : II.defs()) { + storeLiveOutReg(MBB, RI.getReg(), RI.getParent(), MRI, TRI, PHIInfo); + } + for (auto &IRI : II.implicit_operands()) { + if (IRI.isDef()) { + storeLiveOutReg(MBB, IRI.getReg(), IRI.getParent(), MRI, TRI, PHIInfo); + } + } + } + + // If we have a successor with a PHI, source coming from this MBB we have to + // add the register as live out + for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), + E = MBB->succ_end(); + SI != E; ++SI) { + for (auto &II : *(*SI)) { + if (II.isPHI()) { + MachineInstr &PHI = II; + int numPreds = getPHINumInputs(PHI); + for (int i = 0; i < numPreds; ++i) { + if (getPHIPred(PHI, i) == MBB) { + unsigned PHIReg = getPHISourceReg(PHI, i); + DEBUG(dbgs() << "Add LiveOut (PhiSource BB#" << MBB->getNumber() + << " -> BB#" << (*SI)->getNumber() + << "): " << PrintReg(PHIReg, TRI) << "\n"); + addLiveOut(PHIReg); + } + } + } + } + } + + DEBUG(dbgs() << "-Store Live Outs Endn-\n"); +} + +void LinearizedRegion::storeMBBLiveOuts(MachineBasicBlock *MBB, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo, + RegionMRT *TopRegion) { + for (auto &II : *MBB) { + for (auto &RI : II.defs()) { + storeLiveOutRegRegion(TopRegion, RI.getReg(), RI.getParent(), MRI, TRI, + PHIInfo); + } + for (auto &IRI : II.implicit_operands()) { + if (IRI.isDef()) { + storeLiveOutRegRegion(TopRegion, IRI.getReg(), IRI.getParent(), MRI, + TRI, PHIInfo); + } + } + } +} + +void LinearizedRegion::storeLiveOuts(RegionMRT *Region, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo, + RegionMRT *CurrentTopRegion) { + MachineBasicBlock *Exit = Region->getSucc(); + + RegionMRT *TopRegion = + CurrentTopRegion == nullptr ? Region : CurrentTopRegion; + + // Check if exit is end of function, if so, no live outs. + if (Exit == nullptr) + return; + + auto Children = Region->getChildren(); + for (auto CI : *Children) { + if (CI->isMBB()) { + auto MBB = CI->getMBBMRT()->getMBB(); + storeMBBLiveOuts(MBB, MRI, TRI, PHIInfo, TopRegion); + } else { + LinearizedRegion *SubRegion = CI->getRegionMRT()->getLinearizedRegion(); + // We should be limited to only store registers that are live out from the + // lineaized region + for (auto MBBI : SubRegion->MBBs) { + storeMBBLiveOuts(MBBI, MRI, TRI, PHIInfo, TopRegion); + } + } + } + + if (CurrentTopRegion == nullptr) { + auto Succ = Region->getSucc(); + for (auto &II : *Succ) { + if (II.isPHI()) { + MachineInstr &PHI = II; + int numPreds = getPHINumInputs(PHI); + for (int i = 0; i < numPreds; ++i) { + if (Region->contains(getPHIPred(PHI, i))) { + unsigned PHIReg = getPHISourceReg(PHI, i); + DEBUG(dbgs() << "Add Region LiveOut (" << (void *)Region + << "): " << PrintReg(PHIReg, TRI) << "\n"); + addLiveOut(PHIReg); + } + } + } + } + } +} + +void LinearizedRegion::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { + OS << "Linearized Region {"; + bool IsFirst = true; + for (const auto &MBB : MBBs) { + if (IsFirst) { + IsFirst = false; + } else { + OS << " ,"; + } + OS << MBB->getNumber(); + } + OS << "} (" << Entry->getNumber() << ", " + << (Exit == nullptr ? -1 : Exit->getNumber()) + << "): In:" << PrintReg(getBBSelectRegIn(), TRI) + << " Out:" << PrintReg(getBBSelectRegOut(), TRI) << " {"; + for (auto &LI : LiveOuts) { + OS << PrintReg(LI, TRI) << " "; + } + OS << "} \n"; +} + +unsigned LinearizedRegion::getBBSelectRegIn() { + return getRegionMRT()->getBBSelectRegIn(); +} + +unsigned LinearizedRegion::getBBSelectRegOut() { + return getRegionMRT()->getBBSelectRegOut(); +} + +void LinearizedRegion::setHasLoop(bool Value) { HasLoop = Value; } + +bool LinearizedRegion::getHasLoop() { return HasLoop; } + +void LinearizedRegion::addLiveOut(unsigned VReg) { LiveOuts.insert(VReg); } + +void LinearizedRegion::removeLiveOut(unsigned Reg) { + if (isLiveOut(Reg)) + LiveOuts.erase(Reg); +} + +void LinearizedRegion::replaceLiveOut(unsigned OldReg, unsigned NewReg) { + if (isLiveOut(OldReg)) { + removeLiveOut(OldReg); + addLiveOut(NewReg); + } +} + +void LinearizedRegion::replaceRegister(unsigned Register, unsigned NewRegister, + MachineRegisterInfo *MRI, + bool ReplaceInside, bool ReplaceOutside, + bool IncludeLoopPHI) { + assert(Register != NewRegister && "Cannot replace a reg with itself"); + + DEBUG(dbgs() << "Pepareing to replace register (region): " + << PrintReg(Register, MRI->getTargetRegisterInfo()) << " with " + << PrintReg(NewRegister, MRI->getTargetRegisterInfo()) << "\n"); + + // If we are replacing outside, we also need to update the LiveOuts + if (ReplaceOutside && + (isLiveOut(Register) || this->getParent()->isLiveOut(Register))) { + LinearizedRegion *Current = this; + while (Current != nullptr && Current->getEntry() != nullptr) { + DEBUG(dbgs() << "Region before register replace\n"); + DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo())); + Current->replaceLiveOut(Register, NewRegister); + DEBUG(dbgs() << "Region after register replace\n"); + DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo())); + Current = Current->getParent(); + } + } + + for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register), + E = MRI->reg_end(); + I != E;) { + MachineOperand &O = *I; + ++I; + + // We don't rewrite defs. + if (O.isDef()) + continue; + + bool IsInside = contains(O.getParent()->getParent()); + bool IsLoopPHI = IsInside && (O.getParent()->isPHI() && + O.getParent()->getParent() == getEntry()); + bool ShouldReplace = (IsInside && ReplaceInside) || + (!IsInside && ReplaceOutside) || + (IncludeLoopPHI && IsLoopPHI); + if (ShouldReplace) { + + if (TargetRegisterInfo::isPhysicalRegister(NewRegister)) { + DEBUG(dbgs() << "Trying to substitute physical register: " + << PrintReg(NewRegister, MRI->getTargetRegisterInfo()) + << "\n"); + llvm_unreachable("Cannot substitute physical registers"); + } else { + DEBUG(dbgs() << "Replacing register (region): " + << PrintReg(Register, MRI->getTargetRegisterInfo()) + << " with " + << PrintReg(NewRegister, MRI->getTargetRegisterInfo()) + << "\n"); + O.setReg(NewRegister); + } + } + } +} + +void LinearizedRegion::replaceRegisterInsideRegion(unsigned Register, + unsigned NewRegister, + bool IncludeLoopPHIs, + MachineRegisterInfo *MRI) { + replaceRegister(Register, NewRegister, MRI, true, false, IncludeLoopPHIs); +} + +void LinearizedRegion::replaceRegisterOutsideRegion(unsigned Register, + unsigned NewRegister, + bool IncludeLoopPHIs, + MachineRegisterInfo *MRI) { + replaceRegister(Register, NewRegister, MRI, false, true, IncludeLoopPHIs); +} + +DenseSet<unsigned> *LinearizedRegion::getLiveOuts() { return &LiveOuts; } + +void LinearizedRegion::setEntry(MachineBasicBlock *NewEntry) { + Entry = NewEntry; +} + +MachineBasicBlock *LinearizedRegion::getEntry() { return Entry; } + +void LinearizedRegion::setExit(MachineBasicBlock *NewExit) { Exit = NewExit; } + +MachineBasicBlock *LinearizedRegion::getExit() { return Exit; } + +void LinearizedRegion::addMBB(MachineBasicBlock *MBB) { MBBs.insert(MBB); } + +void LinearizedRegion::addMBBs(LinearizedRegion *InnerRegion) { + for (const auto &MBB : InnerRegion->MBBs) { + addMBB(MBB); + } +} + +bool LinearizedRegion::contains(MachineBasicBlock *MBB) { + return MBBs.count(MBB) == 1; +} + +bool LinearizedRegion::isLiveOut(unsigned Reg) { + return LiveOuts.count(Reg) == 1; +} + +bool LinearizedRegion::hasNoDef(unsigned Reg, MachineRegisterInfo *MRI) { + return MRI->def_begin(Reg) == MRI->def_end(); +} + +// After the code has been structurized, what was flagged as kills +// before are no longer register kills. +void LinearizedRegion::removeFalseRegisterKills(MachineRegisterInfo *MRI) { + const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo(); + for (auto MBBI : MBBs) { + MachineBasicBlock *MBB = MBBI; + for (auto &II : *MBB) { + for (auto &RI : II.uses()) { + if (RI.isReg()) { + unsigned Reg = RI.getReg(); + if (TRI->isVirtualRegister(Reg)) { + if (hasNoDef(Reg, MRI)) + continue; + if (!MRI->hasOneDef(Reg)) { + DEBUG(this->getEntry()->getParent()->dump()); + DEBUG(dbgs() << PrintReg(Reg, TRI) << "\n"); + } + + if (MRI->def_begin(Reg) == MRI->def_end()) { + DEBUG(dbgs() << "Register " + << PrintReg(Reg, MRI->getTargetRegisterInfo()) + << " has NO defs\n"); + } else if (!MRI->hasOneDef(Reg)) { + DEBUG(dbgs() << "Register " + << PrintReg(Reg, MRI->getTargetRegisterInfo()) + << " has multiple defs\n"); + } + + assert(MRI->hasOneDef(Reg) && "Register has multiple definitions"); + MachineOperand *Def = &(*(MRI->def_begin(Reg))); + MachineOperand *UseOperand = &(RI); + bool UseIsOutsideDefMBB = Def->getParent()->getParent() != MBB; + if (UseIsOutsideDefMBB && UseOperand->isKill()) { + DEBUG(dbgs() << "Removing kill flag on register: " + << PrintReg(Reg, TRI) << "\n"); + UseOperand->setIsKill(false); + } + } + } + } + } + } +} + +void LinearizedRegion::initLiveOut(RegionMRT *Region, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo) { + storeLiveOuts(Region, MRI, TRI, PHIInfo); +} + +LinearizedRegion::LinearizedRegion(MachineBasicBlock *MBB, + const MachineRegisterInfo *MRI, + const TargetRegisterInfo *TRI, + PHILinearize &PHIInfo) { + setEntry(MBB); + setExit(MBB); + storeLiveOuts(MBB, MRI, TRI, PHIInfo); + MBBs.insert(MBB); + Parent = nullptr; +} + +LinearizedRegion::LinearizedRegion() { + setEntry(nullptr); + setExit(nullptr); + Parent = nullptr; +} + +LinearizedRegion::~LinearizedRegion() {} + +class AMDGPUMachineCFGStructurizer : public MachineFunctionPass { +private: + const MachineRegionInfo *Regions; + const SIInstrInfo *TII; + const TargetRegisterInfo *TRI; + MachineRegisterInfo *MRI; + unsigned BBSelectRegister; + PHILinearize PHIInfo; + DenseMap<MachineBasicBlock *, MachineBasicBlock *> FallthroughMap; + + void getPHIRegionIndices(RegionMRT *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &RegionIndices); + void getPHIRegionIndices(LinearizedRegion *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &RegionIndices); + void getPHINonRegionIndices(LinearizedRegion *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &PHINonRegionIndices); + + void storePHILinearizationInfoDest( + unsigned LDestReg, MachineInstr &PHI, + SmallVector<unsigned, 2> *RegionIndices = nullptr); + + unsigned storePHILinearizationInfo(MachineInstr &PHI, + SmallVector<unsigned, 2> *RegionIndices); + + void extractKilledPHIs(MachineBasicBlock *MBB); + + bool shrinkPHI(MachineInstr &PHI, SmallVector<unsigned, 2> &PHIIndices, + unsigned *ReplaceReg); + + bool shrinkPHI(MachineInstr &PHI, unsigned CombinedSourceReg, + MachineBasicBlock *SourceMBB, + SmallVector<unsigned, 2> &PHIIndices, unsigned *ReplaceReg); + + void replacePHI(MachineInstr &PHI, unsigned CombinedSourceReg, + MachineBasicBlock *LastMerge, + SmallVector<unsigned, 2> &PHIRegionIndices); + void replaceEntryPHI(MachineInstr &PHI, unsigned CombinedSourceReg, + MachineBasicBlock *IfMBB, + SmallVector<unsigned, 2> &PHIRegionIndices); + void replaceLiveOutRegs(MachineInstr &PHI, + SmallVector<unsigned, 2> &PHIRegionIndices, + unsigned CombinedSourceReg, + LinearizedRegion *LRegion); + void rewriteRegionExitPHI(RegionMRT *Region, MachineBasicBlock *LastMerge, + MachineInstr &PHI, LinearizedRegion *LRegion); + + void rewriteRegionExitPHIs(RegionMRT *Region, MachineBasicBlock *LastMerge, + LinearizedRegion *LRegion); + void rewriteRegionEntryPHI(LinearizedRegion *Region, MachineBasicBlock *IfMBB, + MachineInstr &PHI); + void rewriteRegionEntryPHIs(LinearizedRegion *Region, + MachineBasicBlock *IfMBB); + + bool regionIsSimpleIf(RegionMRT *Region); + + void transformSimpleIfRegion(RegionMRT *Region); + + void eliminateDeadBranchOperands(MachineBasicBlock::instr_iterator &II); + + void insertUnconditionalBranch(MachineBasicBlock *MBB, + MachineBasicBlock *Dest, + const DebugLoc &DL = DebugLoc()); + + MachineBasicBlock *createLinearizedExitBlock(RegionMRT *Region); + + void insertMergePHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, unsigned DestRegister, + unsigned IfSourceRegister, unsigned CodeSourceRegister, + bool IsUndefIfSource = false); + + MachineBasicBlock *createIfBlock(MachineBasicBlock *MergeBB, + MachineBasicBlock *CodeBBStart, + MachineBasicBlock *CodeBBEnd, + MachineBasicBlock *SelectBB, unsigned IfReg, + bool InheritPreds); + + void prunePHIInfo(MachineBasicBlock *MBB); + void createEntryPHI(LinearizedRegion *CurrentRegion, unsigned DestReg); + + void createEntryPHIs(LinearizedRegion *CurrentRegion); + void resolvePHIInfos(MachineBasicBlock *FunctionEntry); + + void replaceRegisterWith(unsigned Register, unsigned NewRegister); + + MachineBasicBlock *createIfRegion(MachineBasicBlock *MergeBB, + MachineBasicBlock *CodeBB, + LinearizedRegion *LRegion, + unsigned BBSelectRegIn, + unsigned BBSelectRegOut); + + MachineBasicBlock * + createIfRegion(MachineBasicBlock *MergeMBB, LinearizedRegion *InnerRegion, + LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB, + unsigned BBSelectRegIn, unsigned BBSelectRegOut); + void ensureCondIsNotKilled(SmallVector<MachineOperand, 1> Cond); + + void rewriteCodeBBTerminator(MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + unsigned BBSelectReg); + + MachineInstr *getDefInstr(unsigned Reg); + void insertChainedPHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + LinearizedRegion *InnerRegion, unsigned DestReg, + unsigned SourceReg); + bool containsDef(MachineBasicBlock *MBB, LinearizedRegion *InnerRegion, + unsigned Register); + void rewriteLiveOutRegs(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + LinearizedRegion *InnerRegion, + LinearizedRegion *LRegion); + + void splitLoopPHI(MachineInstr &PHI, MachineBasicBlock *Entry, + MachineBasicBlock *EntrySucc, LinearizedRegion *LRegion); + void splitLoopPHIs(MachineBasicBlock *Entry, MachineBasicBlock *EntrySucc, + LinearizedRegion *LRegion); + + MachineBasicBlock *splitExit(LinearizedRegion *LRegion); + + MachineBasicBlock *splitEntry(LinearizedRegion *LRegion); + + LinearizedRegion *initLinearizedRegion(RegionMRT *Region); + + bool structurizeComplexRegion(RegionMRT *Region); + + bool structurizeRegion(RegionMRT *Region); + + bool structurizeRegions(RegionMRT *Region, bool isTopRegion); + +public: + static char ID; + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired<MachineRegionInfoPass>(); + MachineFunctionPass::getAnalysisUsage(AU); + } + + AMDGPUMachineCFGStructurizer() : MachineFunctionPass(ID) { + initializeAMDGPUMachineCFGStructurizerPass(*PassRegistry::getPassRegistry()); + } + + void initFallthroughMap(MachineFunction &MF); + + void createLinearizedRegion(RegionMRT *Region, unsigned SelectOut); + + unsigned initializeSelectRegisters(MRT *MRT, unsigned ExistingExitReg, + MachineRegisterInfo *MRI, + const SIInstrInfo *TII); + + RegionMRT *RMRT; + void setRegionMRT(RegionMRT *RegionTree) { RMRT = RegionTree; } + + RegionMRT *getRegionMRT() { return RMRT; } + + bool runOnMachineFunction(MachineFunction &MF) override; +}; +} + +char AMDGPUMachineCFGStructurizer::ID = 0; + +bool AMDGPUMachineCFGStructurizer::regionIsSimpleIf(RegionMRT *Region) { + MachineBasicBlock *Entry = Region->getEntry(); + MachineBasicBlock *Succ = Region->getSucc(); + bool FoundBypass = false; + bool FoundIf = false; + + if (Entry->succ_size() != 2) { + return false; + } + + for (MachineBasicBlock::const_succ_iterator SI = Entry->succ_begin(), + E = Entry->succ_end(); + SI != E; ++SI) { + MachineBasicBlock *Current = *SI; + + if (Current == Succ) { + FoundBypass = true; + } else if ((Current->succ_size() == 1) && + *(Current->succ_begin()) == Succ) { + FoundIf = true; + } + } + + return FoundIf && FoundBypass; +} + +void AMDGPUMachineCFGStructurizer::transformSimpleIfRegion(RegionMRT *Region) { + MachineBasicBlock *Entry = Region->getEntry(); + MachineBasicBlock *Exit = Region->getExit(); + TII->convertNonUniformIfRegion(Entry, Exit); +} + +static void fixMBBTerminator(MachineBasicBlock *MBB) { + + if (MBB->succ_size() == 1) { + auto *Succ = *(MBB->succ_begin()); + for (auto &TI : MBB->terminators()) { + for (auto &UI : TI.uses()) { + if (UI.isMBB() && UI.getMBB() != Succ) { + UI.setMBB(Succ); + } + } + } + } +} + +static void fixRegionTerminator(RegionMRT *Region) { + MachineBasicBlock *InternalSucc = nullptr; + MachineBasicBlock *ExternalSucc = nullptr; + LinearizedRegion *LRegion = Region->getLinearizedRegion(); + auto Exit = LRegion->getExit(); + + SmallPtrSet<MachineBasicBlock *, 2> Successors; + for (MachineBasicBlock::const_succ_iterator SI = Exit->succ_begin(), + SE = Exit->succ_end(); + SI != SE; ++SI) { + MachineBasicBlock *Succ = *SI; + if (LRegion->contains(Succ)) { + // Do not allow re-assign + assert(InternalSucc == nullptr); + InternalSucc = Succ; + } else { + // Do not allow re-assign + assert(ExternalSucc == nullptr); + ExternalSucc = Succ; + } + } + + for (auto &TI : Exit->terminators()) { + for (auto &UI : TI.uses()) { + if (UI.isMBB()) { + auto Target = UI.getMBB(); + if (Target != InternalSucc && Target != ExternalSucc) { + UI.setMBB(ExternalSucc); + } + } + } + } +} + +// If a region region is just a sequence of regions (and the exit +// block in the case of the top level region), we can simply skip +// linearizing it, because it is already linear +bool regionIsSequence(RegionMRT *Region) { + auto Children = Region->getChildren(); + for (auto CI : *Children) { + if (!CI->isRegion()) { + if (CI->getMBBMRT()->getMBB()->succ_size() > 1) { + return false; + } + } + } + return true; +} + +void fixupRegionExits(RegionMRT *Region) { + auto Children = Region->getChildren(); + for (auto CI : *Children) { + if (!CI->isRegion()) { + fixMBBTerminator(CI->getMBBMRT()->getMBB()); + } else { + fixRegionTerminator(CI->getRegionMRT()); + } + } +} + +void AMDGPUMachineCFGStructurizer::getPHIRegionIndices( + RegionMRT *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &PHIRegionIndices) { + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + MachineBasicBlock *Pred = getPHIPred(PHI, i); + if (Region->contains(Pred)) { + PHIRegionIndices.push_back(i); + } + } +} + +void AMDGPUMachineCFGStructurizer::getPHIRegionIndices( + LinearizedRegion *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &PHIRegionIndices) { + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + MachineBasicBlock *Pred = getPHIPred(PHI, i); + if (Region->contains(Pred)) { + PHIRegionIndices.push_back(i); + } + } +} + +void AMDGPUMachineCFGStructurizer::getPHINonRegionIndices( + LinearizedRegion *Region, MachineInstr &PHI, + SmallVector<unsigned, 2> &PHINonRegionIndices) { + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + MachineBasicBlock *Pred = getPHIPred(PHI, i); + if (!Region->contains(Pred)) { + PHINonRegionIndices.push_back(i); + } + } +} + +void AMDGPUMachineCFGStructurizer::storePHILinearizationInfoDest( + unsigned LDestReg, MachineInstr &PHI, + SmallVector<unsigned, 2> *RegionIndices) { + if (RegionIndices) { + for (auto i : *RegionIndices) { + PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i)); + } + } else { + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i)); + } + } +} + +unsigned AMDGPUMachineCFGStructurizer::storePHILinearizationInfo( + MachineInstr &PHI, SmallVector<unsigned, 2> *RegionIndices) { + unsigned DestReg = getPHIDestReg(PHI); + unsigned LinearizeDestReg = + MRI->createVirtualRegister(MRI->getRegClass(DestReg)); + PHIInfo.addDest(LinearizeDestReg, PHI.getDebugLoc()); + storePHILinearizationInfoDest(LinearizeDestReg, PHI, RegionIndices); + return LinearizeDestReg; +} + +void AMDGPUMachineCFGStructurizer::extractKilledPHIs(MachineBasicBlock *MBB) { + // We need to create a new chain for the killed phi, but there is no + // need to do the renaming outside or inside the block. + SmallPtrSet<MachineInstr *, 2> PHIs; + for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(), + E = MBB->instr_end(); + I != E; ++I) { + MachineInstr &Instr = *I; + if (Instr.isPHI()) { + unsigned PHIDestReg = getPHIDestReg(Instr); + DEBUG(dbgs() << "Extractking killed phi:\n"); + DEBUG(Instr.dump()); + PHIs.insert(&Instr); + PHIInfo.addDest(PHIDestReg, Instr.getDebugLoc()); + storePHILinearizationInfoDest(PHIDestReg, Instr); + } + } + + for (auto PI : PHIs) { + PI->eraseFromParent(); + } +} + +static bool isPHIRegionIndex(SmallVector<unsigned, 2> PHIRegionIndices, + unsigned Index) { + for (auto i : PHIRegionIndices) { + if (i == Index) + return true; + } + return false; +} + +bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI, + SmallVector<unsigned, 2> &PHIIndices, + unsigned *ReplaceReg) { + return shrinkPHI(PHI, 0, nullptr, PHIIndices, ReplaceReg); +} + +bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI, + unsigned CombinedSourceReg, + MachineBasicBlock *SourceMBB, + SmallVector<unsigned, 2> &PHIIndices, + unsigned *ReplaceReg) { + DEBUG(dbgs() << "Shrink PHI: "); + DEBUG(PHI.dump()); + DEBUG(dbgs() << " to " << PrintReg(getPHIDestReg(PHI), TRI) + << "<def> = PHI("); + + bool Replaced = false; + unsigned NumInputs = getPHINumInputs(PHI); + int SingleExternalEntryIndex = -1; + for (unsigned i = 0; i < NumInputs; ++i) { + if (!isPHIRegionIndex(PHIIndices, i)) { + if (SingleExternalEntryIndex == -1) { + // Single entry + SingleExternalEntryIndex = i; + } else { + // Multiple entries + SingleExternalEntryIndex = -2; + } + } + } + + if (SingleExternalEntryIndex > -1) { + *ReplaceReg = getPHISourceReg(PHI, SingleExternalEntryIndex); + // We should not rewrite the code, we should only pick up the single value + // that represents the shrunk PHI. + Replaced = true; + } else { + MachineBasicBlock *MBB = PHI.getParent(); + MachineInstrBuilder MIB = + BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI), + getPHIDestReg(PHI)); + if (SourceMBB) { + MIB.addReg(CombinedSourceReg); + MIB.addMBB(SourceMBB); + DEBUG(dbgs() << PrintReg(CombinedSourceReg, TRI) << ", BB#" + << SourceMBB->getNumber()); + } + + for (unsigned i = 0; i < NumInputs; ++i) { + if (isPHIRegionIndex(PHIIndices, i)) { + continue; + } + unsigned SourceReg = getPHISourceReg(PHI, i); + MachineBasicBlock *SourcePred = getPHIPred(PHI, i); + MIB.addReg(SourceReg); + MIB.addMBB(SourcePred); + DEBUG(dbgs() << PrintReg(SourceReg, TRI) << ", BB#" + << SourcePred->getNumber()); + } + DEBUG(dbgs() << ")\n"); + } + PHI.eraseFromParent(); + return Replaced; +} + +void AMDGPUMachineCFGStructurizer::replacePHI( + MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *LastMerge, + SmallVector<unsigned, 2> &PHIRegionIndices) { + DEBUG(dbgs() << "Replace PHI: "); + DEBUG(PHI.dump()); + DEBUG(dbgs() << " with " << PrintReg(getPHIDestReg(PHI), TRI) + << "<def> = PHI("); + + bool HasExternalEdge = false; + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + if (!isPHIRegionIndex(PHIRegionIndices, i)) { + HasExternalEdge = true; + } + } + + if (HasExternalEdge) { + MachineBasicBlock *MBB = PHI.getParent(); + MachineInstrBuilder MIB = + BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI), + getPHIDestReg(PHI)); + MIB.addReg(CombinedSourceReg); + MIB.addMBB(LastMerge); + DEBUG(dbgs() << PrintReg(CombinedSourceReg, TRI) << ", BB#" + << LastMerge->getNumber()); + for (unsigned i = 0; i < NumInputs; ++i) { + if (isPHIRegionIndex(PHIRegionIndices, i)) { + continue; + } + unsigned SourceReg = getPHISourceReg(PHI, i); + MachineBasicBlock *SourcePred = getPHIPred(PHI, i); + MIB.addReg(SourceReg); + MIB.addMBB(SourcePred); + DEBUG(dbgs() << PrintReg(SourceReg, TRI) << ", BB#" + << SourcePred->getNumber()); + } + DEBUG(dbgs() << ")\n"); + } else { + replaceRegisterWith(getPHIDestReg(PHI), CombinedSourceReg); + } + PHI.eraseFromParent(); +} + +void AMDGPUMachineCFGStructurizer::replaceEntryPHI( + MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *IfMBB, + SmallVector<unsigned, 2> &PHIRegionIndices) { + + DEBUG(dbgs() << "Replace entry PHI: "); + DEBUG(PHI.dump()); + DEBUG(dbgs() << " with "); + + unsigned NumInputs = getPHINumInputs(PHI); + unsigned NumNonRegionInputs = NumInputs; + for (unsigned i = 0; i < NumInputs; ++i) { + if (isPHIRegionIndex(PHIRegionIndices, i)) { + NumNonRegionInputs--; + } + } + + if (NumNonRegionInputs == 0) { + auto DestReg = getPHIDestReg(PHI); + replaceRegisterWith(DestReg, CombinedSourceReg); + DEBUG(dbgs() << " register " << PrintReg(CombinedSourceReg, TRI) << "\n"); + PHI.eraseFromParent(); + } else { + DEBUG(dbgs() << PrintReg(getPHIDestReg(PHI), TRI) << "<def> = PHI("); + MachineBasicBlock *MBB = PHI.getParent(); + MachineInstrBuilder MIB = + BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI), + getPHIDestReg(PHI)); + MIB.addReg(CombinedSourceReg); + MIB.addMBB(IfMBB); + DEBUG(dbgs() << PrintReg(CombinedSourceReg, TRI) << ", BB#" + << IfMBB->getNumber()); + unsigned NumInputs = getPHINumInputs(PHI); + for (unsigned i = 0; i < NumInputs; ++i) { + if (isPHIRegionIndex(PHIRegionIndices, i)) { + continue; + } + unsigned SourceReg = getPHISourceReg(PHI, i); + MachineBasicBlock *SourcePred = getPHIPred(PHI, i); + MIB.addReg(SourceReg); + MIB.addMBB(SourcePred); + DEBUG(dbgs() << PrintReg(SourceReg, TRI) << ", BB#" + << SourcePred->getNumber()); + } + DEBUG(dbgs() << ")\n"); + PHI.eraseFromParent(); + } +} + +void AMDGPUMachineCFGStructurizer::replaceLiveOutRegs( + MachineInstr &PHI, SmallVector<unsigned, 2> &PHIRegionIndices, + unsigned CombinedSourceReg, LinearizedRegion *LRegion) { + bool WasLiveOut = false; + for (auto PII : PHIRegionIndices) { + unsigned Reg = getPHISourceReg(PHI, PII); + if (LRegion->isLiveOut(Reg)) { + bool IsDead = true; + + // Check if register is live out of the basic block + MachineBasicBlock *DefMBB = getDefInstr(Reg)->getParent(); + for (auto UI = MRI->use_begin(Reg), E = MRI->use_end(); UI != E; ++UI) { + if ((*UI).getParent()->getParent() != DefMBB) { + IsDead = false; + } + } + + DEBUG(dbgs() << "Register " << PrintReg(Reg, TRI) << " is " + << (IsDead ? "dead" : "alive") << " after PHI replace\n"); + if (IsDead) { + LRegion->removeLiveOut(Reg); + } + WasLiveOut = true; + } + } + + if (WasLiveOut) + LRegion->addLiveOut(CombinedSourceReg); +} + +void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHI(RegionMRT *Region, + MachineBasicBlock *LastMerge, + MachineInstr &PHI, + LinearizedRegion *LRegion) { + SmallVector<unsigned, 2> PHIRegionIndices; + getPHIRegionIndices(Region, PHI, PHIRegionIndices); + unsigned LinearizedSourceReg = + storePHILinearizationInfo(PHI, &PHIRegionIndices); + + replacePHI(PHI, LinearizedSourceReg, LastMerge, PHIRegionIndices); + replaceLiveOutRegs(PHI, PHIRegionIndices, LinearizedSourceReg, LRegion); +} + +void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHI(LinearizedRegion *Region, + MachineBasicBlock *IfMBB, + MachineInstr &PHI) { + SmallVector<unsigned, 2> PHINonRegionIndices; + getPHINonRegionIndices(Region, PHI, PHINonRegionIndices); + unsigned LinearizedSourceReg = + storePHILinearizationInfo(PHI, &PHINonRegionIndices); + replaceEntryPHI(PHI, LinearizedSourceReg, IfMBB, PHINonRegionIndices); +} + +static void collectPHIs(MachineBasicBlock *MBB, + SmallVector<MachineInstr *, 2> &PHIs) { + for (auto &BBI : *MBB) { + if (BBI.isPHI()) { + PHIs.push_back(&BBI); + } + } +} + +void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHIs(RegionMRT *Region, + MachineBasicBlock *LastMerge, + LinearizedRegion *LRegion) { + SmallVector<MachineInstr *, 2> PHIs; + auto Exit = Region->getSucc(); + if (Exit == nullptr) + return; + + collectPHIs(Exit, PHIs); + + for (auto PHII : PHIs) { + rewriteRegionExitPHI(Region, LastMerge, *PHII, LRegion); + } +} + +void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHIs(LinearizedRegion *Region, + MachineBasicBlock *IfMBB) { + SmallVector<MachineInstr *, 2> PHIs; + auto Entry = Region->getEntry(); + + collectPHIs(Entry, PHIs); + + for (auto PHII : PHIs) { + rewriteRegionEntryPHI(Region, IfMBB, *PHII); + } +} + +void AMDGPUMachineCFGStructurizer::insertUnconditionalBranch(MachineBasicBlock *MBB, + MachineBasicBlock *Dest, + const DebugLoc &DL) { + DEBUG(dbgs() << "Inserting unconditional branch: " << MBB->getNumber() + << " -> " << Dest->getNumber() << "\n"); + MachineBasicBlock::instr_iterator Terminator = MBB->getFirstInstrTerminator(); + bool HasTerminator = Terminator != MBB->instr_end(); + if (HasTerminator) { + TII->ReplaceTailWithBranchTo(Terminator, Dest); + } + if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(Dest)) { + TII->insertUnconditionalBranch(*MBB, Dest, DL); + } +} + +static MachineBasicBlock *getSingleExitNode(MachineFunction &MF) { + MachineBasicBlock *result = nullptr; + for (auto &MFI : MF) { + if (MFI.succ_size() == 0) { + if (result == nullptr) { + result = &MFI; + } else { + return nullptr; + } + } + } + + return result; +} + +static bool hasOneExitNode(MachineFunction &MF) { + return getSingleExitNode(MF) != nullptr; +} + +MachineBasicBlock * +AMDGPUMachineCFGStructurizer::createLinearizedExitBlock(RegionMRT *Region) { + auto Exit = Region->getSucc(); + + // If the exit is the end of the function, we just use the existing + MachineFunction *MF = Region->getEntry()->getParent(); + if (Exit == nullptr && hasOneExitNode(*MF)) { + return &(*(--(Region->getEntry()->getParent()->end()))); + } + + MachineBasicBlock *LastMerge = MF->CreateMachineBasicBlock(); + if (Exit == nullptr) { + MachineFunction::iterator ExitIter = MF->end(); + MF->insert(ExitIter, LastMerge); + } else { + MachineFunction::iterator ExitIter = Exit->getIterator(); + MF->insert(ExitIter, LastMerge); + LastMerge->addSuccessor(Exit); + insertUnconditionalBranch(LastMerge, Exit); + DEBUG(dbgs() << "Created exit block: " << LastMerge->getNumber() << "\n"); + } + return LastMerge; +} + +void AMDGPUMachineCFGStructurizer::insertMergePHI(MachineBasicBlock *IfBB, + MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + unsigned DestRegister, + unsigned IfSourceRegister, + unsigned CodeSourceRegister, + bool IsUndefIfSource) { + // If this is the function exit block, we don't need a phi. + if (MergeBB->succ_begin() == MergeBB->succ_end()) { + return; + } + DEBUG(dbgs() << "Merge PHI (BB#" << MergeBB->getNumber() + << "): " << PrintReg(DestRegister, TRI) << "<def> = PHI(" + << PrintReg(IfSourceRegister, TRI) << ", BB#" + << IfBB->getNumber() << PrintReg(CodeSourceRegister, TRI) + << ", BB#" << CodeBB->getNumber() << ")\n"); + const DebugLoc &DL = MergeBB->findDebugLoc(MergeBB->begin()); + MachineInstrBuilder MIB = BuildMI(*MergeBB, MergeBB->instr_begin(), DL, + TII->get(TargetOpcode::PHI), DestRegister); + if (IsUndefIfSource && false) { + MIB.addReg(IfSourceRegister, RegState::Undef); + } else { + MIB.addReg(IfSourceRegister); + } + MIB.addMBB(IfBB); + MIB.addReg(CodeSourceRegister); + MIB.addMBB(CodeBB); +} + +static void removeExternalCFGSuccessors(MachineBasicBlock *MBB) { + for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(), + E = MBB->succ_end(); + PI != E; ++PI) { + if ((*PI) != MBB) { + (MBB)->removeSuccessor(*PI); + } + } +} + +static void removeExternalCFGEdges(MachineBasicBlock *StartMBB, + MachineBasicBlock *EndMBB) { + + // We have to check against the StartMBB successor becasuse a + // structurized region with a loop will have the entry block split, + // and the backedge will go to the entry successor. + DenseSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>> Succs; + unsigned SuccSize = StartMBB->succ_size(); + if (SuccSize > 0) { + MachineBasicBlock *StartMBBSucc = *(StartMBB->succ_begin()); + for (MachineBasicBlock::succ_iterator PI = EndMBB->succ_begin(), + E = EndMBB->succ_end(); + PI != E; ++PI) { + // Either we have a back-edge to the entry block, or a back-edge to the + // succesor of the entry block since the block may be split. + if ((*PI) != StartMBB && + !((*PI) == StartMBBSucc && StartMBB != EndMBB && SuccSize == 1)) { + Succs.insert( + std::pair<MachineBasicBlock *, MachineBasicBlock *>(EndMBB, *PI)); + } + } + } + + for (MachineBasicBlock::pred_iterator PI = StartMBB->pred_begin(), + E = StartMBB->pred_end(); + PI != E; ++PI) { + if ((*PI) != EndMBB) { + Succs.insert( + std::pair<MachineBasicBlock *, MachineBasicBlock *>(*PI, StartMBB)); + } + } + + for (auto SI : Succs) { + std::pair<MachineBasicBlock *, MachineBasicBlock *> Edge = SI; + DEBUG(dbgs() << "Removing edge: BB#" << Edge.first->getNumber() << " -> BB#" + << Edge.second->getNumber() << "\n"); + Edge.first->removeSuccessor(Edge.second); + } +} + +MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfBlock( + MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBBStart, + MachineBasicBlock *CodeBBEnd, MachineBasicBlock *SelectBB, unsigned IfReg, + bool InheritPreds) { + MachineFunction *MF = MergeBB->getParent(); + MachineBasicBlock *IfBB = MF->CreateMachineBasicBlock(); + + if (InheritPreds) { + for (MachineBasicBlock::pred_iterator PI = CodeBBStart->pred_begin(), + E = CodeBBStart->pred_end(); + PI != E; ++PI) { + if ((*PI) != CodeBBEnd) { + MachineBasicBlock *Pred = (*PI); + Pred->addSuccessor(IfBB); + } + } + } + + removeExternalCFGEdges(CodeBBStart, CodeBBEnd); + + auto CodeBBStartI = CodeBBStart->getIterator(); + auto CodeBBEndI = CodeBBEnd->getIterator(); + auto MergeIter = MergeBB->getIterator(); + MF->insert(MergeIter, IfBB); + MF->splice(MergeIter, CodeBBStartI, ++CodeBBEndI); + IfBB->addSuccessor(MergeBB); + IfBB->addSuccessor(CodeBBStart); + + DEBUG(dbgs() << "Created If block: " << IfBB->getNumber() << "\n"); + // Ensure that the MergeBB is a succesor of the CodeEndBB. + if (!CodeBBEnd->isSuccessor(MergeBB)) + CodeBBEnd->addSuccessor(MergeBB); + + DEBUG(dbgs() << "Moved MBB#" << CodeBBStart->getNumber() << " through MBB#" + << CodeBBEnd->getNumber() << "\n"); + + // If we have a single predecessor we can find a reasonable debug location + MachineBasicBlock *SinglePred = + CodeBBStart->pred_size() == 1 ? *(CodeBBStart->pred_begin()) : nullptr; + const DebugLoc &DL = SinglePred + ? SinglePred->findDebugLoc(SinglePred->getFirstTerminator()) + : DebugLoc(); + + unsigned Reg = + TII->insertEQ(IfBB, IfBB->begin(), DL, IfReg, + SelectBB->getNumber() /* CodeBBStart->getNumber() */); + if (&(*(IfBB->getParent()->begin())) == IfBB) { + TII->materializeImmediate(*IfBB, IfBB->begin(), DL, IfReg, + CodeBBStart->getNumber()); + } + MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true); + ArrayRef<MachineOperand> Cond(RegOp); + TII->insertBranch(*IfBB, MergeBB, CodeBBStart, Cond, DL); + + return IfBB; +} + +void AMDGPUMachineCFGStructurizer::ensureCondIsNotKilled( + SmallVector<MachineOperand, 1> Cond) { + if (Cond.size() != 1) + return; + if (!Cond[0].isReg()) + return; + + unsigned CondReg = Cond[0].getReg(); + for (auto UI = MRI->use_begin(CondReg), E = MRI->use_end(); UI != E; ++UI) { + (*UI).setIsKill(false); + } +} + +void AMDGPUMachineCFGStructurizer::rewriteCodeBBTerminator(MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + unsigned BBSelectReg) { + MachineBasicBlock *TrueBB = nullptr; + MachineBasicBlock *FalseBB = nullptr; + SmallVector<MachineOperand, 1> Cond; + MachineBasicBlock *FallthroughBB = FallthroughMap[CodeBB]; + TII->analyzeBranch(*CodeBB, TrueBB, FalseBB, Cond); + + const DebugLoc &DL = CodeBB->findDebugLoc(CodeBB->getFirstTerminator()); + + if (FalseBB == nullptr && TrueBB == nullptr && FallthroughBB == nullptr) { + // This is an exit block, hence no successors. We will assign the + // bb select register to the entry block. + TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL, + BBSelectReg, + CodeBB->getParent()->begin()->getNumber()); + insertUnconditionalBranch(CodeBB, MergeBB, DL); + return; + } + + if (FalseBB == nullptr && TrueBB == nullptr) { + TrueBB = FallthroughBB; + } else if (TrueBB != nullptr) { + FalseBB = + (FallthroughBB && (FallthroughBB != TrueBB)) ? FallthroughBB : FalseBB; + } + + if ((TrueBB != nullptr && FalseBB == nullptr) || (TrueBB == FalseBB)) { + TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL, + BBSelectReg, TrueBB->getNumber()); + } else { + const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectReg); + unsigned TrueBBReg = MRI->createVirtualRegister(RegClass); + unsigned FalseBBReg = MRI->createVirtualRegister(RegClass); + TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL, + TrueBBReg, TrueBB->getNumber()); + TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL, + FalseBBReg, FalseBB->getNumber()); + ensureCondIsNotKilled(Cond); + TII->insertVectorSelect(*CodeBB, CodeBB->getFirstTerminator(), DL, + BBSelectReg, Cond, TrueBBReg, FalseBBReg); + } + + insertUnconditionalBranch(CodeBB, MergeBB, DL); +} + +MachineInstr *AMDGPUMachineCFGStructurizer::getDefInstr(unsigned Reg) { + if (MRI->def_begin(Reg) == MRI->def_end()) { + DEBUG(dbgs() << "Register " << PrintReg(Reg, MRI->getTargetRegisterInfo()) + << " has NO defs\n"); + } else if (!MRI->hasOneDef(Reg)) { + DEBUG(dbgs() << "Register " << PrintReg(Reg, MRI->getTargetRegisterInfo()) + << " has multiple defs\n"); + DEBUG(dbgs() << "DEFS BEGIN:\n"); + for (auto DI = MRI->def_begin(Reg), DE = MRI->def_end(); DI != DE; ++DI) { + DEBUG(DI->getParent()->dump()); + } + DEBUG(dbgs() << "DEFS END\n"); + } + + assert(MRI->hasOneDef(Reg) && "Register has multiple definitions"); + return (*(MRI->def_begin(Reg))).getParent(); +} + +void AMDGPUMachineCFGStructurizer::insertChainedPHI(MachineBasicBlock *IfBB, + MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + LinearizedRegion *InnerRegion, + unsigned DestReg, + unsigned SourceReg) { + // In this function we know we are part of a chain already, so we need + // to add the registers to the existing chain, and rename the register + // inside the region. + bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit(); + MachineInstr *DefInstr = getDefInstr(SourceReg); + if (DefInstr->isPHI() && DefInstr->getParent() == CodeBB && IsSingleBB) { + // Handle the case where the def is a PHI-def inside a basic + // block, then we only need to do renaming. Special care needs to + // be taken if the PHI-def is part of an existing chain, or if a + // new one needs to be created. + InnerRegion->replaceRegisterInsideRegion(SourceReg, DestReg, true, MRI); + + // We collect all PHI Information, and if we are at the region entry, + // all PHIs will be removed, and then re-introduced if needed. + storePHILinearizationInfoDest(DestReg, *DefInstr); + // We have picked up all the information we need now and can remove + // the PHI + PHIInfo.removeSource(DestReg, SourceReg, CodeBB); + DefInstr->eraseFromParent(); + } else { + // If this is not a phi-def, or it is a phi-def but from a linearized region + if (IsSingleBB && DefInstr->getParent() == InnerRegion->getEntry()) { + // If this is a single BB and the definition is in this block we + // need to replace any uses outside the region. + InnerRegion->replaceRegisterOutsideRegion(SourceReg, DestReg, false, MRI); + } + const TargetRegisterClass *RegClass = MRI->getRegClass(DestReg); + unsigned NextDestReg = MRI->createVirtualRegister(RegClass); + bool IsLastDef = PHIInfo.getNumSources(DestReg) == 1; + DEBUG(dbgs() << "Insert Chained PHI\n"); + insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, DestReg, NextDestReg, + SourceReg, IsLastDef); + + PHIInfo.removeSource(DestReg, SourceReg, CodeBB); + if (IsLastDef) { + const DebugLoc &DL = IfBB->findDebugLoc(IfBB->getFirstTerminator()); + TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DL, + NextDestReg, 0); + PHIInfo.deleteDef(DestReg); + } else { + PHIInfo.replaceDef(DestReg, NextDestReg); + } + } +} + +bool AMDGPUMachineCFGStructurizer::containsDef(MachineBasicBlock *MBB, + LinearizedRegion *InnerRegion, + unsigned Register) { + return getDefInstr(Register)->getParent() == MBB || + InnerRegion->contains(getDefInstr(Register)->getParent()); +} + +void AMDGPUMachineCFGStructurizer::rewriteLiveOutRegs(MachineBasicBlock *IfBB, + MachineBasicBlock *CodeBB, + MachineBasicBlock *MergeBB, + LinearizedRegion *InnerRegion, + LinearizedRegion *LRegion) { + DenseSet<unsigned> *LiveOuts = InnerRegion->getLiveOuts(); + SmallVector<unsigned, 4> OldLiveOuts; + bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit(); + for (auto OLI : *LiveOuts) { + OldLiveOuts.push_back(OLI); + } + + for (auto LI : OldLiveOuts) { + DEBUG(dbgs() << "LiveOut: " << PrintReg(LI, TRI)); + if (!containsDef(CodeBB, InnerRegion, LI) || + (!IsSingleBB && (getDefInstr(LI)->getParent() == LRegion->getExit()))) { + // If the register simly lives through the CodeBB, we don't have + // to rewrite anything since the register is not defined in this + // part of the code. + DEBUG(dbgs() << "- through"); + continue; + } + DEBUG(dbgs() << "\n"); + unsigned Reg = LI; + if (/*!PHIInfo.isSource(Reg) &&*/ Reg != InnerRegion->getBBSelectRegOut()) { + // If the register is live out, we do want to create a phi, + // unless it is from the Exit block, becasuse in that case there + // is already a PHI, and no need to create a new one. + + // If the register is just a live out def and not part of a phi + // chain, we need to create a PHI node to handle the if region, + // and replace all uses outside of the region with the new dest + // register, unless it is the outgoing BB select register. We have + // already creaed phi nodes for these. + const TargetRegisterClass *RegClass = MRI->getRegClass(Reg); + unsigned PHIDestReg = MRI->createVirtualRegister(RegClass); + unsigned IfSourceReg = MRI->createVirtualRegister(RegClass); + // Create initializer, this value is never used, but is needed + // to satisfy SSA. + DEBUG(dbgs() << "Initializer for reg: " << PrintReg(Reg) << "\n"); + TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DebugLoc(), + IfSourceReg, 0); + + InnerRegion->replaceRegisterOutsideRegion(Reg, PHIDestReg, true, MRI); + DEBUG(dbgs() << "Insert Non-Chained Live out PHI\n"); + insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, PHIDestReg, + IfSourceReg, Reg, true); + } + } + + // Handle the chained definitions in PHIInfo, checking if this basic block + // is a source block for a definition. + SmallVector<unsigned, 4> Sources; + if (PHIInfo.findSourcesFromMBB(CodeBB, Sources)) { + DEBUG(dbgs() << "Inserting PHI Live Out from BB#" << CodeBB->getNumber() + << "\n"); + for (auto SI : Sources) { + unsigned DestReg; + PHIInfo.findDest(SI, CodeBB, DestReg); + insertChainedPHI(IfBB, CodeBB, MergeBB, InnerRegion, DestReg, SI); + } + DEBUG(dbgs() << "Insertion done.\n"); + } + + DEBUG(PHIInfo.dump(MRI)); +} + +void AMDGPUMachineCFGStructurizer::prunePHIInfo(MachineBasicBlock *MBB) { + DEBUG(dbgs() << "Before PHI Prune\n"); + DEBUG(PHIInfo.dump(MRI)); + SmallVector<std::tuple<unsigned, unsigned, MachineBasicBlock *>, 4> + ElimiatedSources; + for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE; + ++DRI) { + + unsigned DestReg = *DRI; + auto SE = PHIInfo.sources_end(DestReg); + + bool MBBContainsPHISource = false; + // Check if there is a PHI source in this MBB + for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) { + unsigned SourceReg = (*SRI).first; + MachineOperand *Def = &(*(MRI->def_begin(SourceReg))); + if (Def->getParent()->getParent() == MBB) { + MBBContainsPHISource = true; + } + } + + // If so, all other sources are useless since we know this block + // is always executed when the region is executed. + if (MBBContainsPHISource) { + for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) { + PHILinearize::PHISourceT Source = *SRI; + unsigned SourceReg = Source.first; + MachineBasicBlock *SourceMBB = Source.second; + MachineOperand *Def = &(*(MRI->def_begin(SourceReg))); + if (Def->getParent()->getParent() != MBB) { + ElimiatedSources.push_back( + std::make_tuple(DestReg, SourceReg, SourceMBB)); + } + } + } + } + + // Remove the PHI sources that are in the given MBB + for (auto &SourceInfo : ElimiatedSources) { + PHIInfo.removeSource(std::get<0>(SourceInfo), std::get<1>(SourceInfo), + std::get<2>(SourceInfo)); + } + DEBUG(dbgs() << "After PHI Prune\n"); + DEBUG(PHIInfo.dump(MRI)); +} + +void AMDGPUMachineCFGStructurizer::createEntryPHI(LinearizedRegion *CurrentRegion, + unsigned DestReg) { + MachineBasicBlock *Entry = CurrentRegion->getEntry(); + MachineBasicBlock *Exit = CurrentRegion->getExit(); + + DEBUG(dbgs() << "RegionExit: " << Exit->getNumber() + << " Pred: " << (*(Entry->pred_begin()))->getNumber() << "\n"); + + int NumSources = 0; + auto SE = PHIInfo.sources_end(DestReg); + + for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) { + NumSources++; + } + + if (NumSources == 1) { + auto SRI = PHIInfo.sources_begin(DestReg); + unsigned SourceReg = (*SRI).first; + replaceRegisterWith(DestReg, SourceReg); + } else { + const DebugLoc &DL = Entry->findDebugLoc(Entry->begin()); + MachineInstrBuilder MIB = BuildMI(*Entry, Entry->instr_begin(), DL, + TII->get(TargetOpcode::PHI), DestReg); + DEBUG(dbgs() << "Entry PHI " << PrintReg(DestReg, TRI) << "<def> = PHI("); + + unsigned CurrentBackedgeReg = 0; + + for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) { + unsigned SourceReg = (*SRI).first; + + if (CurrentRegion->contains((*SRI).second)) { + if (CurrentBackedgeReg == 0) { + CurrentBackedgeReg = SourceReg; + } else { + MachineInstr *PHIDefInstr = getDefInstr(SourceReg); + MachineBasicBlock *PHIDefMBB = PHIDefInstr->getParent(); + const TargetRegisterClass *RegClass = + MRI->getRegClass(CurrentBackedgeReg); + unsigned NewBackedgeReg = MRI->createVirtualRegister(RegClass); + MachineInstrBuilder BackedgePHI = + BuildMI(*PHIDefMBB, PHIDefMBB->instr_begin(), DL, + TII->get(TargetOpcode::PHI), NewBackedgeReg); + BackedgePHI.addReg(CurrentBackedgeReg); + BackedgePHI.addMBB(getPHIPred(*PHIDefInstr, 0)); + BackedgePHI.addReg(getPHISourceReg(*PHIDefInstr, 1)); + BackedgePHI.addMBB((*SRI).second); + CurrentBackedgeReg = NewBackedgeReg; + DEBUG(dbgs() << "Inserting backedge PHI: " + << PrintReg(NewBackedgeReg, TRI) << "<def> = PHI(" + << PrintReg(CurrentBackedgeReg, TRI) << ", BB#" + << getPHIPred(*PHIDefInstr, 0)->getNumber() << ", " + << PrintReg(getPHISourceReg(*PHIDefInstr, 1), TRI) + << ", BB#" << (*SRI).second->getNumber()); + } + } else { + MIB.addReg(SourceReg); + MIB.addMBB((*SRI).second); + DEBUG(dbgs() << PrintReg(SourceReg, TRI) << ", BB#" + << (*SRI).second->getNumber() << ", "); + } + } + + // Add the final backedge register source to the entry phi + if (CurrentBackedgeReg != 0) { + MIB.addReg(CurrentBackedgeReg); + MIB.addMBB(Exit); + DEBUG(dbgs() << PrintReg(CurrentBackedgeReg, TRI) << ", BB#" + << Exit->getNumber() << ")\n"); + } else { + DEBUG(dbgs() << ")\n"); + } + } +} + +void AMDGPUMachineCFGStructurizer::createEntryPHIs(LinearizedRegion *CurrentRegion) { + DEBUG(PHIInfo.dump(MRI)); + + for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE; + ++DRI) { + + unsigned DestReg = *DRI; + createEntryPHI(CurrentRegion, DestReg); + } + PHIInfo.clear(); +} + +void AMDGPUMachineCFGStructurizer::replaceRegisterWith(unsigned Register, + unsigned NewRegister) { + assert(Register != NewRegister && "Cannot replace a reg with itself"); + + for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register), + E = MRI->reg_end(); + I != E;) { + MachineOperand &O = *I; + ++I; + if (TargetRegisterInfo::isPhysicalRegister(NewRegister)) { + DEBUG(dbgs() << "Trying to substitute physical register: " + << PrintReg(NewRegister, MRI->getTargetRegisterInfo()) + << "\n"); + llvm_unreachable("Cannot substitute physical registers"); + // We don't handle physical registers, but if we need to + // in the future This is how we do it: + // O.substPhysReg(NewRegister, *TRI); + } else { + DEBUG(dbgs() << "Replacing register: " + << PrintReg(Register, MRI->getTargetRegisterInfo()) + << " with " + << PrintReg(NewRegister, MRI->getTargetRegisterInfo()) + << "\n"); + O.setReg(NewRegister); + } + } + PHIInfo.deleteDef(Register); + + getRegionMRT()->replaceLiveOutReg(Register, NewRegister); + + DEBUG(PHIInfo.dump(MRI)); +} + +void AMDGPUMachineCFGStructurizer::resolvePHIInfos(MachineBasicBlock *FunctionEntry) { + DEBUG(dbgs() << "Resolve PHI Infos\n"); + DEBUG(PHIInfo.dump(MRI)); + for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE; + ++DRI) { + unsigned DestReg = *DRI; + DEBUG(dbgs() << "DestReg: " << PrintReg(DestReg, TRI) << "\n"); + auto SRI = PHIInfo.sources_begin(DestReg); + unsigned SourceReg = (*SRI).first; + DEBUG(dbgs() << "DestReg: " << PrintReg(DestReg, TRI) + << " SourceReg: " << PrintReg(SourceReg, TRI) << "\n"); + + assert(PHIInfo.sources_end(DestReg) == ++SRI && + "More than one phi source in entry node"); + replaceRegisterWith(DestReg, SourceReg); + } +} + +static bool isFunctionEntryBlock(MachineBasicBlock *MBB) { + return ((&(*(MBB->getParent()->begin()))) == MBB); +} + +MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion( + MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBB, + LinearizedRegion *CurrentRegion, unsigned BBSelectRegIn, + unsigned BBSelectRegOut) { + if (isFunctionEntryBlock(CodeBB) && !CurrentRegion->getHasLoop()) { + // Handle non-loop function entry block. + // We need to allow loops to the entry block and then + rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut); + resolvePHIInfos(CodeBB); + removeExternalCFGSuccessors(CodeBB); + CodeBB->addSuccessor(MergeBB); + CurrentRegion->addMBB(CodeBB); + return nullptr; + } + if (CurrentRegion->getEntry() == CodeBB && !CurrentRegion->getHasLoop()) { + // Handle non-loop region entry block. + MachineFunction *MF = MergeBB->getParent(); + auto MergeIter = MergeBB->getIterator(); + auto CodeBBStartIter = CodeBB->getIterator(); + auto CodeBBEndIter = ++(CodeBB->getIterator()); + if (CodeBBEndIter != MergeIter) { + MF->splice(MergeIter, CodeBBStartIter, CodeBBEndIter); + } + rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut); + prunePHIInfo(CodeBB); + createEntryPHIs(CurrentRegion); + removeExternalCFGSuccessors(CodeBB); + CodeBB->addSuccessor(MergeBB); + CurrentRegion->addMBB(CodeBB); + return nullptr; + } else { + // Handle internal block. + const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectRegIn); + unsigned CodeBBSelectReg = MRI->createVirtualRegister(RegClass); + rewriteCodeBBTerminator(CodeBB, MergeBB, CodeBBSelectReg); + bool IsRegionEntryBB = CurrentRegion->getEntry() == CodeBB; + MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeBB, CodeBB, CodeBB, + BBSelectRegIn, IsRegionEntryBB); + CurrentRegion->addMBB(IfBB); + // If this is the entry block we need to make the If block the new + // linearized region entry. + if (IsRegionEntryBB) { + CurrentRegion->setEntry(IfBB); + + if (CurrentRegion->getHasLoop()) { + MachineBasicBlock *RegionExit = CurrentRegion->getExit(); + MachineBasicBlock *ETrueBB = nullptr; + MachineBasicBlock *EFalseBB = nullptr; + SmallVector<MachineOperand, 1> ECond; + + const DebugLoc &DL = DebugLoc(); + TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond); + TII->removeBranch(*RegionExit); + + // We need to create a backedge if there is a loop + unsigned Reg = TII->insertNE( + RegionExit, RegionExit->instr_end(), DL, + CurrentRegion->getRegionMRT()->getInnerOutputRegister(), + CurrentRegion->getRegionMRT()->getEntry()->getNumber()); + MachineOperand RegOp = + MachineOperand::CreateReg(Reg, false, false, true); + ArrayRef<MachineOperand> Cond(RegOp); + DEBUG(dbgs() << "RegionExitReg: "); + DEBUG(Cond[0].print(dbgs(), TRI)); + DEBUG(dbgs() << "\n"); + TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit, + Cond, DebugLoc()); + RegionExit->addSuccessor(CurrentRegion->getEntry()); + } + } + CurrentRegion->addMBB(CodeBB); + LinearizedRegion InnerRegion(CodeBB, MRI, TRI, PHIInfo); + + InnerRegion.setParent(CurrentRegion); + DEBUG(dbgs() << "Insert BB Select PHI (BB)\n"); + insertMergePHI(IfBB, CodeBB, MergeBB, BBSelectRegOut, BBSelectRegIn, + CodeBBSelectReg); + InnerRegion.addMBB(MergeBB); + + DEBUG(InnerRegion.print(dbgs(), TRI)); + rewriteLiveOutRegs(IfBB, CodeBB, MergeBB, &InnerRegion, CurrentRegion); + extractKilledPHIs(CodeBB); + if (IsRegionEntryBB) { + createEntryPHIs(CurrentRegion); + } + return IfBB; + } +} + +MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion( + MachineBasicBlock *MergeBB, LinearizedRegion *InnerRegion, + LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB, + unsigned BBSelectRegIn, unsigned BBSelectRegOut) { + unsigned CodeBBSelectReg = + InnerRegion->getRegionMRT()->getInnerOutputRegister(); + MachineBasicBlock *CodeEntryBB = InnerRegion->getEntry(); + MachineBasicBlock *CodeExitBB = InnerRegion->getExit(); + MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeEntryBB, CodeExitBB, + SelectBB, BBSelectRegIn, true); + CurrentRegion->addMBB(IfBB); + bool isEntry = CurrentRegion->getEntry() == InnerRegion->getEntry(); + if (isEntry) { + + if (CurrentRegion->getHasLoop()) { + MachineBasicBlock *RegionExit = CurrentRegion->getExit(); + MachineBasicBlock *ETrueBB = nullptr; + MachineBasicBlock *EFalseBB = nullptr; + SmallVector<MachineOperand, 1> ECond; + + const DebugLoc &DL = DebugLoc(); + TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond); + TII->removeBranch(*RegionExit); + + // We need to create a backedge if there is a loop + unsigned Reg = + TII->insertNE(RegionExit, RegionExit->instr_end(), DL, + CurrentRegion->getRegionMRT()->getInnerOutputRegister(), + CurrentRegion->getRegionMRT()->getEntry()->getNumber()); + MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true); + ArrayRef<MachineOperand> Cond(RegOp); + DEBUG(dbgs() << "RegionExitReg: "); + DEBUG(Cond[0].print(dbgs(), TRI)); + DEBUG(dbgs() << "\n"); + TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit, + Cond, DebugLoc()); + RegionExit->addSuccessor(IfBB); + } + } + CurrentRegion->addMBBs(InnerRegion); + DEBUG(dbgs() << "Insert BB Select PHI (region)\n"); + insertMergePHI(IfBB, CodeExitBB, MergeBB, BBSelectRegOut, BBSelectRegIn, + CodeBBSelectReg); + + rewriteLiveOutRegs(IfBB, /* CodeEntryBB */ CodeExitBB, MergeBB, InnerRegion, + CurrentRegion); + + rewriteRegionEntryPHIs(InnerRegion, IfBB); + + if (isEntry) { + CurrentRegion->setEntry(IfBB); + } + + if (isEntry) { + createEntryPHIs(CurrentRegion); + } + + return IfBB; +} + +void AMDGPUMachineCFGStructurizer::splitLoopPHI(MachineInstr &PHI, + MachineBasicBlock *Entry, + MachineBasicBlock *EntrySucc, + LinearizedRegion *LRegion) { + SmallVector<unsigned, 2> PHIRegionIndices; + getPHIRegionIndices(LRegion, PHI, PHIRegionIndices); + + assert(PHIRegionIndices.size() == 1); + + unsigned RegionIndex = PHIRegionIndices[0]; + unsigned RegionSourceReg = getPHISourceReg(PHI, RegionIndex); + MachineBasicBlock *RegionSourceMBB = getPHIPred(PHI, RegionIndex); + unsigned PHIDest = getPHIDestReg(PHI); + unsigned PHISource = PHIDest; + unsigned ReplaceReg; + + if (shrinkPHI(PHI, PHIRegionIndices, &ReplaceReg)) { + PHISource = ReplaceReg; + } + + const TargetRegisterClass *RegClass = MRI->getRegClass(PHIDest); + unsigned NewDestReg = MRI->createVirtualRegister(RegClass); + LRegion->replaceRegisterInsideRegion(PHIDest, NewDestReg, false, MRI); + MachineInstrBuilder MIB = + BuildMI(*EntrySucc, EntrySucc->instr_begin(), PHI.getDebugLoc(), + TII->get(TargetOpcode::PHI), NewDestReg); + DEBUG(dbgs() << "Split Entry PHI " << PrintReg(NewDestReg, TRI) + << "<def> = PHI("); + MIB.addReg(PHISource); + MIB.addMBB(Entry); + DEBUG(dbgs() << PrintReg(PHISource, TRI) << ", BB#" << Entry->getNumber()); + MIB.addReg(RegionSourceReg); + MIB.addMBB(RegionSourceMBB); + DEBUG(dbgs() << " ," << PrintReg(RegionSourceReg, TRI) << ", BB#" + << RegionSourceMBB->getNumber() << ")\n"); +} + +void AMDGPUMachineCFGStructurizer::splitLoopPHIs(MachineBasicBlock *Entry, + MachineBasicBlock *EntrySucc, + LinearizedRegion *LRegion) { + SmallVector<MachineInstr *, 2> PHIs; + collectPHIs(Entry, PHIs); + + for (auto PHII : PHIs) { + splitLoopPHI(*PHII, Entry, EntrySucc, LRegion); + } +} + +// Split the exit block so that we can insert a end control flow +MachineBasicBlock * +AMDGPUMachineCFGStructurizer::splitExit(LinearizedRegion *LRegion) { + auto MRTRegion = LRegion->getRegionMRT(); + auto Exit = LRegion->getExit(); + auto MF = Exit->getParent(); + auto Succ = MRTRegion->getSucc(); + + auto NewExit = MF->CreateMachineBasicBlock(); + auto AfterExitIter = Exit->getIterator(); + AfterExitIter++; + MF->insert(AfterExitIter, NewExit); + Exit->removeSuccessor(Succ); + Exit->addSuccessor(NewExit); + NewExit->addSuccessor(Succ); + insertUnconditionalBranch(NewExit, Succ); + LRegion->addMBB(NewExit); + LRegion->setExit(NewExit); + + DEBUG(dbgs() << "Created new exit block: " << NewExit->getNumber() << "\n"); + + // Replace any PHI Predecessors in the successor with NewExit + for (auto &II : *Succ) { + MachineInstr &Instr = II; + + // If we are past the PHI instructions we are done + if (!Instr.isPHI()) + break; + + int numPreds = getPHINumInputs(Instr); + for (int i = 0; i < numPreds; ++i) { + auto Pred = getPHIPred(Instr, i); + if (Pred == Exit) { + setPhiPred(Instr, i, NewExit); + } + } + } + + return NewExit; +} + + +static MachineBasicBlock *split(MachineBasicBlock::iterator I) { + // Create the fall-through block. + MachineBasicBlock *MBB = (*I).getParent(); + MachineFunction *MF = MBB->getParent(); + MachineBasicBlock *SuccMBB = MF->CreateMachineBasicBlock(); + auto MBBIter = ++(MBB->getIterator()); + MF->insert(MBBIter, SuccMBB); + SuccMBB->transferSuccessorsAndUpdatePHIs(MBB); + MBB->addSuccessor(SuccMBB); + + // Splice the code over. + SuccMBB->splice(SuccMBB->end(), MBB, I, MBB->end()); + + return SuccMBB; +} + +// Split the entry block separating PHI-nodes and the rest of the code +// This is needed to insert an initializer for the bb select register +// inloop regions. + +MachineBasicBlock * +AMDGPUMachineCFGStructurizer::splitEntry(LinearizedRegion *LRegion) { + MachineBasicBlock *Entry = LRegion->getEntry(); + MachineBasicBlock *EntrySucc = split(Entry->getFirstNonPHI()); + MachineBasicBlock *Exit = LRegion->getExit(); + + DEBUG(dbgs() << "Split BB#" << Entry->getNumber() << " to BB#" + << Entry->getNumber() << " -> BB#" << EntrySucc->getNumber() + << "\n"); + LRegion->addMBB(EntrySucc); + + // Make the backedge go to Entry Succ + if (Exit->isSuccessor(Entry)) { + Exit->removeSuccessor(Entry); + } + Exit->addSuccessor(EntrySucc); + MachineInstr &Branch = *(Exit->instr_rbegin()); + for (auto &UI : Branch.uses()) { + if (UI.isMBB() && UI.getMBB() == Entry) { + UI.setMBB(EntrySucc); + } + } + + splitLoopPHIs(Entry, EntrySucc, LRegion); + + return EntrySucc; +} + +LinearizedRegion * +AMDGPUMachineCFGStructurizer::initLinearizedRegion(RegionMRT *Region) { + LinearizedRegion *LRegion = Region->getLinearizedRegion(); + LRegion->initLiveOut(Region, MRI, TRI, PHIInfo); + LRegion->setEntry(Region->getEntry()); + return LRegion; +} + +static void removeOldExitPreds(RegionMRT *Region) { + MachineBasicBlock *Exit = Region->getSucc(); + if (Exit == nullptr) { + return; + } + for (MachineBasicBlock::pred_iterator PI = Exit->pred_begin(), + E = Exit->pred_end(); + PI != E; ++PI) { + if (Region->contains(*PI)) { + (*PI)->removeSuccessor(Exit); + } + } +} + +static bool mbbHasBackEdge(MachineBasicBlock *MBB, + SmallPtrSet<MachineBasicBlock *, 8> &MBBs) { + for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) { + if (MBBs.count(*SI) != 0) { + return true; + } + } + return false; +} + +static bool containsNewBackedge(MRT *Tree, + SmallPtrSet<MachineBasicBlock *, 8> &MBBs) { + // Need to traverse this in reverse since it is in post order. + if (Tree == nullptr) + return false; + + if (Tree->isMBB()) { + MachineBasicBlock *MBB = Tree->getMBBMRT()->getMBB(); + MBBs.insert(MBB); + if (mbbHasBackEdge(MBB, MBBs)) { + return true; + } + } else { + RegionMRT *Region = Tree->getRegionMRT(); + SetVector<MRT *> *Children = Region->getChildren(); + for (auto CI = Children->rbegin(), CE = Children->rend(); CI != CE; ++CI) { + if (containsNewBackedge(*CI, MBBs)) + return true; + } + } + return false; +} + +static bool containsNewBackedge(RegionMRT *Region) { + SmallPtrSet<MachineBasicBlock *, 8> MBBs; + return containsNewBackedge(Region, MBBs); +} + +bool AMDGPUMachineCFGStructurizer::structurizeComplexRegion(RegionMRT *Region) { + auto *LRegion = initLinearizedRegion(Region); + LRegion->setHasLoop(containsNewBackedge(Region)); + MachineBasicBlock *LastMerge = createLinearizedExitBlock(Region); + MachineBasicBlock *CurrentMerge = LastMerge; + LRegion->addMBB(LastMerge); + LRegion->setExit(LastMerge); + + rewriteRegionExitPHIs(Region, LastMerge, LRegion); + removeOldExitPreds(Region); + + DEBUG(PHIInfo.dump(MRI)); + + SetVector<MRT *> *Children = Region->getChildren(); + DEBUG(dbgs() << "===========If Region Start===============\n"); + if (LRegion->getHasLoop()) { + DEBUG(dbgs() << "Has Backedge: Yes\n"); + } else { + DEBUG(dbgs() << "Has Backedge: No\n"); + } + + unsigned BBSelectRegIn; + unsigned BBSelectRegOut; + for (auto CI = Children->begin(), CE = Children->end(); CI != CE; ++CI) { + DEBUG(dbgs() << "CurrentRegion: \n"); + DEBUG(LRegion->print(dbgs(), TRI)); + + auto CNI = CI; + ++CNI; + + MRT *Child = (*CI); + + if (Child->isRegion()) { + + LinearizedRegion *InnerLRegion = + Child->getRegionMRT()->getLinearizedRegion(); + // We found the block is the exit of an inner region, we need + // to put it in the current linearized region. + + DEBUG(dbgs() << "Linearizing region: "); + DEBUG(InnerLRegion->print(dbgs(), TRI)); + DEBUG(dbgs() << "\n"); + + MachineBasicBlock *InnerEntry = InnerLRegion->getEntry(); + if ((&(*(InnerEntry->getParent()->begin()))) == InnerEntry) { + // Entry has already been linearized, no need to do this region. + unsigned OuterSelect = InnerLRegion->getBBSelectRegOut(); + unsigned InnerSelectReg = + InnerLRegion->getRegionMRT()->getInnerOutputRegister(); + replaceRegisterWith(InnerSelectReg, OuterSelect), + resolvePHIInfos(InnerEntry); + if (!InnerLRegion->getExit()->isSuccessor(CurrentMerge)) + InnerLRegion->getExit()->addSuccessor(CurrentMerge); + continue; + } + + BBSelectRegOut = Child->getBBSelectRegOut(); + BBSelectRegIn = Child->getBBSelectRegIn(); + + DEBUG(dbgs() << "BBSelectRegIn: " << PrintReg(BBSelectRegIn, TRI) + << "\n"); + DEBUG(dbgs() << "BBSelectRegOut: " << PrintReg(BBSelectRegOut, TRI) + << "\n"); + + MachineBasicBlock *IfEnd = CurrentMerge; + CurrentMerge = createIfRegion(CurrentMerge, InnerLRegion, LRegion, + Child->getRegionMRT()->getEntry(), + BBSelectRegIn, BBSelectRegOut); + TII->convertNonUniformIfRegion(CurrentMerge, IfEnd); + } else { + MachineBasicBlock *MBB = Child->getMBBMRT()->getMBB(); + DEBUG(dbgs() << "Linearizing block: " << MBB->getNumber() << "\n"); + + if (MBB == getSingleExitNode(*(MBB->getParent()))) { + // If this is the exit block then we need to skip to the next. + // The "in" register will be transferred to "out" in the next + // iteration. + continue; + } + + BBSelectRegOut = Child->getBBSelectRegOut(); + BBSelectRegIn = Child->getBBSelectRegIn(); + + DEBUG(dbgs() << "BBSelectRegIn: " << PrintReg(BBSelectRegIn, TRI) + << "\n"); + DEBUG(dbgs() << "BBSelectRegOut: " << PrintReg(BBSelectRegOut, TRI) + << "\n"); + + MachineBasicBlock *IfEnd = CurrentMerge; + // This is a basic block that is not part of an inner region, we + // need to put it in the current linearized region. + CurrentMerge = createIfRegion(CurrentMerge, MBB, LRegion, BBSelectRegIn, + BBSelectRegOut); + if (CurrentMerge) { + TII->convertNonUniformIfRegion(CurrentMerge, IfEnd); + } + + DEBUG(PHIInfo.dump(MRI)); + } + } + + LRegion->removeFalseRegisterKills(MRI); + + if (LRegion->getHasLoop()) { + MachineBasicBlock *NewSucc = splitEntry(LRegion); + if (isFunctionEntryBlock(LRegion->getEntry())) { + resolvePHIInfos(LRegion->getEntry()); + } + const DebugLoc &DL = NewSucc->findDebugLoc(NewSucc->getFirstNonPHI()); + unsigned InReg = LRegion->getBBSelectRegIn(); + unsigned InnerSelectReg = + MRI->createVirtualRegister(MRI->getRegClass(InReg)); + unsigned NewInReg = MRI->createVirtualRegister(MRI->getRegClass(InReg)); + TII->materializeImmediate(*(LRegion->getEntry()), + LRegion->getEntry()->getFirstTerminator(), DL, + NewInReg, Region->getEntry()->getNumber()); + // Need to be careful about updating the registers inside the region. + LRegion->replaceRegisterInsideRegion(InReg, InnerSelectReg, false, MRI); + DEBUG(dbgs() << "Loop BBSelect Merge PHI:\n"); + insertMergePHI(LRegion->getEntry(), LRegion->getExit(), NewSucc, + InnerSelectReg, NewInReg, + LRegion->getRegionMRT()->getInnerOutputRegister()); + splitExit(LRegion); + TII->convertNonUniformLoopRegion(NewSucc, LastMerge); + } + + if (Region->isRoot()) { + TII->insertReturn(*LastMerge); + } + + DEBUG(Region->getEntry()->getParent()->dump()); + DEBUG(LRegion->print(dbgs(), TRI)); + DEBUG(PHIInfo.dump(MRI)); + + DEBUG(dbgs() << "===========If Region End===============\n"); + + Region->setLinearizedRegion(LRegion); + return true; +} + +bool AMDGPUMachineCFGStructurizer::structurizeRegion(RegionMRT *Region) { + if (false && regionIsSimpleIf(Region)) { + transformSimpleIfRegion(Region); + return true; + } else if (regionIsSequence(Region)) { + fixupRegionExits(Region); + return false; + } else { + structurizeComplexRegion(Region); + } + return false; +} + +static int structurize_once = 0; + +bool AMDGPUMachineCFGStructurizer::structurizeRegions(RegionMRT *Region, + bool isTopRegion) { + bool Changed = false; + + auto Children = Region->getChildren(); + for (auto CI : *Children) { + if (CI->isRegion()) { + Changed |= structurizeRegions(CI->getRegionMRT(), false); + } + } + + if (structurize_once < 2 || true) { + Changed |= structurizeRegion(Region); + structurize_once++; + } + return Changed; +} + +void AMDGPUMachineCFGStructurizer::initFallthroughMap(MachineFunction &MF) { + DEBUG(dbgs() << "Fallthrough Map:\n"); + for (auto &MBBI : MF) { + MachineBasicBlock *MBB = MBBI.getFallThrough(); + if (MBB != nullptr) { + DEBUG(dbgs() << "Fallthrough: " << MBBI.getNumber() << " -> " + << MBB->getNumber() << "\n"); + } + FallthroughMap[&MBBI] = MBB; + } +} + +void AMDGPUMachineCFGStructurizer::createLinearizedRegion(RegionMRT *Region, + unsigned SelectOut) { + LinearizedRegion *LRegion = new LinearizedRegion(); + if (SelectOut) { + LRegion->addLiveOut(SelectOut); + DEBUG(dbgs() << "Add LiveOut (BBSelect): " << PrintReg(SelectOut, TRI) + << "\n"); + } + LRegion->setRegionMRT(Region); + Region->setLinearizedRegion(LRegion); + LRegion->setParent(Region->getParent() + ? Region->getParent()->getLinearizedRegion() + : nullptr); +} + +unsigned +AMDGPUMachineCFGStructurizer::initializeSelectRegisters(MRT *MRT, unsigned SelectOut, + MachineRegisterInfo *MRI, + const SIInstrInfo *TII) { + if (MRT->isRegion()) { + RegionMRT *Region = MRT->getRegionMRT(); + Region->setBBSelectRegOut(SelectOut); + unsigned InnerSelectOut = createBBSelectReg(TII, MRI); + + // Fixme: Move linearization creation to the original spot + createLinearizedRegion(Region, SelectOut); + + for (auto CI = Region->getChildren()->begin(), + CE = Region->getChildren()->end(); + CI != CE; ++CI) { + InnerSelectOut = + initializeSelectRegisters((*CI), InnerSelectOut, MRI, TII); + } + MRT->setBBSelectRegIn(InnerSelectOut); + return InnerSelectOut; + } else { + MRT->setBBSelectRegOut(SelectOut); + unsigned NewSelectIn = createBBSelectReg(TII, MRI); + MRT->setBBSelectRegIn(NewSelectIn); + return NewSelectIn; + } +} + +static void checkRegOnlyPHIInputs(MachineFunction &MF) { + for (auto &MBBI : MF) { + for (MachineBasicBlock::instr_iterator I = MBBI.instr_begin(), + E = MBBI.instr_end(); + I != E; ++I) { + MachineInstr &Instr = *I; + if (Instr.isPHI()) { + int numPreds = getPHINumInputs(Instr); + for (int i = 0; i < numPreds; ++i) { + assert(Instr.getOperand(i * 2 + 1).isReg() && + "PHI Operand not a register"); + } + } + } + } +} + + +INITIALIZE_PASS_BEGIN(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer", + "AMDGPU Machine CFG Structurizer", false, false) +INITIALIZE_PASS_DEPENDENCY(MachineRegionInfoPass) +INITIALIZE_PASS_END(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer", + "AMDGPU Machine CFG Structurizer", false, false) + +char AMDGPUMachineCFGStructurizerID = AMDGPUMachineCFGStructurizer::ID; + + +bool AMDGPUMachineCFGStructurizer::runOnMachineFunction(MachineFunction &MF) { + const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); + const SIInstrInfo *TII = ST.getInstrInfo(); + TRI = ST.getRegisterInfo(); + MRI = &(MF.getRegInfo()); + initFallthroughMap(MF); + + checkRegOnlyPHIInputs(MF); + DEBUG(dbgs() << "----STRUCTURIZER START----\n"); + DEBUG(MF.dump()); + + Regions = &(getAnalysis<MachineRegionInfoPass>().getRegionInfo()); + DEBUG(Regions->dump()); + + RegionMRT *RTree = MRT::buildMRT(MF, Regions, TII, MRI); + setRegionMRT(RTree); + initializeSelectRegisters(RTree, 0, MRI, TII); + DEBUG(RTree->dump(TRI)); + bool result = structurizeRegions(RTree, true); + delete RTree; + DEBUG(dbgs() << "----STRUCTURIZER END----\n"); + initFallthroughMap(MF); + return result; +} + +FunctionPass *llvm::createAMDGPUMachineCFGStructurizerPass() { + return new AMDGPUMachineCFGStructurizer(); +} diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp index 36dcc699d4ea..e40f39557747 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp @@ -397,14 +397,17 @@ static Value* GEPToVectorIndex(GetElementPtrInst *GEP) { // instructions. static bool canVectorizeInst(Instruction *Inst, User *User) { switch (Inst->getOpcode()) { - case Instruction::Load: + case Instruction::Load: { + LoadInst *LI = cast<LoadInst>(Inst); + return !LI->isVolatile(); + } case Instruction::BitCast: case Instruction::AddrSpaceCast: return true; case Instruction::Store: { // Must be the stored pointer operand, not a stored value. StoreInst *SI = cast<StoreInst>(Inst); - return SI->getPointerOperand() == User; + return (SI->getPointerOperand() == User) && !SI->isVolatile(); } default: return false; diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp index 972c28579f7a..6e301b4ad527 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp @@ -125,6 +125,9 @@ AMDGPUSubtarget::AMDGPUSubtarget(const Triple &TT, StringRef GPU, StringRef FS, HasSDWA(false), HasDPP(false), FlatAddressSpace(false), + FlatInstOffsets(false), + FlatGlobalInsts(false), + FlatScratchInsts(false), R600ALUInst(false), CaymanISA(false), diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h b/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h index a5cda817ac11..bed7d326b3dd 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h @@ -145,6 +145,9 @@ protected: bool HasSDWA; bool HasDPP; bool FlatAddressSpace; + bool FlatInstOffsets; + bool FlatGlobalInsts; + bool FlatScratchInsts; bool R600ALUInst; bool CaymanISA; bool CFALUBug; @@ -380,6 +383,18 @@ public: return FlatAddressSpace; } + bool hasFlatInstOffsets() const { + return FlatInstOffsets; + } + + bool hasFlatGlobalInsts() const { + return FlatGlobalInsts; + } + + bool hasFlatScratchInsts() const { + return FlatScratchInsts; + } + bool isMesaKernel(const MachineFunction &MF) const { return isMesa3DOS() && !AMDGPU::isShader(MF.getFunction()->getCallingConv()); } diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp index cd5bad04d0b3..386a88b0520f 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp @@ -118,6 +118,13 @@ static cl::opt<bool> EnableSIInsertWaitcntsPass( cl::desc("Use new waitcnt insertion pass"), cl::init(false)); +// Option to run late CFG structurizer +static cl::opt<bool> LateCFGStructurize( + "amdgpu-late-structurize", + cl::desc("Enable late CFG structurization"), + cl::init(false), + cl::Hidden); + extern "C" void LLVMInitializeAMDGPUTarget() { // Register the target RegisterTargetMachine<R600TargetMachine> X(getTheAMDGPUTarget()); @@ -702,11 +709,15 @@ bool GCNPassConfig::addPreISel() { // Merge divergent exit nodes. StructurizeCFG won't recognize the multi-exit // regions formed by them. addPass(&AMDGPUUnifyDivergentExitNodesID); - addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions + if (!LateCFGStructurize) { + addPass(createStructurizeCFGPass(true)); // true -> SkipUniformRegions + } addPass(createSinkingPass()); addPass(createSITypeRewriter()); addPass(createAMDGPUAnnotateUniformValues()); - addPass(createSIAnnotateControlFlowPass()); + if (!LateCFGStructurize) { + addPass(createSIAnnotateControlFlowPass()); + } return false; } @@ -770,6 +781,9 @@ bool GCNPassConfig::addGlobalInstructionSelect() { #endif void GCNPassConfig::addPreRegAlloc() { + if (LateCFGStructurize) { + addPass(createAMDGPUMachineCFGStructurizerPass()); + } addPass(createSIWholeQuadModePass()); } diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp index c9482c37ec80..beafebc1284a 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp @@ -363,13 +363,22 @@ int AMDGPUTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, unsigned Index) { switch (Opcode) { case Instruction::ExtractElement: - case Instruction::InsertElement: + case Instruction::InsertElement: { + unsigned EltSize + = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); + if (EltSize < 32) { + if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) + return 0; + return BaseT::getVectorInstrCost(Opcode, ValTy, Index); + } + // Extracts are just reads of a subregister, so are free. Inserts are // considered free because we don't want to have any cost for scalarizing // operations, and we don't have to copy into a different register class. // Dynamic indexing isn't free and is best avoided. return Index == ~0u ? 2 : 0; + } default: return BaseT::getVectorInstrCost(Opcode, ValTy, Index); } @@ -479,3 +488,26 @@ bool AMDGPUTTIImpl::isSourceOfDivergence(const Value *V) const { return false; } + +unsigned AMDGPUTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, + Type *SubTp) { + if (ST->hasVOP3PInsts()) { + VectorType *VT = cast<VectorType>(Tp); + if (VT->getNumElements() == 2 && + DL.getTypeSizeInBits(VT->getElementType()) == 16) { + // With op_sel VOP3P instructions freely can access the low half or high + // half of a register, so any swizzle is free. + + switch (Kind) { + case TTI::SK_Broadcast: + case TTI::SK_Reverse: + case TTI::SK_PermuteSingleSrc: + return 0; + default: + break; + } + } + } + + return BaseT::getShuffleCost(Kind, Tp, Index, SubTp); +} diff --git a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h index 71d6306bc1a5..e0024e21e82b 100644 --- a/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h +++ b/contrib/llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.h @@ -114,6 +114,9 @@ public: } unsigned getVectorSplitCost() { return 0; } + + unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, + Type *SubTp); }; } // end namespace llvm diff --git a/contrib/llvm/lib/Target/AMDGPU/FLATInstructions.td b/contrib/llvm/lib/Target/AMDGPU/FLATInstructions.td index b0ac0e689a0b..8ba9efd42c70 100644 --- a/contrib/llvm/lib/Target/AMDGPU/FLATInstructions.td +++ b/contrib/llvm/lib/Target/AMDGPU/FLATInstructions.td @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// -def FLATAtomic : ComplexPattern<i64, 3, "SelectFlat">; +def FLATAtomic : ComplexPattern<i64, 2, "SelectFlat">; //===----------------------------------------------------------------------===// // FLAT classes @@ -62,7 +62,9 @@ class FLAT_Real <bits<7> op, FLAT_Pseudo ps> : bits<8> vdst; bits<1> slc; bits<1> glc; - bits<1> tfe; + + // We don't use tfe right now, and it was removed in gfx9. + bits<1> tfe = 0; // 15-0 is reserved. let Inst{16} = !if(ps.has_glc, glc, ps.glcValue); @@ -79,8 +81,8 @@ class FLAT_Real <bits<7> op, FLAT_Pseudo ps> : class FLAT_Load_Pseudo <string opName, RegisterClass regClass> : FLAT_Pseudo< opName, (outs regClass:$vdst), - (ins VReg_64:$vaddr, GLC:$glc, slc:$slc, tfe:$tfe), - " $vdst, $vaddr$glc$slc$tfe"> { + (ins VReg_64:$vaddr, GLC:$glc, slc:$slc), + " $vdst, $vaddr$glc$slc"> { let has_data = 0; let mayLoad = 1; } @@ -88,8 +90,8 @@ class FLAT_Load_Pseudo <string opName, RegisterClass regClass> : FLAT_Pseudo< class FLAT_Store_Pseudo <string opName, RegisterClass vdataClass> : FLAT_Pseudo< opName, (outs), - (ins VReg_64:$vaddr, vdataClass:$vdata, GLC:$glc, slc:$slc, tfe:$tfe), - " $vaddr, $vdata$glc$slc$tfe"> { + (ins VReg_64:$vaddr, vdataClass:$vdata, GLC:$glc, slc:$slc), + " $vaddr, $vdata$glc$slc"> { let mayLoad = 0; let mayStore = 1; let has_vdst = 0; @@ -105,8 +107,8 @@ multiclass FLAT_Atomic_Pseudo< def "" : FLAT_Pseudo <opName, (outs), - (ins VReg_64:$vaddr, data_rc:$vdata, slc:$slc, tfe:$tfe), - " $vaddr, $vdata$slc$tfe", + (ins VReg_64:$vaddr, data_rc:$vdata, slc:$slc), + " $vaddr, $vdata$slc", []>, AtomicNoRet <NAME, 0> { let mayLoad = 1; @@ -119,10 +121,10 @@ multiclass FLAT_Atomic_Pseudo< def _RTN : FLAT_Pseudo <opName, (outs vdst_rc:$vdst), - (ins VReg_64:$vaddr, data_rc:$vdata, slc:$slc, tfe:$tfe), - " $vdst, $vaddr, $vdata glc$slc$tfe", + (ins VReg_64:$vaddr, data_rc:$vdata, slc:$slc), + " $vdst, $vaddr, $vdata glc$slc", [(set vt:$vdst, - (atomic (FLATAtomic i64:$vaddr, i1:$slc, i1:$tfe), data_vt:$vdata))]>, + (atomic (FLATAtomic i64:$vaddr, i1:$slc), data_vt:$vdata))]>, AtomicNoRet <NAME, 1> { let mayLoad = 1; let mayStore = 1; @@ -311,30 +313,30 @@ def flat_truncstorei16 : flat_st <truncstorei16>; // Patterns for global loads with no offset. class FlatLoadPat <FLAT_Pseudo inst, SDPatternOperator node, ValueType vt> : Pat < (vt (node i64:$addr)), - (inst $addr, 0, 0, 0) + (inst $addr, 0, 0) >; class FlatLoadAtomicPat <FLAT_Pseudo inst, SDPatternOperator node, ValueType vt> : Pat < (vt (node i64:$addr)), - (inst $addr, 1, 0, 0) + (inst $addr, 1, 0) >; class FlatStorePat <FLAT_Pseudo inst, SDPatternOperator node, ValueType vt> : Pat < (node vt:$data, i64:$addr), - (inst $addr, $data, 0, 0, 0) + (inst $addr, $data, 0, 0) >; class FlatStoreAtomicPat <FLAT_Pseudo inst, SDPatternOperator node, ValueType vt> : Pat < // atomic store follows atomic binop convention so the address comes // first. (node i64:$addr, vt:$data), - (inst $addr, $data, 1, 0, 0) + (inst $addr, $data, 1, 0) >; class FlatAtomicPat <FLAT_Pseudo inst, SDPatternOperator node, ValueType vt, ValueType data_vt = vt> : Pat < (vt (node i64:$addr, data_vt:$data)), - (inst $addr, $data, 0, 0) + (inst $addr, $data, 0) >; let Predicates = [isCIVI] in { diff --git a/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp b/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp index bf16a8216001..8066428fe44a 100644 --- a/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.cpp @@ -27,7 +27,7 @@ void llvm::printLivesAt(SlotIndex SI, unsigned Num = 0; for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { const unsigned Reg = TargetRegisterInfo::index2VirtReg(I); - if (MRI.reg_nodbg_empty(Reg)) + if (!LIS.hasInterval(Reg)) continue; const auto &LI = LIS.getInterval(Reg); if (LI.hasSubRanges()) { @@ -131,13 +131,13 @@ bool GCNRegPressure::less(const SISubtarget &ST, const GCNRegPressure& O, unsigned MaxOccupancy) const { const auto SGPROcc = std::min(MaxOccupancy, - ST.getOccupancyWithNumSGPRs(getSGRPNum())); + ST.getOccupancyWithNumSGPRs(getSGPRNum())); const auto VGPROcc = std::min(MaxOccupancy, - ST.getOccupancyWithNumVGPRs(getVGRPNum())); + ST.getOccupancyWithNumVGPRs(getVGPRNum())); const auto OtherSGPROcc = std::min(MaxOccupancy, - ST.getOccupancyWithNumSGPRs(O.getSGRPNum())); + ST.getOccupancyWithNumSGPRs(O.getSGPRNum())); const auto OtherVGPROcc = std::min(MaxOccupancy, - ST.getOccupancyWithNumVGPRs(O.getVGRPNum())); + ST.getOccupancyWithNumVGPRs(O.getVGPRNum())); const auto Occ = std::min(SGPROcc, VGPROcc); const auto OtherOcc = std::min(OtherSGPROcc, OtherVGPROcc); @@ -167,17 +167,17 @@ bool GCNRegPressure::less(const SISubtarget &ST, return VW < OtherVW; } } - return SGPRImportant ? (getSGRPNum() < O.getSGRPNum()): - (getVGRPNum() < O.getVGRPNum()); + return SGPRImportant ? (getSGPRNum() < O.getSGPRNum()): + (getVGPRNum() < O.getVGPRNum()); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void GCNRegPressure::print(raw_ostream &OS, const SISubtarget *ST) const { - OS << "VGPRs: " << getVGRPNum(); - if (ST) OS << "(O" << ST->getOccupancyWithNumVGPRs(getVGRPNum()) << ')'; - OS << ", SGPRs: " << getSGRPNum(); - if (ST) OS << "(O" << ST->getOccupancyWithNumSGPRs(getSGRPNum()) << ')'; + OS << "VGPRs: " << getVGPRNum(); + if (ST) OS << "(O" << ST->getOccupancyWithNumVGPRs(getVGPRNum()) << ')'; + OS << ", SGPRs: " << getSGPRNum(); + if (ST) OS << "(O" << ST->getOccupancyWithNumSGPRs(getSGPRNum()) << ')'; OS << ", LVGPR WT: " << getVGPRTuplesWeight() << ", LSGPR WT: " << getSGPRTuplesWeight(); if (ST) OS << " -> Occ: " << getOccupancy(*ST); @@ -192,7 +192,6 @@ LaneBitmask llvm::getLiveLaneMask(unsigned Reg, SlotIndex SI, const LiveIntervals &LIS, const MachineRegisterInfo &MRI) { - assert(!MRI.reg_nodbg_empty(Reg)); LaneBitmask LiveMask; const auto &LI = LIS.getInterval(Reg); if (LI.hasSubRanges()) { @@ -214,7 +213,7 @@ GCNRPTracker::LiveRegSet llvm::getLiveRegs(SlotIndex SI, GCNRPTracker::LiveRegSet LiveRegs; for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { auto Reg = TargetRegisterInfo::index2VirtReg(I); - if (MRI.reg_nodbg_empty(Reg)) + if (!LIS.hasInterval(Reg)) continue; auto LiveMask = getLiveLaneMask(Reg, SI, LIS, MRI); if (LiveMask.any()) @@ -223,13 +222,7 @@ GCNRPTracker::LiveRegSet llvm::getLiveRegs(SlotIndex SI, return LiveRegs; } -void GCNUpwardRPTracker::reset(const MachineInstr &MI) { - MRI = &MI.getParent()->getParent()->getRegInfo(); - LiveRegs = getLiveRegsAfter(MI, LIS); - MaxPressure = CurPressure = getRegPressure(*MRI, LiveRegs); -} - -LaneBitmask GCNUpwardRPTracker::getDefRegMask(const MachineOperand &MO) const { +LaneBitmask GCNRPTracker::getDefRegMask(const MachineOperand &MO) const { assert(MO.isDef() && MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())); @@ -241,7 +234,7 @@ LaneBitmask GCNUpwardRPTracker::getDefRegMask(const MachineOperand &MO) const { MRI->getTargetRegisterInfo()->getSubRegIndexLaneMask(MO.getSubReg()); } -LaneBitmask GCNUpwardRPTracker::getUsedRegMask(const MachineOperand &MO) const { +LaneBitmask GCNRPTracker::getUsedRegMask(const MachineOperand &MO) const { assert(MO.isUse() && MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())); @@ -259,6 +252,18 @@ LaneBitmask GCNUpwardRPTracker::getUsedRegMask(const MachineOperand &MO) const { return getLiveLaneMask(MO.getReg(), SI, LIS, *MRI); } +void GCNUpwardRPTracker::reset(const MachineInstr &MI, + const LiveRegSet *LiveRegsCopy) { + MRI = &MI.getParent()->getParent()->getRegInfo(); + if (LiveRegsCopy) { + if (&LiveRegs != LiveRegsCopy) + LiveRegs = *LiveRegsCopy; + } else { + LiveRegs = getLiveRegsAfter(MI, LIS); + } + MaxPressure = CurPressure = getRegPressure(*MRI, LiveRegs); +} + void GCNUpwardRPTracker::recede(const MachineInstr &MI) { assert(MRI && "call reset first"); @@ -297,6 +302,100 @@ void GCNUpwardRPTracker::recede(const MachineInstr &MI) { MaxPressure = max(MaxPressure, CurPressure); } +bool GCNDownwardRPTracker::reset(const MachineInstr &MI, + const LiveRegSet *LiveRegsCopy) { + MRI = &MI.getParent()->getParent()->getRegInfo(); + LastTrackedMI = nullptr; + MBBEnd = MI.getParent()->end(); + NextMI = &MI; + NextMI = skipDebugInstructionsForward(NextMI, MBBEnd); + if (NextMI == MBBEnd) + return false; + if (LiveRegsCopy) { + if (&LiveRegs != LiveRegsCopy) + LiveRegs = *LiveRegsCopy; + } else { + LiveRegs = getLiveRegsBefore(*NextMI, LIS); + } + MaxPressure = CurPressure = getRegPressure(*MRI, LiveRegs); + return true; +} + +bool GCNDownwardRPTracker::advanceBeforeNext() { + assert(MRI && "call reset first"); + + NextMI = skipDebugInstructionsForward(NextMI, MBBEnd); + if (NextMI == MBBEnd) + return false; + + SlotIndex SI = LIS.getInstructionIndex(*NextMI).getBaseIndex(); + assert(SI.isValid()); + + // Remove dead registers or mask bits. + for (auto &It : LiveRegs) { + const LiveInterval &LI = LIS.getInterval(It.first); + if (LI.hasSubRanges()) { + for (const auto &S : LI.subranges()) { + if (!S.liveAt(SI)) { + auto PrevMask = It.second; + It.second &= ~S.LaneMask; + CurPressure.inc(It.first, PrevMask, It.second, *MRI); + } + } + } else if (!LI.liveAt(SI)) { + auto PrevMask = It.second; + It.second = LaneBitmask::getNone(); + CurPressure.inc(It.first, PrevMask, It.second, *MRI); + } + if (It.second.none()) + LiveRegs.erase(It.first); + } + + MaxPressure = max(MaxPressure, CurPressure); + + return true; +} + +void GCNDownwardRPTracker::advanceToNext() { + LastTrackedMI = &*NextMI++; + + // Add new registers or mask bits. + for (const auto &MO : LastTrackedMI->defs()) { + if (!MO.isReg()) + continue; + unsigned Reg = MO.getReg(); + if (!TargetRegisterInfo::isVirtualRegister(Reg)) + continue; + auto &LiveMask = LiveRegs[Reg]; + auto PrevMask = LiveMask; + LiveMask |= getDefRegMask(MO); + CurPressure.inc(Reg, PrevMask, LiveMask, *MRI); + } + + MaxPressure = max(MaxPressure, CurPressure); +} + +bool GCNDownwardRPTracker::advance() { + // If we have just called reset live set is actual. + if ((NextMI == MBBEnd) || (LastTrackedMI && !advanceBeforeNext())) + return false; + advanceToNext(); + return true; +} + +bool GCNDownwardRPTracker::advance(MachineBasicBlock::const_iterator End) { + while (NextMI != End) + if (!advance()) return false; + return true; +} + +bool GCNDownwardRPTracker::advance(MachineBasicBlock::const_iterator Begin, + MachineBasicBlock::const_iterator End, + const LiveRegSet *LiveRegsCopy) { + reset(*Begin, LiveRegsCopy); + return advance(End); +} + #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD static void reportMismatch(const GCNRPTracker::LiveRegSet &LISLR, @@ -352,4 +451,16 @@ bool GCNUpwardRPTracker::isValid() const { return true; } +void GCNRPTracker::printLiveRegs(raw_ostream &OS, const LiveRegSet& LiveRegs, + const MachineRegisterInfo &MRI) { + const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo(); + for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { + unsigned Reg = TargetRegisterInfo::index2VirtReg(I); + auto It = LiveRegs.find(Reg); + if (It != LiveRegs.end() && It->second.any()) + OS << ' ' << PrintVRegOrUnit(Reg, TRI) << ':' + << PrintLaneMask(It->second); + } + OS << '\n'; +} #endif diff --git a/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.h b/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.h index 82e76a7bfddc..9875ca6a6d16 100644 --- a/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.h +++ b/contrib/llvm/lib/Target/AMDGPU/GCNRegPressure.h @@ -33,19 +33,19 @@ struct GCNRegPressure { clear(); } - bool empty() const { return getSGRPNum() == 0 && getVGRPNum() == 0; } + bool empty() const { return getSGPRNum() == 0 && getVGPRNum() == 0; } void clear() { std::fill(&Value[0], &Value[TOTAL_KINDS], 0); } - unsigned getSGRPNum() const { return Value[SGPR32]; } - unsigned getVGRPNum() const { return Value[VGPR32]; } + unsigned getSGPRNum() const { return Value[SGPR32]; } + unsigned getVGPRNum() const { return Value[VGPR32]; } unsigned getVGPRTuplesWeight() const { return Value[VGPR_TUPLE]; } unsigned getSGPRTuplesWeight() const { return Value[SGPR_TUPLE]; } unsigned getOccupancy(const SISubtarget &ST) const { - return std::min(ST.getOccupancyWithNumSGPRs(getSGRPNum()), - ST.getOccupancyWithNumVGPRs(getVGRPNum())); + return std::min(ST.getOccupancyWithNumSGPRs(getSGPRNum()), + ST.getOccupancyWithNumVGPRs(getVGPRNum())); } void inc(unsigned Reg, @@ -92,16 +92,21 @@ public: typedef DenseMap<unsigned, LaneBitmask> LiveRegSet; protected: + const LiveIntervals &LIS; LiveRegSet LiveRegs; GCNRegPressure CurPressure, MaxPressure; const MachineInstr *LastTrackedMI = nullptr; mutable const MachineRegisterInfo *MRI = nullptr; - GCNRPTracker() {} + GCNRPTracker(const LiveIntervals &LIS_) : LIS(LIS_) {} + LaneBitmask getDefRegMask(const MachineOperand &MO) const; + LaneBitmask getUsedRegMask(const MachineOperand &MO) const; public: // live regs for the current state const decltype(LiveRegs) &getLiveRegs() const { return LiveRegs; } const MachineInstr *getLastTrackedMI() const { return LastTrackedMI; } + void clearMaxPressure() { MaxPressure.clear(); } + // returns MaxPressure, resetting it decltype(MaxPressure) moveMaxPressure() { auto Res = MaxPressure; @@ -111,17 +116,16 @@ public: decltype(LiveRegs) moveLiveRegs() { return std::move(LiveRegs); } + static void printLiveRegs(raw_ostream &OS, const LiveRegSet& LiveRegs, + const MachineRegisterInfo &MRI); }; class GCNUpwardRPTracker : public GCNRPTracker { - const LiveIntervals &LIS; - LaneBitmask getDefRegMask(const MachineOperand &MO) const; - LaneBitmask getUsedRegMask(const MachineOperand &MO) const; public: - GCNUpwardRPTracker(const LiveIntervals &LIS_) : LIS(LIS_) {} + GCNUpwardRPTracker(const LiveIntervals &LIS_) : GCNRPTracker(LIS_) {} // reset tracker to the point just below MI // filling live regs upon this point using LIS - void reset(const MachineInstr &MI); + void reset(const MachineInstr &MI, const LiveRegSet *LiveRegs = nullptr); // move to the state just above the MI void recede(const MachineInstr &MI); @@ -131,6 +135,41 @@ public: bool isValid() const; }; +class GCNDownwardRPTracker : public GCNRPTracker { + // Last position of reset or advanceBeforeNext + MachineBasicBlock::const_iterator NextMI; + + MachineBasicBlock::const_iterator MBBEnd; + +public: + GCNDownwardRPTracker(const LiveIntervals &LIS_) : GCNRPTracker(LIS_) {} + + const MachineBasicBlock::const_iterator getNext() const { return NextMI; } + + // Reset tracker to the point before the MI + // filling live regs upon this point using LIS. + // Returns false if block is empty except debug values. + bool reset(const MachineInstr &MI, const LiveRegSet *LiveRegs = nullptr); + + // Move to the state right before the next MI. Returns false if reached + // end of the block. + bool advanceBeforeNext(); + + // Move to the state at the MI, advanceBeforeNext has to be called first. + void advanceToNext(); + + // Move to the state at the next MI. Returns false if reached end of block. + bool advance(); + + // Advance instructions until before End. + bool advance(MachineBasicBlock::const_iterator End); + + // Reset to Begin and advance to End. + bool advance(MachineBasicBlock::const_iterator Begin, + MachineBasicBlock::const_iterator End, + const LiveRegSet *LiveRegsCopy = nullptr); +}; + LaneBitmask getLiveLaneMask(unsigned Reg, SlotIndex SI, const LiveIntervals &LIS, diff --git a/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp b/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp index 630442625aa3..8ec46665daf5 100644 --- a/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp @@ -316,46 +316,57 @@ GCNScheduleDAGMILive::GCNScheduleDAGMILive(MachineSchedContext *C, MFI(*MF.getInfo<SIMachineFunctionInfo>()), StartingOccupancy(ST.getOccupancyWithLocalMemSize(MFI.getLDSSize(), *MF.getFunction())), - MinOccupancy(StartingOccupancy), Stage(0) { + MinOccupancy(StartingOccupancy), Stage(0), RegionIdx(0) { DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n"); } void GCNScheduleDAGMILive::schedule() { + if (Stage == 0) { + // Just record regions at the first pass. + Regions.push_back(std::make_pair(RegionBegin, RegionEnd)); + return; + } + std::vector<MachineInstr*> Unsched; Unsched.reserve(NumRegionInstrs); for (auto &I : *this) Unsched.push_back(&I); - std::pair<unsigned, unsigned> PressureBefore; + GCNRegPressure PressureBefore; if (LIS) { - DEBUG(dbgs() << "Pressure before scheduling:\n"); - discoverLiveIns(); - PressureBefore = getRealRegPressure(); + PressureBefore = Pressure[RegionIdx]; + + DEBUG(dbgs() << "Pressure before scheduling:\nRegion live-ins:"; + GCNRPTracker::printLiveRegs(dbgs(), LiveIns[RegionIdx], MRI); + dbgs() << "Region live-in pressure: "; + llvm::getRegPressure(MRI, LiveIns[RegionIdx]).print(dbgs()); + dbgs() << "Region register pressure: "; + PressureBefore.print(dbgs())); } ScheduleDAGMILive::schedule(); - if (Stage == 0) - Regions.push_back(std::make_pair(RegionBegin, RegionEnd)); + Regions[RegionIdx] = std::make_pair(RegionBegin, RegionEnd); if (!LIS) return; // Check the results of scheduling. GCNMaxOccupancySchedStrategy &S = (GCNMaxOccupancySchedStrategy&)*SchedImpl; - DEBUG(dbgs() << "Pressure after scheduling:\n"); auto PressureAfter = getRealRegPressure(); - LiveIns.clear(); - if (PressureAfter.first <= S.SGPRCriticalLimit && - PressureAfter.second <= S.VGPRCriticalLimit) { + DEBUG(dbgs() << "Pressure after scheduling: "; PressureAfter.print(dbgs())); + + if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit && + PressureAfter.getVGPRNum() <= S.VGPRCriticalLimit) { + Pressure[RegionIdx] = PressureAfter; DEBUG(dbgs() << "Pressure in desired limits, done.\n"); return; } - unsigned WavesAfter = getMaxWaves(PressureAfter.first, - PressureAfter.second, MF); - unsigned WavesBefore = getMaxWaves(PressureBefore.first, - PressureBefore.second, MF); + unsigned WavesAfter = getMaxWaves(PressureAfter.getSGPRNum(), + PressureAfter.getVGPRNum(), MF); + unsigned WavesBefore = getMaxWaves(PressureBefore.getSGPRNum(), + PressureBefore.getVGPRNum(), MF); DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore << ", after " << WavesAfter << ".\n"); @@ -368,8 +379,10 @@ void GCNScheduleDAGMILive::schedule() { << MinOccupancy << ".\n"); } - if (WavesAfter >= WavesBefore) + if (WavesAfter >= WavesBefore) { + Pressure[RegionIdx] = PressureAfter; return; + } DEBUG(dbgs() << "Attempting to revert scheduling.\n"); RegionEnd = RegionBegin; @@ -398,166 +411,139 @@ void GCNScheduleDAGMILive::schedule() { DEBUG(dbgs() << "Scheduling " << *MI); } RegionBegin = Unsched.front()->getIterator(); - if (Stage == 0) - Regions.back() = std::make_pair(RegionBegin, RegionEnd); + Regions[RegionIdx] = std::make_pair(RegionBegin, RegionEnd); placeDebugValues(); } -static inline void setMask(const MachineRegisterInfo &MRI, - const SIRegisterInfo *SRI, unsigned Reg, - LaneBitmask &PrevMask, LaneBitmask NewMask, - unsigned &SGPRs, unsigned &VGPRs) { - int NewRegs = countPopulation(NewMask.getAsInteger()) - - countPopulation(PrevMask.getAsInteger()); - if (SRI->isSGPRReg(MRI, Reg)) - SGPRs += NewRegs; - if (SRI->isVGPR(MRI, Reg)) - VGPRs += NewRegs; - assert ((int)SGPRs >= 0 && (int)VGPRs >= 0); - PrevMask = NewMask; +GCNRegPressure GCNScheduleDAGMILive::getRealRegPressure() const { + GCNDownwardRPTracker RPTracker(*LIS); + RPTracker.advance(begin(), end(), &LiveIns[RegionIdx]); + return RPTracker.moveMaxPressure(); } -void GCNScheduleDAGMILive::discoverLiveIns() { - unsigned SGPRs = 0; - unsigned VGPRs = 0; +void GCNScheduleDAGMILive::computeBlockPressure(const MachineBasicBlock *MBB) { + GCNDownwardRPTracker RPTracker(*LIS); + + // If the block has the only successor then live-ins of that successor are + // live-outs of the current block. We can reuse calculated live set if the + // successor will be sent to scheduling past current block. + const MachineBasicBlock *OnlySucc = nullptr; + if (MBB->succ_size() == 1 && !(*MBB->succ_begin())->empty()) { + SlotIndexes *Ind = LIS->getSlotIndexes(); + if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(*MBB->succ_begin())) + OnlySucc = *MBB->succ_begin(); + } - auto &MI = *begin()->getParent()->getFirstNonDebugInstr(); - const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo*>(TRI); - SlotIndex SI = LIS->getInstructionIndex(MI).getBaseIndex(); - assert (SI.isValid()); - - DEBUG(dbgs() << "Region live-ins:"); - for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { - unsigned Reg = TargetRegisterInfo::index2VirtReg(I); - if (MRI.reg_nodbg_empty(Reg)) - continue; - const LiveInterval &LI = LIS->getInterval(Reg); - LaneBitmask LaneMask = LaneBitmask::getNone(); - if (LI.hasSubRanges()) { - for (const auto &S : LI.subranges()) - if (S.liveAt(SI)) - LaneMask |= S.LaneMask; - } else if (LI.liveAt(SI)) { - LaneMask = MRI.getMaxLaneMaskForVReg(Reg); - } + // Scheduler sends regions from the end of the block upwards. + size_t CurRegion = RegionIdx; + for (size_t E = Regions.size(); CurRegion != E; ++CurRegion) + if (Regions[CurRegion].first->getParent() != MBB) + break; + --CurRegion; + + auto I = MBB->begin(); + auto LiveInIt = MBBLiveIns.find(MBB); + if (LiveInIt != MBBLiveIns.end()) { + auto LiveIn = std::move(LiveInIt->second); + RPTracker.reset(*MBB->begin(), &LiveIn); + MBBLiveIns.erase(LiveInIt); + } else { + I = Regions[CurRegion].first; + RPTracker.reset(*I); + } - if (LaneMask.any()) { - setMask(MRI, SRI, Reg, LiveIns[Reg], LaneMask, SGPRs, VGPRs); + for ( ; ; ) { + I = RPTracker.getNext(); - DEBUG(dbgs() << ' ' << PrintVRegOrUnit(Reg, SRI) << ':' - << PrintLaneMask(LiveIns[Reg])); + if (Regions[CurRegion].first == I) { + LiveIns[CurRegion] = RPTracker.getLiveRegs(); + RPTracker.clearMaxPressure(); } - } - LiveInPressure = std::make_pair(SGPRs, VGPRs); + if (Regions[CurRegion].second == I) { + Pressure[CurRegion] = RPTracker.moveMaxPressure(); + if (CurRegion-- == RegionIdx) + break; + } + RPTracker.advanceToNext(); + RPTracker.advanceBeforeNext(); + } - DEBUG(dbgs() << "\nLive-in pressure:\nSGPR = " << SGPRs - << "\nVGPR = " << VGPRs << '\n'); + if (OnlySucc) { + if (I != MBB->end()) { + RPTracker.advanceToNext(); + RPTracker.advance(MBB->end()); + } + RPTracker.reset(*OnlySucc->begin(), &RPTracker.getLiveRegs()); + RPTracker.advanceBeforeNext(); + MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs(); + } } -std::pair<unsigned, unsigned> -GCNScheduleDAGMILive::getRealRegPressure() const { - unsigned SGPRs, MaxSGPRs, VGPRs, MaxVGPRs; - SGPRs = MaxSGPRs = LiveInPressure.first; - VGPRs = MaxVGPRs = LiveInPressure.second; - - const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo*>(TRI); - DenseMap<unsigned, LaneBitmask> LiveRegs(LiveIns); +void GCNScheduleDAGMILive::finalizeSchedule() { + GCNMaxOccupancySchedStrategy &S = (GCNMaxOccupancySchedStrategy&)*SchedImpl; + DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n"); - for (const MachineInstr &MI : *this) { - if (MI.isDebugValue()) - continue; - SlotIndex SI = LIS->getInstructionIndex(MI).getBaseIndex(); - assert (SI.isValid()); + LiveIns.resize(Regions.size()); + Pressure.resize(Regions.size()); - // Remove dead registers or mask bits. - for (auto &It : LiveRegs) { - if (It.second.none()) - continue; - const LiveInterval &LI = LIS->getInterval(It.first); - if (LI.hasSubRanges()) { - for (const auto &S : LI.subranges()) - if (!S.liveAt(SI)) - setMask(MRI, SRI, It.first, It.second, It.second & ~S.LaneMask, - SGPRs, VGPRs); - } else if (!LI.liveAt(SI)) { - setMask(MRI, SRI, It.first, It.second, LaneBitmask::getNone(), - SGPRs, VGPRs); - } - } + do { + Stage++; + RegionIdx = 0; + MachineBasicBlock *MBB = nullptr; - // Add new registers or mask bits. - for (const auto &MO : MI.defs()) { - if (!MO.isReg()) - continue; - unsigned Reg = MO.getReg(); - if (!TargetRegisterInfo::isVirtualRegister(Reg)) - continue; - unsigned SubRegIdx = MO.getSubReg(); - LaneBitmask LaneMask = SubRegIdx != 0 - ? TRI->getSubRegIndexLaneMask(SubRegIdx) - : MRI.getMaxLaneMaskForVReg(Reg); - LaneBitmask &LM = LiveRegs[Reg]; - setMask(MRI, SRI, Reg, LM, LM | LaneMask, SGPRs, VGPRs); - } - MaxSGPRs = std::max(MaxSGPRs, SGPRs); - MaxVGPRs = std::max(MaxVGPRs, VGPRs); - } + if (Stage > 1) { + // Retry function scheduling if we found resulting occupancy and it is + // lower than used for first pass scheduling. This will give more freedom + // to schedule low register pressure blocks. + // Code is partially copied from MachineSchedulerBase::scheduleRegions(). - DEBUG(dbgs() << "Real region's register pressure:\nSGPR = " << MaxSGPRs - << "\nVGPR = " << MaxVGPRs << '\n'); + if (!LIS || StartingOccupancy <= MinOccupancy) + break; - return std::make_pair(MaxSGPRs, MaxVGPRs); -} + DEBUG(dbgs() + << "Retrying function scheduling with lowest recorded occupancy " + << MinOccupancy << ".\n"); -void GCNScheduleDAGMILive::finalizeSchedule() { - // Retry function scheduling if we found resulting occupancy and it is - // lower than used for first pass scheduling. This will give more freedom - // to schedule low register pressure blocks. - // Code is partially copied from MachineSchedulerBase::scheduleRegions(). + S.setTargetOccupancy(MinOccupancy); + } - if (!LIS || StartingOccupancy <= MinOccupancy) - return; + for (auto Region : Regions) { + RegionBegin = Region.first; + RegionEnd = Region.second; - DEBUG(dbgs() << "Retrying function scheduling with lowest recorded occupancy " - << MinOccupancy << ".\n"); + if (RegionBegin->getParent() != MBB) { + if (MBB) finishBlock(); + MBB = RegionBegin->getParent(); + startBlock(MBB); + if (Stage == 1) + computeBlockPressure(MBB); + } - Stage++; - GCNMaxOccupancySchedStrategy &S = (GCNMaxOccupancySchedStrategy&)*SchedImpl; - S.setTargetOccupancy(MinOccupancy); + unsigned NumRegionInstrs = std::distance(begin(), end()); + enterRegion(MBB, begin(), end(), NumRegionInstrs); - MachineBasicBlock *MBB = nullptr; - for (auto Region : Regions) { - RegionBegin = Region.first; - RegionEnd = Region.second; + // Skip empty scheduling regions (0 or 1 schedulable instructions). + if (begin() == end() || begin() == std::prev(end())) { + exitRegion(); + continue; + } - if (RegionBegin->getParent() != MBB) { - if (MBB) finishBlock(); - MBB = RegionBegin->getParent(); - startBlock(MBB); - } + DEBUG(dbgs() << "********** MI Scheduling **********\n"); + DEBUG(dbgs() << MF.getName() + << ":BB#" << MBB->getNumber() << " " << MBB->getName() + << "\n From: " << *begin() << " To: "; + if (RegionEnd != MBB->end()) dbgs() << *RegionEnd; + else dbgs() << "End"; + dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n'); - unsigned NumRegionInstrs = std::distance(begin(), end()); - enterRegion(MBB, begin(), end(), NumRegionInstrs); + schedule(); - // Skip empty scheduling regions (0 or 1 schedulable instructions). - if (begin() == end() || begin() == std::prev(end())) { exitRegion(); - continue; + ++RegionIdx; } - DEBUG(dbgs() << "********** MI Scheduling **********\n"); - DEBUG(dbgs() << MF.getName() - << ":BB#" << MBB->getNumber() << " " << MBB->getName() - << "\n From: " << *begin() << " To: "; - if (RegionEnd != MBB->end()) dbgs() << *RegionEnd; - else dbgs() << "End"; - dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n'); + finishBlock(); - schedule(); - - exitRegion(); - } - finishBlock(); - LiveIns.shrink_and_clear(); + } while (Stage < 2); } diff --git a/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h b/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h index 15af232704ff..3ed3cd5b3b1c 100644 --- a/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h +++ b/contrib/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h @@ -14,6 +14,7 @@ #ifndef LLVM_LIB_TARGET_AMDGPU_GCNSCHEDSTRATEGY_H #define LLVM_LIB_TARGET_AMDGPU_GCNSCHEDSTRATEGY_H +#include "GCNRegPressure.h" #include "llvm/CodeGen/MachineScheduler.h" namespace llvm { @@ -74,21 +75,28 @@ class GCNScheduleDAGMILive : public ScheduleDAGMILive { // Scheduling stage number. unsigned Stage; + // Current region index. + size_t RegionIdx; + // Vecor of regions recorder for later rescheduling SmallVector<std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>, 32> Regions; - // Region live-ins. - DenseMap<unsigned, LaneBitmask> LiveIns; + // Region live-in cache. + SmallVector<GCNRPTracker::LiveRegSet, 32> LiveIns; + + // Region pressure cache. + SmallVector<GCNRegPressure, 32> Pressure; + + // Temporary basic block live-in cache. + DenseMap<const MachineBasicBlock*, GCNRPTracker::LiveRegSet> MBBLiveIns; - // Number of live-ins to the current region, first SGPR then VGPR. - std::pair<unsigned, unsigned> LiveInPressure; + // Return current region pressure. + GCNRegPressure getRealRegPressure() const; - // Collect current region live-ins. - void discoverLiveIns(); + // Compute and cache live-ins and pressure for all regions in block. + void computeBlockPressure(const MachineBasicBlock *MBB); - // Return current region pressure. First value is SGPR number, second is VGPR. - std::pair<unsigned, unsigned> getRealRegPressure() const; public: GCNScheduleDAGMILive(MachineSchedContext *C, diff --git a/contrib/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp b/contrib/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp index d8cb98fe1b19..8cb35c506135 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp @@ -126,7 +126,7 @@ bool SIAnnotateControlFlow::doInitialization(Module &M) { Void = Type::getVoidTy(Context); Boolean = Type::getInt1Ty(Context); Int64 = Type::getInt64Ty(Context); - ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr); + ReturnStruct = StructType::get(Boolean, Int64); BoolTrue = ConstantInt::getTrue(Context); BoolFalse = ConstantInt::getFalse(Context); diff --git a/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.cpp b/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.cpp index cc93c27731ff..48a14e4dbea2 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.cpp @@ -488,6 +488,7 @@ SITargetLowering::SITargetLowering(const TargetMachine &TM, setTargetDAGCombine(ISD::FCANONICALIZE); setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); setTargetDAGCombine(ISD::ZERO_EXTEND); + setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); // All memory operations. Some folding on the pointer operand is done to help // matching the constant offsets in the addressing modes. @@ -2003,6 +2004,7 @@ MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( break; } assert(Found); + (void)Found; // This should be before all vector instructions. BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) @@ -4604,6 +4606,24 @@ SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, return SDValue(); } +SDValue SITargetLowering::performExtractVectorEltCombine( + SDNode *N, DAGCombinerInfo &DCI) const { + SDValue Vec = N->getOperand(0); + + SelectionDAG &DAG= DCI.DAG; + if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { + SDLoc SL(N); + EVT EltVT = N->getValueType(0); + SDValue Idx = N->getOperand(1); + SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, + Vec.getOperand(0), Idx); + return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); + } + + return SDValue(); +} + + unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, const SDNode *N0, const SDNode *N1) const { @@ -4891,6 +4911,8 @@ SDValue SITargetLowering::PerformDAGCombine(SDNode *N, break; } + case ISD::EXTRACT_VECTOR_ELT: + return performExtractVectorEltCombine(N, DCI); } return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); } diff --git a/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.h b/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.h index d177777ad5ee..046e677756d1 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.h +++ b/contrib/llvm/lib/Target/AMDGPU/SIISelLowering.h @@ -100,6 +100,7 @@ class SITargetLowering final : public AMDGPUTargetLowering { SDValue performMinMaxCombine(SDNode *N, DAGCombinerInfo &DCI) const; SDValue performFMed3Combine(SDNode *N, DAGCombinerInfo &DCI) const; SDValue performCvtPkRTZCombine(SDNode *N, DAGCombinerInfo &DCI) const; + SDValue performExtractVectorEltCombine(SDNode *N, DAGCombinerInfo &DCI) const; unsigned getFusedOpcode(const SelectionDAG &DAG, const SDNode *N0, const SDNode *N1) const; diff --git a/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp index 92e452a3d6a0..065fd09eb356 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp +++ b/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp @@ -496,6 +496,188 @@ int SIInstrInfo::commuteOpcode(unsigned Opcode) const { return Opcode; } +void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB, + MachineBasicBlock::iterator MI, + const DebugLoc &DL, unsigned DestReg, + int64_t Value) const { + MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); + const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg); + if (RegClass == &AMDGPU::SReg_32RegClass || + RegClass == &AMDGPU::SGPR_32RegClass || + RegClass == &AMDGPU::SReg_32_XM0RegClass || + RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) { + BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg) + .addImm(Value); + return; + } + + if (RegClass == &AMDGPU::SReg_64RegClass || + RegClass == &AMDGPU::SGPR_64RegClass || + RegClass == &AMDGPU::SReg_64_XEXECRegClass) { + BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg) + .addImm(Value); + return; + } + + if (RegClass == &AMDGPU::VGPR_32RegClass) { + BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg) + .addImm(Value); + return; + } + if (RegClass == &AMDGPU::VReg_64RegClass) { + BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg) + .addImm(Value); + return; + } + + unsigned EltSize = 4; + unsigned Opcode = AMDGPU::V_MOV_B32_e32; + if (RI.isSGPRClass(RegClass)) { + if (RI.getRegSizeInBits(*RegClass) > 32) { + Opcode = AMDGPU::S_MOV_B64; + EltSize = 8; + } else { + Opcode = AMDGPU::S_MOV_B32; + EltSize = 4; + } + } + + ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize); + for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) { + int64_t IdxValue = Idx == 0 ? Value : 0; + + MachineInstrBuilder Builder = BuildMI(MBB, MI, DL, + get(Opcode), RI.getSubReg(DestReg, Idx)); + Builder.addImm(IdxValue); + } +} + +const TargetRegisterClass * +SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const { + return &AMDGPU::VGPR_32RegClass; +} + +void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB, + MachineBasicBlock::iterator I, + const DebugLoc &DL, unsigned DstReg, + ArrayRef<MachineOperand> Cond, + unsigned TrueReg, + unsigned FalseReg) const { + MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); + assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass && + "Not a VGPR32 reg"); + + if (Cond.size() == 1) { + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .add(Cond[0]); + } else if (Cond.size() == 2) { + assert(Cond[0].isImm() && "Cond[0] is not an immediate"); + switch (Cond[0].getImm()) { + case SIInstrInfo::SCC_TRUE: { + unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg) + .addImm(-1) + .addImm(0); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .addReg(SReg); + break; + } + case SIInstrInfo::SCC_FALSE: { + unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg) + .addImm(0) + .addImm(-1); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .addReg(SReg); + break; + } + case SIInstrInfo::VCCNZ: { + MachineOperand RegOp = Cond[1]; + RegOp.setImplicit(false); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .add(RegOp); + break; + } + case SIInstrInfo::VCCZ: { + MachineOperand RegOp = Cond[1]; + RegOp.setImplicit(false); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(TrueReg) + .addReg(FalseReg) + .add(RegOp); + break; + } + case SIInstrInfo::EXECNZ: { + unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2) + .addImm(0); + BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg) + .addImm(-1) + .addImm(0); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .addReg(SReg); + break; + } + case SIInstrInfo::EXECZ: { + unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2) + .addImm(0); + BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg) + .addImm(0) + .addImm(-1); + BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg) + .addReg(FalseReg) + .addReg(TrueReg) + .addReg(SReg); + llvm_unreachable("Unhandled branch predicate EXECZ"); + break; + } + default: + llvm_unreachable("invalid branch predicate"); + } + } else { + llvm_unreachable("Can only handle Cond size 1 or 2"); + } +} + +unsigned SIInstrInfo::insertEQ(MachineBasicBlock *MBB, + MachineBasicBlock::iterator I, + const DebugLoc &DL, + unsigned SrcReg, int Value) const { + MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); + unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg) + .addImm(Value) + .addReg(SrcReg); + + return Reg; +} + +unsigned SIInstrInfo::insertNE(MachineBasicBlock *MBB, + MachineBasicBlock::iterator I, + const DebugLoc &DL, + unsigned SrcReg, int Value) const { + MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); + unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg) + .addImm(Value) + .addReg(SrcReg); + + return Reg; +} + unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const { if (RI.getRegSizeInBits(*DstRC) == 32) { @@ -834,6 +1016,20 @@ void SIInstrInfo::insertNoop(MachineBasicBlock &MBB, insertWaitStates(MBB, MI, 1); } +void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const { + auto MF = MBB.getParent(); + SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); + + assert(Info->isEntryFunction()); + + if (MBB.succ_empty()) { + bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end(); + if (HasNoTerminator) + BuildMI(MBB, MBB.end(), DebugLoc(), + get(Info->returnsVoid() ? AMDGPU::S_ENDPGM : AMDGPU::SI_RETURN_TO_EPILOG)); + } +} + unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const { switch (MI.getOpcode()) { default: return 1; // FIXME: Do wait states equal cycles? @@ -1241,14 +1437,20 @@ bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB, return false; } - BranchPredicate Pred = getBranchPredicate(I->getOpcode()); - if (Pred == INVALID_BR) - return true; + MachineBasicBlock *CondBB = nullptr; - MachineBasicBlock *CondBB = I->getOperand(0).getMBB(); - Cond.push_back(MachineOperand::CreateImm(Pred)); - Cond.push_back(I->getOperand(1)); // Save the branch register. + if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) { + CondBB = I->getOperand(1).getMBB(); + Cond.push_back(I->getOperand(0)); + } else { + BranchPredicate Pred = getBranchPredicate(I->getOpcode()); + if (Pred == INVALID_BR) + return true; + CondBB = I->getOperand(0).getMBB(); + Cond.push_back(MachineOperand::CreateImm(Pred)); + Cond.push_back(I->getOperand(1)); // Save the branch register. + } ++I; if (I == MBB.end()) { @@ -1351,6 +1553,13 @@ unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB, return 1; } + if(Cond.size() == 1 && Cond[0].isReg()) { + BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO)) + .add(Cond[0]) + .addMBB(TBB); + return 1; + } + assert(TBB && Cond[0].isImm()); unsigned Opcode @@ -1390,9 +1599,16 @@ unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB, bool SIInstrInfo::reverseBranchCondition( SmallVectorImpl<MachineOperand> &Cond) const { - assert(Cond.size() == 2); - Cond[0].setImm(-Cond[0].getImm()); - return false; + if (Cond.size() != 2) { + return true; + } + + if (Cond[0].isImm()) { + Cond[0].setImm(-Cond[0].getImm()); + return false; + } + + return true; } bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB, @@ -3920,6 +4136,82 @@ bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const { return false; } +bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const { + return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO; +} + +void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry, + MachineBasicBlock *IfEnd) const { + MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator(); + assert(TI != IfEntry->end()); + + MachineInstr *Branch = &(*TI); + MachineFunction *MF = IfEntry->getParent(); + MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo(); + + if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) { + unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + MachineInstr *SIIF = + BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg) + .add(Branch->getOperand(0)) + .add(Branch->getOperand(1)); + MachineInstr *SIEND = + BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF)) + .addReg(DstReg); + + IfEntry->erase(TI); + IfEntry->insert(IfEntry->end(), SIIF); + IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND); + } +} + +void SIInstrInfo::convertNonUniformLoopRegion( + MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const { + MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator(); + // We expect 2 terminators, one conditional and one unconditional. + assert(TI != LoopEnd->end()); + + MachineInstr *Branch = &(*TI); + MachineFunction *MF = LoopEnd->getParent(); + MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo(); + + if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) { + + unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + unsigned BackEdgeReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + MachineInstrBuilder HeaderPHIBuilder = + BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg); + for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(), + E = LoopEntry->pred_end(); + PI != E; ++PI) { + if (*PI == LoopEnd) { + HeaderPHIBuilder.addReg(BackEdgeReg); + } else { + MachineBasicBlock *PMBB = *PI; + unsigned ZeroReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); + materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(), + ZeroReg, 0); + HeaderPHIBuilder.addReg(ZeroReg); + } + HeaderPHIBuilder.addMBB(*PI); + } + MachineInstr *HeaderPhi = HeaderPHIBuilder; + MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(), + get(AMDGPU::SI_IF_BREAK), BackEdgeReg) + .addReg(DstReg) + .add(Branch->getOperand(0)); + MachineInstr *SILOOP = + BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP)) + .addReg(BackEdgeReg) + .addMBB(LoopEntry); + + LoopEntry->insert(LoopEntry->begin(), HeaderPhi); + LoopEnd->erase(TI); + LoopEnd->insert(LoopEnd->end(), SIIFBREAK); + LoopEnd->insert(LoopEnd->end(), SILOOP); + } +} + ArrayRef<std::pair<int, const char *>> SIInstrInfo::getSerializableTargetIndices() const { static const std::pair<int, const char *> TargetIndices[] = { diff --git a/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.h index 03a5ef74b179..f6e5e8883f63 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.h +++ b/contrib/llvm/lib/Target/AMDGPU/SIInstrInfo.h @@ -143,6 +143,23 @@ public: RegScavenger *RS, unsigned TmpReg, unsigned Offset, unsigned Size) const; + void materializeImmediate(MachineBasicBlock &MBB, + MachineBasicBlock::iterator MI, + const DebugLoc &DL, + unsigned DestReg, + int64_t Value) const; + + const TargetRegisterClass *getPreferredSelectRegClass( + unsigned Size) const; + + unsigned insertNE(MachineBasicBlock *MBB, + MachineBasicBlock::iterator I, const DebugLoc &DL, + unsigned SrcReg, int Value) const; + + unsigned insertEQ(MachineBasicBlock *MBB, + MachineBasicBlock::iterator I, const DebugLoc &DL, + unsigned SrcReg, int Value) const; + void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, bool isKill, int FrameIndex, @@ -193,7 +210,7 @@ public: bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl<MachineOperand> &Cond, - bool AllowModify) const override; + bool AllowModify = false) const override; unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved = nullptr) const override; @@ -218,6 +235,11 @@ public: unsigned DstReg, ArrayRef<MachineOperand> Cond, unsigned TrueReg, unsigned FalseReg) const override; + void insertVectorSelect(MachineBasicBlock &MBB, + MachineBasicBlock::iterator I, const DebugLoc &DL, + unsigned DstReg, ArrayRef<MachineOperand> Cond, + unsigned TrueReg, unsigned FalseReg) const; + bool areMemAccessesTriviallyDisjoint(MachineInstr &MIa, MachineInstr &MIb, AliasAnalysis *AA = nullptr) const override; @@ -705,6 +727,7 @@ public: void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override; + void insertReturn(MachineBasicBlock &MBB) const; /// \brief Return the number of wait states that result from executing this /// instruction. unsigned getNumWaitStates(const MachineInstr &MI) const; @@ -750,6 +773,14 @@ public: bool mayAccessFlatAddressSpace(const MachineInstr &MI) const; + bool isNonUniformBranchInstr(MachineInstr &Instr) const; + + void convertNonUniformIfRegion(MachineBasicBlock *IfEntry, + MachineBasicBlock *IfEnd) const; + + void convertNonUniformLoopRegion(MachineBasicBlock *LoopEntry, + MachineBasicBlock *LoopEnd) const; + ArrayRef<std::pair<int, const char *>> getSerializableTargetIndices() const override; diff --git a/contrib/llvm/lib/Target/AMDGPU/SIInstructions.td b/contrib/llvm/lib/Target/AMDGPU/SIInstructions.td index 7ccb54f54e34..3b4bdc864253 100644 --- a/contrib/llvm/lib/Target/AMDGPU/SIInstructions.td +++ b/contrib/llvm/lib/Target/AMDGPU/SIInstructions.td @@ -174,6 +174,13 @@ def SI_MASK_BRANCH : VPseudoInstSI < let isTerminator = 1 in { + def SI_NON_UNIFORM_BRCOND_PSEUDO : CFPseudoInstSI < + (outs), + (ins SReg_64:$vcc, brtarget:$target), + [(brcond i1:$vcc, bb:$target)]> { + let Size = 12; +} + def SI_IF: CFPseudoInstSI < (outs SReg_64:$dst), (ins SReg_64:$vcc, brtarget:$target), [(set i64:$dst, (AMDGPUif i1:$vcc, bb:$target))], 1, 1> { diff --git a/contrib/llvm/lib/Target/AMDGPU/VOP2Instructions.td b/contrib/llvm/lib/Target/AMDGPU/VOP2Instructions.td index 2281f338ab45..4a11d9471f1d 100644 --- a/contrib/llvm/lib/Target/AMDGPU/VOP2Instructions.td +++ b/contrib/llvm/lib/Target/AMDGPU/VOP2Instructions.td @@ -164,8 +164,11 @@ multiclass VOP2eInst <string opName, class VOP_MADAK <ValueType vt> : VOPProfile <[vt, vt, vt, vt]> { field Operand ImmOpType = !if(!eq(vt.Size, 32), f32kimm, f16kimm); field dag Ins32 = (ins VCSrc_f32:$src0, VGPR_32:$src1, ImmOpType:$imm); - field string Asm32 = "$vdst, $src0, $src1, $imm"; field bit HasExt = 0; + + // Hack to stop printing _e64 + let DstRC = RegisterOperand<VGPR_32>; + field string Asm32 = " $vdst, $src0, $src1, $imm"; } def VOP_MADAK_F16 : VOP_MADAK <f16>; @@ -174,8 +177,11 @@ def VOP_MADAK_F32 : VOP_MADAK <f32>; class VOP_MADMK <ValueType vt> : VOPProfile <[vt, vt, vt, vt]> { field Operand ImmOpType = !if(!eq(vt.Size, 32), f32kimm, f16kimm); field dag Ins32 = (ins VCSrc_f32:$src0, ImmOpType:$imm, VGPR_32:$src1); - field string Asm32 = "$vdst, $src0, $imm, $src1"; field bit HasExt = 0; + + // Hack to stop printing _e64 + let DstRC = RegisterOperand<VGPR_32>; + field string Asm32 = " $vdst, $src0, $imm, $src1"; } def VOP_MADMK_F16 : VOP_MADMK <f16>; @@ -298,7 +304,7 @@ def VOP_WRITELANE : VOPProfile<[i32, i32, i32]> { let SubtargetPredicate = isGCN in { defm V_CNDMASK_B32 : VOP2eInst <"v_cndmask_b32", VOP2e_I32_I32_I32_I1>; -def V_MADMK_F32 : VOP2_Pseudo <"v_madmk_f32", VOP_MADMK_F32>; +def V_MADMK_F32 : VOP2_Pseudo <"v_madmk_f32", VOP_MADMK_F32, [], "">; let isCommutable = 1 in { defm V_ADD_F32 : VOP2Inst <"v_add_f32", VOP_F32_F32_F32, fadd>; @@ -328,7 +334,7 @@ let Constraints = "$vdst = $src2", DisableEncoding="$src2", defm V_MAC_F32 : VOP2Inst <"v_mac_f32", VOP_MAC_F32>; } -def V_MADAK_F32 : VOP2_Pseudo <"v_madak_f32", VOP_MADAK_F32>; +def V_MADAK_F32 : VOP2_Pseudo <"v_madak_f32", VOP_MADAK_F32, [], "">; // No patterns so that the scalar instructions are always selected. // The scalar versions will be replaced with vector when needed later. @@ -383,7 +389,7 @@ defm V_LSHL_B32 : VOP2Inst <"v_lshl_b32", VOP_I32_I32_I32>; let SubtargetPredicate = isVI in { -def V_MADMK_F16 : VOP2_Pseudo <"v_madmk_f16", VOP_MADMK_F16>; +def V_MADMK_F16 : VOP2_Pseudo <"v_madmk_f16", VOP_MADMK_F16, [], "">; defm V_LSHLREV_B16 : VOP2Inst <"v_lshlrev_b16", VOP_I16_I16_I16>; defm V_LSHRREV_B16 : VOP2Inst <"v_lshrrev_b16", VOP_I16_I16_I16>; defm V_ASHRREV_I16 : VOP2Inst <"v_ashrrev_i16", VOP_I16_I16_I16>; @@ -394,7 +400,7 @@ defm V_ADD_F16 : VOP2Inst <"v_add_f16", VOP_F16_F16_F16, fadd>; defm V_SUB_F16 : VOP2Inst <"v_sub_f16", VOP_F16_F16_F16, fsub>; defm V_SUBREV_F16 : VOP2Inst <"v_subrev_f16", VOP_F16_F16_F16, null_frag, "v_sub_f16">; defm V_MUL_F16 : VOP2Inst <"v_mul_f16", VOP_F16_F16_F16, fmul>; -def V_MADAK_F16 : VOP2_Pseudo <"v_madak_f16", VOP_MADAK_F16>; +def V_MADAK_F16 : VOP2_Pseudo <"v_madak_f16", VOP_MADAK_F16, [], "">; defm V_ADD_U16 : VOP2Inst <"v_add_u16", VOP_I16_I16_I16>; defm V_SUB_U16 : VOP2Inst <"v_sub_u16" , VOP_I16_I16_I16>; defm V_SUBREV_U16 : VOP2Inst <"v_subrev_u16", VOP_I16_I16_I16, null_frag, "v_sub_u16">; @@ -651,6 +657,17 @@ multiclass VOP2_Real_e64_vi <bits<10> op> { VOP3e_vi <op, !cast<VOP3_Pseudo>(NAME#"_e64").Pfl>; } +multiclass VOP2_Real_e64only_vi <bits<10> op> { + def _e64_vi : + VOP3_Real<!cast<VOP3_Pseudo>(NAME#"_e64"), SIEncodingFamily.VI>, + VOP3e_vi <op, !cast<VOP3_Pseudo>(NAME#"_e64").Pfl> { + // Hack to stop printing _e64 + VOP3_Pseudo ps = !cast<VOP3_Pseudo>(NAME#"_e64"); + let OutOperandList = (outs VGPR_32:$vdst); + let AsmString = ps.Mnemonic # " " # ps.AsmOperands; + } +} + multiclass Base_VOP2be_Real_e32e64_vi <bits<6> op> : VOP2_Real_e32_vi<op> { def _e64_vi : VOP3_Real<!cast<VOP3_Pseudo>(NAME#"_e64"), SIEncodingFamily.VI>, @@ -718,17 +735,17 @@ defm V_SUBBREV_U32 : VOP2be_Real_e32e64_vi <0x1e>; defm V_READLANE_B32 : VOP32_Real_vi <0x289>; defm V_WRITELANE_B32 : VOP32_Real_vi <0x28a>; -defm V_BFM_B32 : VOP2_Real_e64_vi <0x293>; -defm V_BCNT_U32_B32 : VOP2_Real_e64_vi <0x28b>; -defm V_MBCNT_LO_U32_B32 : VOP2_Real_e64_vi <0x28c>; -defm V_MBCNT_HI_U32_B32 : VOP2_Real_e64_vi <0x28d>; -defm V_LDEXP_F32 : VOP2_Real_e64_vi <0x288>; -defm V_CVT_PKACCUM_U8_F32 : VOP2_Real_e64_vi <0x1f0>; -defm V_CVT_PKNORM_I16_F32 : VOP2_Real_e64_vi <0x294>; -defm V_CVT_PKNORM_U16_F32 : VOP2_Real_e64_vi <0x295>; -defm V_CVT_PKRTZ_F16_F32 : VOP2_Real_e64_vi <0x296>; -defm V_CVT_PK_U16_U32 : VOP2_Real_e64_vi <0x297>; -defm V_CVT_PK_I16_I32 : VOP2_Real_e64_vi <0x298>; +defm V_BFM_B32 : VOP2_Real_e64only_vi <0x293>; +defm V_BCNT_U32_B32 : VOP2_Real_e64only_vi <0x28b>; +defm V_MBCNT_LO_U32_B32 : VOP2_Real_e64only_vi <0x28c>; +defm V_MBCNT_HI_U32_B32 : VOP2_Real_e64only_vi <0x28d>; +defm V_LDEXP_F32 : VOP2_Real_e64only_vi <0x288>; +defm V_CVT_PKACCUM_U8_F32 : VOP2_Real_e64only_vi <0x1f0>; +defm V_CVT_PKNORM_I16_F32 : VOP2_Real_e64only_vi <0x294>; +defm V_CVT_PKNORM_U16_F32 : VOP2_Real_e64only_vi <0x295>; +defm V_CVT_PKRTZ_F16_F32 : VOP2_Real_e64only_vi <0x296>; +defm V_CVT_PK_U16_U32 : VOP2_Real_e64only_vi <0x297>; +defm V_CVT_PK_I16_I32 : VOP2_Real_e64only_vi <0x298>; defm V_ADD_F16 : VOP2_Real_e32e64_vi <0x1f>; defm V_SUB_F16 : VOP2_Real_e32e64_vi <0x20>; diff --git a/contrib/llvm/lib/Target/AMDGPU/VOP3Instructions.td b/contrib/llvm/lib/Target/AMDGPU/VOP3Instructions.td index 217a07488853..ffa6c60d6b1f 100644 --- a/contrib/llvm/lib/Target/AMDGPU/VOP3Instructions.td +++ b/contrib/llvm/lib/Target/AMDGPU/VOP3Instructions.td @@ -232,7 +232,6 @@ def V_ASHRREV_I64 : VOP3Inst <"v_ashrrev_i64", VOP3_Profile<VOP_I64_I32_I64>>; let SubtargetPredicate = isCIVI in { -def V_MQSAD_U16_U8 : VOP3Inst <"v_mqsad_u16_u8", VOP3_Profile<VOP_I32_I32_I32>>; def V_QSAD_PK_U16_U8 : VOP3Inst <"v_qsad_pk_u16_u8", VOP3_Profile<VOP_I64_I64_I32_I64>, int_amdgcn_qsad_pk_u16_u8>; def V_MQSAD_U32_U8 : VOP3Inst <"v_mqsad_u32_u8", VOP3_Profile<VOP_V4I32_I64_I32_V4I32>, int_amdgcn_mqsad_u32_u8>; @@ -402,7 +401,6 @@ multiclass VOP3be_Real_ci<bits<9> op> { } } -defm V_MQSAD_U16_U8 : VOP3_Real_ci <0x172>; defm V_QSAD_PK_U16_U8 : VOP3_Real_ci <0x172>; defm V_MQSAD_U32_U8 : VOP3_Real_ci <0x175>; defm V_MAD_U64_U32 : VOP3be_Real_ci <0x176>; @@ -426,7 +424,6 @@ multiclass VOP3be_Real_vi<bits<10> op> { } // End AssemblerPredicates = [isVI], DecoderNamespace = "VI" -defm V_MQSAD_U16_U8 : VOP3_Real_vi <0x172>; defm V_MAD_U64_U32 : VOP3be_Real_vi <0x1E8>; defm V_MAD_I64_I32 : VOP3be_Real_vi <0x1E9>; diff --git a/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h b/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h index 28c407f74125..dd7fe871345a 100644 --- a/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h +++ b/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h @@ -404,21 +404,11 @@ public: /// Returns predicate register associated with the given frame instruction. unsigned getFramePred(const MachineInstr &MI) const { assert(isFrameInstr(MI)); - if (isFrameSetup(MI)) - // Operands of ADJCALLSTACKDOWN: - // - argument declared in ADJCALLSTACKDOWN pattern: - // 0 - frame size - // 1 - predicate code (like ARMCC::AL) - // - added by predOps: - // 2 - predicate reg - return MI.getOperand(2).getReg(); - assert(MI.getOpcode() == ARM::ADJCALLSTACKUP || - MI.getOpcode() == ARM::tADJCALLSTACKUP); - // Operands of ADJCALLSTACKUP: - // - argument declared in ADJCALLSTACKUP pattern: + // Operands of ADJCALLSTACKDOWN/ADJCALLSTACKUP: + // - argument declared in the pattern: // 0 - frame size - // 1 - arg of CALLSEQ_END - // 2 - predicate code + // 1 - arg of CALLSEQ_START/CALLSEQ_END + // 2 - predicate code (like ARMCC::AL) // - added by predOps: // 3 - predicate reg return MI.getOperand(3).getReg(); diff --git a/contrib/llvm/lib/Target/ARM/ARMCallLowering.cpp b/contrib/llvm/lib/Target/ARM/ARMCallLowering.cpp index 9178c67afa6e..46ac4d0ad933 100644 --- a/contrib/llvm/lib/Target/ARM/ARMCallLowering.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMCallLowering.cpp @@ -433,7 +433,7 @@ bool ARMCallLowering::lowerCall(MachineIRBuilder &MIRBuilder, // We now know the size of the stack - update the ADJCALLSTACKDOWN // accordingly. - CallSeqStart.addImm(ArgHandler.StackSize).add(predOps(ARMCC::AL)); + CallSeqStart.addImm(ArgHandler.StackSize).addImm(0).add(predOps(ARMCC::AL)); MIRBuilder.buildInstr(ARM::ADJCALLSTACKUP) .addImm(ArgHandler.StackSize) diff --git a/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp b/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp index 56cac855620d..4f6a73b5980d 100644 --- a/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp @@ -1949,7 +1949,7 @@ bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args, unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) - .addImm(NumBytes)); + .addImm(NumBytes).addImm(0)); // Process the args. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { diff --git a/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp b/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp index e64582402fe1..f8b584db7b99 100644 --- a/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp @@ -473,9 +473,9 @@ ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, } // Use divmod compiler-rt calls for iOS 5.0 and later. - if (Subtarget->isTargetWatchOS() || - (Subtarget->isTargetIOS() && - !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { + if (Subtarget->isTargetMachO() && + !(Subtarget->isTargetIOS() && + Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); } @@ -1817,8 +1817,7 @@ ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass if (!isSibCall) - Chain = DAG.getCALLSEQ_START(Chain, - DAG.getIntPtrConstant(NumBytes, dl, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); @@ -7365,7 +7364,7 @@ SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { const TargetLowering &TLI = DAG.getTargetLoweringInfo(); // Pair of floats / doubles used to pass the result. - Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); + Type *RetTy = StructType::get(ArgTy, ArgTy); auto &DL = DAG.getDataLayout(); ArgListTy Args; @@ -13115,7 +13114,7 @@ SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy(DAG.getDataLayout())); - Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); + Type *RetTy = StructType::get(Ty, Ty); if (Subtarget->isTargetWindows()) InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); @@ -13417,9 +13416,9 @@ Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, } // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html -Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { +Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, + Instruction *Inst, + AtomicOrdering Ord) const { switch (Ord) { case AtomicOrdering::NotAtomic: case AtomicOrdering::Unordered: @@ -13428,7 +13427,7 @@ Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, case AtomicOrdering::Acquire: return nullptr; // Nothing to do case AtomicOrdering::SequentiallyConsistent: - if (!IsStore) + if (!Inst->hasAtomicStore()) return nullptr; // Nothing to do /*FALLTHROUGH*/ case AtomicOrdering::Release: @@ -13442,9 +13441,9 @@ Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, llvm_unreachable("Unknown fence ordering in emitLeadingFence"); } -Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { +Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, + Instruction *Inst, + AtomicOrdering Ord) const { switch (Ord) { case AtomicOrdering::NotAtomic: case AtomicOrdering::Unordered: diff --git a/contrib/llvm/lib/Target/ARM/ARMISelLowering.h b/contrib/llvm/lib/Target/ARM/ARMISelLowering.h index 08c51b66dfe7..875c06210ae6 100644 --- a/contrib/llvm/lib/Target/ARM/ARMISelLowering.h +++ b/contrib/llvm/lib/Target/ARM/ARMISelLowering.h @@ -483,10 +483,10 @@ class InstrItineraryData; void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const override; - Instruction* emitLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord, - bool IsStore, bool IsLoad) const override; - Instruction* emitTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord, - bool IsStore, bool IsLoad) const override; + Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst, + AtomicOrdering Ord) const override; + Instruction *emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst, + AtomicOrdering Ord) const override; unsigned getMaxSupportedInterleaveFactor() const override { return 4; } diff --git a/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td b/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td index a94d6048f02d..d06b7d0896f1 100644 --- a/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td +++ b/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td @@ -16,7 +16,8 @@ // // Type profiles. -def SDT_ARMCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32> ]>; +def SDT_ARMCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>; def SDT_ARMCallSeqEnd : SDCallSeqEnd<[ SDTCisVT<0, i32>, SDTCisVT<1, i32> ]>; def SDT_ARMStructByVal : SDTypeProfile<0, 4, [SDTCisVT<0, i32>, SDTCisVT<1, i32>, @@ -1968,8 +1969,8 @@ PseudoInst<(outs), (ins i32imm:$amt1, i32imm:$amt2, pred:$p), NoItinerary, [(ARMcallseq_end timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKDOWN : -PseudoInst<(outs), (ins i32imm:$amt, pred:$p), NoItinerary, - [(ARMcallseq_start timm:$amt)]>; +PseudoInst<(outs), (ins i32imm:$amt, i32imm:$amt2, pred:$p), NoItinerary, + [(ARMcallseq_start timm:$amt, timm:$amt2)]>; } def HINT : AI<(outs), (ins imm0_239:$imm), MiscFrm, NoItinerary, diff --git a/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td b/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td index 8048c758e998..bee83dfb6f63 100644 --- a/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td +++ b/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td @@ -284,8 +284,8 @@ def tADJCALLSTACKUP : Requires<[IsThumb, IsThumb1Only]>; def tADJCALLSTACKDOWN : - PseudoInst<(outs), (ins i32imm:$amt), NoItinerary, - [(ARMcallseq_start imm:$amt)]>, + PseudoInst<(outs), (ins i32imm:$amt, i32imm:$amt2), NoItinerary, + [(ARMcallseq_start imm:$amt, imm:$amt2)]>, Requires<[IsThumb, IsThumb1Only]>; } diff --git a/contrib/llvm/lib/Target/ARM/ARMInstructionSelector.cpp b/contrib/llvm/lib/Target/ARM/ARMInstructionSelector.cpp index 2ac3fda9f448..8c680cdf9b47 100644 --- a/contrib/llvm/lib/Target/ARM/ARMInstructionSelector.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMInstructionSelector.cpp @@ -101,14 +101,6 @@ static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII, assert(RegBank && "Can't get reg bank for virtual register"); const unsigned DstSize = MRI.getType(DstReg).getSizeInBits(); - (void)DstSize; - unsigned SrcReg = I.getOperand(1).getReg(); - const unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI); - (void)SrcSize; - // We use copies for trunc, so it's ok for the size of the destination to be - // smaller (the higher bits will just be undefined). - assert(DstSize <= SrcSize && "Copy with different width?!"); - assert((RegBank->getID() == ARM::GPRRegBankID || RegBank->getID() == ARM::FPRRegBankID) && "Unsupported reg bank"); @@ -135,28 +127,6 @@ static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII, return true; } -static bool selectFAdd(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, - MachineRegisterInfo &MRI) { - assert(TII.getSubtarget().hasVFP2() && "Can't select fp add without vfp"); - - LLT Ty = MRI.getType(MIB->getOperand(0).getReg()); - unsigned ValSize = Ty.getSizeInBits(); - - if (ValSize == 32) { - if (TII.getSubtarget().useNEONForSinglePrecisionFP()) - return false; - MIB->setDesc(TII.get(ARM::VADDS)); - } else { - assert(ValSize == 64 && "Unsupported size for floating point value"); - if (TII.getSubtarget().isFPOnlySP()) - return false; - MIB->setDesc(TII.get(ARM::VADDD)); - } - MIB.add(predOps(ARMCC::AL)); - - return true; -} - static bool selectSequence(MachineInstrBuilder &MIB, const ARMBaseInstrInfo &TII, MachineRegisterInfo &MRI, @@ -352,6 +322,7 @@ bool ARMInstructionSelector::select(MachineInstr &I) const { } break; } + case G_ANYEXT: case G_TRUNC: { // The high bits are undefined, so there's nothing special to do, just // treat it as a copy. @@ -362,12 +333,12 @@ bool ARMInstructionSelector::select(MachineInstr &I) const { const auto &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI); if (SrcRegBank.getID() != DstRegBank.getID()) { - DEBUG(dbgs() << "G_TRUNC operands on different register banks\n"); + DEBUG(dbgs() << "G_TRUNC/G_ANYEXT operands on different register banks\n"); return false; } if (SrcRegBank.getID() != ARM::GPRRegBankID) { - DEBUG(dbgs() << "G_TRUNC on non-GPR not supported yet\n"); + DEBUG(dbgs() << "G_TRUNC/G_ANYEXT on non-GPR not supported yet\n"); return false; } @@ -393,10 +364,6 @@ bool ARMInstructionSelector::select(MachineInstr &I) const { } MIB.add(predOps(ARMCC::AL)).add(condCodeOp()); break; - case G_FADD: - if (!selectFAdd(MIB, TII, MRI)) - return false; - break; case G_FRAME_INDEX: // Add 0 to the given frame index and hope it will eventually be folded into // the user(s). diff --git a/contrib/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp b/contrib/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp index 9b86030fdd29..5bf6c7aed6b8 100644 --- a/contrib/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMLegalizerInfo.cpp @@ -45,9 +45,11 @@ ARMLegalizerInfo::ARMLegalizerInfo(const ARMSubtarget &ST) { setAction({Op, 1, p0}, Legal); } - for (unsigned Op : {G_ADD, G_SUB, G_MUL}) - for (auto Ty : {s1, s8, s16, s32}) - setAction({Op, Ty}, Legal); + for (unsigned Op : {G_ADD, G_SUB, G_MUL}) { + for (auto Ty : {s1, s8, s16}) + setAction({Op, Ty}, WidenScalar); + setAction({Op, s32}, Legal); + } for (unsigned Op : {G_SDIV, G_UDIV}) { for (auto Ty : {s8, s16}) diff --git a/contrib/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp b/contrib/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp index 581d5fe159fd..7e4d598a6e0b 100644 --- a/contrib/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMOptimizeBarriersPass.cpp @@ -88,13 +88,15 @@ bool ARMOptimizeBarriersPass::runOnMachineFunction(MachineFunction &MF) { } } } + bool Changed = false; // Remove the tagged DMB for (auto MI : ToRemove) { MI->eraseFromParent(); ++NumDMBsRemoved; + Changed = true; } - return NumDMBsRemoved > 0; + return Changed; } /// createARMOptimizeBarriersPass - Returns an instance of the remove double diff --git a/contrib/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp b/contrib/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp index 13a32211f88c..a20997c95cd9 100644 --- a/contrib/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMRegisterBankInfo.cpp @@ -225,6 +225,7 @@ ARMRegisterBankInfo::getInstrMapping(const MachineInstr &MI) const { case G_UDIV: case G_SEXT: case G_ZEXT: + case G_ANYEXT: case G_TRUNC: case G_GEP: // FIXME: We're abusing the fact that everything lives in a GPR for now; in diff --git a/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp b/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp index d09f3ecbaa28..5583d6148b08 100644 --- a/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp +++ b/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp @@ -13,7 +13,9 @@ #include "ARM.h" #include "ARMCallLowering.h" #include "ARMLegalizerInfo.h" +#ifdef LLVM_BUILD_GLOBAL_ISEL #include "ARMRegisterBankInfo.h" +#endif #include "ARMSubtarget.h" #include "ARMTargetMachine.h" #include "ARMTargetObjectFile.h" diff --git a/contrib/llvm/lib/Target/AVR/AVRFrameLowering.cpp b/contrib/llvm/lib/Target/AVR/AVRFrameLowering.cpp index c297865db820..0ec8e8b08ceb 100644 --- a/contrib/llvm/lib/Target/AVR/AVRFrameLowering.cpp +++ b/contrib/llvm/lib/Target/AVR/AVRFrameLowering.cpp @@ -375,7 +375,7 @@ MachineBasicBlock::iterator AVRFrameLowering::eliminateCallFramePseudoInstr( DebugLoc DL = MI->getDebugLoc(); unsigned int Opcode = MI->getOpcode(); - int Amount = MI->getOperand(0).getImm(); + int Amount = TII.getFrameSize(*MI); // Adjcallstackup does not need to allocate stack space for the call, instead // we insert push instructions that will allocate the necessary stack. diff --git a/contrib/llvm/lib/Target/AVR/AVRISelLowering.cpp b/contrib/llvm/lib/Target/AVR/AVRISelLowering.cpp index f0ab6acedad1..ef9c00e4b784 100644 --- a/contrib/llvm/lib/Target/AVR/AVRISelLowering.cpp +++ b/contrib/llvm/lib/Target/AVR/AVRISelLowering.cpp @@ -361,7 +361,7 @@ SDValue AVRTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy(DAG.getDataLayout())); - Type *RetTy = (Type *)StructType::get(Ty, Ty, nullptr); + Type *RetTy = (Type *)StructType::get(Ty, Ty); SDLoc dl(Op); TargetLowering::CallLoweringInfo CLI(DAG); @@ -1166,8 +1166,7 @@ SDValue AVRTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, // Get a count of how many bytes are to be pushed on the stack. unsigned NumBytes = CCInfo.getNextStackOffset(); - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), - DL); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; @@ -1611,8 +1610,9 @@ AVRTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *trueMBB = MF->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *falseMBB = MF->CreateMachineBasicBlock(LLVM_BB); - MachineFunction::iterator I = MBB->getParent()->begin(); - ++I; + MachineFunction::iterator I; + for (I = MF->begin(); I != MF->end() && &(*I) != MBB; ++I); + if (I != MF->end()) ++I; MF->insert(I, trueMBB); MF->insert(I, falseMBB); diff --git a/contrib/llvm/lib/Target/AVR/AVRInstrInfo.td b/contrib/llvm/lib/Target/AVR/AVRInstrInfo.td index 1b6547ef7795..06ad2b3ffdf8 100644 --- a/contrib/llvm/lib/Target/AVR/AVRInstrInfo.td +++ b/contrib/llvm/lib/Target/AVR/AVRInstrInfo.td @@ -17,7 +17,7 @@ include "AVRInstrFormats.td" // AVR Type Profiles //===----------------------------------------------------------------------===// -def SDT_AVRCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i16>]>; +def SDT_AVRCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i16>, SDTCisVT<1, i16>]>; def SDT_AVRCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i16>, SDTCisVT<1, i16>]>; def SDT_AVRCall : SDTypeProfile<0, -1, [SDTCisVT<0, iPTR>]>; def SDT_AVRWrapper : SDTypeProfile<1, 1, [SDTCisSameAs<0, 1>, SDTCisPtrTy<0>]>; @@ -333,9 +333,9 @@ let Defs = [SP, SREG], Uses = [SP] in { def ADJCALLSTACKDOWN : Pseudo<(outs), - (ins i16imm:$amt), + (ins i16imm:$amt, i16imm:$amt2), "#ADJCALLSTACKDOWN", - [(AVRcallseq_start timm:$amt)]>; + [(AVRcallseq_start timm:$amt, timm:$amt2)]>; // R31R30 is used to update SP, since it is a scratch reg and this instruction // is placed after the function call then R31R30 should be always free. diff --git a/contrib/llvm/lib/Target/AVR/AVRRegisterInfo.cpp b/contrib/llvm/lib/Target/AVR/AVRRegisterInfo.cpp index 2813e24d2ac7..11a47bad78ba 100644 --- a/contrib/llvm/lib/Target/AVR/AVRRegisterInfo.cpp +++ b/contrib/llvm/lib/Target/AVR/AVRRegisterInfo.cpp @@ -52,7 +52,6 @@ AVRRegisterInfo::getCallPreservedMask(const MachineFunction &MF, BitVector AVRRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const AVRTargetMachine &TM = static_cast<const AVRTargetMachine&>(MF.getTarget()); - const TargetFrameLowering *TFI = TM.getSubtargetImpl()->getFrameLowering(); // Reserve the intermediate result registers r1 and r2 // The result of instructions like 'mul' is always stored here. diff --git a/contrib/llvm/lib/Target/BPF/BPFISelLowering.cpp b/contrib/llvm/lib/Target/BPF/BPFISelLowering.cpp index b9b3dff95c0a..6897161c903c 100644 --- a/contrib/llvm/lib/Target/BPF/BPFISelLowering.cpp +++ b/contrib/llvm/lib/Target/BPF/BPFISelLowering.cpp @@ -257,8 +257,7 @@ SDValue BPFTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, } auto PtrVT = getPointerTy(MF.getDataLayout()); - Chain = DAG.getCALLSEQ_START( - Chain, DAG.getConstant(NumBytes, CLI.DL, PtrVT, true), CLI.DL); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); SmallVector<std::pair<unsigned, SDValue>, MaxArgs> RegsToPass; diff --git a/contrib/llvm/lib/Target/BPF/BPFInstrInfo.td b/contrib/llvm/lib/Target/BPF/BPFInstrInfo.td index 93ee24371c4d..c6c0ff587c6b 100644 --- a/contrib/llvm/lib/Target/BPF/BPFInstrInfo.td +++ b/contrib/llvm/lib/Target/BPF/BPFInstrInfo.td @@ -16,7 +16,8 @@ include "BPFInstrFormats.td" // Instruction Operands and Patterns // These are target-independent nodes, but have target-specific formats. -def SDT_BPFCallSeqStart : SDCallSeqStart<[SDTCisVT<0, iPTR>]>; +def SDT_BPFCallSeqStart : SDCallSeqStart<[SDTCisVT<0, iPTR>, + SDTCisVT<1, iPTR>]>; def SDT_BPFCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, iPTR>, SDTCisVT<1, iPTR>]>; def SDT_BPFCall : SDTypeProfile<0, -1, [SDTCisVT<0, iPTR>]>; def SDT_BPFSetFlag : SDTypeProfile<0, 3, [SDTCisSameAs<0, 1>]>; @@ -445,9 +446,9 @@ let isReturn = 1, isTerminator = 1, hasDelaySlot=0, isBarrier = 1, // ADJCALLSTACKDOWN/UP pseudo insns let Defs = [R11], Uses = [R11] in { -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i64imm:$amt), - "#ADJCALLSTACKDOWN $amt", - [(BPFcallseq_start timm:$amt)]>; +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2), + "#ADJCALLSTACKDOWN $amt1 $amt2", + [(BPFcallseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2), "#ADJCALLSTACKUP $amt1 $amt2", [(BPFcallseq_end timm:$amt1, timm:$amt2)]>; diff --git a/contrib/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp b/contrib/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp index 861af94f1e38..1dffebe97f2d 100644 --- a/contrib/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp +++ b/contrib/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp @@ -848,8 +848,7 @@ HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, SDValue Glue; if (!IsTailCall) { - SDValue C = DAG.getConstant(NumBytes, dl, PtrVT, true); - Chain = DAG.getCALLSEQ_START(Chain, C, dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); Glue = Chain.getValue(1); } diff --git a/contrib/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp b/contrib/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp index 5a5799dbe009..e4df7ff5c200 100644 --- a/contrib/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp +++ b/contrib/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp @@ -1209,7 +1209,7 @@ bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V, KnownBits Known(T->getBitWidth()); computeKnownBits(V, Known, DL); - return Known.Zero.countLeadingOnes() >= IterCount; + return Known.countMinLeadingZeros() >= IterCount; } diff --git a/contrib/llvm/lib/Target/Hexagon/HexagonPatterns.td b/contrib/llvm/lib/Target/Hexagon/HexagonPatterns.td index 32503d111c24..81b5e10c1173 100644 --- a/contrib/llvm/lib/Target/Hexagon/HexagonPatterns.td +++ b/contrib/llvm/lib/Target/Hexagon/HexagonPatterns.td @@ -714,7 +714,8 @@ def: Pat<(i1 0), (PS_false)>; def: Pat<(i1 1), (PS_true)>; // Pseudo instructions. -def SDT_SPCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32> ]>; +def SDT_SPCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>; def SDT_SPCallSeqEnd : SDCallSeqEnd<[ SDTCisVT<0, i32>, SDTCisVT<1, i32> ]>; @@ -732,8 +733,8 @@ def HexagonTCRet : SDNode<"HexagonISD::TC_RETURN", SDT_SPCall, [SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>; -def: Pat<(callseq_start timm:$amt), - (ADJCALLSTACKDOWN imm:$amt)>; +def: Pat<(callseq_start timm:$amt, timm:$amt2), + (ADJCALLSTACKDOWN imm:$amt, imm:$amt2)>; def: Pat<(callseq_end timm:$amt1, timm:$amt2), (ADJCALLSTACKUP imm:$amt1, imm:$amt2)>; diff --git a/contrib/llvm/lib/Target/Hexagon/HexagonPseudo.td b/contrib/llvm/lib/Target/Hexagon/HexagonPseudo.td index 8c2caea2d5c5..0f99dfe342b8 100644 --- a/contrib/llvm/lib/Target/Hexagon/HexagonPseudo.td +++ b/contrib/llvm/lib/Target/Hexagon/HexagonPseudo.td @@ -80,7 +80,7 @@ def PS_false : InstHexagon<(outs PredRegs:$dst), (ins), "", [(set I1:$dst, 0)], "", C2_andn.Itinerary, TypeCR>; let Defs = [R29, R30], Uses = [R31, R30, R29], isPseudo = 1 in -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt), +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), ".error \"should not emit\" ", []>; let Defs = [R29, R30, R31], Uses = [R29], isPseudo = 1 in diff --git a/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.cpp b/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.cpp index d156294a0b0c..0a9cac2565f2 100644 --- a/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.cpp +++ b/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.cpp @@ -11,9 +11,9 @@ // //===----------------------------------------------------------------------===// +#include "LanaiISelLowering.h" #include "Lanai.h" #include "LanaiCondCode.h" -#include "LanaiISelLowering.h" #include "LanaiMachineFunctionInfo.h" #include "LanaiSubtarget.h" #include "LanaiTargetObjectFile.h" @@ -38,10 +38,11 @@ #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/Casting.h" -#include "llvm/Support/CommandLine.h" #include "llvm/Support/CodeGen.h" +#include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/KnownBits.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetCallingConv.h" @@ -649,10 +650,7 @@ SDValue LanaiTargetLowering::LowerCCCCallTo( ByValArgs.push_back(FIPtr); } - Chain = DAG.getCALLSEQ_START( - Chain, - DAG.getConstant(NumBytes, DL, getPointerTy(DAG.getDataLayout()), true), - DL); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass; SmallVector<SDValue, 12> MemOpChains; @@ -1502,3 +1500,24 @@ SDValue LanaiTargetLowering::PerformDAGCombine(SDNode *N, return SDValue(); } + +void LanaiTargetLowering::computeKnownBitsForTargetNode( + const SDValue Op, KnownBits &Known, const APInt &DemandedElts, + const SelectionDAG &DAG, unsigned Depth) const { + unsigned BitWidth = Known.getBitWidth(); + switch (Op.getOpcode()) { + default: + break; + case LanaiISD::SETCC: + Known = KnownBits(BitWidth); + Known.Zero.setBits(1, BitWidth); + break; + case LanaiISD::SELECT_CC: + KnownBits Known2; + DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1); + DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1); + Known.Zero &= Known2.Zero; + Known.One &= Known2.One; + break; + } +} diff --git a/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.h b/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.h index c2fba4f9d167..49ad52a39771 100644 --- a/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.h +++ b/contrib/llvm/lib/Target/Lanai/LanaiISelLowering.h @@ -106,6 +106,11 @@ public: SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override; + void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, + const APInt &DemandedElts, + const SelectionDAG &DAG, + unsigned Depth = 0) const override; + private: SDValue LowerCCCCallTo(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool IsVarArg, diff --git a/contrib/llvm/lib/Target/Lanai/LanaiInstrInfo.td b/contrib/llvm/lib/Target/Lanai/LanaiInstrInfo.td index 285fca11737d..776fee101dfe 100644 --- a/contrib/llvm/lib/Target/Lanai/LanaiInstrInfo.td +++ b/contrib/llvm/lib/Target/Lanai/LanaiInstrInfo.td @@ -22,7 +22,8 @@ include "LanaiInstrFormats.td" // -------------------------------------------------- // // These are target-independent nodes, but have target-specific formats. -def SDT_LanaiCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>]>; +def SDT_LanaiCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>, + SDTCisVT<1, i32>]>; def SDT_LanaiCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i32>, SDTCisVT<1, i32>]>; def SDT_LanaiCall : SDTypeProfile<0, -1, [SDTCisVT<0, i32>]>; @@ -750,9 +751,9 @@ let isReturn = 1, isTerminator = 1, hasDelaySlot = 1, isBarrier = 1, // Pessimistically assume ADJCALLSTACKDOWN / ADJCALLSTACKUP will become // sub / add which can clobber SP. let Defs = [SP], Uses = [SP] in { - def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt), - "#ADJCALLSTACKDOWN $amt", - [(CallSeqStart timm:$amt)]>; + def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), + "#ADJCALLSTACKDOWN $amt1 $amt2", + [(CallSeqStart timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), "#ADJCALLSTACKUP $amt1 $amt2", [(CallSeqEnd timm:$amt1, timm:$amt2)]>; @@ -770,9 +771,6 @@ let Uses = [SR] in { [(set (i32 GPR:$Rs1), (LanaiSetCC imm:$DDDI))]>; } -// SCC's output is already 1-bit so and'ing with 1 is redundant. -def : Pat<(and (LanaiSetCC imm:$DDDI), 1), (SCC imm:$DDDI)>; - // Select with hardware support let Uses = [SR], isSelect = 1 in { def SELECT : InstRR<0b111, (outs GPR:$Rd), diff --git a/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp b/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp index f1cb0b6c031b..b4ff8f66c55f 100644 --- a/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp +++ b/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp @@ -236,7 +236,7 @@ MachineBasicBlock::iterator MSP430FrameLowering::eliminateCallFramePseudoInstr( // adjcallstackdown instruction into 'add SP, <amt>' // TODO: consider using push / pop instead of sub + store / add MachineInstr &Old = *I; - uint64_t Amount = Old.getOperand(0).getImm(); + uint64_t Amount = TII.getFrameSize(Old); if (Amount != 0) { // We need to keep the stack aligned properly. To do this, we round the // amount of space needed for the outgoing arguments up to the next @@ -252,8 +252,7 @@ MachineBasicBlock::iterator MSP430FrameLowering::eliminateCallFramePseudoInstr( } else { assert(Old.getOpcode() == TII.getCallFrameDestroyOpcode()); // factor out the amount the callee already popped. - uint64_t CalleeAmt = Old.getOperand(1).getImm(); - Amount -= CalleeAmt; + Amount -= TII.getFramePoppedByCallee(Old); if (Amount) New = BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::ADD16ri), MSP430::SP) @@ -272,7 +271,7 @@ MachineBasicBlock::iterator MSP430FrameLowering::eliminateCallFramePseudoInstr( } else if (I->getOpcode() == TII.getCallFrameDestroyOpcode()) { // If we are performing frame pointer elimination and if the callee pops // something off the stack pointer, add it back. - if (uint64_t CalleeAmt = I->getOperand(1).getImm()) { + if (uint64_t CalleeAmt = TII.getFramePoppedByCallee(*I)) { MachineInstr &Old = *I; MachineInstr *New = BuildMI(MF, Old.getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SP) diff --git a/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp b/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp index 40b1dd3cc2eb..cc6e64043f54 100644 --- a/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp +++ b/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp @@ -40,21 +40,24 @@ using namespace llvm; typedef enum { NoHWMult, - HWMultIntr, - HWMultNoIntr + HWMult16, + HWMult32, + HWMultF5 } HWMultUseMode; static cl::opt<HWMultUseMode> -HWMultMode("msp430-hwmult-mode", cl::Hidden, +HWMultMode("mhwmult", cl::Hidden, cl::desc("Hardware multiplier use mode"), - cl::init(HWMultNoIntr), + cl::init(NoHWMult), cl::values( - clEnumValN(NoHWMult, "no", + clEnumValN(NoHWMult, "none", "Do not use hardware multiplier"), - clEnumValN(HWMultIntr, "interrupts", - "Assume hardware multiplier can be used inside interrupts"), - clEnumValN(HWMultNoIntr, "use", - "Assume hardware multiplier cannot be used inside interrupts"))); + clEnumValN(HWMult16, "16bit", + "Use 16-bit hardware multiplier"), + clEnumValN(HWMult32, "32bit", + "Use 32-bit hardware multiplier"), + clEnumValN(HWMultF5, "f5series", + "Use F5 series hardware multiplier"))); MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM, const MSP430Subtarget &STI) @@ -131,29 +134,29 @@ MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM, setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); // FIXME: Implement efficiently multiplication by a constant - setOperationAction(ISD::MUL, MVT::i8, Expand); - setOperationAction(ISD::MULHS, MVT::i8, Expand); - setOperationAction(ISD::MULHU, MVT::i8, Expand); - setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand); - setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand); - setOperationAction(ISD::MUL, MVT::i16, Expand); + setOperationAction(ISD::MUL, MVT::i8, Promote); + setOperationAction(ISD::MULHS, MVT::i8, Promote); + setOperationAction(ISD::MULHU, MVT::i8, Promote); + setOperationAction(ISD::SMUL_LOHI, MVT::i8, Promote); + setOperationAction(ISD::UMUL_LOHI, MVT::i8, Promote); + setOperationAction(ISD::MUL, MVT::i16, LibCall); setOperationAction(ISD::MULHS, MVT::i16, Expand); setOperationAction(ISD::MULHU, MVT::i16, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand); setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand); - setOperationAction(ISD::UDIV, MVT::i8, Expand); - setOperationAction(ISD::UDIVREM, MVT::i8, Expand); - setOperationAction(ISD::UREM, MVT::i8, Expand); - setOperationAction(ISD::SDIV, MVT::i8, Expand); - setOperationAction(ISD::SDIVREM, MVT::i8, Expand); - setOperationAction(ISD::SREM, MVT::i8, Expand); - setOperationAction(ISD::UDIV, MVT::i16, Expand); + setOperationAction(ISD::UDIV, MVT::i8, Promote); + setOperationAction(ISD::UDIVREM, MVT::i8, Promote); + setOperationAction(ISD::UREM, MVT::i8, Promote); + setOperationAction(ISD::SDIV, MVT::i8, Promote); + setOperationAction(ISD::SDIVREM, MVT::i8, Promote); + setOperationAction(ISD::SREM, MVT::i8, Promote); + setOperationAction(ISD::UDIV, MVT::i16, LibCall); setOperationAction(ISD::UDIVREM, MVT::i16, Expand); - setOperationAction(ISD::UREM, MVT::i16, Expand); - setOperationAction(ISD::SDIV, MVT::i16, Expand); + setOperationAction(ISD::UREM, MVT::i16, LibCall); + setOperationAction(ISD::SDIV, MVT::i16, LibCall); setOperationAction(ISD::SDIVREM, MVT::i16, Expand); - setOperationAction(ISD::SREM, MVT::i16, Expand); + setOperationAction(ISD::SREM, MVT::i16, LibCall); // varargs support setOperationAction(ISD::VASTART, MVT::Other, Custom); @@ -162,15 +165,183 @@ MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM, setOperationAction(ISD::VACOPY, MVT::Other, Expand); setOperationAction(ISD::JumpTable, MVT::i16, Custom); - // Libcalls names. - if (HWMultMode == HWMultIntr) { - setLibcallName(RTLIB::MUL_I8, "__mulqi3hw"); - setLibcallName(RTLIB::MUL_I16, "__mulhi3hw"); - } else if (HWMultMode == HWMultNoIntr) { - setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint"); - setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint"); + // EABI Libcalls - EABI Section 6.2 + const struct { + const RTLIB::Libcall Op; + const char * const Name; + const ISD::CondCode Cond; + } LibraryCalls[] = { + // Floating point conversions - EABI Table 6 + { RTLIB::FPROUND_F64_F32, "__mspabi_cvtdf", ISD::SETCC_INVALID }, + { RTLIB::FPEXT_F32_F64, "__mspabi_cvtfd", ISD::SETCC_INVALID }, + // The following is NOT implemented in libgcc + //{ RTLIB::FPTOSINT_F64_I16, "__mspabi_fixdi", ISD::SETCC_INVALID }, + { RTLIB::FPTOSINT_F64_I32, "__mspabi_fixdli", ISD::SETCC_INVALID }, + { RTLIB::FPTOSINT_F64_I64, "__mspabi_fixdlli", ISD::SETCC_INVALID }, + // The following is NOT implemented in libgcc + //{ RTLIB::FPTOUINT_F64_I16, "__mspabi_fixdu", ISD::SETCC_INVALID }, + { RTLIB::FPTOUINT_F64_I32, "__mspabi_fixdul", ISD::SETCC_INVALID }, + { RTLIB::FPTOUINT_F64_I64, "__mspabi_fixdull", ISD::SETCC_INVALID }, + // The following is NOT implemented in libgcc + //{ RTLIB::FPTOSINT_F32_I16, "__mspabi_fixfi", ISD::SETCC_INVALID }, + { RTLIB::FPTOSINT_F32_I32, "__mspabi_fixfli", ISD::SETCC_INVALID }, + { RTLIB::FPTOSINT_F32_I64, "__mspabi_fixflli", ISD::SETCC_INVALID }, + // The following is NOT implemented in libgcc + //{ RTLIB::FPTOUINT_F32_I16, "__mspabi_fixfu", ISD::SETCC_INVALID }, + { RTLIB::FPTOUINT_F32_I32, "__mspabi_fixful", ISD::SETCC_INVALID }, + { RTLIB::FPTOUINT_F32_I64, "__mspabi_fixfull", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc + //{ RTLIB::SINTTOFP_I16_F64, "__mspabi_fltid", ISD::SETCC_INVALID }, + { RTLIB::SINTTOFP_I32_F64, "__mspabi_fltlid", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc but is not in the EABI + { RTLIB::SINTTOFP_I64_F64, "__mspabi_fltllid", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc + //{ RTLIB::UINTTOFP_I16_F64, "__mspabi_fltud", ISD::SETCC_INVALID }, + { RTLIB::UINTTOFP_I32_F64, "__mspabi_fltuld", ISD::SETCC_INVALID }, + // The following IS implemented in libgcc but is not in the EABI + { RTLIB::UINTTOFP_I64_F64, "__mspabi_fltulld", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc + //{ RTLIB::SINTTOFP_I16_F32, "__mspabi_fltif", ISD::SETCC_INVALID }, + { RTLIB::SINTTOFP_I32_F32, "__mspabi_fltlif", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc but is not in the EABI + { RTLIB::SINTTOFP_I64_F32, "__mspabi_fltllif", ISD::SETCC_INVALID }, + // TODO The following IS implemented in libgcc + //{ RTLIB::UINTTOFP_I16_F32, "__mspabi_fltuf", ISD::SETCC_INVALID }, + { RTLIB::UINTTOFP_I32_F32, "__mspabi_fltulf", ISD::SETCC_INVALID }, + // The following IS implemented in libgcc but is not in the EABI + { RTLIB::UINTTOFP_I64_F32, "__mspabi_fltullf", ISD::SETCC_INVALID }, + + // Floating point comparisons - EABI Table 7 + { RTLIB::OEQ_F64, "__mspabi_cmpd", ISD::SETEQ }, + { RTLIB::UNE_F64, "__mspabi_cmpd", ISD::SETNE }, + { RTLIB::OGE_F64, "__mspabi_cmpd", ISD::SETGE }, + { RTLIB::OLT_F64, "__mspabi_cmpd", ISD::SETLT }, + { RTLIB::OLE_F64, "__mspabi_cmpd", ISD::SETLE }, + { RTLIB::OGT_F64, "__mspabi_cmpd", ISD::SETGT }, + { RTLIB::OEQ_F32, "__mspabi_cmpf", ISD::SETEQ }, + { RTLIB::UNE_F32, "__mspabi_cmpf", ISD::SETNE }, + { RTLIB::OGE_F32, "__mspabi_cmpf", ISD::SETGE }, + { RTLIB::OLT_F32, "__mspabi_cmpf", ISD::SETLT }, + { RTLIB::OLE_F32, "__mspabi_cmpf", ISD::SETLE }, + { RTLIB::OGT_F32, "__mspabi_cmpf", ISD::SETGT }, + + // Floating point arithmetic - EABI Table 8 + { RTLIB::ADD_F64, "__mspabi_addd", ISD::SETCC_INVALID }, + { RTLIB::ADD_F32, "__mspabi_addf", ISD::SETCC_INVALID }, + { RTLIB::DIV_F64, "__mspabi_divd", ISD::SETCC_INVALID }, + { RTLIB::DIV_F32, "__mspabi_divf", ISD::SETCC_INVALID }, + { RTLIB::MUL_F64, "__mspabi_mpyd", ISD::SETCC_INVALID }, + { RTLIB::MUL_F32, "__mspabi_mpyf", ISD::SETCC_INVALID }, + { RTLIB::SUB_F64, "__mspabi_subd", ISD::SETCC_INVALID }, + { RTLIB::SUB_F32, "__mspabi_subf", ISD::SETCC_INVALID }, + // The following are NOT implemented in libgcc + // { RTLIB::NEG_F64, "__mspabi_negd", ISD::SETCC_INVALID }, + // { RTLIB::NEG_F32, "__mspabi_negf", ISD::SETCC_INVALID }, + + // TODO: SLL/SRA/SRL are in libgcc, RLL isn't + + // Universal Integer Operations - EABI Table 9 + { RTLIB::SDIV_I16, "__mspabi_divi", ISD::SETCC_INVALID }, + { RTLIB::SDIV_I32, "__mspabi_divli", ISD::SETCC_INVALID }, + { RTLIB::SDIV_I64, "__mspabi_divlli", ISD::SETCC_INVALID }, + { RTLIB::UDIV_I16, "__mspabi_divu", ISD::SETCC_INVALID }, + { RTLIB::UDIV_I32, "__mspabi_divul", ISD::SETCC_INVALID }, + { RTLIB::UDIV_I64, "__mspabi_divull", ISD::SETCC_INVALID }, + { RTLIB::SREM_I16, "__mspabi_remi", ISD::SETCC_INVALID }, + { RTLIB::SREM_I32, "__mspabi_remli", ISD::SETCC_INVALID }, + { RTLIB::SREM_I64, "__mspabi_remlli", ISD::SETCC_INVALID }, + { RTLIB::UREM_I16, "__mspabi_remu", ISD::SETCC_INVALID }, + { RTLIB::UREM_I32, "__mspabi_remul", ISD::SETCC_INVALID }, + { RTLIB::UREM_I64, "__mspabi_remull", ISD::SETCC_INVALID }, + + }; + + for (const auto &LC : LibraryCalls) { + setLibcallName(LC.Op, LC.Name); + if (LC.Cond != ISD::SETCC_INVALID) + setCmpLibcallCC(LC.Op, LC.Cond); + } + + if (HWMultMode == HWMult16) { + const struct { + const RTLIB::Libcall Op; + const char * const Name; + } LibraryCalls[] = { + // Integer Multiply - EABI Table 9 + { RTLIB::MUL_I16, "__mspabi_mpyi_hw" }, + { RTLIB::MUL_I32, "__mspabi_mpyl_hw" }, + { RTLIB::MUL_I64, "__mspabi_mpyll_hw" }, + // TODO The __mspabi_mpysl*_hw functions ARE implemented in libgcc + // TODO The __mspabi_mpyul*_hw functions ARE implemented in libgcc + }; + for (const auto &LC : LibraryCalls) { + setLibcallName(LC.Op, LC.Name); + } + } else if (HWMultMode == HWMult32) { + const struct { + const RTLIB::Libcall Op; + const char * const Name; + } LibraryCalls[] = { + // Integer Multiply - EABI Table 9 + { RTLIB::MUL_I16, "__mspabi_mpyi_hw" }, + { RTLIB::MUL_I32, "__mspabi_mpyl_hw32" }, + { RTLIB::MUL_I64, "__mspabi_mpyll_hw32" }, + // TODO The __mspabi_mpysl*_hw32 functions ARE implemented in libgcc + // TODO The __mspabi_mpyul*_hw32 functions ARE implemented in libgcc + }; + for (const auto &LC : LibraryCalls) { + setLibcallName(LC.Op, LC.Name); + } + } else if (HWMultMode == HWMultF5) { + const struct { + const RTLIB::Libcall Op; + const char * const Name; + } LibraryCalls[] = { + // Integer Multiply - EABI Table 9 + { RTLIB::MUL_I16, "__mspabi_mpyi_f5hw" }, + { RTLIB::MUL_I32, "__mspabi_mpyl_f5hw" }, + { RTLIB::MUL_I64, "__mspabi_mpyll_f5hw" }, + // TODO The __mspabi_mpysl*_f5hw functions ARE implemented in libgcc + // TODO The __mspabi_mpyul*_f5hw functions ARE implemented in libgcc + }; + for (const auto &LC : LibraryCalls) { + setLibcallName(LC.Op, LC.Name); + } + } else { // NoHWMult + const struct { + const RTLIB::Libcall Op; + const char * const Name; + } LibraryCalls[] = { + // Integer Multiply - EABI Table 9 + { RTLIB::MUL_I16, "__mspabi_mpyi" }, + { RTLIB::MUL_I32, "__mspabi_mpyl" }, + { RTLIB::MUL_I64, "__mspabi_mpyll" }, + // The __mspabi_mpysl* functions are NOT implemented in libgcc + // The __mspabi_mpyul* functions are NOT implemented in libgcc + }; + for (const auto &LC : LibraryCalls) { + setLibcallName(LC.Op, LC.Name); + } + setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::MSP430_BUILTIN); } + // Several of the runtime library functions use a special calling conv + setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::MSP430_BUILTIN); + setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::MSP430_BUILTIN); + // TODO: __mspabi_srall, __mspabi_srlll, __mspabi_sllll + setMinFunctionAlignment(1); setPrefFunctionAlignment(2); } @@ -281,10 +452,27 @@ template<typename ArgT> static void AnalyzeArguments(CCState &State, SmallVectorImpl<CCValAssign> &ArgLocs, const SmallVectorImpl<ArgT> &Args) { - static const MCPhysReg RegList[] = { + static const MCPhysReg CRegList[] = { MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15 }; - static const unsigned NbRegs = array_lengthof(RegList); + static const unsigned CNbRegs = array_lengthof(CRegList); + static const MCPhysReg BuiltinRegList[] = { + MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15 + }; + static const unsigned BuiltinNbRegs = array_lengthof(BuiltinRegList); + + ArrayRef<MCPhysReg> RegList; + unsigned NbRegs; + + bool Builtin = (State.getCallingConv() == CallingConv::MSP430_BUILTIN); + if (Builtin) { + RegList = BuiltinRegList; + NbRegs = BuiltinNbRegs; + } else { + RegList = CRegList; + NbRegs = CNbRegs; + } if (State.isVarArg()) { AnalyzeVarArgs(State, Args); @@ -294,6 +482,11 @@ static void AnalyzeArguments(CCState &State, SmallVector<unsigned, 4> ArgsParts; ParseFunctionArgs(Args, ArgsParts); + if (Builtin) { + assert(ArgsParts.size() == 2 && + "Builtin calling convention requires two arguments"); + } + unsigned RegsLeft = NbRegs; bool UsedStack = false; unsigned ValNo = 0; @@ -323,6 +516,11 @@ static void AnalyzeArguments(CCState &State, unsigned Parts = ArgsParts[i]; + if (Builtin) { + assert(Parts == 4 && + "Builtin calling convention requires 64-bit arguments"); + } + if (!UsedStack && Parts == 2 && RegsLeft == 1) { // Special case for 32-bit register split, see EABI section 3.3.3 unsigned Reg = State.AllocateReg(RegList); @@ -400,6 +598,7 @@ MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, switch (CallConv) { default: llvm_unreachable("Unsupported calling convention"); + case CallingConv::MSP430_BUILTIN: case CallingConv::Fast: case CallingConv::C: return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall, @@ -598,7 +797,6 @@ MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, /// LowerCCCCallTo - functions arguments are copied from virtual regs to /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted. -// TODO: sret. SDValue MSP430TargetLowering::LowerCCCCallTo( SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs, @@ -615,8 +813,7 @@ SDValue MSP430TargetLowering::LowerCCCCallTo( unsigned NumBytes = CCInfo.getNextStackOffset(); auto PtrVT = getPointerTy(DAG.getDataLayout()); - Chain = DAG.getCALLSEQ_START(Chain, - DAG.getConstant(NumBytes, dl, PtrVT, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass; SmallVector<SDValue, 12> MemOpChains; diff --git a/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h b/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h index e3259bd6a7bc..d81f17e753c5 100644 --- a/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h +++ b/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h @@ -85,6 +85,12 @@ public: MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded = nullptr) const override; + + int64_t getFramePoppedByCallee(const MachineInstr &I) const { + assert(isFrameInstr(I) && "Not a frame instruction"); + assert(I.getOperand(1).getImm() >= 0 && "Size must not be negative"); + return I.getOperand(1).getImm(); + } }; } diff --git a/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td b/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td index 22fc2474fae6..1cd18611e52c 100644 --- a/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td +++ b/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td @@ -23,7 +23,8 @@ class SDTCisI16<int OpNum> : SDTCisVT<OpNum, i16>; // Type Profiles. //===----------------------------------------------------------------------===// def SDT_MSP430Call : SDTypeProfile<0, -1, [SDTCisVT<0, iPTR>]>; -def SDT_MSP430CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i16>]>; +def SDT_MSP430CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i16>, + SDTCisVT<1, i16>]>; def SDT_MSP430CallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i16>, SDTCisVT<1, i16>]>; def SDT_MSP430Wrapper : SDTypeProfile<1, 1, [SDTCisSameAs<0, 1>, SDTCisPtrTy<0>]>; @@ -113,9 +114,9 @@ def and_su : PatFrag<(ops node:$lhs, node:$rhs), (and node:$lhs, node:$rhs), [{ // Pessimistically assume ADJCALLSTACKDOWN / ADJCALLSTACKUP will become // sub / add which can clobber SR. let Defs = [SP, SR], Uses = [SP] in { -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i16imm:$amt), +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i16imm:$amt1, i16imm:$amt2), "#ADJCALLSTACKDOWN", - [(MSP430callseq_start timm:$amt)]>; + [(MSP430callseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i16imm:$amt1, i16imm:$amt2), "#ADJCALLSTACKUP", [(MSP430callseq_end timm:$amt1, timm:$amt2)]>; @@ -209,7 +210,7 @@ let isCall = 1 in // a use to prevent stack-pointer assignments that appear immediately // before calls from potentially appearing dead. Uses for argument // registers are added manually. - let Defs = [R12, R13, R14, R15, SR], + let Defs = [R11, R12, R13, R14, R15, SR], Uses = [SP] in { def CALLi : II16i<0x0, (outs), (ins i16imm:$dst), diff --git a/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp b/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp index 81cd9d1ad3f8..9600bc28f100 100644 --- a/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp +++ b/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp @@ -41,12 +41,12 @@ MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { const Function* F = MF->getFunction(); static const MCPhysReg CalleeSavedRegs[] = { MSP430::FP, MSP430::R5, MSP430::R6, MSP430::R7, - MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + MSP430::R8, MSP430::R9, MSP430::R10, 0 }; static const MCPhysReg CalleeSavedRegsFP[] = { MSP430::R5, MSP430::R6, MSP430::R7, - MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + MSP430::R8, MSP430::R9, MSP430::R10, 0 }; static const MCPhysReg CalleeSavedRegsIntr[] = { diff --git a/contrib/llvm/lib/Target/Mips/MipsFastISel.cpp b/contrib/llvm/lib/Target/Mips/MipsFastISel.cpp index 21c99da0922d..b83f44a74d5b 100644 --- a/contrib/llvm/lib/Target/Mips/MipsFastISel.cpp +++ b/contrib/llvm/lib/Target/Mips/MipsFastISel.cpp @@ -1133,7 +1133,7 @@ bool MipsFastISel::processCallArgs(CallLoweringInfo &CLI, if (NumBytes < 16) NumBytes = 16; - emitInst(Mips::ADJCALLSTACKDOWN).addImm(16); + emitInst(Mips::ADJCALLSTACKDOWN).addImm(16).addImm(0); // Process the args. MVT firstMVT; for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { diff --git a/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp b/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp index 8f39ebd42a5c..78bae6954c3c 100644 --- a/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp +++ b/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp @@ -2787,7 +2787,7 @@ MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true); if (!IsTailCall) - Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL); + Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL); SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, diff --git a/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td b/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td index b90077d7807d..8761946b8dbb 100644 --- a/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td +++ b/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td @@ -21,7 +21,7 @@ def SDT_MipsCMov : SDTypeProfile<1, 4, [SDTCisSameAs<0, 1>, SDTCisSameAs<1, 2>, SDTCisSameAs<3, 4>, SDTCisInt<4>]>; -def SDT_MipsCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>]>; +def SDT_MipsCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>, SDTCisVT<1, i32>]>; def SDT_MipsCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i32>, SDTCisVT<1, i32>]>; def SDT_MFLOHI : SDTypeProfile<1, 1, [SDTCisInt<0>, SDTCisVT<1, untyped>]>; def SDT_MTLOHI : SDTypeProfile<1, 2, [SDTCisVT<0, untyped>, @@ -1719,8 +1719,8 @@ let isReturn=1, isTerminator=1, isBarrier=1, hasCtrlDep=1, isCTI=1 in { } let Defs = [SP], Uses = [SP], hasSideEffects = 1 in { -def ADJCALLSTACKDOWN : MipsPseudo<(outs), (ins i32imm:$amt), - [(callseq_start timm:$amt)]>; +def ADJCALLSTACKDOWN : MipsPseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), + [(callseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : MipsPseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), [(callseq_end timm:$amt1, timm:$amt2)]>; } diff --git a/contrib/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp b/contrib/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp index 68dcbdfb4211..f8d9c34556bc 100644 --- a/contrib/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp +++ b/contrib/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp @@ -257,7 +257,7 @@ bool OptimizePICCall::isCallViaRegister(MachineInstr &MI, unsigned &Reg, // Get the instruction that loads the function address from the GOT. Reg = MO->getReg(); - Val = (Value*)nullptr; + Val = nullptr; MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); MachineInstr *DefMI = MRI.getVRegDef(Reg); diff --git a/contrib/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp b/contrib/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp index 61fdda8aa109..ebaaf42bc64e 100644 --- a/contrib/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp +++ b/contrib/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp @@ -1430,8 +1430,7 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, return Chain;
SDValue tempChain = Chain;
- Chain = DAG.getCALLSEQ_START(
- Chain, DAG.getIntPtrConstant(uniqueCallSite, dl, true), dl);
+ Chain = DAG.getCALLSEQ_START(Chain, uniqueCallSite, 0, dl);
SDValue InFlag = Chain.getValue(1);
unsigned paramCount = 0;
@@ -1549,7 +1548,9 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, Chain = DAG.getMemIntrinsicNode(
Op, dl, DAG.getVTList(MVT::Other, MVT::Glue), StoreOperands,
- TheStoreType, MachinePointerInfo(), EltAlign);
+ TheStoreType, MachinePointerInfo(), EltAlign,
+ /* Volatile */ false, /* ReadMem */ false,
+ /* WriteMem */ true, /* Size */ 0);
InFlag = Chain.getValue(1);
// Cleanup.
@@ -1609,7 +1610,9 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, theVal, InFlag };
Chain = DAG.getMemIntrinsicNode(NVPTXISD::StoreParam, dl, CopyParamVTs,
CopyParamOps, elemtype,
- MachinePointerInfo());
+ MachinePointerInfo(), /* Align */ 0,
+ /* Volatile */ false, /* ReadMem */ false,
+ /* WriteMem */ true, /* Size */ 0);
InFlag = Chain.getValue(1);
}
@@ -1795,7 +1798,8 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, DAG.getConstant(Offsets[VecIdx], dl, MVT::i32), InFlag};
SDValue RetVal = DAG.getMemIntrinsicNode(
Op, dl, DAG.getVTList(LoadVTs), LoadOperands, TheLoadType,
- MachinePointerInfo(), EltAlign);
+ MachinePointerInfo(), EltAlign, /* Volatile */ false,
+ /* ReadMem */ true, /* WriteMem */ false, /* Size */ 0);
for (unsigned j = 0; j < NumElts; ++j) {
SDValue Ret = RetVal.getValue(j);
@@ -2579,7 +2583,9 @@ NVPTXTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, EVT TheStoreType = ExtendIntegerRetVal ? MVT::i32 : VTs[i];
Chain = DAG.getMemIntrinsicNode(Op, dl, DAG.getVTList(MVT::Other),
StoreOperands, TheStoreType,
- MachinePointerInfo(), 1);
+ MachinePointerInfo(), /* Align */ 1,
+ /* Volatile */ false, /* ReadMem */ false,
+ /* WriteMem */ true, /* Size */ 0);
// Cleanup vector state.
StoreOperands.clear();
}
diff --git a/contrib/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td b/contrib/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td index 9378b29a9d0e..b5b5ea1ed639 100644 --- a/contrib/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td +++ b/contrib/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td @@ -3101,7 +3101,8 @@ def : Pat<(brcond (i1 (setne Int1Regs:$a, -1)), bb:$target), (CBranchOther Int1Regs:$a, bb:$target)>;
// Call
-def SDT_NVPTXCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>]>;
+def SDT_NVPTXCallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>,
+ SDTCisVT<1, i32>]>;
def SDT_NVPTXCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i32>, SDTCisVT<1, i32>]>;
def callseq_start : SDNode<"ISD::CALLSEQ_START", SDT_NVPTXCallSeqStart,
@@ -3126,10 +3127,10 @@ class Pseudo<dag outs, dag ins, string asmstr, list<dag> pattern> : NVPTXInst<outs, ins, asmstr, pattern>;
def Callseq_Start :
- NVPTXInst<(outs), (ins i32imm:$amt),
- "\\{ // callseq $amt\n"
+ NVPTXInst<(outs), (ins i32imm:$amt1, i32imm:$amt2),
+ "\\{ // callseq $amt1, $amt2\n"
"\t.reg .b32 temp_param_reg;",
- [(callseq_start timm:$amt)]>;
+ [(callseq_start timm:$amt1, timm:$amt2)]>;
def Callseq_End :
NVPTXInst<(outs), (ins i32imm:$amt1, i32imm:$amt2),
"\\} // callseq $amt1",
diff --git a/contrib/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp b/contrib/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp index 12ffbfdeacc1..11d22377611b 100644 --- a/contrib/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp +++ b/contrib/llvm/lib/Target/PowerPC/Disassembler/PPCDisassembler.cpp @@ -204,6 +204,17 @@ static const unsigned G8Regs[] = { PPC::X28, PPC::X29, PPC::X30, PPC::X31 }; +static const unsigned G80Regs[] = { + PPC::ZERO8, PPC::X1, PPC::X2, PPC::X3, + PPC::X4, PPC::X5, PPC::X6, PPC::X7, + PPC::X8, PPC::X9, PPC::X10, PPC::X11, + PPC::X12, PPC::X13, PPC::X14, PPC::X15, + PPC::X16, PPC::X17, PPC::X18, PPC::X19, + PPC::X20, PPC::X21, PPC::X22, PPC::X23, + PPC::X24, PPC::X25, PPC::X26, PPC::X27, + PPC::X28, PPC::X29, PPC::X30, PPC::X31 +}; + static const unsigned QFRegs[] = { PPC::QF0, PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, @@ -301,6 +312,12 @@ static DecodeStatus DecodeG8RCRegisterClass(MCInst &Inst, uint64_t RegNo, return decodeRegisterClass(Inst, RegNo, G8Regs); } +static DecodeStatus DecodeG8RC_NOX0RegisterClass(MCInst &Inst, uint64_t RegNo, + uint64_t Address, + const void *Decoder) { + return decodeRegisterClass(Inst, RegNo, G80Regs); +} + #define DecodePointerLikeRegClass0 DecodeGPRCRegisterClass #define DecodePointerLikeRegClass1 DecodeGPRC_NOR0RegisterClass diff --git a/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp b/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp index 609d959c6d08..84bb9ec56800 100644 --- a/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp +++ b/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp @@ -95,7 +95,8 @@ void PPCInstPrinter::printInst(const MCInst *MI, raw_ostream &O, return; } - if (MI->getOpcode() == PPC::RLDICR) { + if (MI->getOpcode() == PPC::RLDICR || + MI->getOpcode() == PPC::RLDICR_32) { unsigned char SH = MI->getOperand(2).getImm(); unsigned char ME = MI->getOperand(3).getImm(); // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH diff --git a/contrib/llvm/lib/Target/PowerPC/PPCFastISel.cpp b/contrib/llvm/lib/Target/PowerPC/PPCFastISel.cpp index 9b91b9ab8f82..2fc8654deeab 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCFastISel.cpp +++ b/contrib/llvm/lib/Target/PowerPC/PPCFastISel.cpp @@ -1330,7 +1330,7 @@ bool PPCFastISel::processCallArgs(SmallVectorImpl<Value*> &Args, // Issue CALLSEQ_START. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TII.getCallFrameSetupOpcode())) - .addImm(NumBytes); + .addImm(NumBytes).addImm(0); // Prepare to assign register arguments. Every argument uses up a // GPR protocol register even if it's passed in a floating-point @@ -2246,6 +2246,7 @@ bool PPCFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, } case PPC::EXTSW: + case PPC::EXTSW_32: case PPC::EXTSW_32_64: { if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8) return false; diff --git a/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp b/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp index 1b0402bf003d..5fa7b2c6bfb1 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp +++ b/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp @@ -54,6 +54,7 @@ #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetRegisterInfo.h" +#include "llvm/ADT/Statistic.h" #include <algorithm> #include <cassert> #include <cstdint> @@ -68,6 +69,14 @@ using namespace llvm; #define DEBUG_TYPE "ppc-codegen" +STATISTIC(NumSextSetcc, + "Number of (sext(setcc)) nodes expanded into GPR sequence."); +STATISTIC(NumZextSetcc, + "Number of (zext(setcc)) nodes expanded into GPR sequence."); +STATISTIC(SignExtensionsAdded, + "Number of sign extensions for compare inputs added."); +STATISTIC(ZeroExtensionsAdded, + "Number of zero extensions for compare inputs added."); // FIXME: Remove this once the bug has been fixed! cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug", cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden); @@ -252,7 +261,28 @@ namespace { #include "PPCGenDAGISel.inc" private: + // Conversion type for interpreting results of a 32-bit instruction as + // a 64-bit value or vice versa. + enum ExtOrTruncConversion { Ext, Trunc }; + + // Modifiers to guide how an ISD::SETCC node's result is to be computed + // in a GPR. + // ZExtOrig - use the original condition code, zero-extend value + // ZExtInvert - invert the condition code, zero-extend value + // SExtOrig - use the original condition code, sign-extend value + // SExtInvert - invert the condition code, sign-extend value + enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert }; + bool trySETCC(SDNode *N); + bool tryEXTEND(SDNode *N); + SDValue signExtendInputIfNeeded(SDValue Input); + SDValue zeroExtendInputIfNeeded(SDValue Input); + SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv); + SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, + int64_t RHSValue, SDLoc dl); + SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, + int64_t RHSValue, SDLoc dl); + SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts); void PeepholePPC64(); void PeepholePPC64ZExt(); @@ -2471,6 +2501,225 @@ bool PPCDAGToDAGISel::trySETCC(SDNode *N) { return true; } +/// If this node is a sign/zero extension of an integer comparison, +/// it can usually be computed in GPR's rather than using comparison +/// instructions and ISEL. We only do this on 64-bit targets for now +/// as the code is specialized for 64-bit (it uses 64-bit instructions +/// and assumes 64-bit registers). +bool PPCDAGToDAGISel::tryEXTEND(SDNode *N) { + if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64()) + return false; + assert((N->getOpcode() == ISD::ZERO_EXTEND || + N->getOpcode() == ISD::SIGN_EXTEND) && + "Expecting a zero/sign extend node!"); + + if (N->getOperand(0).getOpcode() != ISD::SETCC) + return false; + + SDValue WideRes = + getSETCCInGPR(N->getOperand(0), + N->getOpcode() == ISD::SIGN_EXTEND ? + SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig); + + if (!WideRes) + return false; + + SDLoc dl(N); + bool Inputs32Bit = N->getOperand(0).getOperand(0).getValueType() == MVT::i32; + bool Output32Bit = N->getValueType(0) == MVT::i32; + + NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0; + NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1; + + SDValue ConvOp = WideRes; + if (Inputs32Bit != Output32Bit) + ConvOp = addExtOrTrunc(WideRes, Inputs32Bit ? ExtOrTruncConversion::Ext : + ExtOrTruncConversion::Trunc); + ReplaceNode(N, ConvOp.getNode()); + + return true; +} + +/// If the value isn't guaranteed to be sign-extended to 64-bits, extend it. +/// Useful when emitting comparison code for 32-bit values without using +/// the compare instruction (which only considers the lower 32-bits). +SDValue PPCDAGToDAGISel::signExtendInputIfNeeded(SDValue Input) { + assert(Input.getValueType() == MVT::i32 && + "Can only sign-extend 32-bit values here."); + unsigned Opc = Input.getOpcode(); + + // The value was sign extended and then truncated to 32-bits. No need to + // sign extend it again. + if (Opc == ISD::TRUNCATE && + (Input.getOperand(0).getOpcode() == ISD::AssertSext || + Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND)) + return Input; + + LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); + // The input is a sign-extending load. No reason to sign-extend. + if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD) + return Input; + + ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); + // We don't sign-extend constants and already sign-extended values. + if (InputConst || Opc == ISD::AssertSext || Opc == ISD::SIGN_EXTEND_INREG || + Opc == ISD::SIGN_EXTEND) + return Input; + + SDLoc dl(Input); + SignExtensionsAdded++; + return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32, dl, MVT::i32, Input), 0); +} + +/// If the value isn't guaranteed to be zero-extended to 64-bits, extend it. +/// Useful when emitting comparison code for 32-bit values without using +/// the compare instruction (which only considers the lower 32-bits). +SDValue PPCDAGToDAGISel::zeroExtendInputIfNeeded(SDValue Input) { + assert(Input.getValueType() == MVT::i32 && + "Can only zero-extend 32-bit values here."); + LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); + unsigned Opc = Input.getOpcode(); + + // No need to zero-extend loaded values (unless they're loaded with + // a sign-extending load). + if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD) + return Input; + + ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); + bool InputZExtConst = InputConst && InputConst->getSExtValue() >= 0; + // An ISD::TRUNCATE will be lowered to an EXTRACT_SUBREG so we have + // to conservatively actually clear the high bits. We also don't need to + // zero-extend constants or values that are already zero-extended. + if (InputZExtConst || Opc == ISD::AssertZext || Opc == ISD::ZERO_EXTEND) + return Input; + + SDLoc dl(Input); + ZeroExtensionsAdded++; + return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32, Input, + getI64Imm(0, dl), getI64Imm(32, dl)), + 0); +} + +// Handle a 32-bit value in a 64-bit register and vice-versa. These are of +// course not actual zero/sign extensions that will generate machine code, +// they're just a way to reinterpret a 32 bit value in a register as a +// 64 bit value and vice-versa. +SDValue PPCDAGToDAGISel::addExtOrTrunc(SDValue NatWidthRes, + ExtOrTruncConversion Conv) { + SDLoc dl(NatWidthRes); + + // For reinterpreting 32-bit values as 64 bit values, we generate + // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1> + if (Conv == ExtOrTruncConversion::Ext) { + SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0); + SDValue SubRegIdx = + CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); + return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64, + ImDef, NatWidthRes, SubRegIdx), 0); + } + + assert(Conv == ExtOrTruncConversion::Trunc && + "Unknown convertion between 32 and 64 bit values."); + // For reinterpreting 64-bit values as 32-bit values, we just need to + // EXTRACT_SUBREG (i.e. extract the low word). + SDValue SubRegIdx = + CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); + return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32, + NatWidthRes, SubRegIdx), 0); +} + +/// Produces a zero-extended result of comparing two 32-bit values according to +/// the passed condition code. +SDValue PPCDAGToDAGISel::get32BitZExtCompare(SDValue LHS, SDValue RHS, + ISD::CondCode CC, + int64_t RHSValue, SDLoc dl) { + bool IsRHSZero = RHSValue == 0; + switch (CC) { + default: return SDValue(); + case ISD::SETEQ: { + // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5) + // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5) + SDValue Xor = IsRHSZero ? LHS : + SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); + SDValue Clz = + SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); + SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl), + getI32Imm(31, dl) }; + return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, + ShiftOps), 0); + } + } +} + +/// Produces a sign-extended result of comparing two 32-bit values according to +/// the passed condition code. +SDValue PPCDAGToDAGISel::get32BitSExtCompare(SDValue LHS, SDValue RHS, + ISD::CondCode CC, + int64_t RHSValue, SDLoc dl) { + bool IsRHSZero = RHSValue == 0; + switch (CC) { + default: return SDValue(); + case ISD::SETEQ: { + // (sext (setcc %a, %b, seteq)) -> + // (ashr (shl (ctlz (xor %a, %b)), 58), 63) + // (sext (setcc %a, 0, seteq)) -> + // (ashr (shl (ctlz %a), 58), 63) + SDValue CountInput = IsRHSZero ? LHS : + SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); + SDValue Cntlzw = + SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0); + SDValue SHLOps[] = { Cntlzw, getI32Imm(58, dl), getI32Imm(0, dl) }; + SDValue Sldi = + SDValue(CurDAG->getMachineNode(PPC::RLDICR_32, dl, MVT::i32, SHLOps), 0); + return SDValue(CurDAG->getMachineNode(PPC::SRADI_32, dl, MVT::i32, Sldi, + getI32Imm(63, dl)), 0); + } + } +} + +/// Returns an equivalent of a SETCC node but with the result the same width as +/// the inputs. This can nalso be used for SELECT_CC if either the true or false +/// values is a power of two while the other is zero. +SDValue PPCDAGToDAGISel::getSETCCInGPR(SDValue Compare, + SetccInGPROpts ConvOpts) { + assert((Compare.getOpcode() == ISD::SETCC || + Compare.getOpcode() == ISD::SELECT_CC) && + "An ISD::SETCC node required here."); + + SDValue LHS = Compare.getOperand(0); + SDValue RHS = Compare.getOperand(1); + + // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC. + int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2; + ISD::CondCode CC = + cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get(); + EVT InputVT = LHS.getValueType(); + if (InputVT != MVT::i32) + return SDValue(); + + SDLoc dl(Compare); + ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); + int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX; + + if (ConvOpts == SetccInGPROpts::ZExtInvert || + ConvOpts == SetccInGPROpts::SExtInvert) + CC = ISD::getSetCCInverse(CC, true); + + if (ISD::isSignedIntSetCC(CC)) { + LHS = signExtendInputIfNeeded(LHS); + RHS = signExtendInputIfNeeded(RHS); + } else if (ISD::isUnsignedIntSetCC(CC)) { + LHS = zeroExtendInputIfNeeded(LHS); + RHS = zeroExtendInputIfNeeded(RHS); + } + + bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig || + ConvOpts == SetccInGPROpts::SExtInvert; + if (IsSext) + return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl); + return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl); +} + void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) { // Transfer memoperands. MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1); @@ -2508,6 +2757,12 @@ void PPCDAGToDAGISel::Select(SDNode *N) { } break; + case ISD::ZERO_EXTEND: + case ISD::SIGN_EXTEND: + if (tryEXTEND(N)) + return; + break; + case ISD::SETCC: if (trySETCC(N)) return; diff --git a/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp b/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp index 685f24cb502e..17bdd595da10 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp +++ b/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp @@ -923,6 +923,9 @@ PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); // We have target-specific dag combine patterns for the following nodes: + setTargetDAGCombine(ISD::SHL); + setTargetDAGCombine(ISD::SRA); + setTargetDAGCombine(ISD::SRL); setTargetDAGCombine(ISD::SINT_TO_FP); setTargetDAGCombine(ISD::BUILD_VECTOR); if (Subtarget.hasFPCVT()) @@ -4949,8 +4952,7 @@ SDValue PPCTargetLowering::LowerCall_32SVR4( // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), - dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be moved somewhere else @@ -5000,9 +5002,8 @@ SDValue PPCTargetLowering::LowerCall_32SVR4( Flags, DAG, dl); // This must go outside the CALLSEQ_START..END. - SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, - CallSeqStart.getNode()->getOperand(1), - SDLoc(MemcpyCall)); + SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, + SDLoc(MemcpyCall)); DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode()); Chain = CallSeqStart = NewCallSeqStart; @@ -5083,9 +5084,9 @@ SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( CallSeqStart.getNode()->getOperand(0), Flags, DAG, dl); // The MEMCPY must go outside the CALLSEQ_START..END. - SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, - CallSeqStart.getNode()->getOperand(1), - SDLoc(MemcpyCall)); + int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); + SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, + SDLoc(MemcpyCall)); DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode()); return NewCallSeqStart; @@ -5268,8 +5269,7 @@ SDValue PPCTargetLowering::LowerCall_64SVR4( // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass if (!IsSibCall) - Chain = DAG.getCALLSEQ_START(Chain, - DAG.getIntPtrConstant(NumBytes, dl, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be move somewhere else @@ -5828,8 +5828,7 @@ SDValue PPCTargetLowering::LowerCall_Darwin( // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), - dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be move somewhere else @@ -8741,9 +8740,9 @@ static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { // The mappings for emitLeading/TrailingFence is taken from // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html -Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { +Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, + Instruction *Inst, + AtomicOrdering Ord) const { if (Ord == AtomicOrdering::SequentiallyConsistent) return callIntrinsic(Builder, Intrinsic::ppc_sync); if (isReleaseOrStronger(Ord)) @@ -8751,10 +8750,10 @@ Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, return nullptr; } -Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, - AtomicOrdering Ord, bool IsStore, - bool IsLoad) const { - if (IsLoad && isAcquireOrStronger(Ord)) +Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, + Instruction *Inst, + AtomicOrdering Ord) const { + if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) return callIntrinsic(Builder, Intrinsic::ppc_lwsync); // FIXME: this is too conservative, a dependent branch + isync is enough. // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and @@ -11316,6 +11315,12 @@ SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, SDLoc dl(N); switch (N->getOpcode()) { default: break; + case ISD::SHL: + return combineSHL(N, DCI); + case ISD::SRA: + return combineSRA(N, DCI); + case ISD::SRL: + return combineSRL(N, DCI); case PPCISD::SHL: if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. return N->getOperand(0); @@ -12948,3 +12953,58 @@ bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { return Imm.isPosZero(); } } + +// For vector shift operation op, fold +// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) +static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, + SelectionDAG &DAG) { + SDValue N0 = N->getOperand(0); + SDValue N1 = N->getOperand(1); + EVT VT = N0.getValueType(); + unsigned OpSizeInBits = VT.getScalarSizeInBits(); + unsigned Opcode = N->getOpcode(); + unsigned TargetOpcode; + + switch (Opcode) { + default: + llvm_unreachable("Unexpected shift operation"); + case ISD::SHL: + TargetOpcode = PPCISD::SHL; + break; + case ISD::SRL: + TargetOpcode = PPCISD::SRL; + break; + case ISD::SRA: + TargetOpcode = PPCISD::SRA; + break; + } + + if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && + N1->getOpcode() == ISD::AND) + if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) + if (Mask->getZExtValue() == OpSizeInBits - 1) + return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); + + return SDValue(); +} + +SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { + if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) + return Value; + + return SDValue(); +} + +SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { + if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) + return Value; + + return SDValue(); +} + +SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { + if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) + return Value; + + return SDValue(); +} diff --git a/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h b/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h index 32661099b79d..4fc744257262 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h +++ b/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h @@ -117,9 +117,13 @@ namespace llvm { /// at function entry, used for PIC code. GlobalBaseReg, - /// These nodes represent the 32-bit PPC shifts that operate on 6-bit - /// shift amounts. These nodes are generated by the multi-precision shift - /// code. + /// These nodes represent PPC shifts. + /// + /// For scalar types, only the last `n + 1` bits of the shift amounts + /// are used, where n is log2(sizeof(element) * 8). See sld/slw, etc. + /// for exact behaviors. + /// + /// For vector types, only the last n bits are used. See vsld. SRL, SRA, SHL, /// The combination of sra[wd]i and addze used to implemented signed @@ -617,10 +621,10 @@ namespace llvm { return true; } - Instruction* emitLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord, - bool IsStore, bool IsLoad) const override; - Instruction* emitTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord, - bool IsStore, bool IsLoad) const override; + Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst, + AtomicOrdering Ord) const override; + Instruction *emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst, + AtomicOrdering Ord) const override; MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, @@ -999,6 +1003,9 @@ namespace llvm { SDValue DAGCombineBuildVector(SDNode *N, DAGCombinerInfo &DCI) const; SDValue DAGCombineTruncBoolExt(SDNode *N, DAGCombinerInfo &DCI) const; SDValue combineFPToIntToFP(SDNode *N, DAGCombinerInfo &DCI) const; + SDValue combineSHL(SDNode *N, DAGCombinerInfo &DCI) const; + SDValue combineSRA(SDNode *N, DAGCombinerInfo &DCI) const; + SDValue combineSRL(SDNode *N, DAGCombinerInfo &DCI) const; /// ConvertSETCCToSubtract - looks at SETCC that compares ints. It replaces /// SETCC with integer subtraction when (1) there is a legal way of doing it @@ -1017,14 +1024,6 @@ namespace llvm { SDValue combineElementTruncationToVectorTruncation(SDNode *N, DAGCombinerInfo &DCI) const; - - bool supportsModuloShift(ISD::NodeType Inst, - EVT ReturnType) const override { - assert((Inst == ISD::SHL || Inst == ISD::SRA || Inst == ISD::SRL) && - "Expect a shift instruction"); - assert(isOperationLegal(Inst, ReturnType)); - return ReturnType.isVector(); - } }; namespace PPC { diff --git a/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td b/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td index 997b96ca6ec8..a8433919f0f3 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td +++ b/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td @@ -634,10 +634,19 @@ let Interpretation64Bit = 1, isCodeGenOnly = 1 in defm EXTSW_32_64 : XForm_11r<31, 986, (outs g8rc:$rA), (ins gprc:$rS), "extsw", "$rA, $rS", IIC_IntSimple, [(set i64:$rA, (sext i32:$rS))]>, isPPC64; +let isCodeGenOnly = 1 in +def EXTSW_32 : XForm_11<31, 986, (outs gprc:$rA), (ins gprc:$rS), + "extsw $rA, $rS", IIC_IntSimple, + []>, isPPC64; defm SRADI : XSForm_1rc<31, 413, (outs g8rc:$rA), (ins g8rc:$rS, u6imm:$SH), "sradi", "$rA, $rS, $SH", IIC_IntRotateDI, [(set i64:$rA, (sra i64:$rS, (i32 imm:$SH)))]>, isPPC64; +// For fast-isel: +let isCodeGenOnly = 1 in +def SRADI_32 : XSForm_1<31, 413, (outs gprc:$rA), (ins gprc:$rS, u6imm:$SH), + "sradi $rA, $rS, $SH", IIC_IntRotateDI, []>, isPPC64; + defm CNTLZD : XForm_11r<31, 58, (outs g8rc:$rA), (ins g8rc:$rS), "cntlzd", "$rA, $rS", IIC_IntGeneral, [(set i64:$rA, (ctlz i64:$rS))]>; @@ -721,15 +730,26 @@ defm RLDICL : MDForm_1r<30, 0, // For fast-isel: let isCodeGenOnly = 1 in def RLDICL_32_64 : MDForm_1<30, 0, - (outs g8rc:$rA), - (ins gprc:$rS, u6imm:$SH, u6imm:$MBE), - "rldicl $rA, $rS, $SH, $MBE", IIC_IntRotateDI, - []>, isPPC64; + (outs g8rc:$rA), + (ins gprc:$rS, u6imm:$SH, u6imm:$MBE), + "rldicl $rA, $rS, $SH, $MBE", IIC_IntRotateDI, + []>, isPPC64; // End fast-isel. +let isCodeGenOnly = 1 in +def RLDICL_32 : MDForm_1<30, 0, + (outs gprc:$rA), + (ins gprc:$rS, u6imm:$SH, u6imm:$MBE), + "rldicl $rA, $rS, $SH, $MBE", IIC_IntRotateDI, + []>, isPPC64; defm RLDICR : MDForm_1r<30, 1, (outs g8rc:$rA), (ins g8rc:$rS, u6imm:$SH, u6imm:$MBE), "rldicr", "$rA, $rS, $SH, $MBE", IIC_IntRotateDI, []>, isPPC64; +let isCodeGenOnly = 1 in +def RLDICR_32 : MDForm_1<30, 1, + (outs gprc:$rA), (ins gprc:$rS, u6imm:$SH, u6imm:$MBE), + "rldicr $rA, $rS, $SH, $MBE", IIC_IntRotateDI, + []>, isPPC64; defm RLDIC : MDForm_1r<30, 2, (outs g8rc:$rA), (ins g8rc:$rS, u6imm:$SH, u6imm:$MBE), "rldic", "$rA, $rS, $SH, $MBE", IIC_IntRotateDI, diff --git a/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td b/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td index c380766e9f5c..e14d18fd5433 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td +++ b/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td @@ -987,6 +987,12 @@ def : Pat<(v8i16 (shl v8i16:$vA, v8i16:$vB)), (v8i16 (VSLH $vA, $vB))>; def : Pat<(v4i32 (shl v4i32:$vA, v4i32:$vB)), (v4i32 (VSLW $vA, $vB))>; +def : Pat<(v16i8 (PPCshl v16i8:$vA, v16i8:$vB)), + (v16i8 (VSLB $vA, $vB))>; +def : Pat<(v8i16 (PPCshl v8i16:$vA, v8i16:$vB)), + (v8i16 (VSLH $vA, $vB))>; +def : Pat<(v4i32 (PPCshl v4i32:$vA, v4i32:$vB)), + (v4i32 (VSLW $vA, $vB))>; def : Pat<(v16i8 (srl v16i8:$vA, v16i8:$vB)), (v16i8 (VSRB $vA, $vB))>; @@ -994,6 +1000,12 @@ def : Pat<(v8i16 (srl v8i16:$vA, v8i16:$vB)), (v8i16 (VSRH $vA, $vB))>; def : Pat<(v4i32 (srl v4i32:$vA, v4i32:$vB)), (v4i32 (VSRW $vA, $vB))>; +def : Pat<(v16i8 (PPCsrl v16i8:$vA, v16i8:$vB)), + (v16i8 (VSRB $vA, $vB))>; +def : Pat<(v8i16 (PPCsrl v8i16:$vA, v8i16:$vB)), + (v8i16 (VSRH $vA, $vB))>; +def : Pat<(v4i32 (PPCsrl v4i32:$vA, v4i32:$vB)), + (v4i32 (VSRW $vA, $vB))>; def : Pat<(v16i8 (sra v16i8:$vA, v16i8:$vB)), (v16i8 (VSRAB $vA, $vB))>; @@ -1001,6 +1013,12 @@ def : Pat<(v8i16 (sra v8i16:$vA, v8i16:$vB)), (v8i16 (VSRAH $vA, $vB))>; def : Pat<(v4i32 (sra v4i32:$vA, v4i32:$vB)), (v4i32 (VSRAW $vA, $vB))>; +def : Pat<(v16i8 (PPCsra v16i8:$vA, v16i8:$vB)), + (v16i8 (VSRAB $vA, $vB))>; +def : Pat<(v8i16 (PPCsra v8i16:$vA, v8i16:$vB)), + (v8i16 (VSRAH $vA, $vB))>; +def : Pat<(v4i32 (PPCsra v4i32:$vA, v4i32:$vB)), + (v4i32 (VSRAW $vA, $vB))>; // Float to integer and integer to float conversions def : Pat<(v4i32 (fp_to_sint v4f32:$vA)), @@ -1072,14 +1090,24 @@ def:Pat<(vmrgow_swapped_shuffle v16i8:$vA, v16i8:$vB), // Vector shifts def VRLD : VX1_Int_Ty<196, "vrld", int_ppc_altivec_vrld, v2i64>; def VSLD : VXForm_1<1476, (outs vrrc:$vD), (ins vrrc:$vA, vrrc:$vB), - "vsld $vD, $vA, $vB", IIC_VecGeneral, - [(set v2i64:$vD, (shl v2i64:$vA, v2i64:$vB))]>; + "vsld $vD, $vA, $vB", IIC_VecGeneral, []>; def VSRD : VXForm_1<1732, (outs vrrc:$vD), (ins vrrc:$vA, vrrc:$vB), - "vsrd $vD, $vA, $vB", IIC_VecGeneral, - [(set v2i64:$vD, (srl v2i64:$vA, v2i64:$vB))]>; + "vsrd $vD, $vA, $vB", IIC_VecGeneral, []>; def VSRAD : VXForm_1<964, (outs vrrc:$vD), (ins vrrc:$vA, vrrc:$vB), - "vsrad $vD, $vA, $vB", IIC_VecGeneral, - [(set v2i64:$vD, (sra v2i64:$vA, v2i64:$vB))]>; + "vsrad $vD, $vA, $vB", IIC_VecGeneral, []>; + +def : Pat<(v2i64 (shl v2i64:$vA, v2i64:$vB)), + (v2i64 (VSLD $vA, $vB))>; +def : Pat<(v2i64 (PPCshl v2i64:$vA, v2i64:$vB)), + (v2i64 (VSLD $vA, $vB))>; +def : Pat<(v2i64 (srl v2i64:$vA, v2i64:$vB)), + (v2i64 (VSRD $vA, $vB))>; +def : Pat<(v2i64 (PPCsrl v2i64:$vA, v2i64:$vB)), + (v2i64 (VSRD $vA, $vB))>; +def : Pat<(v2i64 (sra v2i64:$vA, v2i64:$vB)), + (v2i64 (VSRAD $vA, $vB))>; +def : Pat<(v2i64 (PPCsra v2i64:$vA, v2i64:$vB)), + (v2i64 (VSRAD $vA, $vB))>; // Vector Integer Arithmetic Instructions let isCommutable = 1 in { diff --git a/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td b/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td index f004ce49cac0..1af5e7f28342 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td +++ b/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td @@ -33,7 +33,8 @@ def SDT_PPCVexts : SDTypeProfile<1, 2, [ SDTCisVT<0, f64>, SDTCisVT<1, f64>, SDTCisPtrTy<2> ]>; -def SDT_PPCCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32> ]>; +def SDT_PPCCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>; def SDT_PPCCallSeqEnd : SDCallSeqEnd<[ SDTCisVT<0, i32>, SDTCisVT<1, i32> ]>; def SDT_PPCvperm : SDTypeProfile<1, 3, [ @@ -1099,9 +1100,11 @@ multiclass AForm_3r<bits<6> opcode, bits<5> xo, dag OOL, dag IOL, let hasCtrlDep = 1 in { let Defs = [R1], Uses = [R1] in { -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins u16imm:$amt), "#ADJCALLSTACKDOWN $amt", - [(callseq_start timm:$amt)]>; -def ADJCALLSTACKUP : Pseudo<(outs), (ins u16imm:$amt1, u16imm:$amt2), "#ADJCALLSTACKUP $amt1 $amt2", +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins u16imm:$amt1, u16imm:$amt2), + "#ADJCALLSTACKDOWN $amt1 $amt2", + [(callseq_start timm:$amt1, timm:$amt2)]>; +def ADJCALLSTACKUP : Pseudo<(outs), (ins u16imm:$amt1, u16imm:$amt2), + "#ADJCALLSTACKUP $amt1 $amt2", [(callseq_end timm:$amt1, timm:$amt2)]>; } @@ -4163,6 +4166,8 @@ def : InstAlias<"rotldi. $rA, $rS, $n", (RLDICLo g8rc:$rA, g8rc:$rS, u6imm:$n, 0 def : InstAlias<"rotld $rA, $rS, $rB", (RLDCL g8rc:$rA, g8rc:$rS, gprc:$rB, 0)>; def : InstAlias<"rotld. $rA, $rS, $rB", (RLDCLo g8rc:$rA, g8rc:$rS, gprc:$rB, 0)>; def : InstAlias<"clrldi $rA, $rS, $n", (RLDICL g8rc:$rA, g8rc:$rS, 0, u6imm:$n)>; +def : InstAlias<"clrldi $rA, $rS, $n", + (RLDICL_32 gprc:$rA, gprc:$rS, 0, u6imm:$n)>; def : InstAlias<"clrldi. $rA, $rS, $n", (RLDICLo g8rc:$rA, g8rc:$rS, 0, u6imm:$n)>; def RLWINMbm : PPCAsmPseudo<"rlwinm $rA, $rS, $n, $b", diff --git a/contrib/llvm/lib/Target/PowerPC/PPCInstrVSX.td b/contrib/llvm/lib/Target/PowerPC/PPCInstrVSX.td index 967557452f24..b98140fedfc0 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCInstrVSX.td +++ b/contrib/llvm/lib/Target/PowerPC/PPCInstrVSX.td @@ -1436,7 +1436,7 @@ let Predicates = [IsISA3_0, HasDirectMove] in { def MTVSRWS: XX1_RS6_RD5_XO<31, 403, (outs vsrc:$XT), (ins gprc:$rA), "mtvsrws $XT, $rA", IIC_VecGeneral, []>; - def MTVSRDD: XX1Form<31, 435, (outs vsrc:$XT), (ins g8rc:$rA, g8rc:$rB), + def MTVSRDD: XX1Form<31, 435, (outs vsrc:$XT), (ins g8rc_nox0:$rA, g8rc:$rB), "mtvsrdd $XT, $rA, $rB", IIC_VecGeneral, []>, Requires<[In64BitMode]>; diff --git a/contrib/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp b/contrib/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp index 0c1260a2965b..c7aa4cb78b7a 100644 --- a/contrib/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp +++ b/contrib/llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp @@ -99,7 +99,8 @@ protected: // Don't really need to save data to the stack - the clobbered // registers are already saved when the SDNode (e.g. PPCaddiTlsgdLAddr) // gets translated to the pseudo instruction (e.g. ADDItlsgdLADDR). - BuildMI(MBB, I, DL, TII->get(PPC::ADJCALLSTACKDOWN)).addImm(0); + BuildMI(MBB, I, DL, TII->get(PPC::ADJCALLSTACKDOWN)).addImm(0) + .addImm(0); // Expand into two ops built prior to the existing instruction. MachineInstr *Addi = BuildMI(MBB, I, DL, TII->get(Opc1), GPR3) diff --git a/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp b/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp index acb34d5baaa8..9e7e3c6b705a 100644 --- a/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp +++ b/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp @@ -773,8 +773,7 @@ SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI, } } - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, dl, true), - dl); + Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, dl); SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; SmallVector<SDValue, 8> MemOpChains; @@ -1165,8 +1164,7 @@ SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI, // Adjust the stack pointer to make room for the arguments. // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls // with more than 6 arguments. - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true), - DL); + Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL); // Collect the set of registers to pass to the function and their values. // This will be emitted as a sequence of CopyToReg nodes glued to the call @@ -2058,7 +2056,7 @@ SDValue SparcTargetLowering::LowerGlobalTLSAddress(SDValue Op, SDValue Chain = DAG.getEntryNode(); SDValue InFlag; - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(1, DL, true), DL); + Chain = DAG.getCALLSEQ_START(Chain, 1, 0, DL); Chain = DAG.getCopyToReg(Chain, DL, SP::O0, Argument, InFlag); InFlag = Chain.getValue(1); SDValue Callee = DAG.getTargetExternalSymbol("__tls_get_addr", PtrVT); @@ -3386,7 +3384,10 @@ SparcTargetLowering::getConstraintType(StringRef Constraint) const { if (Constraint.size() == 1) { switch (Constraint[0]) { default: break; - case 'r': return C_RegisterClass; + case 'r': + case 'f': + case 'e': + return C_RegisterClass; case 'I': // SIMM13 return C_Other; } @@ -3465,6 +3466,24 @@ SparcTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, return std::make_pair(0U, &SP::IntPairRegClass); else return std::make_pair(0U, &SP::IntRegsRegClass); + case 'f': + if (VT == MVT::f32) + return std::make_pair(0U, &SP::FPRegsRegClass); + else if (VT == MVT::f64) + return std::make_pair(0U, &SP::LowDFPRegsRegClass); + else if (VT == MVT::f128) + return std::make_pair(0U, &SP::LowQFPRegsRegClass); + llvm_unreachable("Unknown ValueType for f-register-type!"); + break; + case 'e': + if (VT == MVT::f32) + return std::make_pair(0U, &SP::FPRegsRegClass); + else if (VT == MVT::f64) + return std::make_pair(0U, &SP::DFPRegsRegClass); + else if (VT == MVT::f128) + return std::make_pair(0U, &SP::QFPRegsRegClass); + llvm_unreachable("Unknown ValueType for e-register-type!"); + break; } } else if (!Constraint.empty() && Constraint.size() <= 5 && Constraint[0] == '{' && *(Constraint.end()-1) == '}') { diff --git a/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td b/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td index 5a19c624abb5..ae45c8be6752 100644 --- a/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td +++ b/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td @@ -195,7 +195,8 @@ def SPsjlj_longjmp: SDNode<"SPISD::EH_SJLJ_LONGJMP", [SDNPHasChain, SDNPSideEffect]>; // These are target-independent nodes, but have target-specific formats. -def SDT_SPCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32> ]>; +def SDT_SPCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>; def SDT_SPCallSeqEnd : SDCallSeqEnd<[ SDTCisVT<0, i32>, SDTCisVT<1, i32> ]>; @@ -404,9 +405,9 @@ let Defs = [O7] in { } let Defs = [O6], Uses = [O6] in { -def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt), - "!ADJCALLSTACKDOWN $amt", - [(callseq_start timm:$amt)]>; +def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), + "!ADJCALLSTACKDOWN $amt1, $amt2", + [(callseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2), "!ADJCALLSTACKUP $amt1", [(callseq_end timm:$amt1, timm:$amt2)]>; diff --git a/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td b/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td index 6ecfddfc7d66..6625eaafd992 100644 --- a/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td +++ b/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td @@ -346,11 +346,13 @@ def I64Regs : RegisterClass<"SP", [i64], 64, (add IntRegs)>; // Floating point register classes. def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>; - def DFPRegs : RegisterClass<"SP", [f64], 64, (sequence "D%u", 0, 31)>; - def QFPRegs : RegisterClass<"SP", [f128], 128, (sequence "Q%u", 0, 15)>; +// The Low?FPRegs classes are used only for inline-asm constraints. +def LowDFPRegs : RegisterClass<"SP", [f64], 64, (sequence "D%u", 0, 15)>; +def LowQFPRegs : RegisterClass<"SP", [f128], 128, (sequence "Q%u", 0, 7)>; + // Floating point control register classes. def FCCRegs : RegisterClass<"SP", [i1], 1, (sequence "FCC%u", 0, 3)>; diff --git a/contrib/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp b/contrib/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp index 3f91ca9035a6..efcf6696fd50 100644 --- a/contrib/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp +++ b/contrib/llvm/lib/Target/SystemZ/AsmParser/SystemZAsmParser.cpp @@ -262,6 +262,9 @@ public: bool isMemDisp20(MemoryKind MemKind, RegisterKind RegKind) const { return isMem(MemKind, RegKind) && inRange(Mem.Disp, -524288, 524287); } + bool isMemDisp12Len4(RegisterKind RegKind) const { + return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x10); + } bool isMemDisp12Len8(RegisterKind RegKind) const { return isMemDisp12(BDLMem, RegKind) && inRange(Mem.Length.Imm, 1, 0x100); } @@ -347,6 +350,7 @@ public: bool isBDAddr64Disp20() const { return isMemDisp20(BDMem, ADDR64Reg); } bool isBDXAddr64Disp12() const { return isMemDisp12(BDXMem, ADDR64Reg); } bool isBDXAddr64Disp20() const { return isMemDisp20(BDXMem, ADDR64Reg); } + bool isBDLAddr64Disp12Len4() const { return isMemDisp12Len4(ADDR64Reg); } bool isBDLAddr64Disp12Len8() const { return isMemDisp12Len8(ADDR64Reg); } bool isBDRAddr64Disp12() const { return isMemDisp12(BDRMem, ADDR64Reg); } bool isBDVAddr64Disp12() const { return isMemDisp12(BDVMem, ADDR64Reg); } diff --git a/contrib/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp b/contrib/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp index a281a0aa6bcc..27fd70bc6092 100644 --- a/contrib/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp +++ b/contrib/llvm/lib/Target/SystemZ/Disassembler/SystemZDisassembler.cpp @@ -327,6 +327,18 @@ static DecodeStatus decodeBDXAddr20Operand(MCInst &Inst, uint64_t Field, return MCDisassembler::Success; } +static DecodeStatus decodeBDLAddr12Len4Operand(MCInst &Inst, uint64_t Field, + const unsigned *Regs) { + uint64_t Length = Field >> 16; + uint64_t Base = (Field >> 12) & 0xf; + uint64_t Disp = Field & 0xfff; + assert(Length < 16 && "Invalid BDLAddr12Len4"); + Inst.addOperand(MCOperand::createReg(Base == 0 ? 0 : Regs[Base])); + Inst.addOperand(MCOperand::createImm(Disp)); + Inst.addOperand(MCOperand::createImm(Length + 1)); + return MCDisassembler::Success; +} + static DecodeStatus decodeBDLAddr12Len8Operand(MCInst &Inst, uint64_t Field, const unsigned *Regs) { uint64_t Length = Field >> 16; @@ -399,6 +411,13 @@ static DecodeStatus decodeBDXAddr64Disp20Operand(MCInst &Inst, uint64_t Field, return decodeBDXAddr20Operand(Inst, Field, SystemZMC::GR64Regs); } +static DecodeStatus decodeBDLAddr64Disp12Len4Operand(MCInst &Inst, + uint64_t Field, + uint64_t Address, + const void *Decoder) { + return decodeBDLAddr12Len4Operand(Inst, Field, SystemZMC::GR64Regs); +} + static DecodeStatus decodeBDLAddr64Disp12Len8Operand(MCInst &Inst, uint64_t Field, uint64_t Address, diff --git a/contrib/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp b/contrib/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp index 092eb4011adc..d188f56512ab 100644 --- a/contrib/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp +++ b/contrib/llvm/lib/Target/SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp @@ -77,6 +77,9 @@ private: uint64_t getBDXAddr20Encoding(const MCInst &MI, unsigned OpNum, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &STI) const; + uint64_t getBDLAddr12Len4Encoding(const MCInst &MI, unsigned OpNum, + SmallVectorImpl<MCFixup> &Fixups, + const MCSubtargetInfo &STI) const; uint64_t getBDLAddr12Len8Encoding(const MCInst &MI, unsigned OpNum, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &STI) const; @@ -220,6 +223,17 @@ getBDXAddr20Encoding(const MCInst &MI, unsigned OpNum, } uint64_t SystemZMCCodeEmitter:: +getBDLAddr12Len4Encoding(const MCInst &MI, unsigned OpNum, + SmallVectorImpl<MCFixup> &Fixups, + const MCSubtargetInfo &STI) const { + uint64_t Base = getMachineOpValue(MI, MI.getOperand(OpNum), Fixups, STI); + uint64_t Disp = getMachineOpValue(MI, MI.getOperand(OpNum + 1), Fixups, STI); + uint64_t Len = getMachineOpValue(MI, MI.getOperand(OpNum + 2), Fixups, STI) - 1; + assert(isUInt<4>(Base) && isUInt<12>(Disp) && isUInt<4>(Len)); + return (Len << 16) | (Base << 12) | Disp; +} + +uint64_t SystemZMCCodeEmitter:: getBDLAddr12Len8Encoding(const MCInst &MI, unsigned OpNum, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &STI) const { diff --git a/contrib/llvm/lib/Target/SystemZ/README.txt b/contrib/llvm/lib/Target/SystemZ/README.txt index 86a1322c9e23..74cf653b9d95 100644 --- a/contrib/llvm/lib/Target/SystemZ/README.txt +++ b/contrib/llvm/lib/Target/SystemZ/README.txt @@ -63,7 +63,7 @@ via a register.) -- -We don't use ICM or STCM. +We don't use ICM, STCM, or CLM. -- diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZFeatures.td b/contrib/llvm/lib/Target/SystemZ/SystemZFeatures.td index 716e5add8051..7bfa378aa85c 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZFeatures.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZFeatures.td @@ -68,6 +68,11 @@ def FeaturePopulationCount : SystemZFeature< "Assume that the population-count facility is installed" >; +def FeatureMessageSecurityAssist4 : SystemZFeature< + "message-security-assist-extension4", "MessageSecurityAssist4", + "Assume that the message-security-assist extension facility 4 is installed" +>; + def Arch9NewFeatures : SystemZFeatureList<[ FeatureDistinctOps, FeatureFastSerialization, @@ -75,7 +80,8 @@ def Arch9NewFeatures : SystemZFeatureList<[ FeatureHighWord, FeatureInterlockedAccess1, FeatureLoadStoreOnCond, - FeaturePopulationCount + FeaturePopulationCount, + FeatureMessageSecurityAssist4 ]>; //===----------------------------------------------------------------------===// @@ -133,6 +139,11 @@ def FeatureLoadStoreOnCond2 : SystemZFeature< "Assume that the load/store-on-condition facility 2 is installed" >; +def FeatureMessageSecurityAssist5 : SystemZFeature< + "message-security-assist-extension5", "MessageSecurityAssist5", + "Assume that the message-security-assist extension facility 5 is installed" +>; + def FeatureVector : SystemZFeature< "vector", "Vector", "Assume that the vectory facility is installed" @@ -142,6 +153,7 @@ def FeatureNoVector : SystemZMissingFeature<"Vector">; def Arch11NewFeatures : SystemZFeatureList<[ FeatureLoadAndZeroRightmostByte, FeatureLoadStoreOnCond2, + FeatureMessageSecurityAssist5, FeatureVector ]>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp b/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp index 6989aabb8c6a..235e095f0010 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp +++ b/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp @@ -1110,9 +1110,7 @@ SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI, // Mark the start of the call. if (!IsTailCall) - Chain = DAG.getCALLSEQ_START(Chain, - DAG.getConstant(NumBytes, DL, PtrVT, true), - DL); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); // Copy argument values to their designated locations. SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass; @@ -6354,3 +6352,12 @@ MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter( llvm_unreachable("Unexpected instr type to insert"); } } + +// This is only used by the isel schedulers, and is needed only to prevent +// compiler from crashing when list-ilp is used. +const TargetRegisterClass * +SystemZTargetLowering::getRepRegClassFor(MVT VT) const { + if (VT == MVT::Untyped) + return &SystemZ::ADDR128BitRegClass; + return TargetLowering::getRepRegClassFor(VT); +} diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.h b/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.h index 1c34dc43e8bb..79c8c4d92669 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.h +++ b/contrib/llvm/lib/Target/SystemZ/SystemZISelLowering.h @@ -590,6 +590,8 @@ private: MachineBasicBlock *emitLoadAndTestCmp0(MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const; + + const TargetRegisterClass *getRepRegClassFor(MVT VT) const override; }; } // end namespace llvm diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZInstrFP.td b/contrib/llvm/lib/Target/SystemZ/SystemZInstrFP.td index bb6d27e24828..364b81f98eed 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZInstrFP.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZInstrFP.td @@ -458,6 +458,12 @@ def DXBR : BinaryRRE<"dxbr", 0xB34D, fdiv, FP128, FP128>; def DEB : BinaryRXE<"deb", 0xED0D, fdiv, FP32, load, 4>; def DDB : BinaryRXE<"ddb", 0xED1D, fdiv, FP64, load, 8>; +// Divide to integer. +let Defs = [CC] in { + def DIEBR : TernaryRRFb<"diebr", 0xB353, FP32, FP32, FP32>; + def DIDBR : TernaryRRFb<"didbr", 0xB35B, FP64, FP64, FP64>; +} + //===----------------------------------------------------------------------===// // Comparisons //===----------------------------------------------------------------------===// @@ -469,6 +475,13 @@ let Defs = [CC], CCValues = 0xF in { def CEB : CompareRXE<"ceb", 0xED09, z_fcmp, FP32, load, 4>; def CDB : CompareRXE<"cdb", 0xED19, z_fcmp, FP64, load, 8>; + + def KEBR : CompareRRE<"kebr", 0xB308, null_frag, FP32, FP32>; + def KDBR : CompareRRE<"kdbr", 0xB318, null_frag, FP64, FP64>; + def KXBR : CompareRRE<"kxbr", 0xB348, null_frag, FP128, FP128>; + + def KEB : CompareRXE<"keb", 0xED08, null_frag, FP32, load, 4>; + def KDB : CompareRXE<"kdb", 0xED18, null_frag, FP64, load, 8>; } // Test Data Class. diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZInstrFormats.td b/contrib/llvm/lib/Target/SystemZ/SystemZInstrFormats.td index c727f486087e..a37da2807854 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZInstrFormats.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZInstrFormats.td @@ -710,6 +710,21 @@ class InstRSI<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> let Inst{15-0} = RI2; } +class InstRSLa<bits<16> op, dag outs, dag ins, string asmstr, list<dag> pattern> + : InstSystemZ<6, outs, ins, asmstr, pattern> { + field bits<48> Inst; + field bits<48> SoftFail = 0; + + bits<20> BDL1; + + let Inst{47-40} = op{15-8}; + let Inst{39-36} = BDL1{19-16}; + let Inst{35-32} = 0; + let Inst{31-16} = BDL1{15-0}; + let Inst{15-8} = 0; + let Inst{7-0} = op{7-0}; +} + class InstRSYa<bits<16> op, dag outs, dag ins, string asmstr, list<dag> pattern> : InstSystemZ<6, outs, ins, asmstr, pattern> { field bits<48> Inst; @@ -817,6 +832,37 @@ class InstSSa<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> let Inst{15-0} = BD2; } +class InstSSb<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> + : InstSystemZ<6, outs, ins, asmstr, pattern> { + field bits<48> Inst; + field bits<48> SoftFail = 0; + + bits<20> BDL1; + bits<20> BDL2; + + let Inst{47-40} = op; + let Inst{39-36} = BDL1{19-16}; + let Inst{35-32} = BDL2{19-16}; + let Inst{31-16} = BDL1{15-0}; + let Inst{15-0} = BDL2{15-0}; +} + +class InstSSc<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> + : InstSystemZ<6, outs, ins, asmstr, pattern> { + field bits<48> Inst; + field bits<48> SoftFail = 0; + + bits<20> BDL1; + bits<16> BD2; + bits<4> I3; + + let Inst{47-40} = op; + let Inst{39-36} = BDL1{19-16}; + let Inst{35-32} = I3; + let Inst{31-16} = BDL1{15-0}; + let Inst{15-0} = BD2; +} + class InstSSd<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> : InstSystemZ<6, outs, ins, asmstr, pattern> { field bits<48> Inst; @@ -850,6 +896,20 @@ class InstSSe<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> let Inst{15-0} = BD4; } +class InstSSf<bits<8> op, dag outs, dag ins, string asmstr, list<dag> pattern> + : InstSystemZ<6, outs, ins, asmstr, pattern> { + field bits<48> Inst; + field bits<48> SoftFail = 0; + + bits<16> BD1; + bits<24> BDL2; + + let Inst{47-40} = op; + let Inst{39-32} = BDL2{23-16}; + let Inst{31-16} = BD1; + let Inst{15-0} = BDL2{15-0}; +} + class InstSSE<bits<16> op, dag outs, dag ins, string asmstr, list<dag> pattern> : InstSystemZ<6, outs, ins, asmstr, pattern> { field bits<48> Inst; @@ -1567,6 +1627,9 @@ class ICV<string name> // Inherent: // One register output operand and no input operands. // +// InherentDual: +// Two register output operands and no input operands. +// // StoreInherent: // One address operand. The instruction stores to the address. // @@ -1642,8 +1705,9 @@ class ICV<string name> // Two input operands and an implicit CC output operand. // // Test: -// Two input operands and an implicit CC output operand. The second -// input operand is an "address" operand used as a test class mask. +// One or two input operands and an implicit CC output operand. If +// present, the second input operand is an "address" operand used as +// a test class mask. // // Ternary: // One register output operand and three input operands. @@ -1691,6 +1755,10 @@ class InherentRRE<string mnemonic, bits<16> opcode, RegisterOperand cls, let R2 = 0; } +class InherentDualRRE<string mnemonic, bits<16> opcode, RegisterOperand cls> + : InstRRE<opcode, (outs cls:$R1, cls:$R2), (ins), + mnemonic#"\t$R1, $R2", []>; + class InherentVRIa<string mnemonic, bits<16> opcode, bits<16> value> : InstVRIa<opcode, (outs VR128:$V1), (ins), mnemonic#"\t$V1", []> { let I2 = value; @@ -1714,6 +1782,12 @@ class SideEffectInherentS<string mnemonic, bits<16> opcode, let BD2 = 0; } +class SideEffectInherentRRE<string mnemonic, bits<16> opcode> + : InstRRE<opcode, (outs), (ins), mnemonic, []> { + let R1 = 0; + let R2 = 0; +} + // Allow an optional TLS marker symbol to generate TLS call relocations. class CallRI<string mnemonic, bits<12> opcode> : InstRIb<opcode, (outs), (ins GR64:$R1, brtarget16tls:$RI2), @@ -2084,6 +2158,13 @@ multiclass LoadMultipleRSPair<string mnemonic, bits<8> rsOpcode, } } +class LoadMultipleSSe<string mnemonic, bits<8> opcode, RegisterOperand cls> + : InstSSe<opcode, (outs cls:$R1, cls:$R3), + (ins bdaddr12only:$BD2, bdaddr12only:$BD4), + mnemonic#"\t$R1, $R3, $BD2, $BD4", []> { + let mayLoad = 1; +} + class LoadMultipleVRSa<string mnemonic, bits<16> opcode> : InstVRSa<opcode, (outs VR128:$V1, VR128:$V3), (ins bdaddr12only:$BD2), mnemonic#"\t$V1, $V3, $BD2", []> { @@ -2355,6 +2436,15 @@ class UnaryRRE<string mnemonic, bits<16> opcode, SDPatternOperator operator, let OpType = "reg"; } +class UnaryMemRRFc<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRRFc<opcode, (outs cls2:$R2, cls1:$R1), (ins cls1:$R1src), + mnemonic#"\t$R1, $R2", []> { + let Constraints = "$R1 = $R1src"; + let DisableEncoding = "$R1src"; + let M3 = 0; +} + class UnaryRI<string mnemonic, bits<12> opcode, SDPatternOperator operator, RegisterOperand cls, Immediate imm> : InstRIa<opcode, (outs cls:$R1), (ins imm:$I2), @@ -2585,11 +2675,61 @@ class SideEffectBinaryIE<string mnemonic, bits<16> opcode, : InstIE<opcode, (outs), (ins imm1:$I1, imm2:$I2), mnemonic#"\t$I1, $I2", []>; +class SideEffectBinarySI<string mnemonic, bits<8> opcode, Operand imm> + : InstSI<opcode, (outs), (ins bdaddr12only:$BD1, imm:$I2), + mnemonic#"\t$BD1, $I2", []>; + class SideEffectBinarySIL<string mnemonic, bits<16> opcode, SDPatternOperator operator, Immediate imm> : InstSIL<opcode, (outs), (ins bdaddr12only:$BD1, imm:$I2), mnemonic#"\t$BD1, $I2", [(operator bdaddr12only:$BD1, imm:$I2)]>; +class SideEffectBinarySSa<string mnemonic, bits<8> opcode> + : InstSSa<opcode, (outs), (ins bdladdr12onlylen8:$BDL1, bdaddr12only:$BD2), + mnemonic##"\t$BDL1, $BD2", []>; + +class SideEffectBinarySSb<string mnemonic, bits<8> opcode> + : InstSSb<opcode, + (outs), (ins bdladdr12onlylen4:$BDL1, bdladdr12onlylen4:$BDL2), + mnemonic##"\t$BDL1, $BDL2", []>; + +class SideEffectBinarySSf<string mnemonic, bits<8> opcode> + : InstSSf<opcode, (outs), (ins bdaddr12only:$BD1, bdladdr12onlylen8:$BDL2), + mnemonic##"\t$BD1, $BDL2", []>; + +class SideEffectBinaryMemMemRR<string mnemonic, bits<8> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRR<opcode, (outs cls1:$R1, cls2:$R2), (ins cls1:$R1src, cls2:$R2src), + mnemonic#"\t$R1, $R2", []> { + let Constraints = "$R1 = $R1src, $R2 = $R2src"; + let DisableEncoding = "$R1src, $R2src"; +} + +class SideEffectBinaryMemRRE<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRRE<opcode, (outs cls2:$R2), (ins cls1:$R1, cls2:$R2src), + mnemonic#"\t$R1, $R2", []> { + let Constraints = "$R2 = $R2src"; + let DisableEncoding = "$R2src"; +} + +class SideEffectBinaryMemMemRRE<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRRE<opcode, (outs cls1:$R1, cls2:$R2), (ins cls1:$R1src, cls2:$R2src), + mnemonic#"\t$R1, $R2", []> { + let Constraints = "$R1 = $R1src, $R2 = $R2src"; + let DisableEncoding = "$R1src, $R2src"; +} + +class SideEffectBinaryMemMemRRFc<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRRFc<opcode, (outs cls1:$R1, cls2:$R2), (ins cls1:$R1src, cls2:$R2src), + mnemonic#"\t$R1, $R2", []> { + let Constraints = "$R1 = $R1src, $R2 = $R2src"; + let DisableEncoding = "$R1src, $R2src"; + let M3 = 0; +} + class BinaryRR<string mnemonic, bits<8> opcode, SDPatternOperator operator, RegisterOperand cls1, RegisterOperand cls2> : InstRR<opcode, (outs cls1:$R1), (ins cls1:$R1src, cls2:$R2), @@ -2654,6 +2794,20 @@ class BinaryRRFb<string mnemonic, bits<16> opcode, SDPatternOperator operator, let M4 = 0; } +class BinaryMemRRFc<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2, Immediate imm> + : InstRRFc<opcode, (outs cls2:$R2, cls1:$R1), (ins cls1:$R1src, imm:$M3), + mnemonic#"\t$R1, $R2, $M3", []> { + let Constraints = "$R1 = $R1src"; + let DisableEncoding = "$R1src"; +} + +multiclass BinaryMemRRFcOpt<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> { + def "" : BinaryMemRRFc<mnemonic, opcode, cls1, cls2, imm32zx4>; + def Opt : UnaryMemRRFc<mnemonic, opcode, cls1, cls2>; +} + class BinaryRRFe<string mnemonic, bits<16> opcode, RegisterOperand cls1, RegisterOperand cls2> : InstRRFe<opcode, (outs cls1:$R1), (ins imm32zx4:$M3, cls2:$R2), @@ -3112,6 +3266,34 @@ class BinaryVRX<string mnemonic, bits<16> opcode, SDPatternOperator operator, let AccessBytes = bytes; } +class StoreBinaryRS<string mnemonic, bits<8> opcode, RegisterOperand cls, + bits<5> bytes, AddressingMode mode = bdaddr12only> + : InstRSb<opcode, (outs), (ins cls:$R1, imm32zx4:$M3, mode:$BD2), + mnemonic#"\t$R1, $M3, $BD2", []> { + let mayStore = 1; + let AccessBytes = bytes; +} + +class StoreBinaryRSY<string mnemonic, bits<16> opcode, RegisterOperand cls, + bits<5> bytes, AddressingMode mode = bdaddr20only> + : InstRSYb<opcode, (outs), (ins cls:$R1, imm32zx4:$M3, mode:$BD2), + mnemonic#"\t$R1, $M3, $BD2", []> { + let mayStore = 1; + let AccessBytes = bytes; +} + +multiclass StoreBinaryRSPair<string mnemonic, bits<8> rsOpcode, + bits<16> rsyOpcode, RegisterOperand cls, + bits<5> bytes> { + let DispKey = mnemonic ## #cls in { + let DispSize = "12" in + def "" : StoreBinaryRS<mnemonic, rsOpcode, cls, bytes, bdaddr12pair>; + let DispSize = "20" in + def Y : StoreBinaryRSY<mnemonic#"y", rsyOpcode, cls, bytes, + bdaddr20pair>; + } +} + class StoreBinaryVRV<string mnemonic, bits<16> opcode, bits<5> bytes, Immediate index> : InstVRV<opcode, (outs), (ins VR128:$V1, bdvaddr12only:$VBD2, index:$M3), @@ -3237,6 +3419,40 @@ multiclass CompareRXPair<string mnemonic, bits<8> rxOpcode, bits<16> rxyOpcode, } } +class CompareRS<string mnemonic, bits<8> opcode, RegisterOperand cls, + bits<5> bytes, AddressingMode mode = bdaddr12only> + : InstRSb<opcode, (outs), (ins cls:$R1, imm32zx4:$M3, mode:$BD2), + mnemonic#"\t$R1, $M3, $BD2", []> { + let mayLoad = 1; + let AccessBytes = bytes; +} + +class CompareRSY<string mnemonic, bits<16> opcode, RegisterOperand cls, + bits<5> bytes, AddressingMode mode = bdaddr20only> + : InstRSYb<opcode, (outs), (ins cls:$R1, imm32zx4:$M3, mode:$BD2), + mnemonic#"\t$R1, $M3, $BD2", []> { + let mayLoad = 1; + let AccessBytes = bytes; +} + +multiclass CompareRSPair<string mnemonic, bits<8> rsOpcode, bits<16> rsyOpcode, + RegisterOperand cls, bits<5> bytes> { + let DispKey = mnemonic ## #cls in { + let DispSize = "12" in + def "" : CompareRS<mnemonic, rsOpcode, cls, bytes, bdaddr12pair>; + let DispSize = "20" in + def Y : CompareRSY<mnemonic#"y", rsyOpcode, cls, bytes, bdaddr20pair>; + } +} + +class CompareSSb<string mnemonic, bits<8> opcode> + : InstSSb<opcode, + (outs), (ins bdladdr12onlylen4:$BDL1, bdladdr12onlylen4:$BDL2), + mnemonic##"\t$BDL1, $BDL2", []> { + let isCompare = 1; + let mayLoad = 1; +} + class CompareSI<string mnemonic, bits<8> opcode, SDPatternOperator operator, SDPatternOperator load, Immediate imm, AddressingMode mode = bdaddr12only> @@ -3313,18 +3529,68 @@ class TestRXE<string mnemonic, bits<16> opcode, SDPatternOperator operator, let M3 = 0; } +class TestRSL<string mnemonic, bits<16> opcode> + : InstRSLa<opcode, (outs), (ins bdladdr12onlylen4:$BDL1), + mnemonic#"\t$BDL1", []> { + let mayLoad = 1; +} + +class SideEffectTernarySSc<string mnemonic, bits<8> opcode> + : InstSSc<opcode, (outs), (ins bdladdr12onlylen4:$BDL1, + shift12only:$BD2, imm32zx4:$I3), + mnemonic##"\t$BDL1, $BD2, $I3", []>; + +class SideEffectTernaryMemMemMemRRFb<string mnemonic, bits<16> opcode, + RegisterOperand cls1, + RegisterOperand cls2, + RegisterOperand cls3> + : InstRRFb<opcode, (outs cls1:$R1, cls2:$R2, cls3:$R3), + (ins cls1:$R1src, cls2:$R2src, cls3:$R3src), + mnemonic#"\t$R1, $R3, $R2", []> { + let Constraints = "$R1 = $R1src, $R2 = $R2src, $R3 = $R3src"; + let DisableEncoding = "$R1src, $R2src, $R3src"; + let M4 = 0; +} + class SideEffectTernaryRRFc<string mnemonic, bits<16> opcode, RegisterOperand cls1, RegisterOperand cls2, Immediate imm> : InstRRFc<opcode, (outs), (ins cls1:$R1, cls2:$R2, imm:$M3), mnemonic#"\t$R1, $R2, $M3", []>; +class SideEffectTernaryMemMemRRFc<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2, + Immediate imm> + : InstRRFc<opcode, (outs cls1:$R1, cls2:$R2), + (ins cls1:$R1src, cls2:$R2src, imm:$M3), + mnemonic#"\t$R1, $R2, $M3", []> { + let Constraints = "$R1 = $R1src, $R2 = $R2src"; + let DisableEncoding = "$R1src, $R2src"; +} + +multiclass SideEffectTernaryMemMemRRFcOpt<string mnemonic, bits<16> opcode, + RegisterOperand cls1, + RegisterOperand cls2> { + def "" : SideEffectTernaryMemMemRRFc<mnemonic, opcode, cls1, cls2, imm32zx4>; + def Opt : SideEffectBinaryMemMemRRFc<mnemonic, opcode, cls1, cls2>; +} + class SideEffectTernarySSF<string mnemonic, bits<12> opcode, RegisterOperand cls> : InstSSF<opcode, (outs), (ins bdaddr12only:$BD1, bdaddr12only:$BD2, cls:$R3), mnemonic#"\t$BD1, $BD2, $R3", []>; +class TernaryRRFb<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2, + RegisterOperand cls3> + : InstRRFb<opcode, (outs cls1:$R1, cls3:$R3), + (ins cls1:$R1src, cls2:$R2, imm32zx4:$M4), + mnemonic#"\t$R1, $R3, $R2, $M4", []> { + let Constraints = "$R1 = $R1src"; + let DisableEncoding = "$R1src"; +} + class TernaryRRFe<string mnemonic, bits<16> opcode, RegisterOperand cls1, RegisterOperand cls2> : InstRRFe<opcode, (outs cls1:$R1), @@ -3376,6 +3642,24 @@ multiclass TernaryRSPair<string mnemonic, bits<8> rsOpcode, bits<16> rsyOpcode, } } +class SideEffectTernaryMemMemRS<string mnemonic, bits<8> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRSa<opcode, (outs cls1:$R1, cls2:$R3), + (ins cls1:$R1src, cls2:$R3src, shift12only:$BD2), + mnemonic#"\t$R1, $R3, $BD2", []> { + let Constraints = "$R1 = $R1src, $R3 = $R3src"; + let DisableEncoding = "$R1src, $R3src"; +} + +class SideEffectTernaryMemMemRSY<string mnemonic, bits<16> opcode, + RegisterOperand cls1, RegisterOperand cls2> + : InstRSYa<opcode, (outs cls1:$R1, cls2:$R3), + (ins cls1:$R1src, cls2:$R3src, shift20only:$BD2), + mnemonic#"\t$R1, $R3, $BD2", []> { + let Constraints = "$R1 = $R1src, $R3 = $R3src"; + let DisableEncoding = "$R1src, $R3src"; +} + class TernaryRXF<string mnemonic, bits<16> opcode, SDPatternOperator operator, RegisterOperand cls, SDPatternOperator load, bits<5> bytes> : InstRXF<opcode, (outs cls:$R1), @@ -3981,9 +4265,7 @@ class AtomicLoadWBinaryImm<SDPatternOperator operator, Immediate imm> // another instruction to handle the excess. multiclass MemorySS<string mnemonic, bits<8> opcode, SDPatternOperator sequence, SDPatternOperator loop> { - def "" : InstSSa<opcode, (outs), (ins bdladdr12onlylen8:$BDL1, - bdaddr12only:$BD2), - mnemonic##"\t$BDL1, $BD2", []>; + def "" : SideEffectBinarySSa<mnemonic, opcode>; let usesCustomInserter = 1, hasNoSchedulingInfo = 1 in { def Sequence : Pseudo<(outs), (ins bdaddr12only:$dest, bdaddr12only:$src, imm64:$length), @@ -4003,13 +4285,8 @@ multiclass MemorySS<string mnemonic, bits<8> opcode, // the full loop (the main instruction plus the branch on CC==3). multiclass StringRRE<string mnemonic, bits<16> opcode, SDPatternOperator operator> { - def "" : InstRRE<opcode, (outs GR64:$R1, GR64:$R2), - (ins GR64:$R1src, GR64:$R2src), - mnemonic#"\t$R1, $R2", []> { - let Uses = [R0L]; - let Constraints = "$R1 = $R1src, $R2 = $R2src"; - let DisableEncoding = "$R1src, $R2src"; - } + let Uses = [R0L] in + def "" : SideEffectBinaryMemMemRRE<mnemonic, opcode, GR64, GR64>; let usesCustomInserter = 1, hasNoSchedulingInfo = 1 in def Loop : Pseudo<(outs GR64:$end), (ins GR64:$start1, GR64:$start2, GR32:$char), diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZInstrInfo.td b/contrib/llvm/lib/Target/SystemZ/SystemZInstrInfo.td index d63525f29412..fa5ecdd85243 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZInstrInfo.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZInstrInfo.td @@ -12,8 +12,8 @@ //===----------------------------------------------------------------------===// let hasNoSchedulingInfo = 1 in { - def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i64imm:$amt), - [(callseq_start timm:$amt)]>; + def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2), + [(callseq_start timm:$amt1, timm:$amt2)]>; def ADJCALLSTACKUP : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2), [(callseq_end timm:$amt1, timm:$amt2)]>; } @@ -464,6 +464,11 @@ def MVGHI : StoreSIL<"mvghi", 0xE548, store, imm64sx16>; // Memory-to-memory moves. let mayLoad = 1, mayStore = 1 in defm MVC : MemorySS<"mvc", 0xD2, z_mvc, z_mvc_loop>; +let mayLoad = 1, mayStore = 1, Defs = [CC] in { + def MVCL : SideEffectBinaryMemMemRR<"mvcl", 0x0E, GR128, GR128>; + def MVCLE : SideEffectTernaryMemMemRS<"mvcle", 0xA8, GR128, GR128>; + def MVCLU : SideEffectTernaryMemMemRSY<"mvclu", 0xEB8E, GR128, GR128>; +} // String moves. let mayLoad = 1, mayStore = 1, Defs = [CC] in @@ -707,6 +712,10 @@ def : StoreGR64PC<STHRL, aligned_truncstorei16>; defm : StoreGR64Pair<ST, STY, truncstorei32>; def : StoreGR64PC<STRL, aligned_truncstorei32>; +// Store characters under mask -- not (yet) used for codegen. +defm STCM : StoreBinaryRSPair<"stcm", 0xBE, 0xEB2D, GR32, 0>; +def STCMH : StoreBinaryRSY<"stcmh", 0xEB2C, GRH32, 0>; + //===----------------------------------------------------------------------===// // Multi-register moves //===----------------------------------------------------------------------===// @@ -715,6 +724,7 @@ def : StoreGR64PC<STRL, aligned_truncstorei32>; defm LM : LoadMultipleRSPair<"lm", 0x98, 0xEB98, GR32>; def LMG : LoadMultipleRSY<"lmg", 0xEB04, GR64>; def LMH : LoadMultipleRSY<"lmh", 0xEB96, GRH32>; +def LMD : LoadMultipleSSe<"lmd", 0xEF, GR64>; // Multi-register stores. defm STM : StoreMultipleRSPair<"stm", 0x90, 0xEB90, GR32>; @@ -742,6 +752,10 @@ def STRVH : StoreRXY<"strvh", 0xE33F, z_strvh, GR32, 2>; def STRV : StoreRXY<"strv", 0xE33E, z_strv, GR32, 4>; def STRVG : StoreRXY<"strvg", 0xE32F, z_strvg, GR64, 8>; +// Byte-swapping memory-to-memory moves. +let mayLoad = 1, mayStore = 1 in + def MVCIN : SideEffectBinarySSa<"mvcin", 0xE8>; + //===----------------------------------------------------------------------===// // Load address instructions //===----------------------------------------------------------------------===// @@ -816,6 +830,7 @@ defm : InsertMem<"inserti8", IC32Y, GR32, azextloadi8, bdxaddr20pair>; defm : InsertMem<"inserti8", IC, GR64, azextloadi8, bdxaddr12pair>; defm : InsertMem<"inserti8", ICY, GR64, azextloadi8, bdxaddr20pair>; +// Insert characters under mask -- not (yet) used for codegen. let Defs = [CC] in { defm ICM : TernaryRSPair<"icm", 0xBF, 0xEB81, GR32, 0>; def ICMH : TernaryRSY<"icmh", 0xEB80, GRH32, 0>; @@ -919,6 +934,10 @@ let Defs = [CC] in { defm AL : BinaryRXPair<"al", 0x5E, 0xE35E, addc, GR32, load, 4>; def ALGF : BinaryRXY<"algf", 0xE31A, addc, GR64, azextloadi32, 4>; def ALG : BinaryRXY<"alg", 0xE30A, addc, GR64, load, 8>; + + // Addition to memory. + def ALSI : BinarySIY<"alsi", 0xEB6E, null_frag, imm32sx8>; + def ALGSI : BinarySIY<"algsi", 0xEB7E, null_frag, imm64sx8>; } defm : ZXB<addc, GR64, ALGFR>; @@ -1166,9 +1185,14 @@ def MSGF : BinaryRXY<"msgf", 0xE31C, mul, GR64, asextloadi32, 4>; def MSG : BinaryRXY<"msg", 0xE30C, mul, GR64, load, 8>; // Multiplication of a register, producing two results. +def MR : BinaryRR <"mr", 0x1C, null_frag, GR128, GR32>; +def MLR : BinaryRRE<"mlr", 0xB996, null_frag, GR128, GR32>; def MLGR : BinaryRRE<"mlgr", 0xB986, z_umul_lohi64, GR128, GR64>; // Multiplication of memory, producing two results. +def M : BinaryRX <"m", 0x5C, null_frag, GR128, load, 4>; +def MFY : BinaryRXY<"mfy", 0xE35C, null_frag, GR128, load, 4>; +def ML : BinaryRXY<"ml", 0xE396, null_frag, GR128, load, 4>; def MLG : BinaryRXY<"mlg", 0xE386, z_umul_lohi64, GR128, load, 8>; //===----------------------------------------------------------------------===// @@ -1177,12 +1201,14 @@ def MLG : BinaryRXY<"mlg", 0xE386, z_umul_lohi64, GR128, load, 8>; let hasSideEffects = 1 in { // Do not speculatively execute. // Division and remainder, from registers. + def DR : BinaryRR <"dr", 0x1D, null_frag, GR128, GR32>; def DSGFR : BinaryRRE<"dsgfr", 0xB91D, z_sdivrem32, GR128, GR32>; def DSGR : BinaryRRE<"dsgr", 0xB90D, z_sdivrem64, GR128, GR64>; def DLR : BinaryRRE<"dlr", 0xB997, z_udivrem32, GR128, GR32>; def DLGR : BinaryRRE<"dlgr", 0xB987, z_udivrem64, GR128, GR64>; // Division and remainder, from memory. + def D : BinaryRX <"d", 0x5D, null_frag, GR128, load, 4>; def DSGF : BinaryRXY<"dsgf", 0xE31D, z_sdivrem32, GR128, load, 4>; def DSG : BinaryRXY<"dsg", 0xE30D, z_sdivrem64, GR128, load, 8>; def DL : BinaryRXY<"dl", 0xE397, z_udivrem32, GR128, load, 4>; @@ -1193,23 +1219,32 @@ let hasSideEffects = 1 in { // Do not speculatively execute. // Shifts //===----------------------------------------------------------------------===// -// Shift left. +// Logical shift left. let hasSideEffects = 0 in { defm SLL : BinaryRSAndK<"sll", 0x89, 0xEBDF, shl, GR32>; - defm SLA : BinaryRSAndK<"sla", 0x8B, 0xEBDD, null_frag, GR32>; def SLLG : BinaryRSY<"sllg", 0xEB0D, shl, GR64>; + def SLDL : BinaryRS<"sldl", 0x8D, null_frag, GR128>; +} + +// Arithmetic shift left. +let Defs = [CC] in { + defm SLA : BinaryRSAndK<"sla", 0x8B, 0xEBDD, null_frag, GR32>; + def SLAG : BinaryRSY<"slag", 0xEB0B, null_frag, GR64>; + def SLDA : BinaryRS<"slda", 0x8F, null_frag, GR128>; } // Logical shift right. let hasSideEffects = 0 in { defm SRL : BinaryRSAndK<"srl", 0x88, 0xEBDE, srl, GR32>; def SRLG : BinaryRSY<"srlg", 0xEB0C, srl, GR64>; + def SRDL : BinaryRS<"srdl", 0x8C, null_frag, GR128>; } // Arithmetic shift right. let Defs = [CC], CCValues = 0xE, CompareZeroCCMask = 0xE in { defm SRA : BinaryRSAndK<"sra", 0x8A, 0xEBDC, sra, GR32>; def SRAG : BinaryRSY<"srag", 0xEB0A, sra, GR64>; + def SRDA : BinaryRS<"srda", 0x8E, null_frag, GR128>; } // Rotate left. @@ -1351,8 +1386,12 @@ let Defs = [CC], CCValues = 0xE, IsLogical = 1 in { defm : ZXB<z_ucmp, GR64, CLGFR>; // Memory-to-memory comparison. -let mayLoad = 1, Defs = [CC] in +let mayLoad = 1, Defs = [CC] in { defm CLC : MemorySS<"clc", 0xD5, z_clc, z_clc_loop>; + def CLCL : SideEffectBinaryMemMemRR<"clcl", 0x0F, GR128, GR128>; + def CLCLE : SideEffectTernaryMemMemRS<"clcle", 0xA9, GR128, GR128>; + def CLCLU : SideEffectTernaryMemMemRSY<"clclu", 0xEB8F, GR128, GR128>; +} // String comparison. let mayLoad = 1, Defs = [CC] in @@ -1381,6 +1420,12 @@ let Defs = [CC] in { def TML : InstAlias<"tml\t$R, $I", (TMLL GR32:$R, imm32ll16:$I), 0>; def TMH : InstAlias<"tmh\t$R, $I", (TMLH GR32:$R, imm32lh16:$I), 0>; +// Compare logical characters under mask -- not (yet) used for codegen. +let Defs = [CC] in { + defm CLM : CompareRSPair<"clm", 0xBD, 0xEB21, GR32, 0>; + def CLMH : CompareRSY<"clmh", 0xEB20, GRH32, 0>; +} + //===----------------------------------------------------------------------===// // Prefetch and execution hint //===----------------------------------------------------------------------===// @@ -1581,6 +1626,115 @@ let Predicates = [FeatureInterlockedAccess1], Defs = [CC] in { } //===----------------------------------------------------------------------===// +// Translate and convert +//===----------------------------------------------------------------------===// + +let mayLoad = 1, mayStore = 1 in + def TR : SideEffectBinarySSa<"tr", 0xDC>; + +let mayLoad = 1, Defs = [CC, R0L, R1D] in { + def TRT : SideEffectBinarySSa<"trt", 0xDD>; + def TRTR : SideEffectBinarySSa<"trtr", 0xD0>; +} + +let mayLoad = 1, mayStore = 1, Uses = [R0L] in + def TRE : SideEffectBinaryMemMemRRE<"tre", 0xB2A5, GR128, GR64>; + +let mayLoad = 1, Uses = [R1D], Defs = [CC] in { + defm TRTE : BinaryMemRRFcOpt<"trte", 0xB9BF, GR128, GR64>; + defm TRTRE : BinaryMemRRFcOpt<"trtre", 0xB9BD, GR128, GR64>; +} + +let mayLoad = 1, mayStore = 1, Uses = [R0L, R1D], Defs = [CC] in { + defm TROO : SideEffectTernaryMemMemRRFcOpt<"troo", 0xB993, GR128, GR64>; + defm TROT : SideEffectTernaryMemMemRRFcOpt<"trot", 0xB992, GR128, GR64>; + defm TRTO : SideEffectTernaryMemMemRRFcOpt<"trto", 0xB991, GR128, GR64>; + defm TRTT : SideEffectTernaryMemMemRRFcOpt<"trtt", 0xB990, GR128, GR64>; +} + +let mayLoad = 1, mayStore = 1, Defs = [CC] in { + defm CU12 : SideEffectTernaryMemMemRRFcOpt<"cu12", 0xB2A7, GR128, GR128>; + defm CU14 : SideEffectTernaryMemMemRRFcOpt<"cu14", 0xB9B0, GR128, GR128>; + defm CU21 : SideEffectTernaryMemMemRRFcOpt<"cu21", 0xB2A6, GR128, GR128>; + defm CU24 : SideEffectTernaryMemMemRRFcOpt<"cu24", 0xB9B1, GR128, GR128>; + def CU41 : SideEffectBinaryMemMemRRE<"cu41", 0xB9B2, GR128, GR128>; + def CU42 : SideEffectBinaryMemMemRRE<"cu42", 0xB9B3, GR128, GR128>; + + let isAsmParserOnly = 1 in { + defm CUUTF : SideEffectTernaryMemMemRRFcOpt<"cuutf", 0xB2A6, GR128, GR128>; + defm CUTFU : SideEffectTernaryMemMemRRFcOpt<"cutfu", 0xB2A7, GR128, GR128>; + } +} + +//===----------------------------------------------------------------------===// +// Message-security assist +//===----------------------------------------------------------------------===// + +let mayLoad = 1, mayStore = 1, Uses = [R0L, R1D], Defs = [CC] in { + def KM : SideEffectBinaryMemMemRRE<"km", 0xB92E, GR128, GR128>; + def KMC : SideEffectBinaryMemMemRRE<"kmc", 0xB92F, GR128, GR128>; + + def KIMD : SideEffectBinaryMemRRE<"kimd", 0xB93E, GR64, GR128>; + def KLMD : SideEffectBinaryMemRRE<"klmd", 0xB93F, GR64, GR128>; + def KMAC : SideEffectBinaryMemRRE<"kmac", 0xB91E, GR64, GR128>; + + let Predicates = [FeatureMessageSecurityAssist4] in { + def KMF : SideEffectBinaryMemMemRRE<"kmf", 0xB92A, GR128, GR128>; + def KMO : SideEffectBinaryMemMemRRE<"kmo", 0xB92B, GR128, GR128>; + def KMCTR : SideEffectTernaryMemMemMemRRFb<"kmctr", 0xB92D, + GR128, GR128, GR128>; + def PCC : SideEffectInherentRRE<"pcc", 0xB92C>; + } + let Predicates = [FeatureMessageSecurityAssist5] in + def PPNO : SideEffectBinaryMemMemRRE<"ppno", 0xB93C, GR128, GR128>; +} + +//===----------------------------------------------------------------------===// +// Decimal arithmetic +//===----------------------------------------------------------------------===// + +defm CVB : BinaryRXPair<"cvb",0x4F, 0xE306, null_frag, GR32, load, 4>; +def CVBG : BinaryRXY<"cvbg", 0xE30E, null_frag, GR64, load, 8>; + +defm CVD : StoreRXPair<"cvd", 0x4E, 0xE326, null_frag, GR32, 4>; +def CVDG : StoreRXY<"cvdg", 0xE32E, null_frag, GR64, 8>; + +let mayLoad = 1, mayStore = 1 in { + def MVN : SideEffectBinarySSa<"mvn", 0xD1>; + def MVZ : SideEffectBinarySSa<"mvz", 0xD3>; + def MVO : SideEffectBinarySSb<"mvo", 0xF1>; + + def PACK : SideEffectBinarySSb<"pack", 0xF2>; + def PKA : SideEffectBinarySSf<"pka", 0xE9>; + def PKU : SideEffectBinarySSf<"pku", 0xE1>; + def UNPK : SideEffectBinarySSb<"unpk", 0xF3>; + let Defs = [CC] in { + def UNPKA : SideEffectBinarySSa<"unpka", 0xEA>; + def UNPKU : SideEffectBinarySSa<"unpku", 0xE2>; + } +} + +let mayLoad = 1, mayStore = 1 in { + let Defs = [CC] in { + def AP : SideEffectBinarySSb<"ap", 0xFA>; + def SP : SideEffectBinarySSb<"sp", 0xFB>; + def ZAP : SideEffectBinarySSb<"zap", 0xF8>; + def SRP : SideEffectTernarySSc<"srp", 0xF0>; + } + def MP : SideEffectBinarySSb<"mp", 0xFC>; + def DP : SideEffectBinarySSb<"dp", 0xFD>; + let Defs = [CC] in { + def ED : SideEffectBinarySSa<"ed", 0xDE>; + def EDMK : SideEffectBinarySSa<"edmk", 0xDF>; + } +} + +let Defs = [CC] in { + def CP : CompareSSb<"cp", 0xF9>; + def TP : TestRSL<"tp", 0xEBC0>; +} + +//===----------------------------------------------------------------------===// // Access registers //===----------------------------------------------------------------------===// @@ -1712,12 +1866,39 @@ let usesCustomInserter = 1 in { // Search a block of memory for a character. let mayLoad = 1, Defs = [CC] in - defm SRST : StringRRE<"srst", 0xb25e, z_search_string>; + defm SRST : StringRRE<"srst", 0xB25E, z_search_string>; +let mayLoad = 1, Defs = [CC], Uses = [R0L] in + def SRSTU : SideEffectBinaryMemMemRRE<"srstu", 0xB9BE, GR64, GR64>; + +// Compare until substring equal. +let mayLoad = 1, Defs = [CC], Uses = [R0L, R1L] in + def CUSE : SideEffectBinaryMemMemRRE<"cuse", 0xB257, GR128, GR128>; + +// Compare and form codeword. +let mayLoad = 1, Defs = [CC, R1D, R2D, R3D], Uses = [R1D, R2D, R3D] in + def CFC : SideEffectAddressS<"cfc", 0xB21A, null_frag>; + +// Update tree. +let mayLoad = 1, mayStore = 1, Defs = [CC, R0D, R1D, R2D, R3D, R5D], + Uses = [R0D, R1D, R2D, R3D, R4D, R5D] in + def UPT : SideEffectInherentE<"upt", 0x0102>; + +// Checksum. +let mayLoad = 1, Defs = [CC] in + def CKSM : SideEffectBinaryMemMemRRE<"cksm", 0xB241, GR64, GR128>; + +// Compression call. +let mayLoad = 1, mayStore = 1, Defs = [CC, R1D], Uses = [R0L, R1D] in + def CMPSC : SideEffectBinaryMemMemRRE<"cmpsc", 0xB263, GR128, GR128>; // Supervisor call. let hasSideEffects = 1, isCall = 1, Defs = [CC] in def SVC : SideEffectUnaryI<"svc", 0x0A, imm32zx8>; +// Monitor call. +let hasSideEffects = 1, isCall = 1 in + def MC : SideEffectBinarySI<"mc", 0xAF, imm32zx8>; + // Store clock. let hasSideEffects = 1, Defs = [CC] in { def STCK : StoreInherentS<"stck", 0xB205, null_frag, 8>; @@ -1729,10 +1910,18 @@ let hasSideEffects = 1, Defs = [CC] in { let hasSideEffects = 1, Uses = [R0D], Defs = [R0D, CC] in def STFLE : StoreInherentS<"stfle", 0xB2B0, null_frag, 0>; +// Extract CPU attribute. +let hasSideEffects = 1 in + def ECAG : BinaryRSY<"ecag", 0xEB4C, null_frag, GR64>; + // Extract CPU time. let Defs = [R0D, R1D], hasSideEffects = 1, mayLoad = 1 in def ECTG : SideEffectTernarySSF<"ectg", 0xC81, GR64>; +// Extract PSW. +let hasSideEffects = 1, Uses = [CC] in + def EPSW : InherentDualRRE<"epsw", 0xB98D, GR32>; + // Execute. let hasSideEffects = 1 in { def EX : SideEffectBinaryRX<"ex", 0x44, GR64>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZOperands.td b/contrib/llvm/lib/Target/SystemZ/SystemZOperands.td index 7bb4fe5afb3f..713612129d90 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZOperands.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZOperands.td @@ -531,6 +531,7 @@ def BDAddr64Disp12 : AddressAsmOperand<"BDAddr", "64", "12">; def BDAddr64Disp20 : AddressAsmOperand<"BDAddr", "64", "20">; def BDXAddr64Disp12 : AddressAsmOperand<"BDXAddr", "64", "12">; def BDXAddr64Disp20 : AddressAsmOperand<"BDXAddr", "64", "20">; +def BDLAddr64Disp12Len4 : AddressAsmOperand<"BDLAddr", "64", "12", "Len4">; def BDLAddr64Disp12Len8 : AddressAsmOperand<"BDLAddr", "64", "12", "Len8">; def BDRAddr64Disp12 : AddressAsmOperand<"BDRAddr", "64", "12">; def BDVAddr64Disp12 : AddressAsmOperand<"BDVAddr", "64", "12">; @@ -578,6 +579,7 @@ def bdxaddr20pair : BDXMode<"BDXAddr", "64", "20", "Pair">; def dynalloc12only : BDXMode<"DynAlloc", "64", "12", "Only">; def laaddr12pair : BDXMode<"LAAddr", "64", "12", "Pair">; def laaddr20pair : BDXMode<"LAAddr", "64", "20", "Pair">; +def bdladdr12onlylen4 : BDLMode<"BDLAddr", "64", "12", "Only", "4">; def bdladdr12onlylen8 : BDLMode<"BDLAddr", "64", "12", "Only", "8">; def bdraddr12only : BDRMode<"BDRAddr", "64", "12", "Only">; def bdvaddr12only : BDVMode< "64", "12">; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZOperators.td b/contrib/llvm/lib/Target/SystemZ/SystemZOperators.td index fde26ed4e1c5..adfc69c5d4cf 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZOperators.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZOperators.td @@ -10,7 +10,8 @@ //===----------------------------------------------------------------------===// // Type profiles //===----------------------------------------------------------------------===// -def SDT_CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i64>]>; +def SDT_CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i64>, + SDTCisVT<1, i64>]>; def SDT_CallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i64>, SDTCisVT<1, i64>]>; def SDT_ZCall : SDTypeProfile<0, -1, [SDTCisPtrTy<0>]>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZSchedule.td b/contrib/llvm/lib/Target/SystemZ/SystemZSchedule.td index dbba8ab42b5a..1ce0168f95e9 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZSchedule.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZSchedule.td @@ -56,12 +56,16 @@ def LSU_lat1 : SchedWrite; // Floating point unit (zEC12 and earlier) def FPU : SchedWrite; def FPU2 : SchedWrite; +def DFU : SchedWrite; +def DFU2 : SchedWrite; // Vector sub units (z13) def VecBF : SchedWrite; def VecBF2 : SchedWrite; def VecDF : SchedWrite; def VecDF2 : SchedWrite; +def VecDFX : SchedWrite; +def VecDFX2 : SchedWrite; def VecFPd : SchedWrite; // Blocking BFP div/sqrt unit. def VecMul : SchedWrite; def VecStr : SchedWrite; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td index 7aee6f52e9a7..612c3b6cf96e 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ13.td @@ -76,6 +76,8 @@ def : WriteRes<VecBF, [Z13_VecUnit]> { let Latency = 8; } def : WriteRes<VecBF2, [Z13_VecUnit, Z13_VecUnit]> { let Latency = 9; } def : WriteRes<VecDF, [Z13_VecUnit]> { let Latency = 8; } def : WriteRes<VecDF2, [Z13_VecUnit, Z13_VecUnit]> { let Latency = 9; } +def : WriteRes<VecDFX, [Z13_VecUnit]> { let Latency = 1; } +def : WriteRes<VecDFX2, [Z13_VecUnit, Z13_VecUnit]> { let Latency = 2; } def : WriteRes<VecFPd, [Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, Z13_VecFPdUnit, @@ -179,6 +181,7 @@ def : InstRW<[FXb, LSU, Lat5], (instregex "MVI(Y)?$")>; // Move character def : InstRW<[FXb, LSU, LSU, LSU, Lat8, GroupAlone], (instregex "MVC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCL(E|U)?$")>; // Pseudo -> reg move def : InstRW<[FXa], (instregex "COPY(_TO_REGCLASS)?$")>; @@ -268,6 +271,7 @@ def : InstRW<[FXb, LSU, Lat5], (instregex "LLG(F|T)?AT$")>; def : InstRW<[FXb, LSU, Lat5], (instregex "STC(H|Y|Mux)?$")>; def : InstRW<[FXb, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; +def : InstRW<[FXb, LSU, Lat5], (instregex "STCM(H|Y)?$")>; //===----------------------------------------------------------------------===// // Multi-register moves @@ -277,6 +281,9 @@ def : InstRW<[FXb, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; def : InstRW<[LSU, LSU, LSU, LSU, LSU, Lat10, GroupAlone], (instregex "LM(H|Y|G)?$")>; +// Load multiple disjoint +def : InstRW<[FXb, Lat30, GroupAlone], (instregex "LMD$")>; + // Store multiple (estimated average of ceil(5/2) FXb ops) def : InstRW<[LSU, LSU, FXb, FXb, FXb, Lat10, GroupAlone], (instregex "STM(G|H|Y)?$")>; @@ -288,6 +295,7 @@ def : InstRW<[LSU, LSU, FXb, FXb, FXb, Lat10, def : InstRW<[FXa], (instregex "LRV(G)?R$")>; def : InstRW<[FXa, LSU, Lat5], (instregex "LRV(G|H)?$")>; def : InstRW<[FXb, LSU, Lat5], (instregex "STRV(G|H)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCIN$")>; //===----------------------------------------------------------------------===// // Load address instructions @@ -345,7 +353,7 @@ def : InstRW<[FXa], (instregex "ALGF(I|R)$")>; def : InstRW<[FXa], (instregex "ALGR(K)?$")>; def : InstRW<[FXa], (instregex "ALR(K)?$")>; def : InstRW<[FXa], (instregex "AR(K)?$")>; -def : InstRW<[FXb, LSU, Lat5], (instregex "A(G)?SI$")>; +def : InstRW<[FXb, LSU, Lat5], (instregex "A(L)?(G)?SI$")>; // Logical addition with carry def : InstRW<[FXa, LSU, Lat6, GroupAlone], (instregex "ALC(G)?$")>; @@ -438,11 +446,15 @@ def : InstRW<[FXa, Lat9, GroupAlone], (instregex "MLGR$")>; def : InstRW<[FXa, Lat5], (instregex "MGHI$")>; def : InstRW<[FXa, Lat5], (instregex "MHI$")>; def : InstRW<[FXa, LSU, Lat9], (instregex "MH(Y)?$")>; +def : InstRW<[FXa, Lat7, GroupAlone], (instregex "M(L)?R$")>; +def : InstRW<[FXa, LSU, Lat7, GroupAlone], (instregex "M(FY|L)?$")>; //===----------------------------------------------------------------------===// // Division and remainder //===----------------------------------------------------------------------===// +def : InstRW<[FXa2, FXa2, Lat20, GroupAlone], (instregex "DR$")>; +def : InstRW<[FXa2, FXa2, LSU, Lat30, GroupAlone], (instregex "D$")>; def : InstRW<[FXa, Lat30, GroupAlone], (instregex "DSG(F)?R$")>; def : InstRW<[LSU, FXa, Lat30, GroupAlone], (instregex "DSG(F)?$")>; def : InstRW<[FXa2, FXa2, Lat20, GroupAlone], (instregex "DLR$")>; @@ -456,7 +468,8 @@ def : InstRW<[FXa2, FXa2, LSU, Lat30, GroupAlone], (instregex "DL(G)?$")>; def : InstRW<[FXa], (instregex "SLL(G|K)?$")>; def : InstRW<[FXa], (instregex "SRL(G|K)?$")>; def : InstRW<[FXa], (instregex "SRA(G|K)?$")>; -def : InstRW<[FXa], (instregex "SLA(K)?$")>; +def : InstRW<[FXa], (instregex "SLA(G|K)?$")>; +def : InstRW<[FXa, FXa, FXa, FXa, Lat8], (instregex "S(L|R)D(A|L)$")>; // Rotate def : InstRW<[FXa, LSU, Lat6], (instregex "RLL(G)?$")>; @@ -505,7 +518,7 @@ def : InstRW<[FXb, Lat2], (instregex "CGFR$")>; // Compare logical character def : InstRW<[FXb, LSU, LSU, Lat9, BeginGroup], (instregex "CLC$")>; - +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLCL(E|U)?$")>; def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLST$")>; // Test under mask @@ -516,6 +529,9 @@ def : InstRW<[FXb], (instregex "TMHL(64)?$")>; def : InstRW<[FXb], (instregex "TMLH(64)?$")>; def : InstRW<[FXb], (instregex "TMLL(64)?$")>; +// Compare logical characters under mask +def : InstRW<[FXb, LSU, Lat5], (instregex "CLM(H|Y)?$")>; + //===----------------------------------------------------------------------===// // Prefetch and execution hint //===----------------------------------------------------------------------===// @@ -563,6 +579,42 @@ def : InstRW<[FXb, FXb, LSU, Lat6, GroupAlone], (instregex "STPQ$")>; def : InstRW<[LSU, LSU, Lat5, GroupAlone], (instregex "LPD(G)?$")>; //===----------------------------------------------------------------------===// +// Translate and convert +//===----------------------------------------------------------------------===// + +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "TR(T|TR)?(E|EOpt)?$")>; +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "TR(T|O)(T|O)(Opt)?$")>; +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "CU(12|14|21|24|41|42)(Opt)?$")>; +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "(CUUTF|CUTFU)(Opt)?$")>; + +//===----------------------------------------------------------------------===// +// Message-security assist +//===----------------------------------------------------------------------===// + +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "KM(C|F|O|CTR)?$")>; +def : InstRW<[FXa, Lat30, GroupAlone], (instregex "(KIMD|KLMD|KMAC|PCC|PPNO)$")>; + +//===----------------------------------------------------------------------===// +// Decimal arithmetic +//===----------------------------------------------------------------------===// + +def : InstRW<[FXb, VecDF, LSU, Lat30, GroupAlone], (instregex "CVB(Y|G)?$")>; +def : InstRW<[FXb, VecDF, FXb, Lat30, GroupAlone], (instregex "CVD(Y|G)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MV(N|Z|O)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "(PACK|PKA|PKU)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UNPK(A|U)?$")>; + +def : InstRW<[FXb, VecDFX, LSU, LSU, Lat9, GroupAlone], + (instregex "(A|S|ZA)P$")>; +def : InstRW<[FXb, VecDFX2, LSU, LSU, Lat30, GroupAlone], + (instregex "(M|D)P$")>; +def : InstRW<[FXb, FXb, VecDFX2, LSU, LSU, LSU, Lat15, GroupAlone], + (instregex "SRP$")>; +def : InstRW<[VecDFX, LSU, LSU, Lat5, GroupAlone], (instregex "CP$")>; +def : InstRW<[VecDFX, LSU, Lat4, GroupAlone], (instregex "TP$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "ED(MK)?$")>; + +//===----------------------------------------------------------------------===// // Access registers //===----------------------------------------------------------------------===// @@ -640,13 +692,30 @@ def : InstRW<[FXa], (instregex "ZEXT128_(32|64)$")>; // String instructions def : InstRW<[FXa, LSU, Lat30], (instregex "SRST$")>; +def : InstRW<[LSU, Lat30], (instregex "SRSTU$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CUSE$")>; + +// Various complex instructions +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CFC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UPT$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CKSM$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CMPSC$")>; // Move with key def : InstRW<[FXa, FXa, FXb, LSU, Lat8, GroupAlone], (instregex "MVCK$")>; +// Monitor call +def : InstRW<[FXb], (instregex "MC$")>; + +// Extract CPU attribute +def : InstRW<[FXb, Lat30], (instregex "ECAG$")>; + // Extract CPU Time def : InstRW<[FXa, Lat5, LSU], (instregex "ECTG$")>; +// Extract PSW +def : InstRW<[FXb, Lat30], (instregex "EPSW$")>; + // Execute def : InstRW<[FXb, GroupAlone], (instregex "EX(RL)?$")>; @@ -811,14 +880,17 @@ def : InstRW<[VecFPd, LSU], (instregex "D(E|D)B$")>; def : InstRW<[VecFPd], (instregex "D(E|D)BR$")>; def : InstRW<[VecFPd, VecFPd, GroupAlone], (instregex "DXBR$")>; +// Divide to integer +def : InstRW<[VecFPd, Lat30, GroupAlone], (instregex "DI(E|D)BR$")>; + //===----------------------------------------------------------------------===// // FP: Comparisons //===----------------------------------------------------------------------===// // Compare -def : InstRW<[VecXsPm, LSU, Lat8], (instregex "C(E|D)B$")>; -def : InstRW<[VecXsPm, Lat4], (instregex "C(E|D)BR?$")>; -def : InstRW<[VecDF, VecDF, Lat20, GroupAlone], (instregex "CXBR$")>; +def : InstRW<[VecXsPm, LSU, Lat8], (instregex "(K|C)(E|D)B$")>; +def : InstRW<[VecXsPm, Lat4], (instregex "(K|C)(E|D)BR?$")>; +def : InstRW<[VecDF, VecDF, Lat20, GroupAlone], (instregex "(K|C)XBR$")>; // Test Data Class def : InstRW<[LSU, VecXsPm, Lat9], (instregex "TC(E|D)B$")>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td index a950e54e7601..670df8ff5541 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZ196.td @@ -59,6 +59,7 @@ def : WriteRes<Lat30, []> { let Latency = 30; let NumMicroOps = 0;} def Z196_FXUnit : ProcResource<2>; def Z196_LSUnit : ProcResource<2>; def Z196_FPUnit : ProcResource<1>; +def Z196_DFUnit : ProcResource<1>; // Subtarget specific definitions of scheduling resources. def : WriteRes<FXU, [Z196_FXUnit]> { let Latency = 1; } @@ -66,6 +67,8 @@ def : WriteRes<LSU, [Z196_LSUnit]> { let Latency = 4; } def : WriteRes<LSU_lat1, [Z196_LSUnit]> { let Latency = 1; } def : WriteRes<FPU, [Z196_FPUnit]> { let Latency = 8; } def : WriteRes<FPU2, [Z196_FPUnit, Z196_FPUnit]> { let Latency = 9; } +def : WriteRes<DFU, [Z196_DFUnit]> { let Latency = 2; } +def : WriteRes<DFU2, [Z196_DFUnit, Z196_DFUnit]> { let Latency = 3; } // -------------------------- INSTRUCTIONS ---------------------------------- // @@ -152,6 +155,7 @@ def : InstRW<[FXU, LSU, Lat5], (instregex "MVI(Y)?$")>; // Move character def : InstRW<[LSU, LSU, LSU, FXU, Lat8, GroupAlone], (instregex "MVC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCL(E|U)?$")>; // Pseudo -> reg move def : InstRW<[FXU], (instregex "COPY(_TO_REGCLASS)?$")>; @@ -226,6 +230,7 @@ def : InstRW<[LSU], (instregex "LLG(C|F|H|T|FRL|HRL)$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STC(H|Y|Mux)?$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "STCM(H|Y)?$")>; //===----------------------------------------------------------------------===// // Multi-register moves @@ -235,6 +240,9 @@ def : InstRW<[FXU, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; def : InstRW<[LSU, LSU, LSU, LSU, LSU, Lat10, GroupAlone], (instregex "LM(H|Y|G)?$")>; +// Load multiple disjoint +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "LMD$")>; + // Store multiple (estimated average of 3 ops) def : InstRW<[LSU, LSU, FXU, FXU, FXU, Lat10, GroupAlone], (instregex "STM(H|Y|G)?$")>; @@ -246,6 +254,7 @@ def : InstRW<[LSU, LSU, FXU, FXU, FXU, Lat10, GroupAlone], def : InstRW<[FXU], (instregex "LRV(G)?R$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "LRV(G|H)?$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STRV(G|H)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCIN$")>; //===----------------------------------------------------------------------===// // Load address instructions @@ -285,7 +294,7 @@ def : InstRW<[FXU], (instregex "IILL(64)?$")>; // Addition //===----------------------------------------------------------------------===// -def : InstRW<[FXU, LSU, Lat5], (instregex "A(Y|SI)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "A(L)?(Y|SI)?$")>; def : InstRW<[FXU, FXU, LSU, Lat6, GroupAlone], (instregex "AH(Y)?$")>; def : InstRW<[FXU], (instregex "AIH$")>; def : InstRW<[FXU], (instregex "AFI(Mux)?$")>; @@ -294,15 +303,14 @@ def : InstRW<[FXU], (instregex "AGHI(K)?$")>; def : InstRW<[FXU], (instregex "AGR(K)?$")>; def : InstRW<[FXU], (instregex "AHI(K)?$")>; def : InstRW<[FXU], (instregex "AHIMux(K)?$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "AL(Y)?$")>; def : InstRW<[FXU], (instregex "AL(FI|HSIK)$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "ALG(F)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "ALGF$")>; def : InstRW<[FXU], (instregex "ALGHSIK$")>; def : InstRW<[FXU], (instregex "ALGF(I|R)$")>; def : InstRW<[FXU], (instregex "ALGR(K)?$")>; def : InstRW<[FXU], (instregex "ALR(K)?$")>; def : InstRW<[FXU], (instregex "AR(K)?$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "AG(SI)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "A(L)?G(SI)?$")>; // Logical addition with carry def : InstRW<[FXU, LSU, Lat7, GroupAlone], (instregex "ALC(G)?$")>; @@ -395,11 +403,17 @@ def : InstRW<[FXU, Lat9, GroupAlone], (instregex "MLGR$")>; def : InstRW<[FXU, Lat5], (instregex "MGHI$")>; def : InstRW<[FXU, Lat5], (instregex "MHI$")>; def : InstRW<[FXU, LSU, Lat9], (instregex "MH(Y)?$")>; +def : InstRW<[FXU, Lat7, GroupAlone], (instregex "M(L)?R$")>; +def : InstRW<[FXU, LSU, Lat7, GroupAlone], (instregex "M(FY|L)?$")>; //===----------------------------------------------------------------------===// // Division and remainder //===----------------------------------------------------------------------===// +def : InstRW<[FPU2, FPU2, FXU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], + (instregex "DR$")>; +def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], + (instregex "D$")>; def : InstRW<[FPU2, FPU2, FXU, FXU, FXU, FXU, Lat30, GroupAlone], (instregex "DSG(F)?R$")>; def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, Lat30, GroupAlone], @@ -416,7 +430,8 @@ def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], def : InstRW<[FXU], (instregex "SLL(G|K)?$")>; def : InstRW<[FXU], (instregex "SRL(G|K)?$")>; def : InstRW<[FXU], (instregex "SRA(G|K)?$")>; -def : InstRW<[FXU, Lat2], (instregex "SLA(K)?$")>; +def : InstRW<[FXU, Lat2], (instregex "SLA(G|K)?$")>; +def : InstRW<[FXU, FXU, FXU, FXU, Lat8], (instregex "S(L|R)D(A|L)$")>; // Rotate def : InstRW<[FXU, LSU, Lat6], (instregex "RLL(G)?$")>; @@ -465,7 +480,7 @@ def : InstRW<[FXU, FXU, Lat2, GroupAlone], (instregex "CGFR$")>; // Compare logical character def : InstRW<[LSU, LSU, FXU, Lat9, GroupAlone], (instregex "CLC$")>; - +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLCL(E|U)?$")>; def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLST$")>; // Test under mask @@ -476,6 +491,9 @@ def : InstRW<[FXU], (instregex "TMHL(64)?$")>; def : InstRW<[FXU], (instregex "TMLH(64)?$")>; def : InstRW<[FXU], (instregex "TMLL(64)?$")>; +// Compare logical characters under mask +def : InstRW<[FXU, LSU, Lat5], (instregex "CLM(H|Y)?$")>; + //===----------------------------------------------------------------------===// // Prefetch //===----------------------------------------------------------------------===// @@ -520,6 +538,42 @@ def : InstRW<[FXU, FXU, LSU, LSU, Lat6, GroupAlone], (instregex "STPQ$")>; def : InstRW<[LSU, LSU, Lat5, GroupAlone], (instregex "LPD(G)?$")>; //===----------------------------------------------------------------------===// +// Translate and convert +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "TR(T|TR)?(E|EOpt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "TR(T|O)(T|O)(Opt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "CU(12|14|21|24|41|42)(Opt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "(CUUTF|CUTFU)(Opt)?$")>; + +//===----------------------------------------------------------------------===// +// Message-security assist +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "KM(C|F|O|CTR)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "(KIMD|KLMD|KMAC|PCC)$")>; + +//===----------------------------------------------------------------------===// +// Decimal arithmetic +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, DFU, LSU, Lat30, GroupAlone], (instregex "CVB(Y|G)?$")>; +def : InstRW<[FXU, DFU, FXU, Lat30, GroupAlone], (instregex "CVD(Y|G)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MV(N|Z|O)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "(PACK|PKA|PKU)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UNPK(A|U)?$")>; + +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, LSU, LSU, Lat15, GroupAlone], + (instregex "(A|S|ZA)P$")>; +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, LSU, LSU, Lat30, GroupAlone], + (instregex "(M|D)P$")>; +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, Lat15, GroupAlone], + (instregex "SRP$")>; +def : InstRW<[DFU2, LSU, LSU, LSU, LSU, Lat11, GroupAlone], (instregex "CP$")>; +def : InstRW<[DFU2, LSU, LSU, Lat3, GroupAlone], (instregex "TP$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "ED(MK)?$")>; + +//===----------------------------------------------------------------------===// // Access registers //===----------------------------------------------------------------------===// @@ -571,13 +625,30 @@ def : InstRW<[FXU], (instregex "ZEXT128_(32|64)$")>; // String instructions def : InstRW<[FXU, LSU, Lat30], (instregex "SRST$")>; +def : InstRW<[LSU, Lat30], (instregex "SRSTU$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CUSE$")>; + +// Various complex instructions +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CFC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UPT$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CKSM$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CMPSC$")>; // Move with key def : InstRW<[LSU, Lat8, GroupAlone], (instregex "MVCK$")>; +// Monitor call +def : InstRW<[FXU], (instregex "MC$")>; + +// Extract CPU attribute +def : InstRW<[FXU, Lat30], (instregex "ECAG$")>; + // Extract CPU Time def : InstRW<[FXU, Lat5, LSU], (instregex "ECTG$")>; +// Extract PSW +def : InstRW<[FXU, Lat30], (instregex "EPSW$")>; + // Execute def : InstRW<[LSU, GroupAlone], (instregex "EX(RL)?$")>; @@ -740,14 +811,17 @@ def : InstRW<[FPU, LSU, Lat30], (instregex "D(E|D)B$")>; def : InstRW<[FPU, Lat30], (instregex "D(E|D)BR$")>; def : InstRW<[FPU2, FPU2, Lat30, GroupAlone], (instregex "DXBR$")>; +// Divide to integer +def : InstRW<[FPU, Lat30, GroupAlone], (instregex "DI(E|D)BR$")>; + //===----------------------------------------------------------------------===// // FP: Comparisons //===----------------------------------------------------------------------===// // Compare -def : InstRW<[FPU, LSU, Lat12], (instregex "C(E|D)B$")>; -def : InstRW<[FPU], (instregex "C(E|D)BR$")>; -def : InstRW<[FPU, FPU, Lat30], (instregex "CXBR$")>; +def : InstRW<[FPU, LSU, Lat12], (instregex "(K|C)(E|D)B$")>; +def : InstRW<[FPU], (instregex "(K|C)(E|D)BR$")>; +def : InstRW<[FPU, FPU, Lat30], (instregex "(K|C)XBR$")>; // Test Data Class def : InstRW<[FPU, LSU, Lat15], (instregex "TC(E|D)B$")>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td index 8ab6c826f1ed..1bdb8779dc72 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td +++ b/contrib/llvm/lib/Target/SystemZ/SystemZScheduleZEC12.td @@ -59,6 +59,7 @@ def : WriteRes<Lat30, []> { let Latency = 30; let NumMicroOps = 0;} def ZEC12_FXUnit : ProcResource<2>; def ZEC12_LSUnit : ProcResource<2>; def ZEC12_FPUnit : ProcResource<1>; +def ZEC12_DFUnit : ProcResource<1>; def ZEC12_VBUnit : ProcResource<1>; // Subtarget specific definitions of scheduling resources. @@ -67,6 +68,8 @@ def : WriteRes<LSU, [ZEC12_LSUnit]> { let Latency = 4; } def : WriteRes<LSU_lat1, [ZEC12_LSUnit]> { let Latency = 1; } def : WriteRes<FPU, [ZEC12_FPUnit]> { let Latency = 8; } def : WriteRes<FPU2, [ZEC12_FPUnit, ZEC12_FPUnit]> { let Latency = 9; } +def : WriteRes<DFU, [ZEC12_DFUnit]> { let Latency = 2; } +def : WriteRes<DFU2, [ZEC12_DFUnit, ZEC12_FPUnit]> { let Latency = 3; } def : WriteRes<VBU, [ZEC12_VBUnit]>; // Virtual Branching Unit // -------------------------- INSTRUCTIONS ---------------------------------- // @@ -155,6 +158,7 @@ def : InstRW<[FXU, LSU, Lat5], (instregex "MVI(Y)?$")>; // Move character def : InstRW<[LSU, LSU, LSU, FXU, Lat8, GroupAlone], (instregex "MVC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCL(E|U)?$")>; // Pseudo -> reg move def : InstRW<[FXU], (instregex "COPY(_TO_REGCLASS)?$")>; @@ -236,6 +240,7 @@ def : InstRW<[FXU, LSU, Lat5], (instregex "LLG(F|T)?AT$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STC(H|Y|Mux)?$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "STCM(H|Y)?$")>; //===----------------------------------------------------------------------===// // Multi-register moves @@ -245,6 +250,9 @@ def : InstRW<[FXU, LSU, Lat5], (instregex "STH(H|Y|RL|Mux)?$")>; def : InstRW<[LSU, LSU, LSU, LSU, LSU, Lat10, GroupAlone], (instregex "LM(H|Y|G)?$")>; +// Load multiple disjoint +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "LMD$")>; + // Store multiple (estimated average of 3 ops) def : InstRW<[LSU, LSU, FXU, FXU, FXU, Lat10, GroupAlone], (instregex "STM(H|Y|G)?$")>; @@ -256,6 +264,7 @@ def : InstRW<[LSU, LSU, FXU, FXU, FXU, Lat10, GroupAlone], def : InstRW<[FXU], (instregex "LRV(G)?R$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "LRV(G|H)?$")>; def : InstRW<[FXU, LSU, Lat5], (instregex "STRV(G|H)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MVCIN$")>; //===----------------------------------------------------------------------===// // Load address instructions @@ -295,7 +304,7 @@ def : InstRW<[FXU], (instregex "IILL(64)?$")>; // Addition //===----------------------------------------------------------------------===// -def : InstRW<[FXU, LSU, Lat5], (instregex "A(Y|SI)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "A(L)?(Y|SI)?$")>; def : InstRW<[FXU, LSU, Lat6], (instregex "AH(Y)?$")>; def : InstRW<[FXU], (instregex "AIH$")>; def : InstRW<[FXU], (instregex "AFI(Mux)?$")>; @@ -304,15 +313,14 @@ def : InstRW<[FXU], (instregex "AGHI(K)?$")>; def : InstRW<[FXU], (instregex "AGR(K)?$")>; def : InstRW<[FXU], (instregex "AHI(K)?$")>; def : InstRW<[FXU], (instregex "AHIMux(K)?$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "AL(Y)?$")>; def : InstRW<[FXU], (instregex "AL(FI|HSIK)$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "ALG(F)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "ALGF$")>; def : InstRW<[FXU], (instregex "ALGHSIK$")>; def : InstRW<[FXU], (instregex "ALGF(I|R)$")>; def : InstRW<[FXU], (instregex "ALGR(K)?$")>; def : InstRW<[FXU], (instregex "ALR(K)?$")>; def : InstRW<[FXU], (instregex "AR(K)?$")>; -def : InstRW<[FXU, LSU, Lat5], (instregex "AG(SI)?$")>; +def : InstRW<[FXU, LSU, Lat5], (instregex "A(L)?G(SI)?$")>; // Logical addition with carry def : InstRW<[FXU, LSU, Lat7, GroupAlone], (instregex "ALC(G)?$")>; @@ -405,11 +413,17 @@ def : InstRW<[FXU, Lat9, GroupAlone], (instregex "MLGR$")>; def : InstRW<[FXU, Lat5], (instregex "MGHI$")>; def : InstRW<[FXU, Lat5], (instregex "MHI$")>; def : InstRW<[FXU, LSU, Lat9], (instregex "MH(Y)?$")>; +def : InstRW<[FXU, Lat7, GroupAlone], (instregex "M(L)?R$")>; +def : InstRW<[FXU, LSU, Lat7, GroupAlone], (instregex "M(FY|L)?$")>; //===----------------------------------------------------------------------===// // Division and remainder //===----------------------------------------------------------------------===// +def : InstRW<[FPU2, FPU2, FXU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], + (instregex "DR$")>; +def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], + (instregex "D$")>; def : InstRW<[FPU2, FPU2, FXU, FXU, FXU, FXU, Lat30, GroupAlone], (instregex "DSG(F)?R$")>; def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, Lat30, GroupAlone], @@ -426,7 +440,8 @@ def : InstRW<[FPU2, FPU2, LSU, FXU, FXU, FXU, FXU, Lat30, GroupAlone], def : InstRW<[FXU], (instregex "SLL(G|K)?$")>; def : InstRW<[FXU], (instregex "SRL(G|K)?$")>; def : InstRW<[FXU], (instregex "SRA(G|K)?$")>; -def : InstRW<[FXU], (instregex "SLA(K)?$")>; +def : InstRW<[FXU], (instregex "SLA(G|K)?$")>; +def : InstRW<[FXU, FXU, FXU, FXU, Lat8], (instregex "S(L|R)D(A|L)$")>; // Rotate def : InstRW<[FXU, LSU, Lat6], (instregex "RLL(G)?$")>; @@ -475,7 +490,7 @@ def : InstRW<[FXU, Lat2], (instregex "CGFR$")>; // Compare logical character def : InstRW<[FXU, LSU, LSU, Lat9, GroupAlone], (instregex "CLC$")>; - +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLCL(E|U)?$")>; def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CLST$")>; // Test under mask @@ -486,6 +501,9 @@ def : InstRW<[FXU], (instregex "TMHL(64)?$")>; def : InstRW<[FXU], (instregex "TMLH(64)?$")>; def : InstRW<[FXU], (instregex "TMLL(64)?$")>; +// Compare logical characters under mask +def : InstRW<[FXU, LSU, Lat5], (instregex "CLM(H|Y)?$")>; + //===----------------------------------------------------------------------===// // Prefetch and execution hint //===----------------------------------------------------------------------===// @@ -532,6 +550,42 @@ def : InstRW<[FXU, FXU, LSU, LSU, Lat6, GroupAlone], (instregex "STPQ$")>; def : InstRW<[LSU, LSU, Lat5, GroupAlone], (instregex "LPD(G)?$")>; //===----------------------------------------------------------------------===// +// Translate and convert +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "TR(T|TR)?(E|EOpt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "TR(T|O)(T|O)(Opt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "CU(12|14|21|24|41|42)(Opt)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "(CUUTF|CUTFU)(Opt)?$")>; + +//===----------------------------------------------------------------------===// +// Message-security assist +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "KM(C|F|O|CTR)?$")>; +def : InstRW<[FXU, Lat30, GroupAlone], (instregex "(KIMD|KLMD|KMAC|PCC)$")>; + +//===----------------------------------------------------------------------===// +// Decimal arithmetic +//===----------------------------------------------------------------------===// + +def : InstRW<[FXU, DFU, LSU, Lat30, GroupAlone], (instregex "CVB(Y|G)?$")>; +def : InstRW<[FXU, DFU, FXU, Lat30, GroupAlone], (instregex "CVD(Y|G)?$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "MV(N|Z|O)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "(PACK|PKA|PKU)$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UNPK(A|U)?$")>; + +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, LSU, LSU, Lat15, GroupAlone], + (instregex "(A|S|ZA)P$")>; +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, LSU, LSU, Lat30, GroupAlone], + (instregex "(M|D)P$")>; +def : InstRW<[FXU, FXU, DFU2, LSU, LSU, Lat15, GroupAlone], + (instregex "SRP$")>; +def : InstRW<[DFU2, LSU, LSU, LSU, LSU, Lat11, GroupAlone], (instregex "CP$")>; +def : InstRW<[DFU2, LSU, LSU, Lat3, GroupAlone], (instregex "TP$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "ED(MK)?$")>; + +//===----------------------------------------------------------------------===// // Access registers //===----------------------------------------------------------------------===// @@ -609,13 +663,30 @@ def : InstRW<[FXU], (instregex "ZEXT128_(32|64)$")>; // String instructions def : InstRW<[FXU, LSU, Lat30], (instregex "SRST$")>; +def : InstRW<[LSU, Lat30], (instregex "SRSTU$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CUSE$")>; + +// Various complex instructions +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CFC$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "UPT$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CKSM$")>; +def : InstRW<[LSU, Lat30, GroupAlone], (instregex "CMPSC$")>; // Move with key def : InstRW<[LSU, Lat8, GroupAlone], (instregex "MVCK$")>; +// Monitor call +def : InstRW<[FXU], (instregex "MC$")>; + +// Extract CPU attribute +def : InstRW<[FXU, Lat30], (instregex "ECAG$")>; + // Extract CPU Time def : InstRW<[FXU, Lat5, LSU], (instregex "ECTG$")>; +// Extract PSW +def : InstRW<[FXU, Lat30], (instregex "EPSW$")>; + // Execute def : InstRW<[LSU, GroupAlone], (instregex "EX(RL)?$")>; @@ -778,14 +849,17 @@ def : InstRW<[FPU, LSU, Lat30], (instregex "D(E|D)B$")>; def : InstRW<[FPU, Lat30], (instregex "D(E|D)BR$")>; def : InstRW<[FPU2, FPU2, Lat30, GroupAlone], (instregex "DXBR$")>; +// Divide to integer +def : InstRW<[FPU, Lat30, GroupAlone], (instregex "DI(E|D)BR$")>; + //===----------------------------------------------------------------------===// // FP: Comparisons //===----------------------------------------------------------------------===// // Compare -def : InstRW<[FPU, LSU, Lat12], (instregex "C(E|D)B$")>; -def : InstRW<[FPU], (instregex "C(E|D)BR$")>; -def : InstRW<[FPU, FPU, Lat30], (instregex "CXBR$")>; +def : InstRW<[FPU, LSU, Lat12], (instregex "(K|C)(E|D)B$")>; +def : InstRW<[FPU], (instregex "(K|C)(E|D)BR$")>; +def : InstRW<[FPU, FPU, Lat30], (instregex "(K|C)XBR$")>; // Test Data Class def : InstRW<[FPU, LSU, Lat15], (instregex "TC(E|D)B$")>; diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp b/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp index ce07ea3318a5..022679a7bc18 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp +++ b/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.cpp @@ -37,12 +37,13 @@ SystemZSubtarget::SystemZSubtarget(const Triple &TT, const std::string &CPU, const TargetMachine &TM) : SystemZGenSubtargetInfo(TT, CPU, FS), HasDistinctOps(false), HasLoadStoreOnCond(false), HasHighWord(false), HasFPExtension(false), - HasPopulationCount(false), HasFastSerialization(false), - HasInterlockedAccess1(false), HasMiscellaneousExtensions(false), + HasPopulationCount(false), HasMessageSecurityAssist4(false), + HasFastSerialization(false), HasInterlockedAccess1(false), + HasMiscellaneousExtensions(false), HasExecutionHint(false), HasLoadAndTrap(false), HasTransactionalExecution(false), HasProcessorAssist(false), HasVector(false), HasLoadStoreOnCond2(false), - HasLoadAndZeroRightmostByte(false), + HasLoadAndZeroRightmostByte(false), HasMessageSecurityAssist5(false), TargetTriple(TT), InstrInfo(initializeSubtargetDependencies(CPU, FS)), TLInfo(TM, *this), TSInfo(), FrameLowering() {} diff --git a/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.h b/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.h index cdb61327a16a..770dd7cd939f 100644 --- a/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.h +++ b/contrib/llvm/lib/Target/SystemZ/SystemZSubtarget.h @@ -39,6 +39,7 @@ protected: bool HasHighWord; bool HasFPExtension; bool HasPopulationCount; + bool HasMessageSecurityAssist4; bool HasFastSerialization; bool HasInterlockedAccess1; bool HasMiscellaneousExtensions; @@ -49,6 +50,7 @@ protected: bool HasVector; bool HasLoadStoreOnCond2; bool HasLoadAndZeroRightmostByte; + bool HasMessageSecurityAssist5; private: Triple TargetTriple; @@ -104,6 +106,10 @@ public: // Return true if the target has the population-count facility. bool hasPopulationCount() const { return HasPopulationCount; } + // Return true if the target has the message-security-assist + // extension facility 4. + bool hasMessageSecurityAssist4() const { return HasMessageSecurityAssist4; } + // Return true if the target has the fast-serialization facility. bool hasFastSerialization() const { return HasFastSerialization; } @@ -132,6 +138,10 @@ public: return HasLoadAndZeroRightmostByte; } + // Return true if the target has the message-security-assist + // extension facility 5. + bool hasMessageSecurityAssist5() const { return HasMessageSecurityAssist5; } + // Return true if the target has the vector facility. bool hasVector() const { return HasVector; } diff --git a/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td b/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td index 73d1d4be293b..6b45839c14b0 100644 --- a/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td +++ b/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td @@ -19,8 +19,8 @@ let Defs = [ARGUMENTS] in { // Call sequence markers. These have an immediate which represents the amount of // stack space to allocate or free, which is used for varargs lowering. let Uses = [SP32, SP64], Defs = [SP32, SP64], isCodeGenOnly = 1 in { -def ADJCALLSTACKDOWN : I<(outs), (ins i32imm:$amt), - [(WebAssemblycallseq_start timm:$amt)]>; +def ADJCALLSTACKDOWN : I<(outs), (ins i32imm:$amt, i32imm:$amt2), + [(WebAssemblycallseq_start timm:$amt, timm:$amt2)]>; def ADJCALLSTACKUP : I<(outs), (ins i32imm:$amt, i32imm:$amt2), [(WebAssemblycallseq_end timm:$amt, timm:$amt2)]>; } // isCodeGenOnly = 1 diff --git a/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td b/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td index a601b575f579..fa2146f7db84 100644 --- a/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td +++ b/contrib/llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td @@ -25,7 +25,8 @@ def HasSIMD128 : Predicate<"Subtarget->hasSIMD128()">, // WebAssembly-specific DAG Node Types. //===----------------------------------------------------------------------===// -def SDT_WebAssemblyCallSeqStart : SDCallSeqStart<[SDTCisVT<0, iPTR>]>; +def SDT_WebAssemblyCallSeqStart : SDCallSeqStart<[SDTCisVT<0, iPTR>, + SDTCisVT<1, iPTR>]>; def SDT_WebAssemblyCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, iPTR>, SDTCisVT<1, iPTR>]>; def SDT_WebAssemblyCall0 : SDTypeProfile<0, -1, [SDTCisPtrTy<0>]>; diff --git a/contrib/llvm/lib/Target/X86/X86.td b/contrib/llvm/lib/Target/X86/X86.td index 784c3a6557ff..3a421fe77392 100644 --- a/contrib/llvm/lib/Target/X86/X86.td +++ b/contrib/llvm/lib/Target/X86/X86.td @@ -235,6 +235,8 @@ def FeatureLEAUsesAG : SubtargetFeature<"lea-uses-ag", "LEAUsesAG", "true", "LEA instruction needs inputs at AG stage">; def FeatureSlowLEA : SubtargetFeature<"slow-lea", "SlowLEA", "true", "LEA instruction with certain arguments is slow">; +def FeatureSlow3OpsLEA : SubtargetFeature<"slow-3ops-lea", "Slow3OpsLEA", "true", + "LEA instruction with 3 ops or certain registers is slow">; def FeatureSlowIncDec : SubtargetFeature<"slow-incdec", "SlowIncDec", "true", "INC and DEC instructions are slower than ADD and SUB">; def FeatureSoftFloat @@ -480,6 +482,7 @@ def SNBFeatures : ProcessorFeatures<[], [ FeatureXSAVE, FeatureXSAVEOPT, FeatureLAHFSAHF, + FeatureSlow3OpsLEA, FeatureFastScalarFSQRT, FeatureFastSHLDRotate ]>; diff --git a/contrib/llvm/lib/Target/X86/X86FastISel.cpp b/contrib/llvm/lib/Target/X86/X86FastISel.cpp index ebd179e786da..fc3b4836c178 100644 --- a/contrib/llvm/lib/Target/X86/X86FastISel.cpp +++ b/contrib/llvm/lib/Target/X86/X86FastISel.cpp @@ -180,44 +180,6 @@ private: } // end anonymous namespace. -static std::pair<X86::CondCode, bool> -getX86ConditionCode(CmpInst::Predicate Predicate) { - X86::CondCode CC = X86::COND_INVALID; - bool NeedSwap = false; - switch (Predicate) { - default: break; - // Floating-point Predicates - case CmpInst::FCMP_UEQ: CC = X86::COND_E; break; - case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH; - case CmpInst::FCMP_OGT: CC = X86::COND_A; break; - case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH; - case CmpInst::FCMP_OGE: CC = X86::COND_AE; break; - case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH; - case CmpInst::FCMP_ULT: CC = X86::COND_B; break; - case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH; - case CmpInst::FCMP_ULE: CC = X86::COND_BE; break; - case CmpInst::FCMP_ONE: CC = X86::COND_NE; break; - case CmpInst::FCMP_UNO: CC = X86::COND_P; break; - case CmpInst::FCMP_ORD: CC = X86::COND_NP; break; - case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH; - case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break; - - // Integer Predicates - case CmpInst::ICMP_EQ: CC = X86::COND_E; break; - case CmpInst::ICMP_NE: CC = X86::COND_NE; break; - case CmpInst::ICMP_UGT: CC = X86::COND_A; break; - case CmpInst::ICMP_UGE: CC = X86::COND_AE; break; - case CmpInst::ICMP_ULT: CC = X86::COND_B; break; - case CmpInst::ICMP_ULE: CC = X86::COND_BE; break; - case CmpInst::ICMP_SGT: CC = X86::COND_G; break; - case CmpInst::ICMP_SGE: CC = X86::COND_GE; break; - case CmpInst::ICMP_SLT: CC = X86::COND_L; break; - case CmpInst::ICMP_SLE: CC = X86::COND_LE; break; - } - - return std::make_pair(CC, NeedSwap); -} - static std::pair<unsigned, bool> getX86SSEConditionCode(CmpInst::Predicate Predicate) { unsigned CC; @@ -1559,7 +1521,7 @@ bool X86FastISel::X86SelectCmp(const Instruction *I) { X86::CondCode CC; bool SwapArgs; - std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); + std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate); assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); unsigned Opc = X86::getSETFromCond(CC); @@ -1697,7 +1659,7 @@ bool X86FastISel::X86SelectBranch(const Instruction *I) { bool SwapArgs; unsigned BranchOpc; - std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); + std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate); assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); BranchOpc = X86::GetCondBranchFromCond(CC); @@ -2070,7 +2032,7 @@ bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) { } bool NeedSwap; - std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate); + std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate); assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); const Value *CmpLHS = CI->getOperand(0); @@ -2319,7 +2281,7 @@ bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) { const auto *CI = dyn_cast<CmpInst>(Cond); if (CI && (CI->getParent() == I->getParent())) { bool NeedSwap; - std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate()); + std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate()); if (CC > X86::LAST_VALID_COND) return false; @@ -3293,7 +3255,7 @@ bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) { // Issue CALLSEQ_START unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) - .addImm(NumBytes).addImm(0); + .addImm(NumBytes).addImm(0).addImm(0); // Walk the register/memloc assignments, inserting copies/loads. const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo(); diff --git a/contrib/llvm/lib/Target/X86/X86FixupLEAs.cpp b/contrib/llvm/lib/Target/X86/X86FixupLEAs.cpp index 2cd4c1a3e7b3..9f649dad8bc0 100644 --- a/contrib/llvm/lib/Target/X86/X86FixupLEAs.cpp +++ b/contrib/llvm/lib/Target/X86/X86FixupLEAs.cpp @@ -27,20 +27,26 @@ #include "llvm/Target/TargetInstrInfo.h" using namespace llvm; -#define DEBUG_TYPE "x86-fixup-LEAs" +namespace llvm { +void initializeFixupLEAPassPass(PassRegistry &); +} + +#define FIXUPLEA_DESC "X86 LEA Fixup" +#define FIXUPLEA_NAME "x86-fixup-LEAs" + +#define DEBUG_TYPE FIXUPLEA_NAME STATISTIC(NumLEAs, "Number of LEA instructions created"); namespace { class FixupLEAPass : public MachineFunctionPass { enum RegUsageState { RU_NotUsed, RU_Write, RU_Read }; - static char ID; + /// \brief Loop over all of the instructions in the basic block /// replacing applicable instructions with LEA instructions, /// where appropriate. bool processBasicBlock(MachineFunction &MF, MachineFunction::iterator MFI); - StringRef getPassName() const override { return "X86 LEA Fixup"; } /// \brief Given a machine register, look for the instruction /// which writes it in the current basic block. If found, @@ -62,6 +68,22 @@ class FixupLEAPass : public MachineFunctionPass { void processInstructionForSLM(MachineBasicBlock::iterator &I, MachineFunction::iterator MFI); + + /// \brief Given a LEA instruction which is unprofitable + /// on SNB+ try to replace it with other instructions. + /// According to Intel's Optimization Reference Manual: + /// " For LEA instructions with three source operands and some specific + /// situations, instruction latency has increased to 3 cycles, and must + /// dispatch via port 1: + /// - LEA that has all three source operands: base, index, and offset + /// - LEA that uses base and index registers where the base is EBP, RBP, + /// or R13 + /// - LEA that uses RIP relative addressing mode + /// - LEA that uses 16-bit addressing mode " + /// This function currently handles the first 2 cases only. + MachineInstr *processInstrForSlow3OpLEA(MachineInstr &MI, + MachineFunction::iterator MFI); + /// \brief Look for LEAs that add 1 to reg or subtract 1 from reg /// and convert them to INC or DEC respectively. bool fixupIncDec(MachineBasicBlock::iterator &I, @@ -85,7 +107,13 @@ class FixupLEAPass : public MachineFunctionPass { MachineBasicBlock::iterator &MBBI) const; public: - FixupLEAPass() : MachineFunctionPass(ID) {} + static char ID; + + StringRef getPassName() const override { return FIXUPLEA_DESC; } + + FixupLEAPass() : MachineFunctionPass(ID) { + initializeFixupLEAPassPass(*PassRegistry::getPassRegistry()); + } /// \brief Loop over all of the basic blocks, /// replacing instructions by equivalent LEA instructions @@ -104,9 +132,12 @@ private: bool OptIncDec; bool OptLEA; }; -char FixupLEAPass::ID = 0; } +char FixupLEAPass::ID = 0; + +INITIALIZE_PASS(FixupLEAPass, FIXUPLEA_NAME, FIXUPLEA_DESC, false, false) + MachineInstr * FixupLEAPass::postRAConvertToLEA(MachineFunction::iterator &MFI, MachineBasicBlock::iterator &MBBI) const { @@ -168,7 +199,7 @@ bool FixupLEAPass::runOnMachineFunction(MachineFunction &Func) { MF = &Func; const X86Subtarget &ST = Func.getSubtarget<X86Subtarget>(); OptIncDec = !ST.slowIncDec() || Func.getFunction()->optForMinSize(); - OptLEA = ST.LEAusesAG() || ST.slowLEA(); + OptLEA = ST.LEAusesAG() || ST.slowLEA() || ST.slow3OpsLEA(); if (!OptLEA && !OptIncDec) return false; @@ -242,9 +273,64 @@ FixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I, return MachineBasicBlock::iterator(); } -static inline bool isLEA(const int opcode) { - return opcode == X86::LEA16r || opcode == X86::LEA32r || - opcode == X86::LEA64r || opcode == X86::LEA64_32r; +static inline bool isLEA(const int Opcode) { + return Opcode == X86::LEA16r || Opcode == X86::LEA32r || + Opcode == X86::LEA64r || Opcode == X86::LEA64_32r; +} + +static inline bool isInefficientLEAReg(unsigned int Reg) { + return Reg == X86::EBP || Reg == X86::RBP || Reg == X86::R13; +} + +static inline bool isRegOperand(const MachineOperand &Op) { + return Op.isReg() && Op.getReg() != X86::NoRegister; +} +/// hasIneffecientLEARegs - LEA that uses base and index registers +/// where the base is EBP, RBP, or R13 +static inline bool hasInefficientLEABaseReg(const MachineOperand &Base, + const MachineOperand &Index) { + return Base.isReg() && isInefficientLEAReg(Base.getReg()) && + isRegOperand(Index); +} + +static inline bool hasLEAOffset(const MachineOperand &Offset) { + return (Offset.isImm() && Offset.getImm() != 0) || Offset.isGlobal(); +} + +// LEA instruction that has all three operands: offset, base and index +static inline bool isThreeOperandsLEA(const MachineOperand &Base, + const MachineOperand &Index, + const MachineOperand &Offset) { + return isRegOperand(Base) && isRegOperand(Index) && hasLEAOffset(Offset); +} + +static inline int getADDrrFromLEA(int LEAOpcode) { + switch (LEAOpcode) { + default: + llvm_unreachable("Unexpected LEA instruction"); + case X86::LEA16r: + return X86::ADD16rr; + case X86::LEA32r: + return X86::ADD32rr; + case X86::LEA64_32r: + case X86::LEA64r: + return X86::ADD64rr; + } +} + +static inline int getADDriFromLEA(int LEAOpcode, const MachineOperand &Offset) { + bool IsInt8 = Offset.isImm() && isInt<8>(Offset.getImm()); + switch (LEAOpcode) { + default: + llvm_unreachable("Unexpected LEA instruction"); + case X86::LEA16r: + return IsInt8 ? X86::ADD16ri8 : X86::ADD16ri; + case X86::LEA32r: + case X86::LEA64_32r: + return IsInt8 ? X86::ADD32ri8 : X86::ADD32ri; + case X86::LEA64r: + return IsInt8 ? X86::ADD64ri8 : X86::ADD64ri32; + } } /// isLEASimpleIncOrDec - Does this LEA have one these forms: @@ -337,8 +423,8 @@ void FixupLEAPass::seekLEAFixup(MachineOperand &p, void FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I, MachineFunction::iterator MFI) { MachineInstr &MI = *I; - const int opcode = MI.getOpcode(); - if (!isLEA(opcode)) + const int Opcode = MI.getOpcode(); + if (!isLEA(Opcode)) return; if (MI.getOperand(5).getReg() != 0 || !MI.getOperand(4).isImm() || !TII->isSafeToClobberEFLAGS(*MFI, I)) @@ -350,53 +436,142 @@ void FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I, return; if (MI.getOperand(2).getImm() > 1) return; - int addrr_opcode, addri_opcode; - switch (opcode) { - default: - llvm_unreachable("Unexpected LEA instruction"); - case X86::LEA16r: - addrr_opcode = X86::ADD16rr; - addri_opcode = X86::ADD16ri; - break; - case X86::LEA32r: - addrr_opcode = X86::ADD32rr; - addri_opcode = X86::ADD32ri; - break; - case X86::LEA64_32r: - case X86::LEA64r: - addrr_opcode = X86::ADD64rr; - addri_opcode = X86::ADD64ri32; - break; - } DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump();); DEBUG(dbgs() << "FixLEA: Replaced by: ";); MachineInstr *NewMI = nullptr; - const MachineOperand &Dst = MI.getOperand(0); // Make ADD instruction for two registers writing to LEA's destination if (SrcR1 != 0 && SrcR2 != 0) { - const MachineOperand &Src1 = MI.getOperand(SrcR1 == DstR ? 1 : 3); - const MachineOperand &Src2 = MI.getOperand(SrcR1 == DstR ? 3 : 1); - NewMI = BuildMI(*MF, MI.getDebugLoc(), TII->get(addrr_opcode)) - .add(Dst) - .add(Src1) - .add(Src2); - MFI->insert(I, NewMI); + const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(Opcode)); + const MachineOperand &Src = MI.getOperand(SrcR1 == DstR ? 3 : 1); + NewMI = + BuildMI(*MFI, I, MI.getDebugLoc(), ADDrr, DstR).addReg(DstR).add(Src); DEBUG(NewMI->dump();); } // Make ADD instruction for immediate if (MI.getOperand(4).getImm() != 0) { + const MCInstrDesc &ADDri = + TII->get(getADDriFromLEA(Opcode, MI.getOperand(4))); const MachineOperand &SrcR = MI.getOperand(SrcR1 == DstR ? 1 : 3); - NewMI = BuildMI(*MF, MI.getDebugLoc(), TII->get(addri_opcode)) - .add(Dst) + NewMI = BuildMI(*MFI, I, MI.getDebugLoc(), ADDri, DstR) .add(SrcR) .addImm(MI.getOperand(4).getImm()); - MFI->insert(I, NewMI); DEBUG(NewMI->dump();); } if (NewMI) { MFI->erase(I); - I = static_cast<MachineBasicBlock::iterator>(NewMI); + I = NewMI; + } +} + +MachineInstr * +FixupLEAPass::processInstrForSlow3OpLEA(MachineInstr &MI, + MachineFunction::iterator MFI) { + + const int LEAOpcode = MI.getOpcode(); + if (!isLEA(LEAOpcode)) + return nullptr; + + const MachineOperand &Dst = MI.getOperand(0); + const MachineOperand &Base = MI.getOperand(1); + const MachineOperand &Scale = MI.getOperand(2); + const MachineOperand &Index = MI.getOperand(3); + const MachineOperand &Offset = MI.getOperand(4); + const MachineOperand &Segment = MI.getOperand(5); + + if (!(isThreeOperandsLEA(Base, Index, Offset) || + hasInefficientLEABaseReg(Base, Index)) || + !TII->isSafeToClobberEFLAGS(*MFI, MI) || + Segment.getReg() != X86::NoRegister) + return nullptr; + + unsigned int DstR = Dst.getReg(); + unsigned int BaseR = Base.getReg(); + unsigned int IndexR = Index.getReg(); + unsigned SSDstR = + (LEAOpcode == X86::LEA64_32r) ? getX86SubSuperRegister(DstR, 64) : DstR; + bool IsScale1 = Scale.getImm() == 1; + bool IsInefficientBase = isInefficientLEAReg(BaseR); + bool IsInefficientIndex = isInefficientLEAReg(IndexR); + + // Skip these cases since it takes more than 2 instructions + // to replace the LEA instruction. + if (IsInefficientBase && SSDstR == BaseR && !IsScale1) + return nullptr; + if (LEAOpcode == X86::LEA64_32r && IsInefficientBase && + (IsInefficientIndex || !IsScale1)) + return nullptr; + + const DebugLoc DL = MI.getDebugLoc(); + const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(LEAOpcode)); + const MCInstrDesc &ADDri = TII->get(getADDriFromLEA(LEAOpcode, Offset)); + + DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI.dump();); + DEBUG(dbgs() << "FixLEA: Replaced by: ";); + + // First try to replace LEA with one or two (for the 3-op LEA case) + // add instructions: + // 1.lea (%base,%index,1), %base => add %index,%base + // 2.lea (%base,%index,1), %index => add %base,%index + if (IsScale1 && (DstR == BaseR || DstR == IndexR)) { + const MachineOperand &Src = DstR == BaseR ? Index : Base; + MachineInstr *NewMI = + BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Src); + DEBUG(NewMI->dump();); + // Create ADD instruction for the Offset in case of 3-Ops LEA. + if (hasLEAOffset(Offset)) { + NewMI = BuildMI(*MFI, MI, DL, ADDri, DstR).addReg(DstR).add(Offset); + DEBUG(NewMI->dump();); + } + return NewMI; + } + // If the base is inefficient try switching the index and base operands, + // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction: + // lea offset(%base,%index,scale),%dst => + // lea (%base,%index,scale); add offset,%dst + if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) { + MachineInstr *NewMI = BuildMI(*MFI, MI, DL, TII->get(LEAOpcode)) + .add(Dst) + .add(IsInefficientBase ? Index : Base) + .add(Scale) + .add(IsInefficientBase ? Base : Index) + .addImm(0) + .add(Segment); + DEBUG(NewMI->dump();); + // Create ADD instruction for the Offset in case of 3-Ops LEA. + if (hasLEAOffset(Offset)) { + NewMI = BuildMI(*MFI, MI, DL, ADDri, DstR).addReg(DstR).add(Offset); + DEBUG(NewMI->dump();); + } + return NewMI; + } + // Handle the rest of the cases with inefficient base register: + assert(SSDstR != BaseR && "SSDstR == BaseR should be handled already!"); + assert(IsInefficientBase && "efficient base should be handled already!"); + + // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst + if (IsScale1 && !hasLEAOffset(Offset)) { + TII->copyPhysReg(*MFI, MI, DL, DstR, BaseR, Base.isKill()); + DEBUG(MI.getPrevNode()->dump();); + + MachineInstr *NewMI = + BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Index); + DEBUG(NewMI->dump();); + return NewMI; } + // lea offset(%base,%index,scale), %dst => + // lea offset( ,%index,scale), %dst; add %base,%dst + MachineInstr *NewMI = BuildMI(*MFI, MI, DL, TII->get(LEAOpcode)) + .add(Dst) + .addReg(0) + .add(Scale) + .add(Index) + .add(Offset) + .add(Segment); + DEBUG(NewMI->dump();); + + NewMI = BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Base); + DEBUG(NewMI->dump();); + return NewMI; } bool FixupLEAPass::processBasicBlock(MachineFunction &MF, @@ -410,8 +585,16 @@ bool FixupLEAPass::processBasicBlock(MachineFunction &MF, if (OptLEA) { if (MF.getSubtarget<X86Subtarget>().isSLM()) processInstructionForSLM(I, MFI); - else - processInstruction(I, MFI); + + else { + if (MF.getSubtarget<X86Subtarget>().slow3OpsLEA()) { + if (auto *NewMI = processInstrForSlow3OpLEA(*I, MFI)) { + MFI->erase(I); + I = NewMI; + } + } else + processInstruction(I, MFI); + } } } return false; diff --git a/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp b/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp index 12a10bf3072f..c899f0fd5100 100644 --- a/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp +++ b/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp @@ -1178,8 +1178,7 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; - if (ConstantSDNode - *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) { + if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) { unsigned Val = CN->getZExtValue(); // Note that we handle x<<1 as (,x,2) rather than (x,x) here so // that the base operand remains free for further matching. If @@ -1187,15 +1186,14 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, // in MatchAddress turns (,x,2) into (x,x), which is cheaper. if (Val == 1 || Val == 2 || Val == 3) { AM.Scale = 1 << Val; - SDValue ShVal = N.getNode()->getOperand(0); + SDValue ShVal = N.getOperand(0); // Okay, we know that we have a scale by now. However, if the scaled // value is an add of something and a constant, we can fold the // constant into the disp field here. if (CurDAG->isBaseWithConstantOffset(ShVal)) { - AM.IndexReg = ShVal.getNode()->getOperand(0); - ConstantSDNode *AddVal = - cast<ConstantSDNode>(ShVal.getNode()->getOperand(1)); + AM.IndexReg = ShVal.getOperand(0); + ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1)); uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val; if (!foldOffsetIntoAddress(Disp, AM)) return false; @@ -1245,28 +1243,27 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr) { - if (ConstantSDNode - *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) + if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 || CN->getZExtValue() == 9) { AM.Scale = unsigned(CN->getZExtValue())-1; - SDValue MulVal = N.getNode()->getOperand(0); + SDValue MulVal = N.getOperand(0); SDValue Reg; // Okay, we know that we have a scale by now. However, if the scaled // value is an add of something and a constant, we can fold the // constant into the disp field here. if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() && - isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) { - Reg = MulVal.getNode()->getOperand(0); + isa<ConstantSDNode>(MulVal.getOperand(1))) { + Reg = MulVal.getOperand(0); ConstantSDNode *AddVal = - cast<ConstantSDNode>(MulVal.getNode()->getOperand(1)); + cast<ConstantSDNode>(MulVal.getOperand(1)); uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue(); if (foldOffsetIntoAddress(Disp, AM)) - Reg = N.getNode()->getOperand(0); + Reg = N.getOperand(0); } else { - Reg = N.getNode()->getOperand(0); + Reg = N.getOperand(0); } AM.IndexReg = AM.Base_Reg = Reg; @@ -1289,7 +1286,7 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, // Test if the LHS of the sub can be folded. X86ISelAddressMode Backup = AM; - if (matchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) { + if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) { AM = Backup; break; } @@ -1300,7 +1297,7 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, } int Cost = 0; - SDValue RHS = Handle.getValue().getNode()->getOperand(1); + SDValue RHS = Handle.getValue().getOperand(1); // If the RHS involves a register with multiple uses, this // transformation incurs an extra mov, due to the neg instruction // clobbering its operand. @@ -1309,7 +1306,7 @@ bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, RHS.getNode()->getOpcode() == ISD::TRUNCATE || RHS.getNode()->getOpcode() == ISD::ANY_EXTEND || (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND && - RHS.getNode()->getOperand(0).getValueType() == MVT::i32)) + RHS.getOperand(0).getValueType() == MVT::i32)) ++Cost; // If the base is a register with multiple uses, this // transformation may save a mov. @@ -2524,7 +2521,7 @@ void X86DAGToDAGISel::Select(SDNode *Node) { N0.getNode()->hasOneUse() && N0.getValueType() != MVT::i8 && X86::isZeroNode(N1)) { - ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1)); + ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); if (!C) break; // For example, convert "testl %eax, $8" to "testb %al, $8" @@ -2532,7 +2529,7 @@ void X86DAGToDAGISel::Select(SDNode *Node) { (!(C->getZExtValue() & 0x80) || hasNoSignedComparisonUses(Node))) { SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8); - SDValue Reg = N0.getNode()->getOperand(0); + SDValue Reg = N0.getOperand(0); // On x86-32, only the ABCD registers have 8-bit subregisters. if (!Subtarget->is64Bit()) { @@ -2568,7 +2565,7 @@ void X86DAGToDAGISel::Select(SDNode *Node) { // Shift the immediate right by 8 bits. SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8, dl, MVT::i8); - SDValue Reg = N0.getNode()->getOperand(0); + SDValue Reg = N0.getOperand(0); // Put the value in an ABCD register. const TargetRegisterClass *TRC; @@ -2605,7 +2602,7 @@ void X86DAGToDAGISel::Select(SDNode *Node) { hasNoSignedComparisonUses(Node))) { SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i16); - SDValue Reg = N0.getNode()->getOperand(0); + SDValue Reg = N0.getOperand(0); // Extract the 16-bit subregister. SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl, @@ -2628,7 +2625,7 @@ void X86DAGToDAGISel::Select(SDNode *Node) { hasNoSignedComparisonUses(Node))) { SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i32); - SDValue Reg = N0.getNode()->getOperand(0); + SDValue Reg = N0.getOperand(0); // Extract the 32-bit subregister. SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl, diff --git a/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp b/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp index 9ee2234595f9..11c08292518a 100644 --- a/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp +++ b/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp @@ -40,6 +40,7 @@ #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" @@ -79,6 +80,17 @@ static cl::opt<int> ExperimentalPrefLoopAlignment( " of the loop header PC will be 0)."), cl::Hidden); +/// Call this when the user attempts to do something unsupported, like +/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike +/// report_fatal_error, so calling code should attempt to recover without +/// crashing. +static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl, + const char *Msg) { + MachineFunction &MF = DAG.getMachineFunction(); + DAG.getContext()->diagnose( + DiagnosticInfoUnsupported(*MF.getFunction(), Msg, dl.getDebugLoc())); +} + X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM, const X86Subtarget &STI) : TargetLowering(TM), Subtarget(STI) { @@ -1381,7 +1393,7 @@ X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM, setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); setOperationAction(ISD::BUILD_VECTOR, VT, Custom); - setOperationAction(ISD::VSELECT, VT, Legal); + setOperationAction(ISD::VSELECT, VT, Custom); setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal); @@ -1445,8 +1457,6 @@ X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM, setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom); setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom); setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom); - setOperationAction(ISD::VSELECT, MVT::v32i16, Legal); - setOperationAction(ISD::VSELECT, MVT::v64i8, Legal); setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom); setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom); setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom); @@ -1479,7 +1489,7 @@ X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM, for (auto VT : { MVT::v64i8, MVT::v32i16 }) { setOperationAction(ISD::BUILD_VECTOR, VT, Custom); - setOperationAction(ISD::VSELECT, VT, Legal); + setOperationAction(ISD::VSELECT, VT, Custom); setOperationAction(ISD::ABS, VT, Legal); setOperationAction(ISD::SRL, VT, Custom); setOperationAction(ISD::SHL, VT, Custom); @@ -2207,15 +2217,17 @@ X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, // or SSE or MMX vectors. if ((ValVT == MVT::f32 || ValVT == MVT::f64 || VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && - (Subtarget.is64Bit() && !Subtarget.hasSSE1())) { - report_fatal_error("SSE register return with SSE disabled"); + (Subtarget.is64Bit() && !Subtarget.hasSSE1())) { + errorUnsupported(DAG, dl, "SSE register return with SSE disabled"); + VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts. + } else if (ValVT == MVT::f64 && + (Subtarget.is64Bit() && !Subtarget.hasSSE2())) { + // Likewise we can't return F64 values with SSE1 only. gcc does so, but + // llvm-gcc has never done it right and no one has noticed, so this + // should be OK for now. + errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled"); + VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts. } - // Likewise we can't return F64 values with SSE1 only. gcc does so, but - // llvm-gcc has never done it right and no one has noticed, so this - // should be OK for now. - if (ValVT == MVT::f64 && - (Subtarget.is64Bit() && !Subtarget.hasSSE2())) - report_fatal_error("SSE2 register return with SSE2 disabled"); // Returns in ST0/ST1 are handled specially: these are pushed as operands to // the RET instruction and handled by the FP Stackifier. @@ -2528,7 +2540,8 @@ SDValue X86TargetLowering::LowerCallResult( // If this is x86-64, and we disabled SSE, we can't return FP values if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) && ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) { - report_fatal_error("SSE register return with SSE disabled"); + errorUnsupported(DAG, dl, "SSE register return with SSE disabled"); + VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts. } // If we prefer to use the value in xmm registers, copy it out as f80 and @@ -3415,8 +3428,8 @@ X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, } if (!IsSibcall) - Chain = DAG.getCALLSEQ_START( - Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush, + NumBytes - NumBytesToPush, dl); SDValue RetAddrFrIdx; // Load return address for tail calls. @@ -6912,9 +6925,9 @@ X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const { // for splat use " (select i1 splat_elt, all-ones, all-zeroes)" if (IsSplat) - return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx), - DAG.getConstant(1, dl, VT), - DAG.getConstant(0, dl, VT)); + return DAG.getSelect(dl, VT, Op.getOperand(SplatIdx), + DAG.getConstant(1, dl, VT), + DAG.getConstant(0, dl, VT)); // insert elements one by one SDValue DstVec; @@ -8386,9 +8399,9 @@ static SDValue lowerVectorShuffleToEXPAND(const SDLoc &DL, MVT VT, Subtarget, DAG, DL); SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL); SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1; - return DAG.getNode(ISD::VSELECT, DL, VT, VMask, - DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector), - ZeroVector); + return DAG.getSelect(DL, VT, VMask, + DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector), + ZeroVector); } static bool matchVectorShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2, @@ -8748,8 +8761,9 @@ static SDValue lowerVectorShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1, V1 = DAG.getBitcast(BlendVT, V1); V2 = DAG.getBitcast(BlendVT, V2); return DAG.getBitcast( - VT, DAG.getNode(ISD::VSELECT, DL, BlendVT, - DAG.getBuildVector(BlendVT, DL, VSELECTMask), V1, V2)); + VT, + DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask), + V1, V2)); } case MVT::v16f32: case MVT::v8f64: @@ -13817,6 +13831,11 @@ SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const { ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode())) return SDValue(); + // If this VSELECT has a vector if i1 as a mask, it will be directly matched + // with patterns on the mask registers on AVX-512. + if (Op->getOperand(0).getValueType().getScalarSizeInBits() == 1) + return Op; + // Try to lower this to a blend-style vector shuffle. This can handle all // constant condition cases. if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG)) @@ -13826,10 +13845,30 @@ SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const { if (!Subtarget.hasSSE41()) return SDValue(); + SDLoc dl(Op); + MVT VT = Op.getSimpleValueType(); + + // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition + // into an i1 condition so that we can use the mask-based 512-bit blend + // instructions. + if (VT.getSizeInBits() == 512) { + SDValue Cond = Op.getOperand(0); + // The vNi1 condition case should be handled above as it can be trivially + // lowered. + assert(Cond.getValueType().getScalarSizeInBits() == + VT.getScalarSizeInBits() && + "Should have a size-matched integer condition!"); + // Build a mask by testing the condition against itself (tests for zero). + MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements()); + SDValue Mask = DAG.getNode(X86ISD::TESTM, dl, MaskVT, Cond, Cond); + // Now return a new VSELECT using the mask. + return DAG.getSelect(dl, VT, Mask, Op.getOperand(1), Op.getOperand(2)); + } + // Only some types will be legal on some subtargets. If we can emit a legal // VSELECT-matching blend, return Op, and but if we need to expand, return // a null value. - switch (Op.getSimpleValueType().SimpleTy) { + switch (VT.SimpleTy) { default: // Most of the vector types have blends past SSE4.1. return Op; @@ -14725,7 +14764,7 @@ X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { // location. SDValue Chain = DAG.getEntryNode(); SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL); + Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); SDValue Args[] = { Chain, Offset }; Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args); Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true), @@ -15348,8 +15387,7 @@ SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, // Get a pointer to FF if the sign bit was set, or to 0 otherwise. SDValue Zero = DAG.getIntPtrConstant(0, dl); SDValue Four = DAG.getIntPtrConstant(4, dl); - SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, - Zero, Four); + SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Zero, Four); FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset); // Load the value out, extending it from f32 to f80. @@ -15621,7 +15659,7 @@ static SDValue LowerZERO_EXTEND_AVX512(SDValue Op, SDValue Zero = DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT); - SDValue SelectedVal = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero); + SDValue SelectedVal = DAG.getSelect(DL, ExtVT, In, One, Zero); if (VT == ExtVT) return SelectedVal; return DAG.getNode(X86ISD::VTRUNC, DL, VT, SelectedVal); @@ -16713,7 +16751,7 @@ static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC, if (BitWidth > AndBitWidth) { KnownBits Known; DAG.computeKnownBits(Op0, Known); - if (Known.Zero.countLeadingOnes() < BitWidth - AndBitWidth) + if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth) return SDValue(); } LHS = Op1; @@ -17455,7 +17493,7 @@ SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64; VCmp = DAG.getBitcast(VCmpVT, VCmp); - SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2); + SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VSel, DAG.getIntPtrConstant(0, DL)); @@ -17483,9 +17521,8 @@ SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0)) Op2Scalar = Op2.getOperand(0); if (Op1Scalar.getNode() && Op2Scalar.getNode()) { - SDValue newSelect = DAG.getNode(ISD::SELECT, DL, - Op1Scalar.getValueType(), - Cond, Op1Scalar, Op2Scalar); + SDValue newSelect = DAG.getSelect(DL, Op1Scalar.getValueType(), Cond, + Op1Scalar, Op2Scalar); if (newSelect.getValueSizeInBits() == VT.getSizeInBits()) return DAG.getBitcast(VT, newSelect); SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect); @@ -17500,8 +17537,7 @@ SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { DAG.getUNDEF(MVT::v8i1), Op1, zeroConst); Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1, DAG.getUNDEF(MVT::v8i1), Op2, zeroConst); - SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1, - Cond, Op1, Op2); + SDValue newSelect = DAG.getSelect(DL, MVT::v8i1, Cond, Op1, Op2); return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst); } @@ -17770,7 +17806,7 @@ static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, } else { SDValue NegOne = getOnesVector(ExtVT, DAG, dl); SDValue Zero = getZeroVector(ExtVT, Subtarget, DAG, dl); - V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero); + V = DAG.getSelect(dl, ExtVT, In, NegOne, Zero); if (ExtVT == VT) return V; } @@ -18572,7 +18608,7 @@ X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, // Chain the dynamic stack allocation so that it doesn't modify the stack // pointer when other instructions are using the stack. - Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); bool Is64Bit = Subtarget.is64Bit(); MVT SPTy = getPointerTy(DAG.getDataLayout()); @@ -19021,8 +19057,10 @@ static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask, SDValue PreservedSrc, const X86Subtarget &Subtarget, SelectionDAG &DAG) { - if (isAllOnesConstant(Mask)) - return Op; + + if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask)) + if (MaskConst->getZExtValue() & 0x1) + return Op; MVT VT = Op.getSimpleValueType(); SDLoc dl(Op); @@ -19081,7 +19119,7 @@ static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn, // registration, or the .set_setframe offset. MCSymbol *OffsetSym = MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol( - GlobalValue::getRealLinkageName(Fn->getName())); + GlobalValue::dropLLVMManglingEscape(Fn->getName())); SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT); SDValue ParentFrameOffset = DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal); @@ -19683,12 +19721,6 @@ static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget &Subtarget DAG.getIntPtrConstant(0, dl)); return DAG.getBitcast(Op.getValueType(), Res); } - case CONVERT_MASK_TO_VEC: { - SDValue Mask = Op.getOperand(1); - MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements()); - SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl); - return DAG.getNode(IntrData->Opc0, dl, VT, VMask); - } case BRCST_SUBVEC_TO_VEC: { SDValue Src = Op.getOperand(1); SDValue Passthru = Op.getOperand(2); @@ -19932,7 +19964,7 @@ static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget &Subtarget SDValue Op1 = Op.getOperand(1); auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal()); MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol( - GlobalValue::getRealLinkageName(Fn->getName())); + GlobalValue::dropLLVMManglingEscape(Fn->getName())); // Generate a simple absolute symbol reference. This intrinsic is only // supported on 32-bit Windows, which isn't PIC. @@ -21741,6 +21773,14 @@ static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG, MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2); SDValue Ex = DAG.getBitcast(ExVT, R); + // ashr(R, 63) === cmp_slt(R, 0) + if (ShiftAmt == 63 && Subtarget.hasSSE42()) { + assert((VT != MVT::v4i64 || Subtarget.hasInt256()) && + "Unsupported PCMPGT op"); + return DAG.getNode(X86ISD::PCMPGT, dl, VT, + getZeroVector(VT, Subtarget, DAG, dl), R); + } + if (ShiftAmt >= 32) { // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32. SDValue Upper = @@ -21839,10 +21879,19 @@ static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG, } // Special case in 32-bit mode, where i64 is expanded into high and low parts. + // TODO: Replace constant extraction with getTargetConstantBitsFromNode. if (!Subtarget.is64Bit() && !Subtarget.hasXOP() && (VT == MVT::v2i64 || (Subtarget.hasInt256() && VT == MVT::v4i64) || (Subtarget.hasAVX512() && VT == MVT::v8i64))) { + // AVX1 targets maybe extracting a 128-bit vector from a 256-bit constant. + unsigned SubVectorScale = 1; + if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR) { + SubVectorScale = + Amt.getOperand(0).getValueSizeInBits() / Amt.getValueSizeInBits(); + Amt = Amt.getOperand(0); + } + // Peek through any splat that was introduced for i64 shift vectorization. int SplatIndex = -1; if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode())) @@ -21859,7 +21908,7 @@ static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG, Amt = Amt.getOperand(0); unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() / - VT.getVectorNumElements(); + (SubVectorScale * VT.getVectorNumElements()); unsigned RatioInLog2 = Log2_32_Ceil(Ratio); uint64_t ShiftAmt = 0; unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio); @@ -22233,23 +22282,21 @@ static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget, V1 = DAG.getBitcast(VT, V1); Sel = DAG.getBitcast(VT, Sel); Sel = DAG.getNode(X86ISD::CVT2MASK, dl, MaskVT, Sel); - return DAG.getBitcast(SelVT, - DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1)); + return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1)); } else if (Subtarget.hasSSE41()) { // On SSE41 targets we make use of the fact that VSELECT lowers // to PBLENDVB which selects bytes based just on the sign bit. V0 = DAG.getBitcast(VT, V0); V1 = DAG.getBitcast(VT, V1); Sel = DAG.getBitcast(VT, Sel); - return DAG.getBitcast(SelVT, - DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1)); + return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1)); } // On pre-SSE41 targets we test for the sign bit by comparing to // zero - a negative value will set all bits of the lanes to true // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering. SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl); SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel); - return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1); + return DAG.getSelect(dl, SelVT, C, V0, V1); }; // Turn 'a' into a mask suitable for VSELECT: a = a << 5; @@ -22371,15 +22418,14 @@ static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget, V0 = DAG.getBitcast(ExtVT, V0); V1 = DAG.getBitcast(ExtVT, V1); Sel = DAG.getBitcast(ExtVT, Sel); - return DAG.getBitcast( - VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1)); + return DAG.getBitcast(VT, DAG.getSelect(dl, ExtVT, Sel, V0, V1)); } // On pre-SSE41 targets we splat the sign bit - a negative value will // set all bits of the lanes to true and VSELECT uses that in // its OR(AND(V0,C),AND(V1,~C)) lowering. SDValue C = DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT)); - return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1); + return DAG.getSelect(dl, VT, C, V0, V1); }; // Turn 'a' into a mask suitable for VSELECT: a = a << 12; @@ -23296,9 +23342,8 @@ static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget, SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout())); - Type *RetTy = isF64 - ? (Type*)StructType::get(ArgTy, ArgTy, nullptr) - : (Type*)VectorType::get(ArgTy, 4); + Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy) + : (Type *)VectorType::get(ArgTy, 4); TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(dl) @@ -25779,7 +25824,7 @@ X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI, // Emit CALLSEQ_START right before the instruction. unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); MachineInstrBuilder CallseqStart = - BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0); + BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0); BB->insert(MachineBasicBlock::iterator(MI), CallseqStart); // Emit CALLSEQ_END right after the instruction. @@ -26517,7 +26562,7 @@ X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, case TargetOpcode::STACKMAP: case TargetOpcode::PATCHPOINT: return emitPatchPoint(MI, BB); - + case TargetOpcode::PATCHABLE_EVENT_CALL: // Do nothing here, handle in xray instrumentation pass. return BB; @@ -29532,7 +29577,7 @@ combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG, SDValue CondNew = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, DAG.getAllOnesConstant(DL, CondVT)); // Vselect cond, op1, op2 = Vselect not(cond), op2, op1 - return DAG.getNode(ISD::VSELECT, DL, VT, CondNew, RHS, LHS); + return DAG.getSelect(DL, VT, CondNew, RHS, LHS); } // To use the condition operand as a bitwise mask, it must have elements that @@ -30015,7 +30060,7 @@ static SDValue combineSelect(SDNode *N, SelectionDAG &DAG, ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE; Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), Cond.getOperand(0), Cond.getOperand(1), NewCC); - return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS); + return DAG.getSelect(DL, VT, Cond, LHS, RHS); } } } @@ -31561,20 +31606,22 @@ static SDValue combineAnd(SDNode *N, SelectionDAG &DAG, // (sub (xor X, M), M) static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, const X86Subtarget &Subtarget) { - assert(N->getOpcode() == ISD::OR); + assert(N->getOpcode() == ISD::OR && "Unexpected Opcode"); SDValue N0 = N->getOperand(0); SDValue N1 = N->getOperand(1); EVT VT = N->getValueType(0); - if (!((VT == MVT::v2i64) || (VT == MVT::v4i64 && Subtarget.hasInt256()))) + if (!((VT.is128BitVector() && Subtarget.hasSSE2()) || + (VT.is256BitVector() && Subtarget.hasInt256()))) return SDValue(); - assert(Subtarget.hasSSE2() && "Unexpected i64 vector without SSE2!"); - // Canonicalize pandn to RHS - if (N0.getOpcode() == X86ISD::ANDNP) + // Canonicalize AND to LHS. + if (N1.getOpcode() == ISD::AND) std::swap(N0, N1); + // TODO: Attempt to match against AND(XOR(-1,X),Y) as well, waiting for + // ANDNP combine allows other combines to happen that prevent matching. if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP) return SDValue(); @@ -31596,20 +31643,10 @@ static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, Y = peekThroughBitcasts(Y); EVT MaskVT = Mask.getValueType(); - - // Validate that the Mask operand is a vector sra node. - // FIXME: what to do for bytes, since there is a psignb/pblendvb, but - // there is no psrai.b unsigned EltBits = MaskVT.getScalarSizeInBits(); - unsigned SraAmt = ~0; - if (Mask.getOpcode() == ISD::SRA) { - if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1))) - if (auto *AmtConst = AmtBV->getConstantSplatNode()) - SraAmt = AmtConst->getZExtValue(); - } else if (Mask.getOpcode() == X86ISD::VSRAI) - SraAmt = Mask.getConstantOperandVal(1); - if ((SraAmt + 1) != EltBits) + // TODO: Attempt to handle floating point cases as well? + if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits) return SDValue(); SDLoc DL(N); @@ -31630,7 +31667,8 @@ static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, // (add (xor X, M), (and M, 1)) // And further to: // (sub (xor X, M), M) - if (X.getValueType() == MaskVT && Y.getValueType() == MaskVT) { + if (X.getValueType() == MaskVT && Y.getValueType() == MaskVT && + DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT)) { auto IsNegV = [](SDNode *N, SDValue V) { return N->getOpcode() == ISD::SUB && N->getOperand(1) == V && ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()); @@ -31642,9 +31680,6 @@ static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, V = Y; if (V) { - if (EltBits != 8 && EltBits != 16 && EltBits != 32) - return SDValue(); - SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask); SDValue SubOp2 = Mask; @@ -31661,8 +31696,8 @@ static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, if (V == Y) std::swap(SubOp1, SubOp2); - return DAG.getBitcast(VT, - DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2)); + SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2); + return DAG.getBitcast(VT, Res); } } @@ -31675,7 +31710,7 @@ static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG, X = DAG.getBitcast(BlendVT, X); Y = DAG.getBitcast(BlendVT, Y); Mask = DAG.getBitcast(BlendVT, Mask); - Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); + Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X); return DAG.getBitcast(VT, Mask); } @@ -33655,8 +33690,7 @@ static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG, // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands // are NaN, the NaN value of Op1 is the result. - auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; - return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax); + return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax); } /// Do target-specific dag combines on X86ISD::ANDNP nodes. @@ -33949,7 +33983,7 @@ static SDValue combineSext(SDNode *N, SelectionDAG &DAG, if (InVT == MVT::i1) { SDValue Zero = DAG.getConstant(0, DL, VT); SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); - return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero); + return DAG.getSelect(DL, VT, N0, AllOnes, Zero); } return SDValue(); } diff --git a/contrib/llvm/lib/Target/X86/X86InstrCompiler.td b/contrib/llvm/lib/Target/X86/X86InstrCompiler.td index 3dc673e3c35a..d003d027ddb9 100644 --- a/contrib/llvm/lib/Target/X86/X86InstrCompiler.td +++ b/contrib/llvm/lib/Target/X86/X86InstrCompiler.td @@ -43,7 +43,8 @@ let hasSideEffects = 0, isNotDuplicable = 1, Uses = [ESP] in // Pessimistically assume ADJCALLSTACKDOWN / ADJCALLSTACKUP will become // sub / add which can clobber EFLAGS. let Defs = [ESP, EFLAGS], Uses = [ESP] in { -def ADJCALLSTACKDOWN32 : I<0, Pseudo, (outs), (ins i32imm:$amt1, i32imm:$amt2), +def ADJCALLSTACKDOWN32 : I<0, Pseudo, (outs), + (ins i32imm:$amt1, i32imm:$amt2, i32imm:$amt3), "#ADJCALLSTACKDOWN", []>, Requires<[NotLP64]>; @@ -52,8 +53,8 @@ def ADJCALLSTACKUP32 : I<0, Pseudo, (outs), (ins i32imm:$amt1, i32imm:$amt2), [(X86callseq_end timm:$amt1, timm:$amt2)]>, Requires<[NotLP64]>; } -def : Pat<(X86callseq_start timm:$amt1), - (ADJCALLSTACKDOWN32 i32imm:$amt1, 0)>, Requires<[NotLP64]>; +def : Pat<(X86callseq_start timm:$amt1, timm:$amt2), + (ADJCALLSTACKDOWN32 i32imm:$amt1, i32imm:$amt2, 0)>, Requires<[NotLP64]>; // ADJCALLSTACKDOWN/UP implicitly use/def RSP because they may be expanded into @@ -62,7 +63,8 @@ def : Pat<(X86callseq_start timm:$amt1), // Pessimistically assume ADJCALLSTACKDOWN / ADJCALLSTACKUP will become // sub / add which can clobber EFLAGS. let Defs = [RSP, EFLAGS], Uses = [RSP] in { -def ADJCALLSTACKDOWN64 : I<0, Pseudo, (outs), (ins i32imm:$amt1, i32imm:$amt2), +def ADJCALLSTACKDOWN64 : I<0, Pseudo, (outs), + (ins i32imm:$amt1, i32imm:$amt2, i32imm:$amt3), "#ADJCALLSTACKDOWN", []>, Requires<[IsLP64]>; @@ -71,8 +73,8 @@ def ADJCALLSTACKUP64 : I<0, Pseudo, (outs), (ins i32imm:$amt1, i32imm:$amt2), [(X86callseq_end timm:$amt1, timm:$amt2)]>, Requires<[IsLP64]>; } -def : Pat<(X86callseq_start timm:$amt1), - (ADJCALLSTACKDOWN64 i32imm:$amt1, 0)>, Requires<[IsLP64]>; +def : Pat<(X86callseq_start timm:$amt1, timm:$amt2), + (ADJCALLSTACKDOWN64 i32imm:$amt1, i32imm:$amt2, 0)>, Requires<[IsLP64]>; // x86-64 va_start lowering magic. diff --git a/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp b/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp index 888daa275265..092ceb207ada 100644 --- a/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp +++ b/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp @@ -5729,6 +5729,44 @@ static X86::CondCode getSwappedCondition(X86::CondCode CC) { } } +std::pair<X86::CondCode, bool> +X86::getX86ConditionCode(CmpInst::Predicate Predicate) { + X86::CondCode CC = X86::COND_INVALID; + bool NeedSwap = false; + switch (Predicate) { + default: break; + // Floating-point Predicates + case CmpInst::FCMP_UEQ: CC = X86::COND_E; break; + case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH; + case CmpInst::FCMP_OGT: CC = X86::COND_A; break; + case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH; + case CmpInst::FCMP_OGE: CC = X86::COND_AE; break; + case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH; + case CmpInst::FCMP_ULT: CC = X86::COND_B; break; + case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH; + case CmpInst::FCMP_ULE: CC = X86::COND_BE; break; + case CmpInst::FCMP_ONE: CC = X86::COND_NE; break; + case CmpInst::FCMP_UNO: CC = X86::COND_P; break; + case CmpInst::FCMP_ORD: CC = X86::COND_NP; break; + case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH; + case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break; + + // Integer Predicates + case CmpInst::ICMP_EQ: CC = X86::COND_E; break; + case CmpInst::ICMP_NE: CC = X86::COND_NE; break; + case CmpInst::ICMP_UGT: CC = X86::COND_A; break; + case CmpInst::ICMP_UGE: CC = X86::COND_AE; break; + case CmpInst::ICMP_ULT: CC = X86::COND_B; break; + case CmpInst::ICMP_ULE: CC = X86::COND_BE; break; + case CmpInst::ICMP_SGT: CC = X86::COND_G; break; + case CmpInst::ICMP_SGE: CC = X86::COND_GE; break; + case CmpInst::ICMP_SLT: CC = X86::COND_L; break; + case CmpInst::ICMP_SLE: CC = X86::COND_LE; break; + } + + return std::make_pair(CC, NeedSwap); +} + /// Return a set opcode for the given condition and /// whether it has memory operand. unsigned X86::getSETFromCond(CondCode CC, bool HasMemoryOperand) { @@ -7589,6 +7627,13 @@ bool X86InstrInfo::expandPostRAPseudo(MachineInstr &MI) const { return Expand2AddrUndef(MIB, get(HasAVX ? X86::VPCMPEQDrr : X86::PCMPEQDrr)); case X86::AVX2_SETALLONES: return Expand2AddrUndef(MIB, get(X86::VPCMPEQDYrr)); + case X86::AVX1_SETALLONES: { + unsigned Reg = MIB->getOperand(0).getReg(); + // VCMPPSYrri with an immediate 0xf should produce VCMPTRUEPS. + MIB->setDesc(get(X86::VCMPPSYrri)); + MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xf); + return true; + } case X86::AVX512_512_SETALLONES: { unsigned Reg = MIB->getOperand(0).getReg(); MIB->setDesc(get(X86::VPTERNLOGDZrri)); @@ -8477,6 +8522,7 @@ MachineInstr *X86InstrInfo::foldMemoryOperandImpl( Alignment = 64; break; case X86::AVX2_SETALLONES: + case X86::AVX1_SETALLONES: case X86::AVX_SET0: case X86::AVX512_256_SET0: Alignment = 32; @@ -8522,6 +8568,7 @@ MachineInstr *X86InstrInfo::foldMemoryOperandImpl( case X86::V_SET0: case X86::V_SETALLONES: case X86::AVX2_SETALLONES: + case X86::AVX1_SETALLONES: case X86::AVX_SET0: case X86::AVX512_128_SET0: case X86::AVX512_256_SET0: @@ -8563,13 +8610,14 @@ MachineInstr *X86InstrInfo::foldMemoryOperandImpl( else if (Opc == X86::AVX512_512_SET0 || Opc == X86::AVX512_512_SETALLONES) Ty = VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext()),16); else if (Opc == X86::AVX2_SETALLONES || Opc == X86::AVX_SET0 || - Opc == X86::AVX512_256_SET0) + Opc == X86::AVX512_256_SET0 || Opc == X86::AVX1_SETALLONES) Ty = VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext()), 8); else Ty = VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext()), 4); bool IsAllOnes = (Opc == X86::V_SETALLONES || Opc == X86::AVX2_SETALLONES || - Opc == X86::AVX512_512_SETALLONES); + Opc == X86::AVX512_512_SETALLONES || + Opc == X86::AVX1_SETALLONES); const Constant *C = IsAllOnes ? Constant::getAllOnesValue(Ty) : Constant::getNullValue(Ty); unsigned CPI = MCP.getConstantPoolIndex(C, Alignment); diff --git a/contrib/llvm/lib/Target/X86/X86InstrInfo.h b/contrib/llvm/lib/Target/X86/X86InstrInfo.h index 38567831b3a4..e64876073ccf 100644 --- a/contrib/llvm/lib/Target/X86/X86InstrInfo.h +++ b/contrib/llvm/lib/Target/X86/X86InstrInfo.h @@ -64,6 +64,10 @@ enum CondCode { // Turn condition code into conditional branch opcode. unsigned GetCondBranchFromCond(CondCode CC); +/// \brief Return a pair of condition code for the given predicate and whether +/// the instruction operands should be swaped to match the condition code. +std::pair<CondCode, bool> getX86ConditionCode(CmpInst::Predicate Predicate); + /// \brief Return a set opcode for the given condition and whether it has /// a memory operand. unsigned getSETFromCond(CondCode CC, bool HasMemoryOperand = false); @@ -186,6 +190,8 @@ public: /// setup..destroy sequence (e.g. by pushes, or inside the callee). int64_t getFrameAdjustment(const MachineInstr &I) const { assert(isFrameInstr(I)); + if (isFrameSetup(I)) + return I.getOperand(2).getImm(); return I.getOperand(1).getImm(); } @@ -193,7 +199,10 @@ public: /// instruction. void setFrameAdjustment(MachineInstr &I, int64_t V) const { assert(isFrameInstr(I)); - I.getOperand(1).setImm(V); + if (isFrameSetup(I)) + I.getOperand(2).setImm(V); + else + I.getOperand(1).setImm(V); } /// getSPAdjust - This returns the stack pointer adjustment made by diff --git a/contrib/llvm/lib/Target/X86/X86InstrInfo.td b/contrib/llvm/lib/Target/X86/X86InstrInfo.td index 902b0c2c04e3..4d7d8ece92d9 100644 --- a/contrib/llvm/lib/Target/X86/X86InstrInfo.td +++ b/contrib/llvm/lib/Target/X86/X86InstrInfo.td @@ -84,7 +84,8 @@ def SDTLockBinaryArithWithFlags : SDTypeProfile<1, 2, [SDTCisVT<0, i32>, def SDTX86Ret : SDTypeProfile<0, -1, [SDTCisVT<0, i32>]>; -def SDT_X86CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>]>; +def SDT_X86CallSeqStart : SDCallSeqStart<[SDTCisVT<0, i32>, + SDTCisVT<1, i32>]>; def SDT_X86CallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, i32>, SDTCisVT<1, i32>]>; @@ -2351,6 +2352,38 @@ let Predicates = [HasBMI2] in { def : Pat<(and (loadi64 addr:$src), (add (shl 1, GR8:$lz), -1)), (BZHI64rm addr:$src, (INSERT_SUBREG (i64 (IMPLICIT_DEF)), GR8:$lz, sub_8bit))>; + + // x & (-1 >> (32 - y)) + def : Pat<(and GR32:$src, (srl -1, (i8 (trunc (sub 32, GR32:$lz))))), + (BZHI32rr GR32:$src, GR32:$lz)>; + def : Pat<(and (loadi32 addr:$src), (srl -1, (i8 (trunc (sub 32, GR32:$lz))))), + (BZHI32rm addr:$src, GR32:$lz)>; + + // x & (-1 >> (64 - y)) + def : Pat<(and GR64:$src, (srl -1, (i8 (trunc (sub 64, GR32:$lz))))), + (BZHI64rr GR64:$src, + (INSERT_SUBREG (i64 (IMPLICIT_DEF)), GR32:$lz, sub_32bit))>; + def : Pat<(and (loadi64 addr:$src), (srl -1, (i8 (trunc (sub 64, GR32:$lz))))), + (BZHI64rm addr:$src, + (INSERT_SUBREG (i64 (IMPLICIT_DEF)), GR32:$lz, sub_32bit))>; + + // x << (32 - y) >> (32 - y) + def : Pat<(srl (shl GR32:$src, (i8 (trunc (sub 32, GR32:$lz)))), + (i8 (trunc (sub 32, GR32:$lz)))), + (BZHI32rr GR32:$src, GR32:$lz)>; + def : Pat<(srl (shl (loadi32 addr:$src), (i8 (trunc (sub 32, GR32:$lz)))), + (i8 (trunc (sub 32, GR32:$lz)))), + (BZHI32rm addr:$src, GR32:$lz)>; + + // x << (64 - y) >> (64 - y) + def : Pat<(srl (shl GR64:$src, (i8 (trunc (sub 64, GR32:$lz)))), + (i8 (trunc (sub 64, GR32:$lz)))), + (BZHI64rr GR64:$src, + (INSERT_SUBREG (i64 (IMPLICIT_DEF)), GR32:$lz, sub_32bit))>; + def : Pat<(srl (shl (loadi64 addr:$src), (i8 (trunc (sub 64, GR32:$lz)))), + (i8 (trunc (sub 64, GR32:$lz)))), + (BZHI64rm addr:$src, + (INSERT_SUBREG (i64 (IMPLICIT_DEF)), GR32:$lz, sub_32bit))>; } // HasBMI2 let Predicates = [HasBMI] in { diff --git a/contrib/llvm/lib/Target/X86/X86InstrSSE.td b/contrib/llvm/lib/Target/X86/X86InstrSSE.td index 48da2fa607af..f73d85e7e01b 100644 --- a/contrib/llvm/lib/Target/X86/X86InstrSSE.td +++ b/contrib/llvm/lib/Target/X86/X86InstrSSE.td @@ -486,6 +486,10 @@ let isReMaterializable = 1, isAsCheapAsAMove = 1, canFoldAsLoad = 1, isPseudo = 1, SchedRW = [WriteZero] in { def V_SETALLONES : I<0, Pseudo, (outs VR128:$dst), (ins), "", [(set VR128:$dst, (v4i32 immAllOnesV))]>; + let Predicates = [HasAVX1Only, OptForMinSize] in { + def AVX1_SETALLONES: I<0, Pseudo, (outs VR256:$dst), (ins), "", + [(set VR256:$dst, (v8i32 immAllOnesV))]>; + } let Predicates = [HasAVX2] in def AVX2_SETALLONES : I<0, Pseudo, (outs VR256:$dst), (ins), "", [(set VR256:$dst, (v8i32 immAllOnesV))]>; @@ -7755,14 +7759,12 @@ def VINSERTF128rm : AVXAIi8<0x18, MRMSrcMem, (outs VR256:$dst), []>, Sched<[WriteFShuffleLd, ReadAfterLd]>, VEX_4V, VEX_L; } - -// Without AVX2 we need to concat two v4i32 V_SETALLONES to create a 256-bit -// all ones value. -let Predicates = [HasAVX1Only] in -def : Pat<(v8i32 immAllOnesV), - (VINSERTF128rr - (INSERT_SUBREG (v8i32 (IMPLICIT_DEF)), (V_SETALLONES), sub_xmm), - (V_SETALLONES), 1)>; +// To create a 256-bit all ones value, we should produce VCMPTRUEPS +// with YMM register containing zero. +// FIXME: Avoid producing vxorps to clear the fake inputs. +let Predicates = [HasAVX1Only] in { +def : Pat<(v8i32 immAllOnesV), (VCMPPSYrri (AVX_SET0), (AVX_SET0), 0xf)>; +} multiclass vinsert_lowering<string InstrStr, ValueType From, ValueType To, PatFrag memop_frag> { diff --git a/contrib/llvm/lib/Target/X86/X86InstructionSelector.cpp b/contrib/llvm/lib/Target/X86/X86InstructionSelector.cpp index d65eb1de8d09..de58d719acb4 100644 --- a/contrib/llvm/lib/Target/X86/X86InstructionSelector.cpp +++ b/contrib/llvm/lib/Target/X86/X86InstructionSelector.cpp @@ -56,13 +56,9 @@ private: bool selectImpl(MachineInstr &I) const; // TODO: remove after suported by Tablegen-erated instruction selection. - unsigned getFAddOp(LLT &Ty, const RegisterBank &RB) const; - unsigned getFSubOp(LLT &Ty, const RegisterBank &RB) const; unsigned getLoadStoreOp(LLT &Ty, const RegisterBank &RB, unsigned Opc, uint64_t Alignment) const; - bool selectBinaryOp(MachineInstr &I, MachineRegisterInfo &MRI, - MachineFunction &MF) const; bool selectLoadStoreOp(MachineInstr &I, MachineRegisterInfo &MRI, MachineFunction &MF) const; bool selectFrameIndexOrGep(MachineInstr &I, MachineRegisterInfo &MRI, @@ -71,6 +67,10 @@ private: MachineFunction &MF) const; bool selectTrunc(MachineInstr &I, MachineRegisterInfo &MRI, MachineFunction &MF) const; + bool selectZext(MachineInstr &I, MachineRegisterInfo &MRI, + MachineFunction &MF) const; + bool selectCmp(MachineInstr &I, MachineRegisterInfo &MRI, + MachineFunction &MF) const; const X86TargetMachine &TM; const X86Subtarget &STI; @@ -226,13 +226,11 @@ bool X86InstructionSelector::select(MachineInstr &I) const { "Generic instruction has unexpected implicit operands\n"); if (selectImpl(I)) - return true; + return true; DEBUG(dbgs() << " C++ instruction selection: "; I.print(dbgs())); // TODO: This should be implemented by tblgen. - if (selectBinaryOp(I, MRI, MF)) - return true; if (selectLoadStoreOp(I, MRI, MF)) return true; if (selectFrameIndexOrGep(I, MRI, MF)) @@ -241,109 +239,14 @@ bool X86InstructionSelector::select(MachineInstr &I) const { return true; if (selectTrunc(I, MRI, MF)) return true; + if (selectZext(I, MRI, MF)) + return true; + if (selectCmp(I, MRI, MF)) + return true; return false; } -unsigned X86InstructionSelector::getFAddOp(LLT &Ty, - const RegisterBank &RB) const { - - if (X86::VECRRegBankID != RB.getID()) - return TargetOpcode::G_FADD; - - if (Ty == LLT::scalar(32)) { - if (STI.hasAVX512()) { - return X86::VADDSSZrr; - } else if (STI.hasAVX()) { - return X86::VADDSSrr; - } else if (STI.hasSSE1()) { - return X86::ADDSSrr; - } - } else if (Ty == LLT::scalar(64)) { - if (STI.hasAVX512()) { - return X86::VADDSDZrr; - } else if (STI.hasAVX()) { - return X86::VADDSDrr; - } else if (STI.hasSSE2()) { - return X86::ADDSDrr; - } - } else if (Ty == LLT::vector(4, 32)) { - if ((STI.hasAVX512()) && (STI.hasVLX())) { - return X86::VADDPSZ128rr; - } else if (STI.hasAVX()) { - return X86::VADDPSrr; - } else if (STI.hasSSE1()) { - return X86::ADDPSrr; - } - } - - return TargetOpcode::G_FADD; -} - -unsigned X86InstructionSelector::getFSubOp(LLT &Ty, - const RegisterBank &RB) const { - - if (X86::VECRRegBankID != RB.getID()) - return TargetOpcode::G_FSUB; - - if (Ty == LLT::scalar(32)) { - if (STI.hasAVX512()) { - return X86::VSUBSSZrr; - } else if (STI.hasAVX()) { - return X86::VSUBSSrr; - } else if (STI.hasSSE1()) { - return X86::SUBSSrr; - } - } else if (Ty == LLT::scalar(64)) { - if (STI.hasAVX512()) { - return X86::VSUBSDZrr; - } else if (STI.hasAVX()) { - return X86::VSUBSDrr; - } else if (STI.hasSSE2()) { - return X86::SUBSDrr; - } - } else if (Ty == LLT::vector(4, 32)) { - if ((STI.hasAVX512()) && (STI.hasVLX())) { - return X86::VSUBPSZ128rr; - } else if (STI.hasAVX()) { - return X86::VSUBPSrr; - } else if (STI.hasSSE1()) { - return X86::SUBPSrr; - } - } - - return TargetOpcode::G_FSUB; -} - -bool X86InstructionSelector::selectBinaryOp(MachineInstr &I, - MachineRegisterInfo &MRI, - MachineFunction &MF) const { - - const unsigned DefReg = I.getOperand(0).getReg(); - LLT Ty = MRI.getType(DefReg); - const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI); - - unsigned NewOpc = I.getOpcode(); - - switch (NewOpc) { - case TargetOpcode::G_FADD: - NewOpc = getFAddOp(Ty, RB); - break; - case TargetOpcode::G_FSUB: - NewOpc = getFSubOp(Ty, RB); - break; - default: - break; - } - - if (NewOpc == I.getOpcode()) - return false; - - I.setDesc(TII.get(NewOpc)); - - return constrainSelectedInstRegOperands(I, TII, TRI, RBI); -} - unsigned X86InstructionSelector::getLoadStoreOp(LLT &Ty, const RegisterBank &RB, unsigned Opc, uint64_t Alignment) const { @@ -562,6 +465,105 @@ bool X86InstructionSelector::selectTrunc(MachineInstr &I, return true; } +bool X86InstructionSelector::selectZext(MachineInstr &I, + MachineRegisterInfo &MRI, + MachineFunction &MF) const { + if (I.getOpcode() != TargetOpcode::G_ZEXT) + return false; + + const unsigned DstReg = I.getOperand(0).getReg(); + const unsigned SrcReg = I.getOperand(1).getReg(); + + const LLT DstTy = MRI.getType(DstReg); + const LLT SrcTy = MRI.getType(SrcReg); + + if (SrcTy == LLT::scalar(1)) { + + unsigned AndOpc; + if (DstTy == LLT::scalar(32)) + AndOpc = X86::AND32ri8; + else if (DstTy == LLT::scalar(64)) + AndOpc = X86::AND64ri8; + else + return false; + + const RegisterBank &RegBank = *RBI.getRegBank(DstReg, MRI, TRI); + unsigned DefReg = + MRI.createVirtualRegister(getRegClassForTypeOnBank(DstTy, RegBank)); + + BuildMI(*I.getParent(), I, I.getDebugLoc(), + TII.get(TargetOpcode::SUBREG_TO_REG), DefReg) + .addImm(0) + .addReg(SrcReg) + .addImm(X86::sub_8bit); + + MachineInstr &AndInst = + *BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AndOpc), DstReg) + .addReg(DefReg) + .addImm(1); + + constrainSelectedInstRegOperands(AndInst, TII, TRI, RBI); + + I.eraseFromParent(); + return true; + } + + return false; +} + +bool X86InstructionSelector::selectCmp(MachineInstr &I, + MachineRegisterInfo &MRI, + MachineFunction &MF) const { + if (I.getOpcode() != TargetOpcode::G_ICMP) + return false; + + X86::CondCode CC; + bool SwapArgs; + std::tie(CC, SwapArgs) = X86::getX86ConditionCode( + (CmpInst::Predicate)I.getOperand(1).getPredicate()); + unsigned OpSet = X86::getSETFromCond(CC); + + unsigned LHS = I.getOperand(2).getReg(); + unsigned RHS = I.getOperand(3).getReg(); + + if (SwapArgs) + std::swap(LHS, RHS); + + unsigned OpCmp; + LLT Ty = MRI.getType(LHS); + + switch (Ty.getSizeInBits()) { + default: + return false; + case 8: + OpCmp = X86::CMP8rr; + break; + case 16: + OpCmp = X86::CMP16rr; + break; + case 32: + OpCmp = X86::CMP32rr; + break; + case 64: + OpCmp = X86::CMP64rr; + break; + } + + MachineInstr &CmpInst = + *BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(OpCmp)) + .addReg(LHS) + .addReg(RHS); + + MachineInstr &SetInst = *BuildMI(*I.getParent(), I, I.getDebugLoc(), + TII.get(OpSet), I.getOperand(0).getReg()); + + constrainSelectedInstRegOperands(CmpInst, TII, TRI, RBI); + constrainSelectedInstRegOperands(SetInst, TII, TRI, RBI); + + I.eraseFromParent(); + return true; +} + InstructionSelector * llvm::createX86InstructionSelector(const X86TargetMachine &TM, X86Subtarget &Subtarget, diff --git a/contrib/llvm/lib/Target/X86/X86IntrinsicsInfo.h b/contrib/llvm/lib/Target/X86/X86IntrinsicsInfo.h index 2a40399ba571..bc73bb1ae8c5 100644 --- a/contrib/llvm/lib/Target/X86/X86IntrinsicsInfo.h +++ b/contrib/llvm/lib/Target/X86/X86IntrinsicsInfo.h @@ -36,7 +36,7 @@ enum IntrinsicType : uint16_t { TRUNCATE_TO_MEM_VI8, TRUNCATE_TO_MEM_VI16, TRUNCATE_TO_MEM_VI32, EXPAND_FROM_MEM, TERLOG_OP_MASK, TERLOG_OP_MASKZ, BROADCASTM, KUNPCK, FIXUPIMM, FIXUPIMM_MASKZ, FIXUPIMMS, - FIXUPIMMS_MASKZ, CONVERT_MASK_TO_VEC, CONVERT_TO_MASK, GATHER_AVX2, MASK_BINOP, + FIXUPIMMS_MASKZ, CONVERT_TO_MASK, GATHER_AVX2, MASK_BINOP, }; struct IntrinsicData { diff --git a/contrib/llvm/lib/Target/X86/X86LegalizerInfo.cpp b/contrib/llvm/lib/Target/X86/X86LegalizerInfo.cpp index 4f5e70414aa9..cf26238c0239 100644 --- a/contrib/llvm/lib/Target/X86/X86LegalizerInfo.cpp +++ b/contrib/llvm/lib/Target/X86/X86LegalizerInfo.cpp @@ -87,10 +87,16 @@ void X86LegalizerInfo::setLegalizerInfo32bit() { setAction({G_ZEXT, s32}, Legal); setAction({G_SEXT, s32}, Legal); - for (auto Ty : {s8, s16}) { + for (auto Ty : {s1, s8, s16}) { setAction({G_ZEXT, 1, Ty}, Legal); setAction({G_SEXT, 1, Ty}, Legal); } + + // Comparison + setAction({G_ICMP, s1}, Legal); + + for (auto Ty : {s8, s16, s32, p0}) + setAction({G_ICMP, 1, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfo64bit() { @@ -139,10 +145,16 @@ void X86LegalizerInfo::setLegalizerInfo64bit() { setAction({G_SEXT, Ty}, Legal); } - for (auto Ty : {s8, s16, s32}) { + for (auto Ty : {s1, s8, s16, s32}) { setAction({G_ZEXT, 1, Ty}, Legal); setAction({G_SEXT, 1, Ty}, Legal); } + + // Comparison + setAction({G_ICMP, s1}, Legal); + + for (auto Ty : {s8, s16, s32, s64, p0}) + setAction({G_ICMP, 1, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE1() { diff --git a/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp b/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp index cf2ceef8013a..7e4cba1c8345 100644 --- a/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp +++ b/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp @@ -320,14 +320,14 @@ X86RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { case CallingConv::X86_RegCall: if (Is64Bit) { if (IsWin64) { - return (HasSSE ? CSR_Win64_RegCall_SaveList : + return (HasSSE ? CSR_Win64_RegCall_SaveList : CSR_Win64_RegCall_NoSSE_SaveList); } else { - return (HasSSE ? CSR_SysV64_RegCall_SaveList : + return (HasSSE ? CSR_SysV64_RegCall_SaveList : CSR_SysV64_RegCall_NoSSE_SaveList); } } else { - return (HasSSE ? CSR_32_RegCall_SaveList : + return (HasSSE ? CSR_32_RegCall_SaveList : CSR_32_RegCall_NoSSE_SaveList); } case CallingConv::Cold: @@ -435,15 +435,15 @@ X86RegisterInfo::getCallPreservedMask(const MachineFunction &MF, return CSR_64_HHVM_RegMask; case CallingConv::X86_RegCall: if (Is64Bit) { - if (IsWin64) { - return (HasSSE ? CSR_Win64_RegCall_RegMask : + if (IsWin64) { + return (HasSSE ? CSR_Win64_RegCall_RegMask : CSR_Win64_RegCall_NoSSE_RegMask); } else { - return (HasSSE ? CSR_SysV64_RegCall_RegMask : + return (HasSSE ? CSR_SysV64_RegCall_RegMask : CSR_SysV64_RegCall_NoSSE_RegMask); } } else { - return (HasSSE ? CSR_32_RegCall_RegMask : + return (HasSSE ? CSR_32_RegCall_RegMask : CSR_32_RegCall_NoSSE_RegMask); } case CallingConv::Cold: diff --git a/contrib/llvm/lib/Target/X86/X86Subtarget.h b/contrib/llvm/lib/Target/X86/X86Subtarget.h index de1514243aeb..02be95e2e556 100644 --- a/contrib/llvm/lib/Target/X86/X86Subtarget.h +++ b/contrib/llvm/lib/Target/X86/X86Subtarget.h @@ -253,6 +253,11 @@ protected: /// True if the LEA instruction with certain arguments is slow bool SlowLEA; + /// True if the LEA instruction has all three source operands: base, index, + /// and offset or if the LEA instruction uses base and index registers where + /// the base is EBP, RBP,or R13 + bool Slow3OpsLEA; + /// True if INC and DEC instructions are slow when writing to flags bool SlowIncDec; @@ -490,6 +495,7 @@ public: bool callRegIndirect() const { return CallRegIndirect; } bool LEAusesAG() const { return LEAUsesAG; } bool slowLEA() const { return SlowLEA; } + bool slow3OpsLEA() const { return Slow3OpsLEA; } bool slowIncDec() const { return SlowIncDec; } bool hasCDI() const { return HasCDI; } bool hasPFI() const { return HasPFI; } diff --git a/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp b/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp index 086f55dd60b5..c6a90725d89c 100644 --- a/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp +++ b/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp @@ -61,6 +61,7 @@ static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner", namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); +void initializeFixupLEAPassPass(PassRegistry &); void initializeX86ExecutionDepsFixPass(PassRegistry &); } // end namespace llvm @@ -75,6 +76,7 @@ extern "C" void LLVMInitializeX86Target() { initializeWinEHStatePassPass(PR); initializeFixupBWInstPassPass(PR); initializeEvexToVexInstPassPass(PR); + initializeFixupLEAPassPass(PR); initializeX86ExecutionDepsFixPass(PR); } @@ -87,7 +89,7 @@ static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { if (TT.isOSFreeBSD()) return llvm::make_unique<X86FreeBSDTargetObjectFile>(); - if (TT.isOSLinux() || TT.isOSNaCl()) + if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU()) return llvm::make_unique<X86LinuxNaClTargetObjectFile>(); if (TT.isOSFuchsia()) return llvm::make_unique<X86FuchsiaTargetObjectFile>(); diff --git a/contrib/llvm/lib/Target/X86/X86TargetTransformInfo.cpp b/contrib/llvm/lib/Target/X86/X86TargetTransformInfo.cpp index f3b619a2956a..80e18161a94b 100644 --- a/contrib/llvm/lib/Target/X86/X86TargetTransformInfo.cpp +++ b/contrib/llvm/lib/Target/X86/X86TargetTransformInfo.cpp @@ -247,35 +247,38 @@ int X86TTIImpl::getArithmeticInstrCost( } static const CostTblEntry SSE2UniformConstCostTable[] = { - { ISD::SHL, MVT::v16i8, 2 }, // psllw + pand. - { ISD::SRL, MVT::v16i8, 2 }, // psrlw + pand. - { ISD::SRA, MVT::v16i8, 4 }, // psrlw, pand, pxor, psubb. - - { ISD::SHL, MVT::v32i8, 4 }, // 2*(psllw + pand). - { ISD::SRL, MVT::v32i8, 4 }, // 2*(psrlw + pand). - { ISD::SRA, MVT::v32i8, 8 }, // 2*(psrlw, pand, pxor, psubb). - - { ISD::SDIV, MVT::v16i16, 12 }, // pmulhw sequence - { ISD::SDIV, MVT::v8i16, 6 }, // pmulhw sequence - { ISD::UDIV, MVT::v16i16, 12 }, // pmulhuw sequence - { ISD::UDIV, MVT::v8i16, 6 }, // pmulhuw sequence - { ISD::SDIV, MVT::v8i32, 38 }, // pmuludq sequence - { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence - { ISD::UDIV, MVT::v8i32, 30 }, // pmuludq sequence - { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence + { ISD::SHL, MVT::v16i8, 2 }, // psllw + pand. + { ISD::SRL, MVT::v16i8, 2 }, // psrlw + pand. + { ISD::SRA, MVT::v16i8, 4 }, // psrlw, pand, pxor, psubb. + + { ISD::SHL, MVT::v32i8, 4+2 }, // 2*(psllw + pand) + split. + { ISD::SRL, MVT::v32i8, 4+2 }, // 2*(psrlw + pand) + split. + { ISD::SRA, MVT::v32i8, 8+2 }, // 2*(psrlw, pand, pxor, psubb) + split. + + { ISD::SDIV, MVT::v16i16, 12+2 }, // 2*pmulhw sequence + split. + { ISD::SDIV, MVT::v8i16, 6 }, // pmulhw sequence + { ISD::UDIV, MVT::v16i16, 12+2 }, // 2*pmulhuw sequence + split. + { ISD::UDIV, MVT::v8i16, 6 }, // pmulhuw sequence + { ISD::SDIV, MVT::v8i32, 38+2 }, // 2*pmuludq sequence + split. + { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence + { ISD::UDIV, MVT::v8i32, 30+2 }, // 2*pmuludq sequence + split. + { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence }; if (Op2Info == TargetTransformInfo::OK_UniformConstantValue && ST->hasSSE2()) { // pmuldq sequence. if (ISD == ISD::SDIV && LT.second == MVT::v8i32 && ST->hasAVX()) - return LT.first * 30; + return LT.first * 32; if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41()) return LT.first * 15; - if (const auto *Entry = CostTableLookup(SSE2UniformConstCostTable, ISD, - LT.second)) - return LT.first * Entry->Cost; + // XOP has faster vXi8 shifts. + if ((ISD != ISD::SHL && ISD != ISD::SRL && ISD != ISD::SRA) || + !ST->hasXOP()) + if (const auto *Entry = + CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second)) + return LT.first * Entry->Cost; } static const CostTblEntry AVX2UniformCostTable[] = { @@ -430,18 +433,18 @@ int X86TTIImpl::getArithmeticInstrCost( { ISD::SRL, MVT::v2i64, 2 }, { ISD::SRA, MVT::v2i64, 2 }, // 256bit shifts require splitting if AVX2 didn't catch them above. - { ISD::SHL, MVT::v32i8, 2 }, - { ISD::SRL, MVT::v32i8, 4 }, - { ISD::SRA, MVT::v32i8, 4 }, - { ISD::SHL, MVT::v16i16, 2 }, - { ISD::SRL, MVT::v16i16, 4 }, - { ISD::SRA, MVT::v16i16, 4 }, - { ISD::SHL, MVT::v8i32, 2 }, - { ISD::SRL, MVT::v8i32, 4 }, - { ISD::SRA, MVT::v8i32, 4 }, - { ISD::SHL, MVT::v4i64, 2 }, - { ISD::SRL, MVT::v4i64, 4 }, - { ISD::SRA, MVT::v4i64, 4 }, + { ISD::SHL, MVT::v32i8, 2+2 }, + { ISD::SRL, MVT::v32i8, 4+2 }, + { ISD::SRA, MVT::v32i8, 4+2 }, + { ISD::SHL, MVT::v16i16, 2+2 }, + { ISD::SRL, MVT::v16i16, 4+2 }, + { ISD::SRA, MVT::v16i16, 4+2 }, + { ISD::SHL, MVT::v8i32, 2+2 }, + { ISD::SRL, MVT::v8i32, 4+2 }, + { ISD::SRA, MVT::v8i32, 4+2 }, + { ISD::SHL, MVT::v4i64, 2+2 }, + { ISD::SRL, MVT::v4i64, 4+2 }, + { ISD::SRA, MVT::v4i64, 4+2 }, }; // Look for XOP lowering tricks. @@ -451,23 +454,28 @@ int X86TTIImpl::getArithmeticInstrCost( static const CostTblEntry SSE2UniformShiftCostTable[] = { // Uniform splats are cheaper for the following instructions. - { ISD::SHL, MVT::v16i16, 2 }, // psllw. - { ISD::SHL, MVT::v8i32, 2 }, // pslld - { ISD::SHL, MVT::v4i64, 2 }, // psllq. - - { ISD::SRL, MVT::v16i16, 2 }, // psrlw. - { ISD::SRL, MVT::v8i32, 2 }, // psrld. - { ISD::SRL, MVT::v4i64, 2 }, // psrlq. - - { ISD::SRA, MVT::v16i16, 2 }, // psraw. - { ISD::SRA, MVT::v8i32, 2 }, // psrad. - { ISD::SRA, MVT::v2i64, 4 }, // 2 x psrad + shuffle. - { ISD::SRA, MVT::v4i64, 8 }, // 2 x psrad + shuffle. + { ISD::SHL, MVT::v16i16, 2+2 }, // 2*psllw + split. + { ISD::SHL, MVT::v8i32, 2+2 }, // 2*pslld + split. + { ISD::SHL, MVT::v4i64, 2+2 }, // 2*psllq + split. + + { ISD::SRL, MVT::v16i16, 2+2 }, // 2*psrlw + split. + { ISD::SRL, MVT::v8i32, 2+2 }, // 2*psrld + split. + { ISD::SRL, MVT::v4i64, 2+2 }, // 2*psrlq + split. + + { ISD::SRA, MVT::v16i16, 2+2 }, // 2*psraw + split. + { ISD::SRA, MVT::v8i32, 2+2 }, // 2*psrad + split. + { ISD::SRA, MVT::v2i64, 4 }, // 2*psrad + shuffle. + { ISD::SRA, MVT::v4i64, 8+2 }, // 2*(2*psrad + shuffle) + split. }; if (ST->hasSSE2() && ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) || (Op2Info == TargetTransformInfo::OK_UniformValue))) { + + // Handle AVX2 uniform v4i64 ISD::SRA, it's not worth a table. + if (ISD == ISD::SRA && LT.second == MVT::v4i64 && ST->hasAVX2()) + return LT.first * 4; // 2*psrad + shuffle. + if (const auto *Entry = CostTableLookup(SSE2UniformShiftCostTable, ISD, LT.second)) return LT.first * Entry->Cost; @@ -581,28 +589,28 @@ int X86TTIImpl::getArithmeticInstrCost( return LT.first * Entry->Cost; static const CostTblEntry SSE41CostTable[] = { - { ISD::SHL, MVT::v16i8, 11 }, // pblendvb sequence. - { ISD::SHL, MVT::v32i8, 2*11 }, // pblendvb sequence. - { ISD::SHL, MVT::v8i16, 14 }, // pblendvb sequence. - { ISD::SHL, MVT::v16i16, 2*14 }, // pblendvb sequence. - { ISD::SHL, MVT::v4i32, 4 }, // pslld/paddd/cvttps2dq/pmulld - { ISD::SHL, MVT::v8i32, 2*4 }, // pslld/paddd/cvttps2dq/pmulld - - { ISD::SRL, MVT::v16i8, 12 }, // pblendvb sequence. - { ISD::SRL, MVT::v32i8, 2*12 }, // pblendvb sequence. - { ISD::SRL, MVT::v8i16, 14 }, // pblendvb sequence. - { ISD::SRL, MVT::v16i16, 2*14 }, // pblendvb sequence. - { ISD::SRL, MVT::v4i32, 11 }, // Shift each lane + blend. - { ISD::SRL, MVT::v8i32, 2*11 }, // Shift each lane + blend. - - { ISD::SRA, MVT::v16i8, 24 }, // pblendvb sequence. - { ISD::SRA, MVT::v32i8, 2*24 }, // pblendvb sequence. - { ISD::SRA, MVT::v8i16, 14 }, // pblendvb sequence. - { ISD::SRA, MVT::v16i16, 2*14 }, // pblendvb sequence. - { ISD::SRA, MVT::v4i32, 12 }, // Shift each lane + blend. - { ISD::SRA, MVT::v8i32, 2*12 }, // Shift each lane + blend. - - { ISD::MUL, MVT::v4i32, 1 } // pmulld + { ISD::SHL, MVT::v16i8, 11 }, // pblendvb sequence. + { ISD::SHL, MVT::v32i8, 2*11+2 }, // pblendvb sequence + split. + { ISD::SHL, MVT::v8i16, 14 }, // pblendvb sequence. + { ISD::SHL, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split. + { ISD::SHL, MVT::v4i32, 4 }, // pslld/paddd/cvttps2dq/pmulld + { ISD::SHL, MVT::v8i32, 2*4+2 }, // pslld/paddd/cvttps2dq/pmulld + split + + { ISD::SRL, MVT::v16i8, 12 }, // pblendvb sequence. + { ISD::SRL, MVT::v32i8, 2*12+2 }, // pblendvb sequence + split. + { ISD::SRL, MVT::v8i16, 14 }, // pblendvb sequence. + { ISD::SRL, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split. + { ISD::SRL, MVT::v4i32, 11 }, // Shift each lane + blend. + { ISD::SRL, MVT::v8i32, 2*11+2 }, // Shift each lane + blend + split. + + { ISD::SRA, MVT::v16i8, 24 }, // pblendvb sequence. + { ISD::SRA, MVT::v32i8, 2*24+2 }, // pblendvb sequence + split. + { ISD::SRA, MVT::v8i16, 14 }, // pblendvb sequence. + { ISD::SRA, MVT::v16i16, 2*14+2 }, // pblendvb sequence + split. + { ISD::SRA, MVT::v4i32, 12 }, // Shift each lane + blend. + { ISD::SRA, MVT::v8i32, 2*12+2 }, // Shift each lane + blend + split. + + { ISD::MUL, MVT::v4i32, 1 } // pmulld }; if (ST->hasSSE41()) @@ -612,33 +620,33 @@ int X86TTIImpl::getArithmeticInstrCost( static const CostTblEntry SSE2CostTable[] = { // We don't correctly identify costs of casts because they are marked as // custom. - { ISD::SHL, MVT::v16i8, 26 }, // cmpgtb sequence. - { ISD::SHL, MVT::v8i16, 32 }, // cmpgtb sequence. - { ISD::SHL, MVT::v4i32, 2*5 }, // We optimized this using mul. - { ISD::SHL, MVT::v2i64, 4 }, // splat+shuffle sequence. - { ISD::SHL, MVT::v4i64, 2*4 }, // splat+shuffle sequence. - - { ISD::SRL, MVT::v16i8, 26 }, // cmpgtb sequence. - { ISD::SRL, MVT::v8i16, 32 }, // cmpgtb sequence. - { ISD::SRL, MVT::v4i32, 16 }, // Shift each lane + blend. - { ISD::SRL, MVT::v2i64, 4 }, // splat+shuffle sequence. - { ISD::SRL, MVT::v4i64, 2*4 }, // splat+shuffle sequence. - - { ISD::SRA, MVT::v16i8, 54 }, // unpacked cmpgtb sequence. - { ISD::SRA, MVT::v8i16, 32 }, // cmpgtb sequence. - { ISD::SRA, MVT::v4i32, 16 }, // Shift each lane + blend. - { ISD::SRA, MVT::v2i64, 12 }, // srl/xor/sub sequence. - { ISD::SRA, MVT::v4i64, 2*12 }, // srl/xor/sub sequence. - - { ISD::MUL, MVT::v16i8, 12 }, // extend/pmullw/trunc sequence. - { ISD::MUL, MVT::v8i16, 1 }, // pmullw - { ISD::MUL, MVT::v4i32, 6 }, // 3*pmuludq/4*shuffle - { ISD::MUL, MVT::v2i64, 8 }, // 3*pmuludq/3*shift/2*add - - { ISD::FDIV, MVT::f32, 23 }, // Pentium IV from http://www.agner.org/ - { ISD::FDIV, MVT::v4f32, 39 }, // Pentium IV from http://www.agner.org/ - { ISD::FDIV, MVT::f64, 38 }, // Pentium IV from http://www.agner.org/ - { ISD::FDIV, MVT::v2f64, 69 }, // Pentium IV from http://www.agner.org/ + { ISD::SHL, MVT::v16i8, 26 }, // cmpgtb sequence. + { ISD::SHL, MVT::v8i16, 32 }, // cmpgtb sequence. + { ISD::SHL, MVT::v4i32, 2*5 }, // We optimized this using mul. + { ISD::SHL, MVT::v2i64, 4 }, // splat+shuffle sequence. + { ISD::SHL, MVT::v4i64, 2*4+2 }, // splat+shuffle sequence + split. + + { ISD::SRL, MVT::v16i8, 26 }, // cmpgtb sequence. + { ISD::SRL, MVT::v8i16, 32 }, // cmpgtb sequence. + { ISD::SRL, MVT::v4i32, 16 }, // Shift each lane + blend. + { ISD::SRL, MVT::v2i64, 4 }, // splat+shuffle sequence. + { ISD::SRL, MVT::v4i64, 2*4+2 }, // splat+shuffle sequence + split. + + { ISD::SRA, MVT::v16i8, 54 }, // unpacked cmpgtb sequence. + { ISD::SRA, MVT::v8i16, 32 }, // cmpgtb sequence. + { ISD::SRA, MVT::v4i32, 16 }, // Shift each lane + blend. + { ISD::SRA, MVT::v2i64, 12 }, // srl/xor/sub sequence. + { ISD::SRA, MVT::v4i64, 2*12+2 }, // srl/xor/sub sequence+split. + + { ISD::MUL, MVT::v16i8, 12 }, // extend/pmullw/trunc sequence. + { ISD::MUL, MVT::v8i16, 1 }, // pmullw + { ISD::MUL, MVT::v4i32, 6 }, // 3*pmuludq/4*shuffle + { ISD::MUL, MVT::v2i64, 8 }, // 3*pmuludq/3*shift/2*add + + { ISD::FDIV, MVT::f32, 23 }, // Pentium IV from http://www.agner.org/ + { ISD::FDIV, MVT::v4f32, 39 }, // Pentium IV from http://www.agner.org/ + { ISD::FDIV, MVT::f64, 38 }, // Pentium IV from http://www.agner.org/ + { ISD::FDIV, MVT::v2f64, 69 }, // Pentium IV from http://www.agner.org/ // It is not a good idea to vectorize division. We have to scalarize it and // in the process we will often end up having to spilling regular diff --git a/contrib/llvm/lib/Target/X86/X86WinEHState.cpp b/contrib/llvm/lib/Target/X86/X86WinEHState.cpp index 500b26b3be17..3ee14a0ff7b1 100644 --- a/contrib/llvm/lib/Target/X86/X86WinEHState.cpp +++ b/contrib/llvm/lib/Target/X86/X86WinEHState.cpp @@ -398,7 +398,7 @@ Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) { /*isVarArg=*/false); Function *Trampoline = Function::Create(TrampolineTy, GlobalValue::InternalLinkage, - Twine("__ehhandler$") + GlobalValue::getRealLinkageName( + Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape( ParentFunc->getName()), TheModule); BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline); diff --git a/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp b/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp index b8742683a0c8..1da189c5cd31 100644 --- a/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp +++ b/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp @@ -409,7 +409,7 @@ static bool isWordAligned(SDValue Value, SelectionDAG &DAG) { KnownBits Known; DAG.computeKnownBits(Value, Known); - return Known.Zero.countTrailingOnes() >= 2; + return Known.countMinTrailingZeros() >= 2; } SDValue XCoreTargetLowering:: @@ -1131,8 +1131,7 @@ SDValue XCoreTargetLowering::LowerCCCCallTo( unsigned NumBytes = RetCCInfo.getNextStackOffset(); auto PtrVT = getPointerTy(DAG.getDataLayout()); - Chain = DAG.getCALLSEQ_START(Chain, - DAG.getConstant(NumBytes, dl, PtrVT, true), dl); + Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass; SmallVector<SDValue, 12> MemOpChains; diff --git a/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td b/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td index f1d52d5a191f..b87ba6548962 100644 --- a/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td +++ b/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td @@ -73,9 +73,10 @@ def XCoreLdwsp : SDNode<"XCoreISD::LDWSP", SDT_XCoreLdwsp, [SDNPHasChain, SDNPMayLoad]>; // These are target-independent nodes, but have target-specific formats. -def SDT_XCoreCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32> ]>; +def SDT_XCoreCallSeqStart : SDCallSeqStart<[ SDTCisVT<0, i32>, + SDTCisVT<1, i32> ]>; def SDT_XCoreCallSeqEnd : SDCallSeqEnd<[ SDTCisVT<0, i32>, - SDTCisVT<1, i32> ]>; + SDTCisVT<1, i32> ]>; def callseq_start : SDNode<"ISD::CALLSEQ_START", SDT_XCoreCallSeqStart, [SDNPHasChain, SDNPOutGlue]>; @@ -323,9 +324,9 @@ class F2R_np<bits<6> opc, string OpcStr> : //===----------------------------------------------------------------------===// let Defs = [SP], Uses = [SP] in { -def ADJCALLSTACKDOWN : PseudoInstXCore<(outs), (ins i32imm:$amt), - "# ADJCALLSTACKDOWN $amt", - [(callseq_start timm:$amt)]>; +def ADJCALLSTACKDOWN : PseudoInstXCore<(outs), (ins i32imm:$amt, i32imm:$amt2), + "# ADJCALLSTACKDOWN $amt, $amt2", + [(callseq_start timm:$amt, timm:$amt2)]>; def ADJCALLSTACKUP : PseudoInstXCore<(outs), (ins i32imm:$amt1, i32imm:$amt2), "# ADJCALLSTACKUP $amt1", [(callseq_end timm:$amt1, timm:$amt2)]>; diff --git a/contrib/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp b/contrib/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp new file mode 100644 index 000000000000..3bae3826d62e --- /dev/null +++ b/contrib/llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp @@ -0,0 +1,171 @@ +//===- LibDriver.cpp - lib.exe-compatible driver --------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Defines an interface to a lib.exe-compatible driver that also understands +// bitcode files. Used by llvm-lib and lld-link /lib. +// +//===----------------------------------------------------------------------===// + +#include "llvm/ToolDrivers/llvm-lib/LibDriver.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Object/ArchiveWriter.h" +#include "llvm/Option/Arg.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Option/Option.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/StringSaver.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/raw_ostream.h" + +using namespace llvm; + +namespace { + +enum { + OPT_INVALID = 0, +#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11) OPT_##ID, +#include "Options.inc" +#undef OPTION +}; + +#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; +#include "Options.inc" +#undef PREFIX + +static const llvm::opt::OptTable::Info infoTable[] = { +#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \ + { \ + X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \ + OPT_##GROUP, OPT_##ALIAS, X6 \ + }, +#include "Options.inc" +#undef OPTION +}; + +class LibOptTable : public llvm::opt::OptTable { +public: + LibOptTable() : OptTable(infoTable, true) {} +}; + +} + +static std::string getOutputPath(llvm::opt::InputArgList *Args, + const llvm::NewArchiveMember &FirstMember) { + if (auto *Arg = Args->getLastArg(OPT_out)) + return Arg->getValue(); + SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier()); + llvm::sys::path::replace_extension(Val, ".lib"); + return Val.str(); +} + +static std::vector<StringRef> getSearchPaths(llvm::opt::InputArgList *Args, + StringSaver &Saver) { + std::vector<StringRef> Ret; + // Add current directory as first item of the search path. + Ret.push_back(""); + + // Add /libpath flags. + for (auto *Arg : Args->filtered(OPT_libpath)) + Ret.push_back(Arg->getValue()); + + // Add $LIB. + Optional<std::string> EnvOpt = sys::Process::GetEnv("LIB"); + if (!EnvOpt.hasValue()) + return Ret; + StringRef Env = Saver.save(*EnvOpt); + while (!Env.empty()) { + StringRef Path; + std::tie(Path, Env) = Env.split(';'); + Ret.push_back(Path); + } + return Ret; +} + +static Optional<std::string> findInputFile(StringRef File, + ArrayRef<StringRef> Paths) { + for (auto Dir : Paths) { + SmallString<128> Path = Dir; + sys::path::append(Path, File); + if (sys::fs::exists(Path)) + return Path.str().str(); + } + return Optional<std::string>(); +} + +int llvm::libDriverMain(llvm::ArrayRef<const char*> ArgsArr) { + SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end()); + BumpPtrAllocator Alloc; + StringSaver Saver(Alloc); + cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine, NewArgs); + ArgsArr = NewArgs; + + LibOptTable Table; + unsigned MissingIndex; + unsigned MissingCount; + llvm::opt::InputArgList Args = + Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount); + if (MissingCount) { + llvm::errs() << "missing arg value for \"" + << Args.getArgString(MissingIndex) << "\", expected " + << MissingCount + << (MissingCount == 1 ? " argument.\n" : " arguments.\n"); + return 1; + } + for (auto *Arg : Args.filtered(OPT_UNKNOWN)) + llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n"; + + if (!Args.hasArgNoClaim(OPT_INPUT)) { + // No input files. To match lib.exe, silently do nothing. + return 0; + } + + std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver); + + std::vector<llvm::NewArchiveMember> Members; + for (auto *Arg : Args.filtered(OPT_INPUT)) { + Optional<std::string> Path = findInputFile(Arg->getValue(), SearchPaths); + if (!Path.hasValue()) { + llvm::errs() << Arg->getValue() << ": no such file or directory\n"; + return 1; + } + Expected<NewArchiveMember> MOrErr = + NewArchiveMember::getFile(Saver.save(*Path), /*Deterministic=*/true); + if (!MOrErr) { + handleAllErrors(MOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) { + llvm::errs() << Arg->getValue() << ": " << EIB.message() << "\n"; + }); + return 1; + } + sys::fs::file_magic Magic = + sys::fs::identify_magic(MOrErr->Buf->getBuffer()); + if (Magic != sys::fs::file_magic::coff_object && + Magic != sys::fs::file_magic::bitcode && + Magic != sys::fs::file_magic::windows_resource) { + llvm::errs() << Arg->getValue() + << ": not a COFF object, bitcode or resource file\n"; + return 1; + } + Members.emplace_back(std::move(*MOrErr)); + } + + std::pair<StringRef, std::error_code> Result = + llvm::writeArchive(getOutputPath(&Args, Members[0]), Members, + /*WriteSymtab=*/true, object::Archive::K_GNU, + /*Deterministic*/ true, Args.hasArg(OPT_llvmlibthin)); + + if (Result.second) { + if (Result.first.empty()) + Result.first = ArgsArr[0]; + llvm::errs() << Result.first << ": " << Result.second.message() << "\n"; + return 1; + } + + return 0; +} diff --git a/contrib/llvm/lib/ToolDrivers/llvm-lib/Options.td b/contrib/llvm/lib/ToolDrivers/llvm-lib/Options.td new file mode 100644 index 000000000000..5a56ef7468d4 --- /dev/null +++ b/contrib/llvm/lib/ToolDrivers/llvm-lib/Options.td @@ -0,0 +1,25 @@ +include "llvm/Option/OptParser.td" + +// lib.exe accepts options starting with either a dash or a slash. + +// Flag that takes no arguments. +class F<string name> : Flag<["/", "-", "-?"], name>; + +// Flag that takes one argument after ":". +class P<string name, string help> : + Joined<["/", "-", "-?"], name#":">, HelpText<help>; + +def libpath: P<"libpath", "Object file search path">; +def out : P<"out", "Path to file to write output">; + +def llvmlibthin : F<"llvmlibthin">; + +//============================================================================== +// The flags below do nothing. They are defined only for lib.exe compatibility. +//============================================================================== + +class QF<string name> : Joined<["/", "-", "-?"], name#":">; + +def ignore : QF<"ignore">; +def machine: QF<"machine">; +def nologo : F<"nologo">; diff --git a/contrib/llvm/lib/Transforms/Coroutines/CoroFrame.cpp b/contrib/llvm/lib/Transforms/Coroutines/CoroFrame.cpp index 19e6789dfa74..4480220f2cd4 100644 --- a/contrib/llvm/lib/Transforms/Coroutines/CoroFrame.cpp +++ b/contrib/llvm/lib/Transforms/Coroutines/CoroFrame.cpp @@ -177,7 +177,7 @@ SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape) // consume. Note, that crossing coro.save also requires a spill, as any code // between coro.save and coro.suspend may resume the coroutine and all of the // state needs to be saved by that time. - auto markSuspendBlock = [&](IntrinsicInst* BarrierInst) { + auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) { BasicBlock *SuspendBlock = BarrierInst->getParent(); auto &B = getBlockData(SuspendBlock); B.Suspend = true; @@ -495,6 +495,78 @@ static Instruction *insertSpills(SpillInfo &Spills, coro::Shape &Shape) { return FramePtr; } +// Sets the unwind edge of an instruction to a particular successor. +static void setUnwindEdgeTo(TerminatorInst *TI, BasicBlock *Succ) { + if (auto *II = dyn_cast<InvokeInst>(TI)) + II->setUnwindDest(Succ); + else if (auto *CS = dyn_cast<CatchSwitchInst>(TI)) + CS->setUnwindDest(Succ); + else if (auto *CR = dyn_cast<CleanupReturnInst>(TI)) + CR->setUnwindDest(Succ); + else + llvm_unreachable("unexpected terminator instruction"); +} + +// Replaces all uses of OldPred with the NewPred block in all PHINodes in a +// block. +static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, + BasicBlock *NewPred, + PHINode *LandingPadReplacement) { + unsigned BBIdx = 0; + for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) { + PHINode *PN = cast<PHINode>(I); + + // We manually update the LandingPadReplacement PHINode and it is the last + // PHI Node. So, if we find it, we are done. + if (LandingPadReplacement == PN) + break; + + // Reuse the previous value of BBIdx if it lines up. In cases where we + // have multiple phi nodes with *lots* of predecessors, this is a speed + // win because we don't have to scan the PHI looking for TIBB. This + // happens because the BB list of PHI nodes are usually in the same + // order. + if (PN->getIncomingBlock(BBIdx) != OldPred) + BBIdx = PN->getBasicBlockIndex(OldPred); + + assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!"); + PN->setIncomingBlock(BBIdx, NewPred); + } +} + +// Uses SplitEdge unless the successor block is an EHPad, in which case do EH +// specific handling. +static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, + LandingPadInst *OriginalPad, + PHINode *LandingPadReplacement) { + auto *PadInst = Succ->getFirstNonPHI(); + if (!LandingPadReplacement && !PadInst->isEHPad()) + return SplitEdge(BB, Succ); + + auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ); + setUnwindEdgeTo(BB->getTerminator(), NewBB); + updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement); + + if (LandingPadReplacement) { + auto *NewLP = OriginalPad->clone(); + auto *Terminator = BranchInst::Create(Succ, NewBB); + NewLP->insertBefore(Terminator); + LandingPadReplacement->addIncoming(NewLP, NewBB); + return NewBB; + } + Value *ParentPad = nullptr; + if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst)) + ParentPad = FuncletPad->getParentPad(); + else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst)) + ParentPad = CatchSwitch->getParentPad(); + else + llvm_unreachable("handling for other EHPads not implemented yet"); + + auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB); + CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB); + return NewBB; +} + static void rewritePHIs(BasicBlock &BB) { // For every incoming edge we will create a block holding all // incoming values in a single PHI nodes. @@ -502,7 +574,7 @@ static void rewritePHIs(BasicBlock &BB) { // loop: // %n.val = phi i32[%n, %entry], [%inc, %loop] // - // It will create: + // It will create: // // loop.from.entry: // %n.loop.pre = phi i32 [%n, %entry] @@ -517,9 +589,22 @@ static void rewritePHIs(BasicBlock &BB) { // TODO: Simplify PHINodes in the basic block to remove duplicate // predecessors. + LandingPadInst *LandingPad = nullptr; + PHINode *ReplPHI = nullptr; + if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) { + // ehAwareSplitEdge will clone the LandingPad in all the edge blocks. + // We replace the original landing pad with a PHINode that will collect the + // results from all of them. + ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad); + ReplPHI->takeName(LandingPad); + LandingPad->replaceAllUsesWith(ReplPHI); + // We will erase the original landing pad at the end of this function after + // ehAwareSplitEdge cloned it in the transition blocks. + } + SmallVector<BasicBlock *, 8> Preds(pred_begin(&BB), pred_end(&BB)); for (BasicBlock *Pred : Preds) { - auto *IncomingBB = SplitEdge(Pred, &BB); + auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI); IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName()); auto *PN = cast<PHINode>(&BB.front()); do { @@ -531,7 +616,14 @@ static void rewritePHIs(BasicBlock &BB) { InputV->addIncoming(V, Pred); PN->setIncomingValue(Index, InputV); PN = dyn_cast<PHINode>(PN->getNextNode()); - } while (PN); + } while (PN != ReplPHI); // ReplPHI is either null or the PHI that replaced + // the landing pad. + } + + if (LandingPad) { + // Calls to ehAwareSplitEdge function cloned the original lading pad. + // No longer need it. + LandingPad->eraseFromParent(); } } diff --git a/contrib/llvm/lib/Transforms/IPO/FunctionImport.cpp b/contrib/llvm/lib/Transforms/IPO/FunctionImport.cpp index 7ed07d63c627..231487923fad 100644 --- a/contrib/llvm/lib/Transforms/IPO/FunctionImport.cpp +++ b/contrib/llvm/lib/Transforms/IPO/FunctionImport.cpp @@ -610,8 +610,7 @@ void llvm::thinLTOInternalizeModule(Module &TheModule, return true; // Lookup the linkage recorded in the summaries during global analysis. - const auto &GS = DefinedGlobals.find(GV.getGUID()); - GlobalValue::LinkageTypes Linkage; + auto GS = DefinedGlobals.find(GV.getGUID()); if (GS == DefinedGlobals.end()) { // Must have been promoted (possibly conservatively). Find original // name so that we can access the correct summary and see if it can @@ -623,7 +622,7 @@ void llvm::thinLTOInternalizeModule(Module &TheModule, std::string OrigId = GlobalValue::getGlobalIdentifier( OrigName, GlobalValue::InternalLinkage, TheModule.getSourceFileName()); - const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); + GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); if (GS == DefinedGlobals.end()) { // Also check the original non-promoted non-globalized name. In some // cases a preempted weak value is linked in as a local copy because @@ -631,15 +630,11 @@ void llvm::thinLTOInternalizeModule(Module &TheModule, // In that case, since it was originally not a local value, it was // recorded in the index using the original name. // FIXME: This may not be needed once PR27866 is fixed. - const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); + GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); assert(GS != DefinedGlobals.end()); - Linkage = GS->second->linkage(); - } else { - Linkage = GS->second->linkage(); } - } else - Linkage = GS->second->linkage(); - return !GlobalValue::isLocalLinkage(Linkage); + } + return !GlobalValue::isLocalLinkage(GS->second->linkage()); }; // FIXME: See if we can just internalize directly here via linkage changes diff --git a/contrib/llvm/lib/Transforms/IPO/Inliner.cpp b/contrib/llvm/lib/Transforms/IPO/Inliner.cpp index 6c83c99ae3be..673d3af0ab52 100644 --- a/contrib/llvm/lib/Transforms/IPO/Inliner.cpp +++ b/contrib/llvm/lib/Transforms/IPO/Inliner.cpp @@ -502,7 +502,7 @@ inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG, std::swap(CallSites[i--], CallSites[--FirstCallInSCC]); InlinedArrayAllocasTy InlinedArrayAllocas; - InlineFunctionInfo InlineInfo(&CG, &GetAssumptionCache); + InlineFunctionInfo InlineInfo(&CG, &GetAssumptionCache, PSI); // Now that we have all of the call sites, loop over them and inline them if // it looks profitable to do so. @@ -872,7 +872,7 @@ PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC, // Setup the data structure used to plumb customization into the // `InlineFunction` routine. InlineFunctionInfo IFI( - /*cg=*/nullptr, &GetAssumptionCache, + /*cg=*/nullptr, &GetAssumptionCache, PSI, &FAM.getResult<BlockFrequencyAnalysis>(*(CS.getCaller())), &FAM.getResult<BlockFrequencyAnalysis>(Callee)); diff --git a/contrib/llvm/lib/Transforms/IPO/PartialInlining.cpp b/contrib/llvm/lib/Transforms/IPO/PartialInlining.cpp index 2db47b3b5622..8dff2fb3be8a 100644 --- a/contrib/llvm/lib/Transforms/IPO/PartialInlining.cpp +++ b/contrib/llvm/lib/Transforms/IPO/PartialInlining.cpp @@ -16,6 +16,7 @@ #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/BlockFrequencyInfo.h" #include "llvm/Analysis/BranchProbabilityInfo.h" +#include "llvm/Analysis/CodeMetrics.h" #include "llvm/Analysis/InlineCost.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/OptimizationDiagnosticInfo.h" @@ -42,6 +43,11 @@ STATISTIC(NumPartialInlined, static cl::opt<bool> DisablePartialInlining("disable-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Disable partial ininling")); +// This is an option used by testing: +static cl::opt<bool> SkipCostAnalysis("skip-partial-inlining-cost-analysis", + cl::init(false), cl::ZeroOrMore, + cl::ReallyHidden, + cl::desc("Skip Cost Analysis")); static cl::opt<unsigned> MaxNumInlineBlocks( "max-num-inline-blocks", cl::init(5), cl::Hidden, @@ -53,6 +59,15 @@ static cl::opt<int> MaxNumPartialInlining( "max-partial-inlining", cl::init(-1), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of partial inlining. The default is unlimited")); +// Used only when PGO or user annotated branch data is absent. It is +// the least value that is used to weigh the outline region. If BFI +// produces larger value, the BFI value will be used. +static cl::opt<int> + OutlineRegionFreqPercent("outline-region-freq-percent", cl::init(75), + cl::Hidden, cl::ZeroOrMore, + cl::desc("Relative frequency of outline region to " + "the entry block")); + namespace { struct FunctionOutliningInfo { @@ -84,8 +99,6 @@ struct PartialInlinerImpl { bool run(Module &M); Function *unswitchFunction(Function *F); - std::unique_ptr<FunctionOutliningInfo> computeOutliningInfo(Function *F); - private: int NumPartialInlining = 0; std::function<AssumptionCache &(Function &)> *GetAssumptionCache; @@ -93,11 +106,84 @@ private: Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI; ProfileSummaryInfo *PSI; - bool shouldPartialInline(CallSite CS, OptimizationRemarkEmitter &ORE); + // Return the frequency of the OutlininingBB relative to F's entry point. + // The result is no larger than 1 and is represented using BP. + // (Note that the outlined region's 'head' block can only have incoming + // edges from the guarding entry blocks). + BranchProbability getOutliningCallBBRelativeFreq(Function *F, + FunctionOutliningInfo *OI, + Function *DuplicateFunction, + BlockFrequencyInfo *BFI, + BasicBlock *OutliningCallBB); + + // Return true if the callee of CS should be partially inlined with + // profit. + bool shouldPartialInline(CallSite CS, Function *F, FunctionOutliningInfo *OI, + BlockFrequencyInfo *CalleeBFI, + BasicBlock *OutliningCallBB, + int OutliningCallOverhead, + OptimizationRemarkEmitter &ORE); + + // Try to inline DuplicateFunction (cloned from F with call to + // the OutlinedFunction into its callers. Return true + // if there is any successful inlining. + bool tryPartialInline(Function *DuplicateFunction, + Function *F, /*orignal function */ + FunctionOutliningInfo *OI, Function *OutlinedFunction, + BlockFrequencyInfo *CalleeBFI); + + // Compute the mapping from use site of DuplicationFunction to the enclosing + // BB's profile count. + void computeCallsiteToProfCountMap(Function *DuplicateFunction, + DenseMap<User *, uint64_t> &SiteCountMap); + bool IsLimitReached() { return (MaxNumPartialInlining != -1 && NumPartialInlining >= MaxNumPartialInlining); } + + CallSite getCallSite(User *U) { + CallSite CS; + if (CallInst *CI = dyn_cast<CallInst>(U)) + CS = CallSite(CI); + else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) + CS = CallSite(II); + else + llvm_unreachable("All uses must be calls"); + return CS; + } + + CallSite getOneCallSiteTo(Function *F) { + User *User = *F->user_begin(); + return getCallSite(User); + } + + std::tuple<DebugLoc, BasicBlock *> getOneDebugLoc(Function *F) { + CallSite CS = getOneCallSiteTo(F); + DebugLoc DLoc = CS.getInstruction()->getDebugLoc(); + BasicBlock *Block = CS.getParent(); + return std::make_tuple(DLoc, Block); + } + + // Returns the costs associated with function outlining: + // - The first value is the non-weighted runtime cost for making the call + // to the outlined function 'OutlinedFunction', including the addtional + // setup cost in the outlined function itself; + // - The second value is the estimated size of the new call sequence in + // basic block 'OutliningCallBB'; + // - The third value is the estimated size of the original code from + // function 'F' that is extracted into the outlined function. + std::tuple<int, int, int> + computeOutliningCosts(Function *F, const FunctionOutliningInfo *OutliningInfo, + Function *OutlinedFunction, + BasicBlock *OutliningCallBB); + // Compute the 'InlineCost' of block BB. InlineCost is a proxy used to + // approximate both the size and runtime cost (Note that in the current + // inline cost analysis, there is no clear distinction there either). + int computeBBInlineCost(BasicBlock *BB); + + std::unique_ptr<FunctionOutliningInfo> computeOutliningInfo(Function *F); + }; struct PartialInlinerLegacyPass : public ModulePass { @@ -157,7 +243,7 @@ PartialInlinerImpl::computeOutliningInfo(Function *F) { return isa<ReturnInst>(TI); }; - auto GetReturnBlock = [=](BasicBlock *Succ1, BasicBlock *Succ2) { + auto GetReturnBlock = [&](BasicBlock *Succ1, BasicBlock *Succ2) { if (IsReturnBlock(Succ1)) return std::make_tuple(Succ1, Succ2); if (IsReturnBlock(Succ2)) @@ -167,7 +253,7 @@ PartialInlinerImpl::computeOutliningInfo(Function *F) { }; // Detect a triangular shape: - auto GetCommonSucc = [=](BasicBlock *Succ1, BasicBlock *Succ2) { + auto GetCommonSucc = [&](BasicBlock *Succ1, BasicBlock *Succ2) { if (IsSuccessor(Succ1, Succ2)) return std::make_tuple(Succ1, Succ2); if (IsSuccessor(Succ2, Succ1)) @@ -223,7 +309,8 @@ PartialInlinerImpl::computeOutliningInfo(Function *F) { // Do sanity check of the entries: threre should not // be any successors (not in the entry set) other than // {ReturnBlock, NonReturnBlock} - assert(OutliningInfo->Entries[0] == &F->front()); + assert(OutliningInfo->Entries[0] == &F->front() && + "Function Entry must be the first in Entries vector"); DenseSet<BasicBlock *> Entries; for (BasicBlock *E : OutliningInfo->Entries) Entries.insert(E); @@ -289,10 +376,54 @@ PartialInlinerImpl::computeOutliningInfo(Function *F) { return OutliningInfo; } -bool PartialInlinerImpl::shouldPartialInline(CallSite CS, - OptimizationRemarkEmitter &ORE) { - // TODO : more sharing with shouldInline in Inliner.cpp +// Check if there is PGO data or user annoated branch data: +static bool hasProfileData(Function *F, FunctionOutliningInfo *OI) { + if (F->getEntryCount()) + return true; + // Now check if any of the entry block has MD_prof data: + for (auto *E : OI->Entries) { + BranchInst *BR = dyn_cast<BranchInst>(E->getTerminator()); + if (!BR || BR->isUnconditional()) + continue; + uint64_t T, F; + if (BR->extractProfMetadata(T, F)) + return true; + } + return false; +} + +BranchProbability PartialInlinerImpl::getOutliningCallBBRelativeFreq( + Function *F, FunctionOutliningInfo *OI, Function *DuplicateFunction, + BlockFrequencyInfo *BFI, BasicBlock *OutliningCallBB) { + + auto EntryFreq = + BFI->getBlockFreq(&DuplicateFunction->getEntryBlock()); + auto OutliningCallFreq = BFI->getBlockFreq(OutliningCallBB); + + auto OutlineRegionRelFreq = + BranchProbability::getBranchProbability(OutliningCallFreq.getFrequency(), + EntryFreq.getFrequency()); + + if (hasProfileData(F, OI)) + return OutlineRegionRelFreq; + + // When profile data is not available, we need to be very + // conservative in estimating the overall savings. We need to make sure + // the outline region relative frequency is not below the threshold + // specified by the option. + OutlineRegionRelFreq = std::max(OutlineRegionRelFreq, BranchProbability(OutlineRegionFreqPercent, 100)); + + return OutlineRegionRelFreq; +} + +bool PartialInlinerImpl::shouldPartialInline( + CallSite CS, Function *F /* Original Callee */, FunctionOutliningInfo *OI, + BlockFrequencyInfo *CalleeBFI, BasicBlock *OutliningCallBB, + int NonWeightedOutliningRcost, OptimizationRemarkEmitter &ORE) { using namespace ore; + if (SkipCostAnalysis) + return true; + Instruction *Call = CS.getInstruction(); Function *Callee = CS.getCalledFunction(); Function *Caller = CS.getCaller(); @@ -302,36 +433,170 @@ bool PartialInlinerImpl::shouldPartialInline(CallSite CS, if (IC.isAlways()) { ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AlwaysInline", Call) - << NV("Callee", Callee) + << NV("Callee", F) << " should always be fully inlined, not partially"); return false; } if (IC.isNever()) { ORE.emit(OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call) - << NV("Callee", Callee) << " not partially inlined into " + << NV("Callee", F) << " not partially inlined into " << NV("Caller", Caller) << " because it should never be inlined (cost=never)"); return false; } if (!IC) { - ORE.emit(OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call) - << NV("Callee", Callee) << " not partially inlined into " + ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "TooCostly", Call) + << NV("Callee", F) << " not partially inlined into " << NV("Caller", Caller) << " because too costly to inline (cost=" << NV("Cost", IC.getCost()) << ", threshold=" << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")"); return false; } + const DataLayout &DL = Caller->getParent()->getDataLayout(); + // The savings of eliminating the call: + int NonWeightedSavings = getCallsiteCost(CS, DL); + BlockFrequency NormWeightedSavings(NonWeightedSavings); + + auto RelativeFreq = + getOutliningCallBBRelativeFreq(F, OI, Callee, CalleeBFI, OutliningCallBB); + auto NormWeightedRcost = + BlockFrequency(NonWeightedOutliningRcost) * RelativeFreq; + + // Weighted saving is smaller than weighted cost, return false + if (NormWeightedSavings < NormWeightedRcost) { + ORE.emit( + OptimizationRemarkAnalysis(DEBUG_TYPE, "OutliningCallcostTooHigh", Call) + << NV("Callee", F) << " not partially inlined into " + << NV("Caller", Caller) << " runtime overhead (overhead=" + << NV("Overhead", (unsigned)NormWeightedRcost.getFrequency()) + << ", savings=" + << NV("Savings", (unsigned)NormWeightedSavings.getFrequency()) << ")" + << " of making the outlined call is too high"); + + return false; + } ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "CanBePartiallyInlined", Call) - << NV("Callee", Callee) << " can be partially inlined into " + << NV("Callee", F) << " can be partially inlined into " << NV("Caller", Caller) << " with cost=" << NV("Cost", IC.getCost()) << " (threshold=" << NV("Threshold", IC.getCostDelta() + IC.getCost()) << ")"); return true; } +// TODO: Ideally we should share Inliner's InlineCost Analysis code. +// For now use a simplified version. The returned 'InlineCost' will be used +// to esimate the size cost as well as runtime cost of the BB. +int PartialInlinerImpl::computeBBInlineCost(BasicBlock *BB) { + int InlineCost = 0; + const DataLayout &DL = BB->getParent()->getParent()->getDataLayout(); + for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { + if (isa<DbgInfoIntrinsic>(I)) + continue; + + if (CallInst *CI = dyn_cast<CallInst>(I)) { + InlineCost += getCallsiteCost(CallSite(CI), DL); + continue; + } + + if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { + InlineCost += getCallsiteCost(CallSite(II), DL); + continue; + } + + if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { + InlineCost += (SI->getNumCases() + 1) * InlineConstants::InstrCost; + continue; + } + InlineCost += InlineConstants::InstrCost; + } + return InlineCost; +} + +std::tuple<int, int, int> PartialInlinerImpl::computeOutliningCosts( + Function *F, const FunctionOutliningInfo *OI, Function *OutlinedFunction, + BasicBlock *OutliningCallBB) { + // First compute the cost of the outlined region 'OI' in the original + // function 'F': + int OutlinedRegionCost = 0; + for (BasicBlock &BB : *F) { + if (&BB != OI->ReturnBlock && + // Assuming Entry set is small -- do a linear search here: + std::find(OI->Entries.begin(), OI->Entries.end(), &BB) == + OI->Entries.end()) { + OutlinedRegionCost += computeBBInlineCost(&BB); + } + } + + // Now compute the cost of the call sequence to the outlined function + // 'OutlinedFunction' in BB 'OutliningCallBB': + int OutliningFuncCallCost = computeBBInlineCost(OutliningCallBB); + + // Now compute the cost of the extracted/outlined function itself: + int OutlinedFunctionCost = 0; + for (BasicBlock &BB : *OutlinedFunction) { + OutlinedFunctionCost += computeBBInlineCost(&BB); + } + + assert(OutlinedFunctionCost >= OutlinedRegionCost && + "Outlined function cost should be no less than the outlined region"); + int OutliningRuntimeOverhead = + OutliningFuncCallCost + (OutlinedFunctionCost - OutlinedRegionCost); + + return std::make_tuple(OutliningFuncCallCost, OutliningRuntimeOverhead, + OutlinedRegionCost); +} + +// Create the callsite to profile count map which is +// used to update the original function's entry count, +// after the function is partially inlined into the callsite. +void PartialInlinerImpl::computeCallsiteToProfCountMap( + Function *DuplicateFunction, + DenseMap<User *, uint64_t> &CallSiteToProfCountMap) { + std::vector<User *> Users(DuplicateFunction->user_begin(), + DuplicateFunction->user_end()); + Function *CurrentCaller = nullptr; + BlockFrequencyInfo *CurrentCallerBFI = nullptr; + + auto ComputeCurrBFI = [&,this](Function *Caller) { + // For the old pass manager: + if (!GetBFI) { + if (CurrentCallerBFI) + delete CurrentCallerBFI; + DominatorTree DT(*Caller); + LoopInfo LI(DT); + BranchProbabilityInfo BPI(*Caller, LI); + CurrentCallerBFI = new BlockFrequencyInfo(*Caller, BPI, LI); + } else { + // New pass manager: + CurrentCallerBFI = &(*GetBFI)(*Caller); + } + }; + + for (User *User : Users) { + CallSite CS = getCallSite(User); + Function *Caller = CS.getCaller(); + if (CurrentCaller != Caller) { + CurrentCaller = Caller; + ComputeCurrBFI(Caller); + } else { + assert(CurrentCallerBFI && "CallerBFI is not set"); + } + BasicBlock *CallBB = CS.getInstruction()->getParent(); + auto Count = CurrentCallerBFI->getBlockProfileCount(CallBB); + if (Count) + CallSiteToProfCountMap[User] = *Count; + else + CallSiteToProfCountMap[User] = 0; + } + if (!GetBFI) { + if (CurrentCallerBFI) + delete CurrentCallerBFI; + } +} + Function *PartialInlinerImpl::unswitchFunction(Function *F) { if (F->hasAddressTaken()) @@ -347,21 +612,21 @@ Function *PartialInlinerImpl::unswitchFunction(Function *F) { if (PSI->isFunctionEntryCold(F)) return nullptr; - std::unique_ptr<FunctionOutliningInfo> OutliningInfo = - computeOutliningInfo(F); + if (F->user_begin() == F->user_end()) + return nullptr; + + std::unique_ptr<FunctionOutliningInfo> OI = computeOutliningInfo(F); - if (!OutliningInfo) + if (!OI) return nullptr; // Clone the function, so that we can hack away on it. ValueToValueMapTy VMap; Function *DuplicateFunction = CloneFunction(F, VMap); - BasicBlock *NewReturnBlock = - cast<BasicBlock>(VMap[OutliningInfo->ReturnBlock]); - BasicBlock *NewNonReturnBlock = - cast<BasicBlock>(VMap[OutliningInfo->NonReturnBlock]); + BasicBlock *NewReturnBlock = cast<BasicBlock>(VMap[OI->ReturnBlock]); + BasicBlock *NewNonReturnBlock = cast<BasicBlock>(VMap[OI->NonReturnBlock]); DenseSet<BasicBlock *> NewEntries; - for (BasicBlock *BB : OutliningInfo->Entries) { + for (BasicBlock *BB : OI->Entries) { NewEntries.insert(cast<BasicBlock>(VMap[BB])); } @@ -390,7 +655,7 @@ Function *PartialInlinerImpl::unswitchFunction(Function *F) { BasicBlock *PreReturn = NewReturnBlock; // only split block when necessary: PHINode *FirstPhi = getFirstPHI(PreReturn); - unsigned NumPredsFromEntries = OutliningInfo->ReturnBlockPreds.size(); + unsigned NumPredsFromEntries = OI->ReturnBlockPreds.size(); if (FirstPhi && FirstPhi->getNumIncomingValues() > NumPredsFromEntries + 1) { NewReturnBlock = NewReturnBlock->splitBasicBlock( @@ -408,14 +673,14 @@ Function *PartialInlinerImpl::unswitchFunction(Function *F) { Ins = NewReturnBlock->getFirstNonPHI(); RetPhi->addIncoming(&*I, PreReturn); - for (BasicBlock *E : OutliningInfo->ReturnBlockPreds) { + for (BasicBlock *E : OI->ReturnBlockPreds) { BasicBlock *NewE = cast<BasicBlock>(VMap[E]); RetPhi->addIncoming(OldPhi->getIncomingValueForBlock(NewE), NewE); OldPhi->removeIncomingValue(NewE); } ++I; } - for (auto E : OutliningInfo->ReturnBlockPreds) { + for (auto E : OI->ReturnBlockPreds) { BasicBlock *NewE = cast<BasicBlock>(VMap[E]); NewE->getTerminator()->replaceUsesOfWith(PreReturn, NewReturnBlock); } @@ -423,7 +688,7 @@ Function *PartialInlinerImpl::unswitchFunction(Function *F) { // Returns true if the block is to be partial inlined into the caller // (i.e. not to be extracted to the out of line function) - auto ToBeInlined = [=](BasicBlock *BB) { + auto ToBeInlined = [&](BasicBlock *BB) { return BB == NewReturnBlock || NewEntries.count(BB); }; // Gather up the blocks that we're going to extract. @@ -443,50 +708,113 @@ Function *PartialInlinerImpl::unswitchFunction(Function *F) { BlockFrequencyInfo BFI(*DuplicateFunction, BPI, LI); // Extract the body of the if. - Function *ExtractedFunction = + Function *OutlinedFunction = CodeExtractor(ToExtract, &DT, /*AggregateArgs*/ false, &BFI, &BPI) .extractCodeRegion(); - // Inline the top-level if test into all callers. + bool AnyInline = + tryPartialInline(DuplicateFunction, F, OI.get(), OutlinedFunction, &BFI); + + // Ditch the duplicate, since we're done with it, and rewrite all remaining + // users (function pointers, etc.) back to the original function. + DuplicateFunction->replaceAllUsesWith(F); + DuplicateFunction->eraseFromParent(); + + if (AnyInline) + return OutlinedFunction; + + // Remove the function that is speculatively created: + if (OutlinedFunction) + OutlinedFunction->eraseFromParent(); + + return nullptr; +} + +bool PartialInlinerImpl::tryPartialInline(Function *DuplicateFunction, + Function *F, + FunctionOutliningInfo *OI, + Function *OutlinedFunction, + BlockFrequencyInfo *CalleeBFI) { + if (OutlinedFunction == nullptr) + return false; + + int NonWeightedRcost; + int SizeCost; + int OutlinedRegionSizeCost; + + auto OutliningCallBB = + getOneCallSiteTo(OutlinedFunction).getInstruction()->getParent(); + + std::tie(SizeCost, NonWeightedRcost, OutlinedRegionSizeCost) = + computeOutliningCosts(F, OI, OutlinedFunction, OutliningCallBB); + + // The call sequence to the outlined function is larger than the original + // outlined region size, it does not increase the chances of inlining + // 'F' with outlining (The inliner usies the size increase to model the + // the cost of inlining a callee). + if (!SkipCostAnalysis && OutlinedRegionSizeCost < SizeCost) { + OptimizationRemarkEmitter ORE(F); + DebugLoc DLoc; + BasicBlock *Block; + std::tie(DLoc, Block) = getOneDebugLoc(DuplicateFunction); + ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "OutlineRegionTooSmall", + DLoc, Block) + << ore::NV("Function", F) + << " not partially inlined into callers (Original Size = " + << ore::NV("OutlinedRegionOriginalSize", OutlinedRegionSizeCost) + << ", Size of call sequence to outlined function = " + << ore::NV("NewSize", SizeCost) << ")"); + return false; + } + + assert(F->user_begin() == F->user_end() && + "F's users should all be replaced!"); std::vector<User *> Users(DuplicateFunction->user_begin(), DuplicateFunction->user_end()); + DenseMap<User *, uint64_t> CallSiteToProfCountMap; + if (F->getEntryCount()) + computeCallsiteToProfCountMap(DuplicateFunction, CallSiteToProfCountMap); + + auto CalleeEntryCount = F->getEntryCount(); + uint64_t CalleeEntryCountV = (CalleeEntryCount ? *CalleeEntryCount : 0); + bool AnyInline = false; for (User *User : Users) { - CallSite CS; - if (CallInst *CI = dyn_cast<CallInst>(User)) - CS = CallSite(CI); - else if (InvokeInst *II = dyn_cast<InvokeInst>(User)) - CS = CallSite(II); - else - llvm_unreachable("All uses must be calls"); + CallSite CS = getCallSite(User); if (IsLimitReached()) continue; OptimizationRemarkEmitter ORE(CS.getCaller()); - if (!shouldPartialInline(CS, ORE)) + + if (!shouldPartialInline(CS, F, OI, CalleeBFI, OutliningCallBB, + NonWeightedRcost, ORE)) continue; - DebugLoc DLoc = CS.getInstruction()->getDebugLoc(); - BasicBlock *Block = CS.getParent(); - ORE.emit(OptimizationRemark(DEBUG_TYPE, "PartiallyInlined", DLoc, Block) - << ore::NV("Callee", F) << " partially inlined into " - << ore::NV("Caller", CS.getCaller())); + ORE.emit( + OptimizationRemark(DEBUG_TYPE, "PartiallyInlined", CS.getInstruction()) + << ore::NV("Callee", F) << " partially inlined into " + << ore::NV("Caller", CS.getCaller())); - InlineFunctionInfo IFI(nullptr, GetAssumptionCache); + InlineFunctionInfo IFI(nullptr, GetAssumptionCache, PSI); InlineFunction(CS, IFI); + + // Now update the entry count: + if (CalleeEntryCountV && CallSiteToProfCountMap.count(User)) { + uint64_t CallSiteCount = CallSiteToProfCountMap[User]; + CalleeEntryCountV -= std::min(CalleeEntryCountV, CallSiteCount); + } + + AnyInline = true; NumPartialInlining++; - // update stats + // Update the stats NumPartialInlined++; } - // Ditch the duplicate, since we're done with it, and rewrite all remaining - // users (function pointers, etc.) back to the original function. - DuplicateFunction->replaceAllUsesWith(F); - DuplicateFunction->eraseFromParent(); - + if (AnyInline && CalleeEntryCount) + F->setEntryCount(CalleeEntryCountV); - return ExtractedFunction; + return AnyInline; } bool PartialInlinerImpl::run(Module &M) { diff --git a/contrib/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp b/contrib/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp index d3a3c24ce7b4..659cb9df00a2 100644 --- a/contrib/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp +++ b/contrib/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp @@ -16,6 +16,7 @@ #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/ModuleSummaryAnalysis.h" +#include "llvm/Analysis/ProfileSummaryInfo.h" #include "llvm/Analysis/TypeMetadataUtils.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/IR/Constants.h" @@ -178,7 +179,7 @@ void filterModule( else GO = new GlobalVariable( *M, GA->getValueType(), false, GlobalValue::ExternalLinkage, - (Constant *)nullptr, "", (GlobalVariable *)nullptr, + nullptr, "", nullptr, GA->getThreadLocalMode(), GA->getType()->getAddressSpace()); GO->takeName(GA); GA->replaceAllUsesWith(GO); @@ -320,7 +321,8 @@ void splitAndWriteThinLTOBitcode( // FIXME: Try to re-use BSI and PFI from the original module here. - ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, nullptr); + ProfileSummaryInfo PSI(M); + ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI); SmallVector<char, 0> Buffer; diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp index 153a186d5ed4..0ca62b7ae40c 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp @@ -847,92 +847,6 @@ Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) { return createFMul(OpndVal, Coeff.getValue(Instr->getType())); } -/// \brief Return true if we can prove that adding the two values of the -/// knownbits will not overflow. -/// Otherwise return false. -static bool checkRippleForAdd(const KnownBits &LHSKnown, - const KnownBits &RHSKnown) { - // Addition of two 2's complement numbers having opposite signs will never - // overflow. - if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) || - (LHSKnown.isNonNegative() && RHSKnown.isNegative())) - return true; - - // If either of the values is known to be non-negative, adding them can only - // overflow if the second is also non-negative, so we can assume that. - // Two non-negative numbers will only overflow if there is a carry to the - // sign bit, so we can check if even when the values are as big as possible - // there is no overflow to the sign bit. - if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) { - APInt MaxLHS = ~LHSKnown.Zero; - MaxLHS.clearSignBit(); - APInt MaxRHS = ~RHSKnown.Zero; - MaxRHS.clearSignBit(); - APInt Result = std::move(MaxLHS) + std::move(MaxRHS); - return Result.isSignBitClear(); - } - - // If either of the values is known to be negative, adding them can only - // overflow if the second is also negative, so we can assume that. - // Two negative number will only overflow if there is no carry to the sign - // bit, so we can check if even when the values are as small as possible - // there is overflow to the sign bit. - if (LHSKnown.isNegative() || RHSKnown.isNegative()) { - APInt MinLHS = LHSKnown.One; - MinLHS.clearSignBit(); - APInt MinRHS = RHSKnown.One; - MinRHS.clearSignBit(); - APInt Result = std::move(MinLHS) + std::move(MinRHS); - return Result.isSignBitSet(); - } - - // If we reached here it means that we know nothing about the sign bits. - // In this case we can't know if there will be an overflow, since by - // changing the sign bits any two values can be made to overflow. - return false; -} - -/// Return true if we can prove that: -/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS)) -/// This basically requires proving that the add in the original type would not -/// overflow to change the sign bit or have a carry out. -bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS, - Instruction &CxtI) { - // There are different heuristics we can use for this. Here are some simple - // ones. - - // If LHS and RHS each have at least two sign bits, the addition will look - // like - // - // XX..... + - // YY..... - // - // If the carry into the most significant position is 0, X and Y can't both - // be 1 and therefore the carry out of the addition is also 0. - // - // If the carry into the most significant position is 1, X and Y can't both - // be 0 and therefore the carry out of the addition is also 1. - // - // Since the carry into the most significant position is always equal to - // the carry out of the addition, there is no signed overflow. - if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 && - ComputeNumSignBits(RHS, 0, &CxtI) > 1) - return true; - - unsigned BitWidth = LHS->getType()->getScalarSizeInBits(); - KnownBits LHSKnown(BitWidth); - computeKnownBits(LHS, LHSKnown, 0, &CxtI); - - KnownBits RHSKnown(BitWidth); - computeKnownBits(RHS, RHSKnown, 0, &CxtI); - - // Check if carry bit of addition will not cause overflow. - if (checkRippleForAdd(LHSKnown, RHSKnown)) - return true; - - return false; -} - /// \brief Return true if we can prove that: /// (sub LHS, RHS) === (sub nsw LHS, RHS) /// This basically requires proving that the add in the original type would not @@ -968,13 +882,9 @@ bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS, bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction &CxtI) { // If the LHS is negative and the RHS is non-negative, no unsigned wrap. - bool LHSKnownNonNegative, LHSKnownNegative; - bool RHSKnownNonNegative, RHSKnownNegative; - ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0, - &CxtI); - ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0, - &CxtI); - if (LHSKnownNegative && RHSKnownNonNegative) + KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI); + KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI); + if (LHSKnown.isNegative() && RHSKnown.isNonNegative()) return true; return false; @@ -1041,6 +951,57 @@ static Value *checkForNegativeOperand(BinaryOperator &I, return nullptr; } +static Instruction *foldAddWithConstant(BinaryOperator &Add, + InstCombiner::BuilderTy &Builder) { + Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1); + const APInt *C; + if (!match(Op1, m_APInt(C))) + return nullptr; + + if (C->isSignMask()) { + // If wrapping is not allowed, then the addition must set the sign bit: + // X + (signmask) --> X | signmask + if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap()) + return BinaryOperator::CreateOr(Op0, Op1); + + // If wrapping is allowed, then the addition flips the sign bit of LHS: + // X + (signmask) --> X ^ signmask + return BinaryOperator::CreateXor(Op0, Op1); + } + + Value *X; + const APInt *C2; + Type *Ty = Add.getType(); + + // Is this add the last step in a convoluted sext? + // add(zext(xor i16 X, -32768), -32768) --> sext X + if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) && + C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C) + return CastInst::Create(Instruction::SExt, X, Ty); + + // (add (zext (add nuw X, C2)), C) --> (zext (add nuw X, C2 + C)) + // FIXME: This should check hasOneUse to not increase the instruction count? + if (C->isNegative() && + match(Op0, m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2)))) && + C->sge(-C2->sext(C->getBitWidth()))) { + Constant *NewC = + ConstantInt::get(X->getType(), *C2 + C->trunc(C2->getBitWidth())); + return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty); + } + + // Shifts and add used to flip and mask off the low bit: + // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1 + const APInt *C3; + if (*C == 1 && match(Op0, m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C2)), + m_APInt(C3)))) && + C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) { + Value *NotX = Builder.CreateNot(X); + return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1)); + } + + return nullptr; +} + Instruction *InstCombiner::visitAdd(BinaryOperator &I) { bool Changed = SimplifyAssociativeOrCommutative(I); Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); @@ -1056,41 +1017,11 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) { if (Value *V = SimplifyUsingDistributiveLaws(I)) return replaceInstUsesWith(I, V); - const APInt *RHSC; - if (match(RHS, m_APInt(RHSC))) { - if (RHSC->isSignMask()) { - // If wrapping is not allowed, then the addition must set the sign bit: - // X + (signmask) --> X | signmask - if (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) - return BinaryOperator::CreateOr(LHS, RHS); - - // If wrapping is allowed, then the addition flips the sign bit of LHS: - // X + (signmask) --> X ^ signmask - return BinaryOperator::CreateXor(LHS, RHS); - } - - // Is this add the last step in a convoluted sext? - Value *X; - const APInt *C; - if (match(LHS, m_ZExt(m_Xor(m_Value(X), m_APInt(C)))) && - C->isMinSignedValue() && - C->sext(LHS->getType()->getScalarSizeInBits()) == *RHSC) { - // add(zext(xor i16 X, -32768), -32768) --> sext X - return CastInst::Create(Instruction::SExt, X, LHS->getType()); - } - - if (RHSC->isNegative() && - match(LHS, m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C)))) && - RHSC->sge(-C->sext(RHSC->getBitWidth()))) { - // (add (zext (add nuw X, C)), Val) -> (zext (add nuw X, C+Val)) - Constant *NewC = - ConstantInt::get(X->getType(), *C + RHSC->trunc(C->getBitWidth())); - return new ZExtInst(Builder->CreateNUWAdd(X, NewC), I.getType()); - } - } + if (Instruction *X = foldAddWithConstant(I, *Builder)) + return X; - // FIXME: Use the match above instead of dyn_cast to allow these transforms - // for splat vectors. + // FIXME: This should be moved into the above helper function to allow these + // transforms for splat vectors. if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { // zext(bool) + C -> bool ? C + 1 : C if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS)) @@ -1285,8 +1216,7 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) { Constant *CI = ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType()); if (ConstantExpr::getZExt(CI, I.getType()) == RHSC && - computeOverflowForUnsignedAdd(LHSConv->getOperand(0), CI, &I) == - OverflowResult::NeverOverflows) { + willNotOverflowUnsignedAdd(LHSConv->getOperand(0), CI, I)) { // Insert the new, smaller add. Value *NewAdd = Builder->CreateNUWAdd(LHSConv->getOperand(0), CI, "addconv"); @@ -1303,9 +1233,8 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) { if (LHSConv->getOperand(0)->getType() == RHSConv->getOperand(0)->getType() && (LHSConv->hasOneUse() || RHSConv->hasOneUse()) && - computeOverflowForUnsignedAdd(LHSConv->getOperand(0), - RHSConv->getOperand(0), - &I) == OverflowResult::NeverOverflows) { + willNotOverflowUnsignedAdd(LHSConv->getOperand(0), + RHSConv->getOperand(0), I)) { // Insert the new integer add. Value *NewAdd = Builder->CreateNUWAdd( LHSConv->getOperand(0), RHSConv->getOperand(0), "addconv"); @@ -1347,15 +1276,13 @@ Instruction *InstCombiner::visitAdd(BinaryOperator &I) { } // TODO(jingyue): Consider WillNotOverflowSignedAdd and - // WillNotOverflowUnsignedAdd to reduce the number of invocations of + // willNotOverflowUnsignedAdd to reduce the number of invocations of // computeKnownBits. if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) { Changed = true; I.setHasNoSignedWrap(true); } - if (!I.hasNoUnsignedWrap() && - computeOverflowForUnsignedAdd(LHS, RHS, &I) == - OverflowResult::NeverOverflows) { + if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) { Changed = true; I.setHasNoUnsignedWrap(true); } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp index b114801cc1c0..82dc88f1b3ad 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp @@ -23,21 +23,6 @@ using namespace PatternMatch; #define DEBUG_TYPE "instcombine" -static inline Value *dyn_castNotVal(Value *V) { - // If this is not(not(x)) don't return that this is a not: we want the two - // not's to be folded first. - if (BinaryOperator::isNot(V)) { - Value *Operand = BinaryOperator::getNotArgument(V); - if (!IsFreeToInvert(Operand, Operand->hasOneUse())) - return Operand; - } - - // Constants can be considered to be not'ed values... - if (ConstantInt *C = dyn_cast<ConstantInt>(V)) - return ConstantInt::get(C->getType(), ~C->getValue()); - return nullptr; -} - /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into /// a four bit mask. static unsigned getFCmpCode(FCmpInst::Predicate CC) { @@ -713,9 +698,8 @@ Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, } // This simplification is only valid if the upper range is not negative. - bool IsNegative, IsNotNegative; - ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1); - if (!IsNotNegative) + KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1); + if (!Known.isNonNegative()) return nullptr; if (Inverted) @@ -1013,26 +997,22 @@ Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) { /// (~A & ~B) == (~(A | B)) /// (~A | ~B) == (~(A & B)) static Instruction *matchDeMorgansLaws(BinaryOperator &I, - InstCombiner::BuilderTy *Builder) { + InstCombiner::BuilderTy &Builder) { auto Opcode = I.getOpcode(); assert((Opcode == Instruction::And || Opcode == Instruction::Or) && "Trying to match De Morgan's Laws with something other than and/or"); + // Flip the logic operation. - if (Opcode == Instruction::And) - Opcode = Instruction::Or; - else - Opcode = Instruction::And; + Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And; - Value *Op0 = I.getOperand(0); - Value *Op1 = I.getOperand(1); - // TODO: Use pattern matchers instead of dyn_cast. - if (Value *Op0NotVal = dyn_castNotVal(Op0)) - if (Value *Op1NotVal = dyn_castNotVal(Op1)) - if (Op0->hasOneUse() && Op1->hasOneUse()) { - Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal, - I.getName() + ".demorgan"); - return BinaryOperator::CreateNot(LogicOp); - } + Value *A, *B; + if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) && + match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) && + !IsFreeToInvert(A, A->hasOneUse()) && + !IsFreeToInvert(B, B->hasOneUse())) { + Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan"); + return BinaryOperator::CreateNot(AndOr); + } return nullptr; } @@ -1376,7 +1356,7 @@ Instruction *InstCombiner::visitAnd(BinaryOperator &I) { if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I)) return FoldedLogic; - if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder)) + if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder)) return DeMorgan; { @@ -2005,18 +1985,6 @@ Instruction *InstCombiner::visitOr(BinaryOperator &I) { if (Value *V = SimplifyBSwap(I)) return replaceInstUsesWith(I, V); - if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { - ConstantInt *C1 = nullptr; Value *X = nullptr; - // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2) - if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && - Op0->hasOneUse()) { - Value *Or = Builder->CreateOr(X, RHS); - Or->takeName(Op0); - return BinaryOperator::CreateXor(Or, - Builder->getInt(C1->getValue() & ~RHS->getValue())); - } - } - if (isa<Constant>(Op1)) if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I)) return FoldedLogic; @@ -2167,7 +2135,7 @@ Instruction *InstCombiner::visitOr(BinaryOperator &I) { if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A)))) return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C)); - if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder)) + if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder)) return DeMorgan; // Canonicalize xor to the RHS. @@ -2399,27 +2367,44 @@ Instruction *InstCombiner::visitXor(BinaryOperator &I) { } // Is this a 'not' (~) fed by a binary operator? - BinaryOperator *NotOp; - if (match(&I, m_Not(m_BinOp(NotOp)))) { - if (NotOp->getOpcode() == Instruction::And || - NotOp->getOpcode() == Instruction::Or) { + BinaryOperator *NotVal; + if (match(&I, m_Not(m_BinOp(NotVal)))) { + if (NotVal->getOpcode() == Instruction::And || + NotVal->getOpcode() == Instruction::Or) { // Apply DeMorgan's Law when inverts are free: // ~(X & Y) --> (~X | ~Y) // ~(X | Y) --> (~X & ~Y) - if (IsFreeToInvert(NotOp->getOperand(0), - NotOp->getOperand(0)->hasOneUse()) && - IsFreeToInvert(NotOp->getOperand(1), - NotOp->getOperand(1)->hasOneUse())) { - Value *NotX = Builder->CreateNot(NotOp->getOperand(0), "notlhs"); - Value *NotY = Builder->CreateNot(NotOp->getOperand(1), "notrhs"); - if (NotOp->getOpcode() == Instruction::And) + if (IsFreeToInvert(NotVal->getOperand(0), + NotVal->getOperand(0)->hasOneUse()) && + IsFreeToInvert(NotVal->getOperand(1), + NotVal->getOperand(1)->hasOneUse())) { + Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs"); + Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs"); + if (NotVal->getOpcode() == Instruction::And) return BinaryOperator::CreateOr(NotX, NotY); return BinaryOperator::CreateAnd(NotX, NotY); } - } else if (NotOp->getOpcode() == Instruction::AShr) { - // ~(~X >>s Y) --> (X >>s Y) - if (Value *Op0NotVal = dyn_castNotVal(NotOp->getOperand(0))) - return BinaryOperator::CreateAShr(Op0NotVal, NotOp->getOperand(1)); + } + + // ~(~X >>s Y) --> (X >>s Y) + if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y)))) + return BinaryOperator::CreateAShr(X, Y); + + // If we are inverting a right-shifted constant, we may be able to eliminate + // the 'not' by inverting the constant and using the opposite shift type. + // Canonicalization rules ensure that only a negative constant uses 'ashr', + // but we must check that in case that transform has not fired yet. + const APInt *C; + if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) { + // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits) + Constant *NotC = ConstantInt::get(I.getType(), ~(*C)); + return BinaryOperator::CreateLShr(NotC, Y); + } + + if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) { + // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits) + Constant *NotC = ConstantInt::get(I.getType(), ~(*C)); + return BinaryOperator::CreateAShr(NotC, Y); } } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp index 6989d67f0060..face7abcc95f 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp @@ -1384,10 +1384,10 @@ static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) { // Create a mask for bits above (ctlz) or below (cttz) the first known one. bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz; - unsigned PossibleZeros = IsTZ ? Known.One.countTrailingZeros() - : Known.One.countLeadingZeros(); - unsigned DefiniteZeros = IsTZ ? Known.Zero.countTrailingOnes() - : Known.Zero.countLeadingOnes(); + unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros() + : Known.countMaxLeadingZeros(); + unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros() + : Known.countMinLeadingZeros(); // If all bits above (ctlz) or below (cttz) the first known one are known // zero, this value is constant. diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp index 312d9baae43a..001a4bcf16f3 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp @@ -559,6 +559,9 @@ Instruction *InstCombiner::visitTrunc(TruncInst &CI) { return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero); } + // FIXME: Maybe combine the next two transforms to handle the no cast case + // more efficiently. Support vector types. Cleanup code by using m_OneUse. + // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion. Value *A = nullptr; ConstantInt *Cst = nullptr; if (Src->hasOneUse() && @@ -588,15 +591,20 @@ Instruction *InstCombiner::visitTrunc(TruncInst &CI) { // the sign bit of the original value; performing ashr instead of lshr // generates bits of the same value as the sign bit. if (Src->hasOneUse() && - match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst))) && - cast<Instruction>(Src)->getOperand(0)->hasOneUse()) { + match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst)))) { + Value *SExt = cast<Instruction>(Src)->getOperand(0); + const unsigned SExtSize = SExt->getType()->getPrimitiveSizeInBits(); const unsigned ASize = A->getType()->getPrimitiveSizeInBits(); + unsigned ShiftAmt = Cst->getZExtValue(); // This optimization can be only performed when zero bits generated by // the original lshr aren't pulled into the value after truncation, so we - // can only shift by values smaller than the size of destination type (in - // bits). - if (Cst->getValue().ult(ASize)) { - Value *Shift = Builder->CreateAShr(A, Cst->getZExtValue()); + // can only shift by values no larger than the number of extension bits. + // FIXME: Instead of bailing when the shift is too large, use and to clear + // the extra bits. + if (SExt->hasOneUse() && ShiftAmt <= SExtSize - ASize) { + // If shifting by the size of the original value in bits or more, it is + // being filled with the sign bit, so shift by ASize-1 to avoid ub. + Value *Shift = Builder->CreateAShr(A, std::min(ShiftAmt, ASize-1)); Shift->takeName(Src); return CastInst::CreateIntegerCast(Shift, CI.getType(), true); } @@ -1180,9 +1188,8 @@ Instruction *InstCombiner::visitSExt(SExtInst &CI) { // If we know that the value being extended is positive, we can use a zext // instead. - bool KnownZero, KnownOne; - ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI); - if (KnownZero) { + KnownBits Known = computeKnownBits(Src, 0, &CI); + if (Known.isNonNegative()) { Value *ZExt = Builder->CreateZExt(Src, DestTy); return replaceInstUsesWith(CI, ZExt); } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp index 34ce235b3fe2..60ed4057cedd 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp @@ -2785,6 +2785,9 @@ Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) { } /// Try to fold icmp (binop), X or icmp X, (binop). +/// TODO: A large part of this logic is duplicated in InstSimplify's +/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code +/// duplication. Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); @@ -2794,7 +2797,7 @@ Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { if (!BO0 && !BO1) return nullptr; - CmpInst::Predicate Pred = I.getPredicate(); + const CmpInst::Predicate Pred = I.getPredicate(); bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; if (BO0 && isa<OverflowingBinaryOperator>(BO0)) NoOp0WrapProblem = @@ -3029,21 +3032,20 @@ Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { case Instruction::Sub: case Instruction::Xor: if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b - return new ICmpInst(I.getPredicate(), BO0->getOperand(0), - BO1->getOperand(0)); + return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { if (CI->getValue().isSignMask()) { - ICmpInst::Predicate Pred = + ICmpInst::Predicate NewPred = I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); - return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); + return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); } if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) { - ICmpInst::Predicate Pred = + ICmpInst::Predicate NewPred = I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); - Pred = I.getSwappedPredicate(Pred); - return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); + NewPred = I.getSwappedPredicate(NewPred); + return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); } } break; @@ -3062,21 +3064,27 @@ Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { AP.getBitWidth() - AP.countTrailingZeros())); Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask); Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask); - return new ICmpInst(I.getPredicate(), And1, And2); + return new ICmpInst(Pred, And1, And2); } } break; + case Instruction::UDiv: case Instruction::LShr: - if (I.isSigned()) + if (I.isSigned() || !BO0->isExact() || !BO1->isExact()) break; - LLVM_FALLTHROUGH; + return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); + case Instruction::SDiv: + if (!I.isEquality() || !BO0->isExact() || !BO1->isExact()) + break; + return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); + case Instruction::AShr: if (!BO0->isExact() || !BO1->isExact()) break; - return new ICmpInst(I.getPredicate(), BO0->getOperand(0), - BO1->getOperand(0)); + return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); + case Instruction::Shl: { bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); @@ -3084,8 +3092,7 @@ Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { break; if (!NSW && I.isSigned()) break; - return new ICmpInst(I.getPredicate(), BO0->getOperand(0), - BO1->getOperand(0)); + return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); } } } @@ -3096,7 +3103,7 @@ Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { auto BitwiseAnd = m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value())); - if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) { + if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) { auto *Zero = Constant::getNullValue(BO0->getType()); return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/contrib/llvm/lib/Transforms/InstCombine/InstCombineInternal.h index 3be6419a129a..1424f61fe701 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineInternal.h +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineInternal.h @@ -30,6 +30,7 @@ #include "llvm/IR/PatternMatch.h" #include "llvm/Pass.h" #include "llvm/Support/Dwarf.h" +#include "llvm/Support/KnownBits.h" #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" #include "llvm/Transforms/Utils/Local.h" @@ -388,10 +389,21 @@ private: bool DoTransform = true); Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI); - bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction &CxtI); + bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction &CxtI) { + return computeOverflowForSignedAdd(LHS, RHS, &CxtI) == + OverflowResult::NeverOverflows; + }; + bool willNotOverflowUnsignedAdd(Value *LHS, Value *RHS, Instruction &CxtI) { + return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) == + OverflowResult::NeverOverflows; + }; bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction &CxtI); bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction &CxtI); bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction &CxtI); + bool willNotOverflowUnsignedMul(Value *LHS, Value *RHS, Instruction &CxtI) { + return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) == + OverflowResult::NeverOverflows; + }; Value *EmitGEPOffset(User *GEP); Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN); Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask); @@ -492,7 +504,11 @@ public: void computeKnownBits(Value *V, KnownBits &Known, unsigned Depth, Instruction *CxtI) const { - return llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT); + llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT); + } + KnownBits computeKnownBits(Value *V, unsigned Depth, + Instruction *CxtI) const { + return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT); } bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0, @@ -503,11 +519,6 @@ public: Instruction *CxtI = nullptr) const { return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT); } - void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne, - unsigned Depth = 0, Instruction *CxtI = nullptr) const { - return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, &AC, CxtI, - &DT); - } OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS, const Instruction *CxtI) { return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT); @@ -516,6 +527,11 @@ public: const Instruction *CxtI) { return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT); } + OverflowResult computeOverflowForSignedAdd(const Value *LHS, + const Value *RHS, + const Instruction *CxtI) const { + return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT); + } /// Maximum size of array considered when transforming. uint64_t MaxArraySizeForCombine; diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp index 675553017838..a4d84ae81aa0 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp @@ -885,10 +885,8 @@ static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI, // first non-zero index. auto IsAllNonNegative = [&]() { for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) { - bool KnownNonNegative, KnownNegative; - IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative, - KnownNegative, 0, MemI); - if (KnownNonNegative) + KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI); + if (Known.isNonNegative()) continue; return false; } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp index face9d9237ae..2a35259f2103 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp @@ -162,11 +162,9 @@ bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS, // product is exactly the minimum negative number. // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000 // For simplicity we just check if at least one side is not negative. - bool LHSNonNegative, LHSNegative; - bool RHSNonNegative, RHSNegative; - ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI); - ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI); - if (LHSNonNegative || RHSNonNegative) + KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI); + KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI); + if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) return true; } return false; @@ -422,8 +420,7 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) { Constant *CI = ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType()); if (ConstantExpr::getZExt(CI, I.getType()) == Op1C && - computeOverflowForUnsignedMul(Op0Conv->getOperand(0), CI, &I) == - OverflowResult::NeverOverflows) { + willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) { // Insert the new, smaller mul. Value *NewMul = Builder->CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv"); @@ -440,9 +437,8 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) { if (Op0Conv->getOperand(0)->getType() == Op1Conv->getOperand(0)->getType() && (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) && - computeOverflowForUnsignedMul(Op0Conv->getOperand(0), - Op1Conv->getOperand(0), - &I) == OverflowResult::NeverOverflows) { + willNotOverflowUnsignedMul(Op0Conv->getOperand(0), + Op1Conv->getOperand(0), I)) { // Insert the new integer mul. Value *NewMul = Builder->CreateNUWMul( Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv"); @@ -456,9 +452,7 @@ Instruction *InstCombiner::visitMul(BinaryOperator &I) { I.setHasNoSignedWrap(true); } - if (!I.hasNoUnsignedWrap() && - computeOverflowForUnsignedMul(Op0, Op1, &I) == - OverflowResult::NeverOverflows) { + if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) { Changed = true; I.setHasNoUnsignedWrap(true); } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp index 05b01774cd5e..4028a92771a4 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp @@ -611,7 +611,7 @@ Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask, SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1)) return I; - unsigned Leaders = Known2.Zero.countLeadingOnes(); + unsigned Leaders = Known2.countMinLeadingZeros(); Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask; break; } diff --git a/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp index 1792cb585f87..65b1148cb03b 100644 --- a/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp +++ b/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp @@ -2212,9 +2212,9 @@ Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { // Canonicalize fcmp_one -> fcmp_oeq FCmpInst::Predicate FPred; Value *Y; - if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), - TrueDest, FalseDest)) && - BI.getCondition()->hasOneUse()) + if (match(&BI, m_Br(m_OneUse(m_FCmp(FPred, m_Value(X), m_Value(Y))), + TrueDest, FalseDest))) { + // TODO: Why are we only transforming these 3 predicates? if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || FPred == FCmpInst::FCMP_OGE) { FCmpInst *Cond = cast<FCmpInst>(BI.getCondition()); @@ -2225,12 +2225,12 @@ Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { Worklist.Add(Cond); return &BI; } + } // Canonicalize icmp_ne -> icmp_eq ICmpInst::Predicate IPred; - if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), - TrueDest, FalseDest)) && - BI.getCondition()->hasOneUse()) + if (match(&BI, m_Br(m_OneUse(m_ICmp(IPred, m_Value(X), m_Value(Y))), + TrueDest, FalseDest))) { if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || IPred == ICmpInst::ICMP_SGE) { @@ -2241,6 +2241,7 @@ Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { Worklist.Add(Cond); return &BI; } + } return nullptr; } @@ -2264,8 +2265,8 @@ Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth(); KnownBits Known(BitWidth); computeKnownBits(Cond, Known, 0, &SI); - unsigned LeadingKnownZeros = Known.Zero.countLeadingOnes(); - unsigned LeadingKnownOnes = Known.One.countLeadingOnes(); + unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); + unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); // Compute the number of leading bits we can ignore. // TODO: A better way to determine this would use ComputeNumSignBits(). @@ -3141,7 +3142,7 @@ combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, // Lower dbg.declare intrinsics otherwise their value may be clobbered // by instcombiner. - bool DbgDeclaresChanged = LowerDbgDeclare(F); + bool MadeIRChange = LowerDbgDeclare(F); // Iterate while there is work to do. int Iteration = 0; @@ -3150,18 +3151,17 @@ combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " << F.getName() << "\n"); - bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist); + MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines, AA, AC, TLI, DT, DL, LI); IC.MaxArraySizeForCombine = MaxArraySize; - Changed |= IC.run(); - if (!Changed) + if (!IC.run()) break; } - return DbgDeclaresChanged || Iteration > 1; + return MadeIRChange || Iteration > 1; } PreservedAnalyses InstCombinePass::run(Function &F, diff --git a/contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp index b034ccc46933..7eea44d6aca0 100644 --- a/contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp +++ b/contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp @@ -613,7 +613,15 @@ public: bool UseGlobalsGC = true) : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan), Recover(Recover || ClRecover), - UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC) {} + UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC), + // Not a typo: ClWithComdat is almost completely pointless without + // ClUseGlobalsGC (because then it only works on modules without + // globals, which are rare); it is a prerequisite for ClUseGlobalsGC; + // and both suffer from gold PR19002 for which UseGlobalsGC constructor + // argument is designed as workaround. Therefore, disable both + // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to + // do globals-gc. + UseCtorComdat(UseGlobalsGC && ClWithComdat) {} bool runOnModule(Module &M) override; static char ID; // Pass identification, replacement for typeid StringRef getPassName() const override { return "AddressSanitizerModule"; } @@ -656,6 +664,7 @@ private: bool CompileKernel; bool Recover; bool UseGlobalsGC; + bool UseCtorComdat; Type *IntptrTy; LLVMContext *C; Triple TargetTriple; @@ -1677,7 +1686,7 @@ AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer, : GlobalVariable::PrivateLinkage; GlobalVariable *Metadata = new GlobalVariable( M, Initializer->getType(), false, Linkage, Initializer, - Twine("__asan_global_") + GlobalValue::getRealLinkageName(OriginalName)); + Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName)); Metadata->setSection(getGlobalMetadataSection()); return Metadata; } @@ -1782,7 +1791,7 @@ void AddressSanitizerModule::InstrumentGlobalsMachO( // On recent Mach-O platforms, use a structure which binds the liveness of // the global variable to the metadata struct. Keep the list of "Liveness" GV // created to be added to llvm.compiler.used - StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr); + StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy); SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size()); for (size_t i = 0; i < ExtendedGlobals.size(); i++) { @@ -1793,9 +1802,9 @@ void AddressSanitizerModule::InstrumentGlobalsMachO( // On recent Mach-O platforms, we emit the global metadata in a way that // allows the linker to properly strip dead globals. - auto LivenessBinder = ConstantStruct::get( - LivenessTy, Initializer->getAggregateElement(0u), - ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr); + auto LivenessBinder = + ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u), + ConstantExpr::getPointerCast(Metadata, IntptrTy)); GlobalVariable *Liveness = new GlobalVariable( M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder, Twine("__asan_binder_") + G->getName()); @@ -1893,7 +1902,7 @@ bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool // We initialize an array of such structures and pass it to a run-time call. StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy, - IntptrTy, IntptrTy, IntptrTy, nullptr); + IntptrTy, IntptrTy, IntptrTy); SmallVector<GlobalVariable *, 16> NewGlobals(n); SmallVector<Constant *, 16> Initializers(n); @@ -1929,10 +1938,9 @@ bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0); Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize); - StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr); - Constant *NewInitializer = - ConstantStruct::get(NewTy, G->getInitializer(), - Constant::getNullValue(RightRedZoneTy), nullptr); + StructType *NewTy = StructType::get(Ty, RightRedZoneTy); + Constant *NewInitializer = ConstantStruct::get( + NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy)); // Create a new global variable with enough space for a redzone. GlobalValue::LinkageTypes Linkage = G->getLinkage(); @@ -2013,7 +2021,7 @@ bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool ConstantExpr::getPointerCast(Name, IntptrTy), ConstantExpr::getPointerCast(ModuleName, IntptrTy), ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, - ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr); + ConstantExpr::getPointerCast(ODRIndicator, IntptrTy)); if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true; @@ -2073,7 +2081,7 @@ bool AddressSanitizerModule::runOnModule(Module &M) { // Put the constructor and destructor in comdat if both // (1) global instrumentation is not TU-specific // (2) target is ELF. - if (ClWithComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) { + if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) { AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName)); appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority, AsanCtorFunction); diff --git a/contrib/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp b/contrib/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp index 8786781933ea..e2e3cbdbc295 100644 --- a/contrib/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp +++ b/contrib/llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp @@ -388,7 +388,7 @@ FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) { ArgTypes.push_back(ShadowPtrTy); Type *RetType = T->getReturnType(); if (!RetType->isVoidTy()) - RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr); + RetType = StructType::get(RetType, ShadowTy); return FunctionType::get(RetType, ArgTypes, T->isVarArg()); } @@ -476,16 +476,14 @@ bool DataFlowSanitizer::doInitialization(Module &M) { GetArgTLS = ConstantExpr::getIntToPtr( ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)), PointerType::getUnqual( - FunctionType::get(PointerType::getUnqual(ArgTLSTy), - (Type *)nullptr))); + FunctionType::get(PointerType::getUnqual(ArgTLSTy), false))); } if (GetRetvalTLSPtr) { RetvalTLS = nullptr; GetRetvalTLS = ConstantExpr::getIntToPtr( ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)), PointerType::getUnqual( - FunctionType::get(PointerType::getUnqual(ShadowTy), - (Type *)nullptr))); + FunctionType::get(PointerType::getUnqual(ShadowTy), false))); } ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000); diff --git a/contrib/llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp b/contrib/llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp index 7dea1dee756a..e89384c559fe 100644 --- a/contrib/llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp +++ b/contrib/llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp @@ -398,8 +398,8 @@ GlobalVariable *EfficiencySanitizer::createCacheFragInfoGV( // u64 *ArrayCounter; // }; auto *StructInfoTy = - StructType::get(Int8PtrTy, Int32Ty, Int32Ty, Int32PtrTy, Int32PtrTy, - Int8PtrPtrTy, Int64PtrTy, Int64PtrTy, nullptr); + StructType::get(Int8PtrTy, Int32Ty, Int32Ty, Int32PtrTy, Int32PtrTy, + Int8PtrPtrTy, Int64PtrTy, Int64PtrTy); auto *StructInfoPtrTy = StructInfoTy->getPointerTo(); // This structure should be kept consistent with the CacheFragInfo struct // in the runtime library. @@ -408,8 +408,7 @@ GlobalVariable *EfficiencySanitizer::createCacheFragInfoGV( // u32 NumStructs; // StructInfo *Structs; // }; - auto *CacheFragInfoTy = - StructType::get(Int8PtrTy, Int32Ty, StructInfoPtrTy, nullptr); + auto *CacheFragInfoTy = StructType::get(Int8PtrTy, Int32Ty, StructInfoPtrTy); std::vector<StructType *> Vec = M.getIdentifiedStructTypes(); unsigned NumStructs = 0; @@ -457,24 +456,23 @@ GlobalVariable *EfficiencySanitizer::createCacheFragInfoGV( ArrayCounterIdx[0] = ConstantInt::get(Int32Ty, 0); ArrayCounterIdx[1] = ConstantInt::get(Int32Ty, getArrayCounterIdx(StructTy)); - Initializers.push_back( - ConstantStruct::get( - StructInfoTy, - ConstantExpr::getPointerCast(StructCounterName, Int8PtrTy), - ConstantInt::get(Int32Ty, - DL.getStructLayout(StructTy)->getSizeInBytes()), - ConstantInt::get(Int32Ty, StructTy->getNumElements()), - Offset == nullptr ? ConstantPointerNull::get(Int32PtrTy) : - ConstantExpr::getPointerCast(Offset, Int32PtrTy), - Size == nullptr ? ConstantPointerNull::get(Int32PtrTy) : - ConstantExpr::getPointerCast(Size, Int32PtrTy), - TypeName == nullptr ? ConstantPointerNull::get(Int8PtrPtrTy) : - ConstantExpr::getPointerCast(TypeName, Int8PtrPtrTy), - ConstantExpr::getGetElementPtr(CounterArrayTy, Counters, - FieldCounterIdx), - ConstantExpr::getGetElementPtr(CounterArrayTy, Counters, - ArrayCounterIdx), - nullptr)); + Initializers.push_back(ConstantStruct::get( + StructInfoTy, + ConstantExpr::getPointerCast(StructCounterName, Int8PtrTy), + ConstantInt::get(Int32Ty, + DL.getStructLayout(StructTy)->getSizeInBytes()), + ConstantInt::get(Int32Ty, StructTy->getNumElements()), + Offset == nullptr ? ConstantPointerNull::get(Int32PtrTy) + : ConstantExpr::getPointerCast(Offset, Int32PtrTy), + Size == nullptr ? ConstantPointerNull::get(Int32PtrTy) + : ConstantExpr::getPointerCast(Size, Int32PtrTy), + TypeName == nullptr + ? ConstantPointerNull::get(Int8PtrPtrTy) + : ConstantExpr::getPointerCast(TypeName, Int8PtrPtrTy), + ConstantExpr::getGetElementPtr(CounterArrayTy, Counters, + FieldCounterIdx), + ConstantExpr::getGetElementPtr(CounterArrayTy, Counters, + ArrayCounterIdx))); } // Structs. Constant *StructInfo; @@ -491,11 +489,8 @@ GlobalVariable *EfficiencySanitizer::createCacheFragInfoGV( auto *CacheFragInfoGV = new GlobalVariable( M, CacheFragInfoTy, true, GlobalVariable::InternalLinkage, - ConstantStruct::get(CacheFragInfoTy, - UnitName, - ConstantInt::get(Int32Ty, NumStructs), - StructInfo, - nullptr)); + ConstantStruct::get(CacheFragInfoTy, UnitName, + ConstantInt::get(Int32Ty, NumStructs), StructInfo)); return CacheFragInfoGV; } diff --git a/contrib/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/contrib/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp index 15333a5317dd..ff753c20a94a 100644 --- a/contrib/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp +++ b/contrib/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp @@ -1576,13 +1576,16 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> { Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy, bool Signed = false) { Type *srcTy = V->getType(); + size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); + size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); + if (srcSizeInBits > 1 && dstSizeInBits == 1) + return IRB.CreateICmpNE(V, getCleanShadow(V)); + if (dstTy->isIntegerTy() && srcTy->isIntegerTy()) return IRB.CreateIntCast(V, dstTy, Signed); if (dstTy->isVectorTy() && srcTy->isVectorTy() && dstTy->getVectorNumElements() == srcTy->getVectorNumElements()) return IRB.CreateIntCast(V, dstTy, Signed); - size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); - size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits)); Value *V2 = IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed); diff --git a/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp b/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp index 3f1a77b49a44..ee493a8ec7e1 100644 --- a/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp +++ b/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp @@ -442,9 +442,8 @@ static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) { bool Changed = false; if (!NUW) { - ConstantRange NUWRange = - LRange.makeGuaranteedNoWrapRegion(BinaryOperator::Add, LRange, - OBO::NoUnsignedWrap); + ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion( + BinaryOperator::Add, LRange, OBO::NoUnsignedWrap); if (!NUWRange.isEmptySet()) { bool NewNUW = NUWRange.contains(LazyRRange()); AddOp->setHasNoUnsignedWrap(NewNUW); @@ -452,9 +451,8 @@ static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) { } } if (!NSW) { - ConstantRange NSWRange = - LRange.makeGuaranteedNoWrapRegion(BinaryOperator::Add, LRange, - OBO::NoSignedWrap); + ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion( + BinaryOperator::Add, LRange, OBO::NoSignedWrap); if (!NSWRange.isEmptySet()) { bool NewNSW = NSWRange.contains(LazyRRange()); AddOp->setHasNoSignedWrap(NewNSW); diff --git a/contrib/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp b/contrib/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp index 48d5ae88cda9..6693a26e8890 100644 --- a/contrib/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp +++ b/contrib/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp @@ -144,6 +144,10 @@ private: bool recognizePopcount(); void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, PHINode *CntPhi, Value *Var); + bool recognizeAndInsertCTLZ(); + void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst, + PHINode *CntPhi, Value *Var, const DebugLoc DL, + bool ZeroCheck, bool IsCntPhiUsedOutsideLoop); /// @} }; @@ -994,7 +998,7 @@ bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, } bool LoopIdiomRecognize::runOnNoncountableLoop() { - return recognizePopcount(); + return recognizePopcount() || recognizeAndInsertCTLZ(); } /// Check if the given conditional branch is based on the comparison between @@ -1159,6 +1163,167 @@ static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, return true; } +/// Return true if the idiom is detected in the loop. +/// +/// Additionally: +/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) +/// or nullptr if there is no such. +/// 2) \p CntPhi is set to the corresponding phi node +/// or nullptr if there is no such. +/// 3) \p Var is set to the value whose CTLZ could be used. +/// 4) \p DefX is set to the instruction calculating Loop exit condition. +/// +/// The core idiom we are trying to detect is: +/// \code +/// if (x0 == 0) +/// goto loop-exit // the precondition of the loop +/// cnt0 = init-val; +/// do { +/// x = phi (x0, x.next); //PhiX +/// cnt = phi(cnt0, cnt.next); +/// +/// cnt.next = cnt + 1; +/// ... +/// x.next = x >> 1; // DefX +/// ... +/// } while(x.next != 0); +/// +/// loop-exit: +/// \endcode +static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX, + Instruction *&CntInst, PHINode *&CntPhi, + Instruction *&DefX) { + BasicBlock *LoopEntry; + Value *VarX = nullptr; + + DefX = nullptr; + PhiX = nullptr; + CntInst = nullptr; + CntPhi = nullptr; + LoopEntry = *(CurLoop->block_begin()); + + // step 1: Check if the loop-back branch is in desirable form. + if (Value *T = matchCondition( + dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) + DefX = dyn_cast<Instruction>(T); + else + return false; + + // step 2: detect instructions corresponding to "x.next = x >> 1" + if (!DefX || DefX->getOpcode() != Instruction::AShr) + return false; + if (ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1))) + if (!Shft || !Shft->isOne()) + return false; + VarX = DefX->getOperand(0); + + // step 3: Check the recurrence of variable X + PhiX = dyn_cast<PHINode>(VarX); + if (!PhiX || (PhiX->getOperand(0) != DefX && PhiX->getOperand(1) != DefX)) + return false; + + // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 + // TODO: We can skip the step. If loop trip count is known (CTLZ), + // then all uses of "cnt.next" could be optimized to the trip count + // plus "cnt0". Currently it is not optimized. + // This step could be used to detect POPCNT instruction: + // cnt.next = cnt + (x.next & 1) + for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), + IterE = LoopEntry->end(); + Iter != IterE; Iter++) { + Instruction *Inst = &*Iter; + if (Inst->getOpcode() != Instruction::Add) + continue; + + ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); + if (!Inc || !Inc->isOne()) + continue; + + PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); + if (!Phi || Phi->getParent() != LoopEntry) + continue; + + CntInst = Inst; + CntPhi = Phi; + break; + } + if (!CntInst) + return false; + + return true; +} + +/// Recognize CTLZ idiom in a non-countable loop and convert the loop +/// to countable (with CTLZ trip count). +/// If CTLZ inserted as a new trip count returns true; otherwise, returns false. +bool LoopIdiomRecognize::recognizeAndInsertCTLZ() { + // Give up if the loop has multiple blocks or multiple backedges. + if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) + return false; + + Instruction *CntInst, *DefX; + PHINode *CntPhi, *PhiX; + if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX)) + return false; + + bool IsCntPhiUsedOutsideLoop = false; + for (User *U : CntPhi->users()) + if (!CurLoop->contains(dyn_cast<Instruction>(U))) { + IsCntPhiUsedOutsideLoop = true; + break; + } + bool IsCntInstUsedOutsideLoop = false; + for (User *U : CntInst->users()) + if (!CurLoop->contains(dyn_cast<Instruction>(U))) { + IsCntInstUsedOutsideLoop = true; + break; + } + // If both CntInst and CntPhi are used outside the loop the profitability + // is questionable. + if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) + return false; + + // For some CPUs result of CTLZ(X) intrinsic is undefined + // when X is 0. If we can not guarantee X != 0, we need to check this + // when expand. + bool ZeroCheck = false; + // It is safe to assume Preheader exist as it was checked in + // parent function RunOnLoop. + BasicBlock *PH = CurLoop->getLoopPreheader(); + Value *InitX = PhiX->getIncomingValueForBlock(PH); + // If we check X != 0 before entering the loop we don't need a zero + // check in CTLZ intrinsic. + if (BasicBlock *PreCondBB = PH->getSinglePredecessor()) + if (BranchInst *PreCondBr = + dyn_cast<BranchInst>(PreCondBB->getTerminator())) { + if (matchCondition(PreCondBr, PH) == InitX) + ZeroCheck = true; + } + + // Check if CTLZ intrinsic is profitable. Assume it is always profitable + // if we delete the loop (the loop has only 6 instructions): + // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] + // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] + // %shr = ashr %n.addr.0, 1 + // %tobool = icmp eq %shr, 0 + // %inc = add nsw %i.0, 1 + // br i1 %tobool + + IRBuilder<> Builder(PH->getTerminator()); + SmallVector<const Value *, 2> Ops = + {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()}; + ArrayRef<const Value *> Args(Ops); + if (CurLoop->getHeader()->size() != 6 && + TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) > + TargetTransformInfo::TCC_Basic) + return false; + + const DebugLoc DL = DefX->getDebugLoc(); + transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck, + IsCntPhiUsedOutsideLoop); + return true; +} + /// Recognizes a population count idiom in a non-countable loop. /// /// If detected, transforms the relevant code to issue the popcount intrinsic @@ -1222,6 +1387,134 @@ static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, return CI; } +static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val, + const DebugLoc &DL, bool ZeroCheck) { + Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()}; + Type *Tys[] = {Val->getType()}; + + Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); + Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys); + CallInst *CI = IRBuilder.CreateCall(Func, Ops); + CI->setDebugLoc(DL); + + return CI; +} + +/// Transform the following loop: +/// loop: +/// CntPhi = PHI [Cnt0, CntInst] +/// PhiX = PHI [InitX, DefX] +/// CntInst = CntPhi + 1 +/// DefX = PhiX >> 1 +// LOOP_BODY +/// Br: loop if (DefX != 0) +/// Use(CntPhi) or Use(CntInst) +/// +/// Into: +/// If CntPhi used outside the loop: +/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) +/// Count = CountPrev + 1 +/// else +/// Count = BitWidth(InitX) - CTLZ(InitX) +/// loop: +/// CntPhi = PHI [Cnt0, CntInst] +/// PhiX = PHI [InitX, DefX] +/// PhiCount = PHI [Count, Dec] +/// CntInst = CntPhi + 1 +/// DefX = PhiX >> 1 +/// Dec = PhiCount - 1 +/// LOOP_BODY +/// Br: loop if (Dec != 0) +/// Use(CountPrev + Cnt0) // Use(CntPhi) +/// or +/// Use(Count + Cnt0) // Use(CntInst) +/// +/// If LOOP_BODY is empty the loop will be deleted. +/// If CntInst and DefX are not used in LOOP_BODY they will be removed. +void LoopIdiomRecognize::transformLoopToCountable( + BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX, + const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { + BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator()); + + // Step 1: Insert the CTLZ instruction at the end of the preheader block + // Count = BitWidth - CTLZ(InitX); + // If there are uses of CntPhi create: + // CountPrev = BitWidth - CTLZ(InitX >> 1); + IRBuilder<> Builder(PreheaderBr); + Builder.SetCurrentDebugLocation(DL); + Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext; + + if (IsCntPhiUsedOutsideLoop) + InitXNext = Builder.CreateAShr(InitX, + ConstantInt::get(InitX->getType(), 1)); + else + InitXNext = InitX; + CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck); + Count = Builder.CreateSub( + ConstantInt::get(CTLZ->getType(), + CTLZ->getType()->getIntegerBitWidth()), + CTLZ); + if (IsCntPhiUsedOutsideLoop) { + CountPrev = Count; + Count = Builder.CreateAdd( + CountPrev, + ConstantInt::get(CountPrev->getType(), 1)); + } + if (IsCntPhiUsedOutsideLoop) + NewCount = Builder.CreateZExtOrTrunc(CountPrev, + cast<IntegerType>(CntInst->getType())); + else + NewCount = Builder.CreateZExtOrTrunc(Count, + cast<IntegerType>(CntInst->getType())); + + // If the CTLZ counter's initial value is not zero, insert Add Inst. + Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); + ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); + if (!InitConst || !InitConst->isZero()) + NewCount = Builder.CreateAdd(NewCount, CntInitVal); + + // Step 2: Insert new IV and loop condition: + // loop: + // ... + // PhiCount = PHI [Count, Dec] + // ... + // Dec = PhiCount - 1 + // ... + // Br: loop if (Dec != 0) + BasicBlock *Body = *(CurLoop->block_begin()); + auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); + ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); + Type *Ty = Count->getType(); + + PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); + + Builder.SetInsertPoint(LbCond); + Instruction *TcDec = cast<Instruction>( + Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), + "tcdec", false, true)); + + TcPhi->addIncoming(Count, Preheader); + TcPhi->addIncoming(TcDec, Body); + + CmpInst::Predicate Pred = + (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; + LbCond->setPredicate(Pred); + LbCond->setOperand(0, TcDec); + LbCond->setOperand(1, ConstantInt::get(Ty, 0)); + + // Step 3: All the references to the original counter outside + // the loop are replaced with the NewCount -- the value returned from + // __builtin_ctlz(x). + if (IsCntPhiUsedOutsideLoop) + CntPhi->replaceUsesOutsideBlock(NewCount, Body); + else + CntInst->replaceUsesOutsideBlock(NewCount, Body); + + // step 4: Forget the "non-computable" trip-count SCEV associated with the + // loop. The loop would otherwise not be deleted even if it becomes empty. + SE->forgetLoop(CurLoop); +} + void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, PHINode *CntPhi, Value *Var) { diff --git a/contrib/llvm/lib/Transforms/Scalar/NewGVN.cpp b/contrib/llvm/lib/Transforms/Scalar/NewGVN.cpp index 3c9850b156ac..5e0a705782ea 100644 --- a/contrib/llvm/lib/Transforms/Scalar/NewGVN.cpp +++ b/contrib/llvm/lib/Transforms/Scalar/NewGVN.cpp @@ -283,7 +283,6 @@ public: // Forward propagation info const Expression *getDefiningExpr() const { return DefiningExpr; } - void setDefiningExpr(const Expression *E) { DefiningExpr = E; } // Value member set bool empty() const { return Members.empty(); } @@ -317,6 +316,9 @@ public: --StoreCount; } + // True if this class has no memory members. + bool definesNoMemory() const { return StoreCount == 0 && memory_empty(); } + // Return true if two congruence classes are equivalent to each other. This // means // that every field but the ID number and the dead field are equivalent. @@ -401,9 +403,12 @@ class NewGVN { MemorySSAWalker *MSSAWalker; const DataLayout &DL; std::unique_ptr<PredicateInfo> PredInfo; - BumpPtrAllocator ExpressionAllocator; - ArrayRecycler<Value *> ArgRecycler; - TarjanSCC SCCFinder; + + // These are the only two things the create* functions should have + // side-effects on due to allocating memory. + mutable BumpPtrAllocator ExpressionAllocator; + mutable ArrayRecycler<Value *> ArgRecycler; + mutable TarjanSCC SCCFinder; const SimplifyQuery SQ; // Number of function arguments, used by ranking @@ -430,11 +435,12 @@ class NewGVN { // In order to correctly ensure propagation, we must keep track of what // comparisons we used, so that when the values of the comparisons change, we // propagate the information to the places we used the comparison. - DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers; - // Mapping from MemoryAccess we used to the MemoryAccess we used it with. Has + mutable DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> + PredicateToUsers; // the same reasoning as PredicateToUsers. When we skip MemoryAccesses for // stores, we no longer can rely solely on the def-use chains of MemorySSA. - DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>> MemoryToUsers; + mutable DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>> + MemoryToUsers; // A table storing which memorydefs/phis represent a memory state provably // equivalent to another memory state. @@ -457,7 +463,7 @@ class NewGVN { DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState; enum PhiCycleState { PCS_Unknown, PCS_CycleFree, PCS_Cycle }; - DenseMap<const PHINode *, PhiCycleState> PhiCycleState; + mutable DenseMap<const PHINode *, PhiCycleState> PhiCycleState; // Expression to class mapping. using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>; ExpressionClassMap ExpressionToClass; @@ -511,21 +517,24 @@ public: private: // Expression handling. - const Expression *createExpression(Instruction *); - const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *); - PHIExpression *createPHIExpression(Instruction *, bool &HasBackedge, - bool &AllConstant); - const VariableExpression *createVariableExpression(Value *); - const ConstantExpression *createConstantExpression(Constant *); - const Expression *createVariableOrConstant(Value *V); - const UnknownExpression *createUnknownExpression(Instruction *); + const Expression *createExpression(Instruction *) const; + const Expression *createBinaryExpression(unsigned, Type *, Value *, + Value *) const; + PHIExpression *createPHIExpression(Instruction *, bool &HasBackEdge, + bool &AllConstant) const; + const VariableExpression *createVariableExpression(Value *) const; + const ConstantExpression *createConstantExpression(Constant *) const; + const Expression *createVariableOrConstant(Value *V) const; + const UnknownExpression *createUnknownExpression(Instruction *) const; const StoreExpression *createStoreExpression(StoreInst *, - const MemoryAccess *); + const MemoryAccess *) const; LoadExpression *createLoadExpression(Type *, Value *, LoadInst *, - const MemoryAccess *); - const CallExpression *createCallExpression(CallInst *, const MemoryAccess *); - const AggregateValueExpression *createAggregateValueExpression(Instruction *); - bool setBasicExpressionInfo(Instruction *, BasicExpression *); + const MemoryAccess *) const; + const CallExpression *createCallExpression(CallInst *, + const MemoryAccess *) const; + const AggregateValueExpression * + createAggregateValueExpression(Instruction *) const; + bool setBasicExpressionInfo(Instruction *, BasicExpression *) const; // Congruence class handling. CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) { @@ -560,17 +569,18 @@ private: // Symbolic evaluation. const Expression *checkSimplificationResults(Expression *, Instruction *, - Value *); - const Expression *performSymbolicEvaluation(Value *); + Value *) const; + const Expression *performSymbolicEvaluation(Value *) const; const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *, - Instruction *, MemoryAccess *); - const Expression *performSymbolicLoadEvaluation(Instruction *); - const Expression *performSymbolicStoreEvaluation(Instruction *); - const Expression *performSymbolicCallEvaluation(Instruction *); - const Expression *performSymbolicPHIEvaluation(Instruction *); - const Expression *performSymbolicAggrValueEvaluation(Instruction *); - const Expression *performSymbolicCmpEvaluation(Instruction *); - const Expression *performSymbolicPredicateInfoEvaluation(Instruction *); + Instruction *, + MemoryAccess *) const; + const Expression *performSymbolicLoadEvaluation(Instruction *) const; + const Expression *performSymbolicStoreEvaluation(Instruction *) const; + const Expression *performSymbolicCallEvaluation(Instruction *) const; + const Expression *performSymbolicPHIEvaluation(Instruction *) const; + const Expression *performSymbolicAggrValueEvaluation(Instruction *) const; + const Expression *performSymbolicCmpEvaluation(Instruction *) const; + const Expression *performSymbolicPredicateInfoEvaluation(Instruction *) const; // Congruence finding. bool someEquivalentDominates(const Instruction *, const Instruction *) const; @@ -620,8 +630,8 @@ private: void markPredicateUsersTouched(Instruction *); void markValueLeaderChangeTouched(CongruenceClass *CC); void markMemoryLeaderChangeTouched(CongruenceClass *CC); - void addPredicateUsers(const PredicateBase *, Instruction *); - void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U); + void addPredicateUsers(const PredicateBase *, Instruction *) const; + void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const; // Main loop of value numbering void iterateTouchedInstructions(); @@ -634,7 +644,7 @@ private: void verifyIterationSettled(Function &F); bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const; BasicBlock *getBlockForValue(Value *V) const; - void deleteExpression(const Expression *E); + void deleteExpression(const Expression *E) const; unsigned InstrToDFSNum(const Value *V) const { assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses"); return InstrDFS.lookup(V); @@ -654,7 +664,7 @@ private: ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst()) : InstrDFS.lookup(MA); } - bool isCycleFree(const PHINode *PN); + bool isCycleFree(const PHINode *PN) const; template <class T, class Range> T *getMinDFSOfRange(const Range &) const; // Debug counter info. When verifying, we have to reset the value numbering // debug counter to the same state it started in to get the same results. @@ -702,7 +712,7 @@ BasicBlock *NewGVN::getBlockForValue(Value *V) const { // Delete a definitely dead expression, so it can be reused by the expression // allocator. Some of these are not in creation functions, so we have to accept // const versions. -void NewGVN::deleteExpression(const Expression *E) { +void NewGVN::deleteExpression(const Expression *E) const { assert(isa<BasicExpression>(E)); auto *BE = cast<BasicExpression>(E); const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler); @@ -710,7 +720,7 @@ void NewGVN::deleteExpression(const Expression *E) { } PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge, - bool &AllConstant) { + bool &AllConstant) const { BasicBlock *PHIBlock = I->getParent(); auto *PN = cast<PHINode>(I); auto *E = @@ -722,30 +732,46 @@ PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge, unsigned PHIRPO = RPOOrdering.lookup(DT->getNode(PHIBlock)); + // NewGVN assumes the operands of a PHI node are in a consistent order across + // PHIs. LLVM doesn't seem to always guarantee this. While we need to fix + // this in LLVM at some point we don't want GVN to find wrong congruences. + // Therefore, here we sort uses in predecessor order. + // We're sorting the values by pointer. In theory this might be cause of + // non-determinism, but here we don't rely on the ordering for anything + // significant, e.g. we don't create new instructions based on it so we're + // fine. + SmallVector<const Use *, 4> PHIOperands; + for (const Use &U : PN->operands()) + PHIOperands.push_back(&U); + std::sort(PHIOperands.begin(), PHIOperands.end(), + [&](const Use *U1, const Use *U2) { + return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2); + }); + // Filter out unreachable phi operands. - auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) { - return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock}); + auto Filtered = make_filter_range(PHIOperands, [&](const Use *U) { + return ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}); }); std::transform(Filtered.begin(), Filtered.end(), op_inserter(E), - [&](const Use &U) -> Value * { - auto *BB = PN->getIncomingBlock(U); + [&](const Use *U) -> Value * { + auto *BB = PN->getIncomingBlock(*U); auto *DTN = DT->getNode(BB); if (RPOOrdering.lookup(DTN) >= PHIRPO) HasBackedge = true; - AllConstant &= isa<UndefValue>(U) || isa<Constant>(U); + AllConstant &= isa<UndefValue>(*U) || isa<Constant>(*U); // Don't try to transform self-defined phis. - if (U == PN) + if (*U == PN) return PN; - return lookupOperandLeader(U); + return lookupOperandLeader(*U); }); return E; } // Set basic expression info (Arguments, type, opcode) for Expression // E from Instruction I in block B. -bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) { +bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) const { bool AllConstant = true; if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) E->setType(GEP->getSourceElementType()); @@ -766,7 +792,8 @@ bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) { } const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T, - Value *Arg1, Value *Arg2) { + Value *Arg1, + Value *Arg2) const { auto *E = new (ExpressionAllocator) BasicExpression(2); E->setType(T); @@ -795,7 +822,8 @@ const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T, // TODO: Once finished, this should not take an Instruction, we only // use it for printing. const Expression *NewGVN::checkSimplificationResults(Expression *E, - Instruction *I, Value *V) { + Instruction *I, + Value *V) const { if (!V) return nullptr; if (auto *C = dyn_cast<Constant>(V)) { @@ -827,7 +855,7 @@ const Expression *NewGVN::checkSimplificationResults(Expression *E, return nullptr; } -const Expression *NewGVN::createExpression(Instruction *I) { +const Expression *NewGVN::createExpression(Instruction *I) const { auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands()); bool AllConstant = setBasicExpressionInfo(I, E); @@ -913,7 +941,7 @@ const Expression *NewGVN::createExpression(Instruction *I) { } const AggregateValueExpression * -NewGVN::createAggregateValueExpression(Instruction *I) { +NewGVN::createAggregateValueExpression(Instruction *I) const { if (auto *II = dyn_cast<InsertValueInst>(I)) { auto *E = new (ExpressionAllocator) AggregateValueExpression(I->getNumOperands(), II->getNumIndices()); @@ -932,32 +960,32 @@ NewGVN::createAggregateValueExpression(Instruction *I) { llvm_unreachable("Unhandled type of aggregate value operation"); } -const VariableExpression *NewGVN::createVariableExpression(Value *V) { +const VariableExpression *NewGVN::createVariableExpression(Value *V) const { auto *E = new (ExpressionAllocator) VariableExpression(V); E->setOpcode(V->getValueID()); return E; } -const Expression *NewGVN::createVariableOrConstant(Value *V) { +const Expression *NewGVN::createVariableOrConstant(Value *V) const { if (auto *C = dyn_cast<Constant>(V)) return createConstantExpression(C); return createVariableExpression(V); } -const ConstantExpression *NewGVN::createConstantExpression(Constant *C) { +const ConstantExpression *NewGVN::createConstantExpression(Constant *C) const { auto *E = new (ExpressionAllocator) ConstantExpression(C); E->setOpcode(C->getValueID()); return E; } -const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) { +const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) const { auto *E = new (ExpressionAllocator) UnknownExpression(I); E->setOpcode(I->getOpcode()); return E; } -const CallExpression *NewGVN::createCallExpression(CallInst *CI, - const MemoryAccess *MA) { +const CallExpression * +NewGVN::createCallExpression(CallInst *CI, const MemoryAccess *MA) const { // FIXME: Add operand bundles for calls. auto *E = new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA); @@ -1017,9 +1045,8 @@ Value *NewGVN::lookupOperandLeader(Value *V) const { const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const { auto *CC = getMemoryClass(MA); assert(CC->getMemoryLeader() && - "Every MemoryAccess should be mapped to a " - "congruence class with a represenative memory " - "access"); + "Every MemoryAccess should be mapped to a congruence class with a " + "representative memory access"); return CC->getMemoryLeader(); } @@ -1032,7 +1059,7 @@ bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const { LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp, LoadInst *LI, - const MemoryAccess *MA) { + const MemoryAccess *MA) const { auto *E = new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA)); E->allocateOperands(ArgRecycler, ExpressionAllocator); @@ -1050,8 +1077,8 @@ LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp, return E; } -const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI, - const MemoryAccess *MA) { +const StoreExpression * +NewGVN::createStoreExpression(StoreInst *SI, const MemoryAccess *MA) const { auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand()); auto *E = new (ExpressionAllocator) StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA); @@ -1068,7 +1095,7 @@ const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI, return E; } -const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) { +const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) const { // Unlike loads, we never try to eliminate stores, so we do not check if they // are simple and avoid value numbering them. auto *SI = cast<StoreInst>(I); @@ -1126,7 +1153,7 @@ const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) { const Expression * NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr, LoadInst *LI, Instruction *DepInst, - MemoryAccess *DefiningAccess) { + MemoryAccess *DefiningAccess) const { assert((!LI || LI->isSimple()) && "Not a simple load"); if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) { // Can't forward from non-atomic to atomic without violating memory model. @@ -1201,7 +1228,7 @@ NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr, return nullptr; } -const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) { +const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) const { auto *LI = cast<LoadInst>(I); // We can eliminate in favor of non-simple loads, but we won't be able to @@ -1239,7 +1266,7 @@ const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) { } const Expression * -NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) { +NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) const { auto *PI = PredInfo->getPredicateInfoFor(I); if (!PI) return nullptr; @@ -1284,7 +1311,7 @@ NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) { return nullptr; if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) { - DEBUG(dbgs() << "Copy is not of any condition operands!"); + DEBUG(dbgs() << "Copy is not of any condition operands!\n"); return nullptr; } Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0)); @@ -1329,7 +1356,7 @@ NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) { } // Evaluate read only and pure calls, and create an expression result. -const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) { +const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) const { auto *CI = cast<CallInst>(I); if (auto *II = dyn_cast<IntrinsicInst>(I)) { // Instrinsics with the returned attribute are copies of arguments. @@ -1366,8 +1393,7 @@ bool NewGVN::setMemoryClass(const MemoryAccess *From, DEBUG(dbgs() << "Setting " << *From); DEBUG(dbgs() << " equivalent to congruence class "); DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader "); - DEBUG(dbgs() << *NewClass->getMemoryLeader()); - DEBUG(dbgs() << "\n"); + DEBUG(dbgs() << *NewClass->getMemoryLeader() << "\n"); auto LookupResult = MemoryAccessToClass.find(From); bool Changed = false; @@ -1381,7 +1407,7 @@ bool NewGVN::setMemoryClass(const MemoryAccess *From, NewClass->memory_insert(MP); // This may have killed the class if it had no non-memory members if (OldClass->getMemoryLeader() == From) { - if (OldClass->memory_empty()) { + if (OldClass->definesNoMemory()) { OldClass->setMemoryLeader(nullptr); } else { OldClass->setMemoryLeader(getNextMemoryLeader(OldClass)); @@ -1406,7 +1432,7 @@ bool NewGVN::setMemoryClass(const MemoryAccess *From, // Determine if a phi is cycle-free. That means the values in the phi don't // depend on any expressions that can change value as a result of the phi. // For example, a non-cycle free phi would be v = phi(0, v+1). -bool NewGVN::isCycleFree(const PHINode *PN) { +bool NewGVN::isCycleFree(const PHINode *PN) const { // In order to compute cycle-freeness, we do SCC finding on the phi, and see // what kind of SCC it ends up in. If it is a singleton, it is cycle-free. // If it is not in a singleton, it is only cycle free if the other members are @@ -1436,7 +1462,7 @@ bool NewGVN::isCycleFree(const PHINode *PN) { } // Evaluate PHI nodes symbolically, and create an expression result. -const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) { +const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) const { // True if one of the incoming phi edges is a backedge. bool HasBackedge = false; // All constant tracks the state of whether all the *original* phi operands @@ -1510,7 +1536,8 @@ const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) { return E; } -const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) { +const Expression * +NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) const { if (auto *EI = dyn_cast<ExtractValueInst>(I)) { auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand()); if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) { @@ -1548,7 +1575,7 @@ const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) { return createAggregateValueExpression(I); } -const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) { +const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) const { auto *CI = dyn_cast<CmpInst>(I); // See if our operands are equal to those of a previous predicate, and if so, // if it implies true or false. @@ -1663,7 +1690,7 @@ const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) { } // Substitute and symbolize the value before value numbering. -const Expression *NewGVN::performSymbolicEvaluation(Value *V) { +const Expression *NewGVN::performSymbolicEvaluation(Value *V) const { const Expression *E = nullptr; if (auto *C = dyn_cast<Constant>(V)) E = createConstantExpression(C); @@ -1749,7 +1776,7 @@ void NewGVN::markUsersTouched(Value *V) { } } -void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) { +void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) const { DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n"); MemoryToUsers[To].insert(U); } @@ -1772,7 +1799,7 @@ void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) { } // Add I to the set of users of a given predicate. -void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) { +void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) const { if (auto *PBranch = dyn_cast<PredicateBranch>(PB)) PredicateToUsers[PBranch->Condition].insert(I); else if (auto *PAssume = dyn_cast<PredicateBranch>(PB)) @@ -1825,8 +1852,7 @@ const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const { // TODO: If this ends up to slow, we can maintain a next memory leader like we // do for regular leaders. // Make sure there will be a leader to find - assert((CC->getStoreCount() > 0 || !CC->memory_empty()) && - "Can't get next leader if there is none"); + assert(!CC->definesNoMemory() && "Can't get next leader if there is none"); if (CC->getStoreCount() > 0) { if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first)) return MSSA->getMemoryAccess(NL); @@ -1898,7 +1924,7 @@ void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I, setMemoryClass(InstMA, NewClass); // Now, fixup the old class if necessary if (OldClass->getMemoryLeader() == InstMA) { - if (OldClass->getStoreCount() != 0 || !OldClass->memory_empty()) { + if (!OldClass->definesNoMemory()) { OldClass->setMemoryLeader(getNextMemoryLeader(OldClass)); DEBUG(dbgs() << "Memory class leader change for class " << OldClass->getID() << " to " @@ -1956,10 +1982,9 @@ void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E, if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) { // If it's a store expression we are using, it means we are not equivalent // to something earlier. - if (isa<StoreExpression>(E)) { - assert(lookupOperandLeader(SI->getValueOperand()) != - NewClass->getLeader()); - NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand())); + if (auto *SE = dyn_cast<StoreExpression>(E)) { + assert(SE->getStoredValue() != NewClass->getLeader()); + NewClass->setStoredValue(SE->getStoredValue()); markValueLeaderChangeTouched(NewClass); // Shift the new class leader to be the store DEBUG(dbgs() << "Changing leader of congruence class " @@ -1985,7 +2010,7 @@ void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E, // See if we destroyed the class or need to swap leaders. if (OldClass->empty() && OldClass != TOPClass) { if (OldClass->getDefiningExpr()) { - DEBUG(dbgs() << "Erasing expression " << OldClass->getDefiningExpr() + DEBUG(dbgs() << "Erasing expression " << *OldClass->getDefiningExpr() << " from table\n"); ExpressionToClass.erase(OldClass->getDefiningExpr()); } @@ -2064,7 +2089,7 @@ void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) { } else if (const auto *SE = dyn_cast<StoreExpression>(E)) { StoreInst *SI = SE->getStoreInst(); NewClass->setLeader(SI); - NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand())); + NewClass->setStoredValue(SE->getStoredValue()); // The RepMemoryAccess field will be filled in properly by the // moveValueToNewCongruenceClass call. } else { @@ -2523,6 +2548,19 @@ void NewGVN::verifyMemoryCongruency() const { return false; if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first)) return !isInstructionTriviallyDead(MemDef->getMemoryInst()); + + // We could have phi nodes which operands are all trivially dead, + // so we don't process them. + if (auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) { + for (auto &U : MemPHI->incoming_values()) { + if (Instruction *I = dyn_cast<Instruction>(U.get())) { + if (!isInstructionTriviallyDead(I)) + return true; + } + } + return false; + } + return true; }; diff --git a/contrib/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp b/contrib/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp index fb1b47c48276..4f608c97147d 100644 --- a/contrib/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp +++ b/contrib/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp @@ -55,7 +55,7 @@ static void replaceLoopUsesWithConstant(Loop &L, Value &LIC, /// Update the dominator tree after removing one exiting predecessor of a loop /// exit block. static void updateLoopExitIDom(BasicBlock *LoopExitBB, Loop &L, - DominatorTree &DT) { + DominatorTree &DT) { assert(pred_begin(LoopExitBB) != pred_end(LoopExitBB) && "Cannot have empty predecessors of the loop exit block if we split " "off a block to unswitch!"); @@ -137,6 +137,98 @@ static void updateDTAfterUnswitch(BasicBlock *UnswitchedBB, BasicBlock *OldPH, } } +/// Check that all the LCSSA PHI nodes in the loop exit block have trivial +/// incoming values along this edge. +static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, + BasicBlock &ExitBB) { + for (Instruction &I : ExitBB) { + auto *PN = dyn_cast<PHINode>(&I); + if (!PN) + // No more PHIs to check. + return true; + + // If the incoming value for this edge isn't loop invariant the unswitch + // won't be trivial. + if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) + return false; + } + llvm_unreachable("Basic blocks should never be empty!"); +} + +/// Rewrite the PHI nodes in an unswitched loop exit basic block. +/// +/// Requires that the loop exit and unswitched basic block are the same, and +/// that the exiting block was a unique predecessor of that block. Rewrites the +/// PHI nodes in that block such that what were LCSSA PHI nodes become trivial +/// PHI nodes from the old preheader that now contains the unswitched +/// terminator. +static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, + BasicBlock &OldExitingBB, + BasicBlock &OldPH) { + for (Instruction &I : UnswitchedBB) { + auto *PN = dyn_cast<PHINode>(&I); + if (!PN) + // No more PHIs to check. + break; + + // When the loop exit is directly unswitched we just need to update the + // incoming basic block. We loop to handle weird cases with repeated + // incoming blocks, but expect to typically only have one operand here. + for (auto i : llvm::seq<int>(0, PN->getNumOperands())) { + assert(PN->getIncomingBlock(i) == &OldExitingBB && + "Found incoming block different from unique predecessor!"); + PN->setIncomingBlock(i, &OldPH); + } + } +} + +/// Rewrite the PHI nodes in the loop exit basic block and the split off +/// unswitched block. +/// +/// Because the exit block remains an exit from the loop, this rewrites the +/// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI +/// nodes into the unswitched basic block to select between the value in the +/// old preheader and the loop exit. +static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, + BasicBlock &UnswitchedBB, + BasicBlock &OldExitingBB, + BasicBlock &OldPH) { + assert(&ExitBB != &UnswitchedBB && + "Must have different loop exit and unswitched blocks!"); + Instruction *InsertPt = &*UnswitchedBB.begin(); + for (Instruction &I : ExitBB) { + auto *PN = dyn_cast<PHINode>(&I); + if (!PN) + // No more PHIs to check. + break; + + auto *NewPN = PHINode::Create(PN->getType(), /*NumReservedValues*/ 2, + PN->getName() + ".split", InsertPt); + + // Walk backwards over the old PHI node's inputs to minimize the cost of + // removing each one. We have to do this weird loop manually so that we + // create the same number of new incoming edges in the new PHI as we expect + // each case-based edge to be included in the unswitched switch in some + // cases. + // FIXME: This is really, really gross. It would be much cleaner if LLVM + // allowed us to create a single entry for a predecessor block without + // having separate entries for each "edge" even though these edges are + // required to produce identical results. + for (int i = PN->getNumIncomingValues() - 1; i >= 0; --i) { + if (PN->getIncomingBlock(i) != &OldExitingBB) + continue; + + Value *Incoming = PN->removeIncomingValue(i); + NewPN->addIncoming(Incoming, &OldPH); + } + + // Now replace the old PHI with the new one and wire the old one in as an + // input to the new one. + PN->replaceAllUsesWith(NewPN); + NewPN->addIncoming(PN, &ExitBB); + } +} + /// Unswitch a trivial branch if the condition is loop invariant. /// /// This routine should only be called when loop code leading to the branch has @@ -187,10 +279,8 @@ static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, assert(L.contains(ContinueBB) && "Cannot have both successors exit and still be in the loop!"); - // If the loop exit block contains phi nodes, this isn't trivial. - // FIXME: We should examine the PHI to determine whether or not we can handle - // it trivially. - if (isa<PHINode>(LoopExitBB->begin())) + auto *ParentBB = BI.getParent(); + if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) return false; DEBUG(dbgs() << " unswitching trivial branch when: " << CondVal @@ -209,14 +299,13 @@ static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, BasicBlock *UnswitchedBB; if (BasicBlock *PredBB = LoopExitBB->getUniquePredecessor()) { (void)PredBB; - assert(PredBB == BI.getParent() && "A branch's parent is't a predecessor!"); + assert(PredBB == BI.getParent() && + "A branch's parent isn't a predecessor!"); UnswitchedBB = LoopExitBB; } else { UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI); } - BasicBlock *ParentBB = BI.getParent(); - // Now splice the branch to gate reaching the new preheader and re-point its // successors. OldPH->getInstList().splice(std::prev(OldPH->end()), @@ -229,6 +318,13 @@ static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, // terminator. BranchInst::Create(ContinueBB, ParentBB); + // Rewrite the relevant PHI nodes. + if (UnswitchedBB == LoopExitBB) + rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH); + else + rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB, + *ParentBB, *OldPH); + // Now we need to update the dominator tree. updateDTAfterUnswitch(UnswitchedBB, OldPH, DT); // But if we split something off of the loop exit block then we also removed @@ -278,6 +374,8 @@ static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, if (!L.isLoopInvariant(LoopCond)) return false; + auto *ParentBB = SI.getParent(); + // FIXME: We should compute this once at the start and update it! SmallVector<BasicBlock *, 16> ExitBlocks; L.getExitBlocks(ExitBlocks); @@ -287,12 +385,13 @@ static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, SmallVector<int, 4> ExitCaseIndices; for (auto Case : SI.cases()) { auto *SuccBB = Case.getCaseSuccessor(); - if (ExitBlockSet.count(SuccBB) && !isa<PHINode>(SuccBB->begin())) + if (ExitBlockSet.count(SuccBB) && + areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB)) ExitCaseIndices.push_back(Case.getCaseIndex()); } BasicBlock *DefaultExitBB = nullptr; if (ExitBlockSet.count(SI.getDefaultDest()) && - !isa<PHINode>(SI.getDefaultDest()->begin()) && + areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) && !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) DefaultExitBB = SI.getDefaultDest(); else if (ExitCaseIndices.empty()) @@ -330,7 +429,6 @@ static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, if (CommonSuccBB) { SI.setDefaultDest(CommonSuccBB); } else { - BasicBlock *ParentBB = SI.getParent(); BasicBlock *UnreachableBB = BasicBlock::Create( ParentBB->getContext(), Twine(ParentBB->getName()) + ".unreachable_default", @@ -358,30 +456,44 @@ static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, // Now add the unswitched switch. auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH); - // Split any exit blocks with remaining in-loop predecessors. We walk in - // reverse so that we split in the same order as the cases appeared. This is - // purely for convenience of reading the resulting IR, but it doesn't cost - // anything really. + // Rewrite the IR for the unswitched basic blocks. This requires two steps. + // First, we split any exit blocks with remaining in-loop predecessors. Then + // we update the PHIs in one of two ways depending on if there was a split. + // We walk in reverse so that we split in the same order as the cases + // appeared. This is purely for convenience of reading the resulting IR, but + // it doesn't cost anything really. + SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs; SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap; // Handle the default exit if necessary. // FIXME: It'd be great if we could merge this with the loop below but LLVM's // ranges aren't quite powerful enough yet. - if (DefaultExitBB && !pred_empty(DefaultExitBB)) { - auto *SplitBB = - SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI); - updateLoopExitIDom(DefaultExitBB, L, DT); - DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; + if (DefaultExitBB) { + if (pred_empty(DefaultExitBB)) { + UnswitchedExitBBs.insert(DefaultExitBB); + rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH); + } else { + auto *SplitBB = + SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI); + rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB, + *ParentBB, *OldPH); + updateLoopExitIDom(DefaultExitBB, L, DT); + DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; + } } // Note that we must use a reference in the for loop so that we update the // container. for (auto &CasePair : reverse(ExitCases)) { // Grab a reference to the exit block in the pair so that we can update it. - BasicBlock *&ExitBB = CasePair.second; + BasicBlock *ExitBB = CasePair.second; // If this case is the last edge into the exit block, we can simply reuse it // as it will no longer be a loop exit. No mapping necessary. - if (pred_empty(ExitBB)) + if (pred_empty(ExitBB)) { + // Only rewrite once. + if (UnswitchedExitBBs.insert(ExitBB).second) + rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH); continue; + } // Otherwise we need to split the exit block so that we retain an exit // block from the loop and a target for the unswitched condition. @@ -389,9 +501,12 @@ static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, if (!SplitExitBB) { // If this is the first time we see this, do the split and remember it. SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI); + rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB, + *ParentBB, *OldPH); updateLoopExitIDom(ExitBB, L, DT); } - ExitBB = SplitExitBB; + // Update the case pair to point to the split block. + CasePair.second = SplitExitBB; } // Now add the unswitched cases. We do this in reverse order as we built them diff --git a/contrib/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp b/contrib/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp index a0fc966cee2c..a7c308b59877 100644 --- a/contrib/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp +++ b/contrib/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp @@ -208,6 +208,47 @@ bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) { return false; } +static unsigned ComputeSpeculationCost(const Instruction *I, + const TargetTransformInfo &TTI) { + switch (Operator::getOpcode(I)) { + case Instruction::GetElementPtr: + case Instruction::Add: + case Instruction::Mul: + case Instruction::And: + case Instruction::Or: + case Instruction::Select: + case Instruction::Shl: + case Instruction::Sub: + case Instruction::LShr: + case Instruction::AShr: + case Instruction::Xor: + case Instruction::ZExt: + case Instruction::SExt: + case Instruction::Call: + case Instruction::BitCast: + case Instruction::PtrToInt: + case Instruction::IntToPtr: + case Instruction::AddrSpaceCast: + case Instruction::FPToUI: + case Instruction::FPToSI: + case Instruction::UIToFP: + case Instruction::SIToFP: + case Instruction::FPExt: + case Instruction::FPTrunc: + case Instruction::FAdd: + case Instruction::FSub: + case Instruction::FMul: + case Instruction::FDiv: + case Instruction::FRem: + case Instruction::ICmp: + case Instruction::FCmp: + return TTI.getUserCost(I); + + default: + return UINT_MAX; // Disallow anything not whitelisted. + } +} + bool SpeculativeExecutionPass::considerHoistingFromTo( BasicBlock &FromBlock, BasicBlock &ToBlock) { SmallSet<const Instruction *, 8> NotHoisted; @@ -223,7 +264,7 @@ bool SpeculativeExecutionPass::considerHoistingFromTo( unsigned TotalSpeculationCost = 0; for (auto& I : FromBlock) { - const unsigned Cost = TTI->getUserCost(&I); + const unsigned Cost = ComputeSpeculationCost(&I, *TTI); if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) && AllPrecedingUsesFromBlockHoisted(&I)) { TotalSpeculationCost += Cost; diff --git a/contrib/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp b/contrib/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp index 7ffdad597a9b..83ec7f55d1af 100644 --- a/contrib/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp +++ b/contrib/llvm/lib/Transforms/Utils/BypassSlowDivision.cpp @@ -261,10 +261,10 @@ ValueRange FastDivInsertionTask::getValueRange(Value *V, computeKnownBits(V, Known, DL); - if (Known.Zero.countLeadingOnes() >= HiBits) + if (Known.countMinLeadingZeros() >= HiBits) return VALRNG_KNOWN_SHORT; - if (Known.One.countLeadingZeros() < HiBits) + if (Known.countMaxLeadingZeros() < HiBits) return VALRNG_LIKELY_LONG; // Long integer divisions are often used in hashtable implementations. It's diff --git a/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp b/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp index d5124ac89016..4aa26fd14fee 100644 --- a/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp +++ b/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp @@ -41,6 +41,7 @@ BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix, Function *F, ClonedCodeInfo *CodeInfo) { + DenseMap<const MDNode *, MDNode *> Cache; BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "", F); if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix); @@ -50,6 +51,9 @@ BasicBlock *llvm::CloneBasicBlock(const BasicBlock *BB, for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE; ++II) { Instruction *NewInst = II->clone(); + if (F && F->getSubprogram()) + DebugLoc::reparentDebugInfo(*NewInst, BB->getParent()->getSubprogram(), + F->getSubprogram(), Cache); if (II->hasName()) NewInst->setName(II->getName()+NameSuffix); NewBB->getInstList().push_back(NewInst); @@ -120,12 +124,28 @@ void llvm::CloneFunctionInto(Function *NewFunc, const Function *OldFunc, SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; OldFunc->getAllMetadata(MDs); - for (auto MD : MDs) - NewFunc->addMetadata( - MD.first, - *MapMetadata(MD.second, VMap, - ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, - TypeMapper, Materializer)); + for (auto MD : MDs) { + MDNode *NewMD; + bool MustCloneSP = + (MD.first == LLVMContext::MD_dbg && OldFunc->getParent() && + OldFunc->getParent() == NewFunc->getParent()); + if (MustCloneSP) { + auto *SP = cast<DISubprogram>(MD.second); + NewMD = DISubprogram::getDistinct( + NewFunc->getContext(), SP->getScope(), SP->getName(), + NewFunc->getName(), SP->getFile(), SP->getLine(), SP->getType(), + SP->isLocalToUnit(), SP->isDefinition(), SP->getScopeLine(), + SP->getContainingType(), SP->getVirtuality(), SP->getVirtualIndex(), + SP->getThisAdjustment(), SP->getFlags(), SP->isOptimized(), + SP->getUnit(), SP->getTemplateParams(), SP->getDeclaration(), + SP->getVariables(), SP->getThrownTypes()); + } else + NewMD = + MapMetadata(MD.second, VMap, + ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges, + TypeMapper, Materializer); + NewFunc->addMetadata(MD.first, *NewMD); + } // Loop over all of the basic blocks in the function, cloning them as // appropriate. Note that we save BE this way in order to handle cloning of diff --git a/contrib/llvm/lib/Transforms/Utils/CloneModule.cpp b/contrib/llvm/lib/Transforms/Utils/CloneModule.cpp index 4e9d67252d6c..5444b752de82 100644 --- a/contrib/llvm/lib/Transforms/Utils/CloneModule.cpp +++ b/contrib/llvm/lib/Transforms/Utils/CloneModule.cpp @@ -96,7 +96,7 @@ std::unique_ptr<Module> llvm::CloneModule( else GV = new GlobalVariable( *New, I->getValueType(), false, GlobalValue::ExternalLinkage, - (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr, + nullptr, I->getName(), nullptr, I->getThreadLocalMode(), I->getType()->getAddressSpace()); VMap[&*I] = GV; // We do not copy attributes (mainly because copying between different diff --git a/contrib/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp b/contrib/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp index 8c2386554da5..78d7474e5b95 100644 --- a/contrib/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp +++ b/contrib/llvm/lib/Transforms/Utils/EscapeEnumerator.cpp @@ -67,8 +67,7 @@ IRBuilder<> *EscapeEnumerator::Next() { // Create a cleanup block. LLVMContext &C = F.getContext(); BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F); - Type *ExnTy = - StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr); + Type *ExnTy = StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C)); if (!F.hasPersonalityFn()) { Constant *PersFn = getDefaultPersonalityFn(F.getParent()); F.setPersonalityFn(PersFn); diff --git a/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp b/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp index 6d56e08af99f..9cb4762b683c 100644 --- a/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp +++ b/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp @@ -1302,41 +1302,6 @@ static bool hasLifetimeMarkers(AllocaInst *AI) { return false; } -/// Rebuild the entire inlined-at chain for this instruction so that the top of -/// the chain now is inlined-at the new call site. -static DebugLoc -updateInlinedAtInfo(const DebugLoc &DL, DILocation *InlinedAtNode, - LLVMContext &Ctx, - DenseMap<const DILocation *, DILocation *> &IANodes) { - SmallVector<DILocation *, 3> InlinedAtLocations; - DILocation *Last = InlinedAtNode; - DILocation *CurInlinedAt = DL; - - // Gather all the inlined-at nodes - while (DILocation *IA = CurInlinedAt->getInlinedAt()) { - // Skip any we've already built nodes for - if (DILocation *Found = IANodes[IA]) { - Last = Found; - break; - } - - InlinedAtLocations.push_back(IA); - CurInlinedAt = IA; - } - - // Starting from the top, rebuild the nodes to point to the new inlined-at - // location (then rebuilding the rest of the chain behind it) and update the - // map of already-constructed inlined-at nodes. - for (const DILocation *MD : reverse(InlinedAtLocations)) { - Last = IANodes[MD] = DILocation::getDistinct( - Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last); - } - - // And finally create the normal location for this instruction, referring to - // the new inlined-at chain. - return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last); -} - /// Return the result of AI->isStaticAlloca() if AI were moved to the entry /// block. Allocas used in inalloca calls and allocas of dynamic array size /// cannot be static. @@ -1364,14 +1329,16 @@ static void fixupLineNumbers(Function *Fn, Function::iterator FI, // Cache the inlined-at nodes as they're built so they are reused, without // this every instruction's inlined-at chain would become distinct from each // other. - DenseMap<const DILocation *, DILocation *> IANodes; + DenseMap<const MDNode *, MDNode *> IANodes; for (; FI != Fn->end(); ++FI) { for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { if (DebugLoc DL = BI->getDebugLoc()) { - BI->setDebugLoc( - updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes)); + auto IA = DebugLoc::appendInlinedAt(DL, InlinedAtNode, BI->getContext(), + IANodes); + auto IDL = DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), IA); + BI->setDebugLoc(IDL); continue; } @@ -1429,11 +1396,12 @@ static void updateCallerBFI(BasicBlock *CallSiteBlock, /// Update the branch metadata for cloned call instructions. static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, const Optional<uint64_t> &CalleeEntryCount, - const Instruction *TheCall) { + const Instruction *TheCall, + ProfileSummaryInfo *PSI) { if (!CalleeEntryCount.hasValue() || CalleeEntryCount.getValue() < 1) return; Optional<uint64_t> CallSiteCount = - ProfileSummaryInfo::getProfileCount(TheCall, nullptr); + PSI ? PSI->getProfileCount(TheCall, nullptr) : None; uint64_t CallCount = std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0, CalleeEntryCount.getValue()); @@ -1456,16 +1424,16 @@ static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, /// The callsite's block count is subtracted from the callee's function entry /// count. static void updateCalleeCount(BlockFrequencyInfo *CallerBFI, BasicBlock *CallBB, - Instruction *CallInst, Function *Callee) { + Instruction *CallInst, Function *Callee, + ProfileSummaryInfo *PSI) { // If the callee has a original count of N, and the estimated count of // callsite is M, the new callee count is set to N - M. M is estimated from // the caller's entry count, its entry block frequency and the block frequency // of the callsite. Optional<uint64_t> CalleeCount = Callee->getEntryCount(); - if (!CalleeCount.hasValue()) + if (!CalleeCount.hasValue() || !PSI) return; - Optional<uint64_t> CallCount = - ProfileSummaryInfo::getProfileCount(CallInst, CallerBFI); + Optional<uint64_t> CallCount = PSI->getProfileCount(CallInst, CallerBFI); if (!CallCount.hasValue()) return; // Since CallSiteCount is an estimate, it could exceed the original callee @@ -1668,9 +1636,10 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI, updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI, CalledFunc->front()); - updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall); + updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), TheCall, + IFI.PSI); // Update the profile count of callee. - updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc); + updateCalleeCount(IFI.CallerBFI, OrigBB, TheCall, CalledFunc, IFI.PSI); // Inject byval arguments initialization. for (std::pair<Value*, Value*> &Init : ByValInit) diff --git a/contrib/llvm/lib/Transforms/Utils/InstructionNamer.cpp b/contrib/llvm/lib/Transforms/Utils/InstructionNamer.cpp index 8a1973d1db05..53b432fcafd4 100644 --- a/contrib/llvm/lib/Transforms/Utils/InstructionNamer.cpp +++ b/contrib/llvm/lib/Transforms/Utils/InstructionNamer.cpp @@ -26,16 +26,15 @@ namespace { InstNamer() : FunctionPass(ID) { initializeInstNamerPass(*PassRegistry::getPassRegistry()); } - + void getAnalysisUsage(AnalysisUsage &Info) const override { Info.setPreservesAll(); } bool runOnFunction(Function &F) override { - for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); - AI != AE; ++AI) - if (!AI->hasName() && !AI->getType()->isVoidTy()) - AI->setName("arg"); + for (auto &Arg : F.args()) + if (!Arg.hasName()) + Arg.setName("arg"); for (BasicBlock &BB : F) { if (!BB.hasName()) @@ -48,11 +47,11 @@ namespace { return true; } }; - + char InstNamer::ID = 0; } -INITIALIZE_PASS(InstNamer, "instnamer", +INITIALIZE_PASS(InstNamer, "instnamer", "Assign names to anonymous instructions", false, false) char &llvm::InstructionNamerID = InstNamer::ID; //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/lib/Transforms/Utils/Local.cpp b/contrib/llvm/lib/Transforms/Utils/Local.cpp index ce6b703f3528..1ca509472b5f 100644 --- a/contrib/llvm/lib/Transforms/Utils/Local.cpp +++ b/contrib/llvm/lib/Transforms/Utils/Local.cpp @@ -1041,7 +1041,7 @@ unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, KnownBits Known(BitWidth); computeKnownBits(V, Known, DL, 0, AC, CxtI, DT); - unsigned TrailZ = Known.Zero.countTrailingOnes(); + unsigned TrailZ = Known.countMinTrailingZeros(); // Avoid trouble with ridiculously large TrailZ values, such as // those computed from a null pointer. @@ -1105,8 +1105,9 @@ static bool PhiHasDebugValue(DILocalVariable *DIVar, void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, StoreInst *SI, DIBuilder &Builder) { auto *DIVar = DDI->getVariable(); - auto *DIExpr = DDI->getExpression(); assert(DIVar && "Missing variable"); + auto *DIExpr = DDI->getExpression(); + Value *DV = SI->getOperand(0); // If an argument is zero extended then use argument directly. The ZExt // may be zapped by an optimization pass in future. @@ -1116,34 +1117,28 @@ void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0)); if (ExtendedArg) { - // We're now only describing a subset of the variable. The fragment we're - // describing will always be smaller than the variable size, because - // VariableSize == Size of Alloca described by DDI. Since SI stores - // to the alloca described by DDI, if it's first operand is an extend, - // we're guaranteed that before extension, the value was narrower than - // the size of the alloca, hence the size of the described variable. - SmallVector<uint64_t, 3> Ops; - unsigned FragmentOffset = 0; - // If this already is a bit fragment, we drop the bit fragment from the - // expression and record the offset. - auto Fragment = DIExpr->getFragmentInfo(); - if (Fragment) { - Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3); - FragmentOffset = Fragment->OffsetInBits; - } else { - Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()); + // If this DDI was already describing only a fragment of a variable, ensure + // that fragment is appropriately narrowed here. + // But if a fragment wasn't used, describe the value as the original + // argument (rather than the zext or sext) so that it remains described even + // if the sext/zext is optimized away. This widens the variable description, + // leaving it up to the consumer to know how the smaller value may be + // represented in a larger register. + if (auto Fragment = DIExpr->getFragmentInfo()) { + unsigned FragmentOffset = Fragment->OffsetInBits; + SmallVector<uint64_t, 3> Ops(DIExpr->elements_begin(), + DIExpr->elements_end() - 3); + Ops.push_back(dwarf::DW_OP_LLVM_fragment); + Ops.push_back(FragmentOffset); + const DataLayout &DL = DDI->getModule()->getDataLayout(); + Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); + DIExpr = Builder.createExpression(Ops); } - Ops.push_back(dwarf::DW_OP_LLVM_fragment); - Ops.push_back(FragmentOffset); - const DataLayout &DL = DDI->getModule()->getDataLayout(); - Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType())); - auto NewDIExpr = Builder.createExpression(Ops); - if (!LdStHasDebugValue(DIVar, NewDIExpr, SI)) - Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr, - DDI->getDebugLoc(), SI); - } else if (!LdStHasDebugValue(DIVar, DIExpr, SI)) - Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr, - DDI->getDebugLoc(), SI); + DV = ExtendedArg; + } + if (!LdStHasDebugValue(DIVar, DIExpr, SI)) + Builder.insertDbgValueIntrinsic(DV, 0, DIVar, DIExpr, DDI->getDebugLoc(), + SI); } /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value @@ -1781,44 +1776,43 @@ void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) { combineMetadata(K, J, KnownIDs); } -unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, - DominatorTree &DT, - const BasicBlockEdge &Root) { +template <typename RootType, typename DominatesFn> +static unsigned replaceDominatedUsesWith(Value *From, Value *To, + const RootType &Root, + const DominatesFn &Dominates) { assert(From->getType() == To->getType()); - + unsigned Count = 0; for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); - UI != UE; ) { + UI != UE;) { Use &U = *UI++; - if (DT.dominates(Root, U)) { - U.set(To); - DEBUG(dbgs() << "Replace dominated use of '" - << From->getName() << "' as " - << *To << " in " << *U << "\n"); - ++Count; - } + if (!Dominates(Root, U)) + continue; + U.set(To); + DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as " + << *To << " in " << *U << "\n"); + ++Count; } return Count; } unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, - const BasicBlock *BB) { - assert(From->getType() == To->getType()); + const BasicBlockEdge &Root) { + auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) { + return DT.dominates(Root, U); + }; + return ::replaceDominatedUsesWith(From, To, Root, Dominates); +} - unsigned Count = 0; - for (Value::use_iterator UI = From->use_begin(), UE = From->use_end(); - UI != UE;) { - Use &U = *UI++; - auto *I = cast<Instruction>(U.getUser()); - if (DT.properlyDominates(BB, I->getParent())) { - U.set(To); - DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as " - << *To << " in " << *U << "\n"); - ++Count; - } - } - return Count; +unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To, + DominatorTree &DT, + const BasicBlock *BB) { + auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) { + auto *I = cast<Instruction>(U.getUser())->getParent(); + return DT.properlyDominates(BB, I); + }; + return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates); } bool llvm::callsGCLeafFunction(ImmutableCallSite CS) { diff --git a/contrib/llvm/lib/Transforms/Utils/LoopUtils.cpp b/contrib/llvm/lib/Transforms/Utils/LoopUtils.cpp index 175d013a011d..81f033e7d51a 100644 --- a/contrib/llvm/lib/Transforms/Utils/LoopUtils.cpp +++ b/contrib/llvm/lib/Transforms/Utils/LoopUtils.cpp @@ -18,6 +18,7 @@ #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" +#include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" #include "llvm/Analysis/ScalarEvolutionExpander.h" @@ -1112,3 +1113,203 @@ Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { else return (FalseVal + (TrueVal / 2)) / TrueVal; } + +/// \brief Adds a 'fast' flag to floating point operations. +static Value *addFastMathFlag(Value *V) { + if (isa<FPMathOperator>(V)) { + FastMathFlags Flags; + Flags.setUnsafeAlgebra(); + cast<Instruction>(V)->setFastMathFlags(Flags); + } + return V; +} + +// Helper to generate a log2 shuffle reduction. +Value * +llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, + RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, + ArrayRef<Value *> RedOps) { + unsigned VF = Src->getType()->getVectorNumElements(); + // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles + // and vector ops, reducing the set of values being computed by half each + // round. + assert(isPowerOf2_32(VF) && + "Reduction emission only supported for pow2 vectors!"); + Value *TmpVec = Src; + SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); + for (unsigned i = VF; i != 1; i >>= 1) { + // Move the upper half of the vector to the lower half. + for (unsigned j = 0; j != i / 2; ++j) + ShuffleMask[j] = Builder.getInt32(i / 2 + j); + + // Fill the rest of the mask with undef. + std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), + UndefValue::get(Builder.getInt32Ty())); + + Value *Shuf = Builder.CreateShuffleVector( + TmpVec, UndefValue::get(TmpVec->getType()), + ConstantVector::get(ShuffleMask), "rdx.shuf"); + + if (Op != Instruction::ICmp && Op != Instruction::FCmp) { + // Floating point operations had to be 'fast' to enable the reduction. + TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op, + TmpVec, Shuf, "bin.rdx")); + } else { + assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && + "Invalid min/max"); + TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec, + Shuf); + } + if (!RedOps.empty()) + propagateIRFlags(TmpVec, RedOps); + } + // The result is in the first element of the vector. + return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); +} + +/// Create a simple vector reduction specified by an opcode and some +/// flags (if generating min/max reductions). +Value *llvm::createSimpleTargetReduction( + IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, + Value *Src, TargetTransformInfo::ReductionFlags Flags, + ArrayRef<Value *> RedOps) { + assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); + + Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType()); + std::function<Value*()> BuildFunc; + using RD = RecurrenceDescriptor; + RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; + // TODO: Support creating ordered reductions. + FastMathFlags FMFUnsafe; + FMFUnsafe.setUnsafeAlgebra(); + + switch (Opcode) { + case Instruction::Add: + BuildFunc = [&]() { return Builder.CreateAddReduce(Src); }; + break; + case Instruction::Mul: + BuildFunc = [&]() { return Builder.CreateMulReduce(Src); }; + break; + case Instruction::And: + BuildFunc = [&]() { return Builder.CreateAndReduce(Src); }; + break; + case Instruction::Or: + BuildFunc = [&]() { return Builder.CreateOrReduce(Src); }; + break; + case Instruction::Xor: + BuildFunc = [&]() { return Builder.CreateXorReduce(Src); }; + break; + case Instruction::FAdd: + BuildFunc = [&]() { + auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src); + cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe); + return Rdx; + }; + break; + case Instruction::FMul: + BuildFunc = [&]() { + auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src); + cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe); + return Rdx; + }; + break; + case Instruction::ICmp: + if (Flags.IsMaxOp) { + MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax; + BuildFunc = [&]() { + return Builder.CreateIntMaxReduce(Src, Flags.IsSigned); + }; + } else { + MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin; + BuildFunc = [&]() { + return Builder.CreateIntMinReduce(Src, Flags.IsSigned); + }; + } + break; + case Instruction::FCmp: + if (Flags.IsMaxOp) { + MinMaxKind = RD::MRK_FloatMax; + BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); }; + } else { + MinMaxKind = RD::MRK_FloatMin; + BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); }; + } + break; + default: + llvm_unreachable("Unhandled opcode"); + break; + } + if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags)) + return BuildFunc(); + return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); +} + +/// Create a vector reduction using a given recurrence descriptor. +Value *llvm::createTargetReduction(IRBuilder<> &Builder, + const TargetTransformInfo *TTI, + RecurrenceDescriptor &Desc, Value *Src, + bool NoNaN) { + // TODO: Support in-order reductions based on the recurrence descriptor. + RecurrenceDescriptor::RecurrenceKind RecKind = Desc.getRecurrenceKind(); + TargetTransformInfo::ReductionFlags Flags; + Flags.NoNaN = NoNaN; + auto getSimpleRdx = [&](unsigned Opc) { + return createSimpleTargetReduction(Builder, TTI, Opc, Src, Flags); + }; + switch (RecKind) { + case RecurrenceDescriptor::RK_FloatAdd: + return getSimpleRdx(Instruction::FAdd); + case RecurrenceDescriptor::RK_FloatMult: + return getSimpleRdx(Instruction::FMul); + case RecurrenceDescriptor::RK_IntegerAdd: + return getSimpleRdx(Instruction::Add); + case RecurrenceDescriptor::RK_IntegerMult: + return getSimpleRdx(Instruction::Mul); + case RecurrenceDescriptor::RK_IntegerAnd: + return getSimpleRdx(Instruction::And); + case RecurrenceDescriptor::RK_IntegerOr: + return getSimpleRdx(Instruction::Or); + case RecurrenceDescriptor::RK_IntegerXor: + return getSimpleRdx(Instruction::Xor); + case RecurrenceDescriptor::RK_IntegerMinMax: { + switch (Desc.getMinMaxRecurrenceKind()) { + case RecurrenceDescriptor::MRK_SIntMax: + Flags.IsSigned = true; + Flags.IsMaxOp = true; + break; + case RecurrenceDescriptor::MRK_UIntMax: + Flags.IsMaxOp = true; + break; + case RecurrenceDescriptor::MRK_SIntMin: + Flags.IsSigned = true; + break; + case RecurrenceDescriptor::MRK_UIntMin: + break; + default: + llvm_unreachable("Unhandled MRK"); + } + return getSimpleRdx(Instruction::ICmp); + } + case RecurrenceDescriptor::RK_FloatMinMax: { + Flags.IsMaxOp = + Desc.getMinMaxRecurrenceKind() == RecurrenceDescriptor::MRK_FloatMax; + return getSimpleRdx(Instruction::FCmp); + } + default: + llvm_unreachable("Unhandled RecKind"); + } +} + +void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL) { + if (auto *VecOp = dyn_cast<Instruction>(I)) { + if (auto *I0 = dyn_cast<Instruction>(VL[0])) { + // VecOVp is initialized to the 0th scalar, so start counting from index + // '1'. + VecOp->copyIRFlags(I0); + for (int i = 1, e = VL.size(); i < e; ++i) { + if (auto *Scalar = dyn_cast<Instruction>(VL[i])) + VecOp->andIRFlags(Scalar); + } + } + } +} diff --git a/contrib/llvm/lib/Transforms/Utils/ModuleUtils.cpp b/contrib/llvm/lib/Transforms/Utils/ModuleUtils.cpp index 29d334f2968f..2ef3d6336ae2 100644 --- a/contrib/llvm/lib/Transforms/Utils/ModuleUtils.cpp +++ b/contrib/llvm/lib/Transforms/Utils/ModuleUtils.cpp @@ -35,7 +35,7 @@ static void appendToGlobalArray(const char *Array, Module &M, Function *F, // Upgrade a 2-field global array type to the new 3-field format if needed. if (Data && OldEltTy->getNumElements() < 3) EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy), - IRB.getInt8PtrTy(), nullptr); + IRB.getInt8PtrTy()); else EltTy = OldEltTy; if (Constant *Init = GVCtor->getInitializer()) { @@ -44,10 +44,10 @@ static void appendToGlobalArray(const char *Array, Module &M, Function *F, for (unsigned i = 0; i != n; ++i) { auto Ctor = cast<Constant>(Init->getOperand(i)); if (EltTy != OldEltTy) - Ctor = ConstantStruct::get( - EltTy, Ctor->getAggregateElement((unsigned)0), - Ctor->getAggregateElement(1), - Constant::getNullValue(IRB.getInt8PtrTy()), nullptr); + Ctor = + ConstantStruct::get(EltTy, Ctor->getAggregateElement((unsigned)0), + Ctor->getAggregateElement(1), + Constant::getNullValue(IRB.getInt8PtrTy())); CurrentCtors.push_back(Ctor); } } @@ -55,7 +55,7 @@ static void appendToGlobalArray(const char *Array, Module &M, Function *F, } else { // Use the new three-field struct if there isn't one already. EltTy = StructType::get(IRB.getInt32Ty(), PointerType::getUnqual(FnTy), - IRB.getInt8PtrTy(), nullptr); + IRB.getInt8PtrTy()); } // Build a 2 or 3 field global_ctor entry. We don't take a comdat key. diff --git a/contrib/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp b/contrib/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp index 9e71d746de34..1de579ed41b0 100644 --- a/contrib/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp +++ b/contrib/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp @@ -1450,11 +1450,11 @@ static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, // x86_64 can't use {float, float} since that would be returned in both // xmm0 and xmm1, which isn't what a real struct would do. ResTy = T.getArch() == Triple::x86_64 - ? static_cast<Type *>(VectorType::get(ArgTy, 2)) - : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr)); + ? static_cast<Type *>(VectorType::get(ArgTy, 2)) + : static_cast<Type *>(StructType::get(ArgTy, ArgTy)); } else { Name = "__sincospi_stret"; - ResTy = StructType::get(ArgTy, ArgTy, nullptr); + ResTy = StructType::get(ArgTy, ArgTy); } Module *M = OrigCallee->getParent(); diff --git a/contrib/llvm/lib/Transforms/Utils/VNCoercion.cpp b/contrib/llvm/lib/Transforms/Utils/VNCoercion.cpp index 83bd29dbca65..60d9ede2c487 100644 --- a/contrib/llvm/lib/Transforms/Utils/VNCoercion.cpp +++ b/contrib/llvm/lib/Transforms/Utils/VNCoercion.cpp @@ -303,6 +303,15 @@ static T *getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL) { LLVMContext &Ctx = SrcVal->getType()->getContext(); + // If two pointers are in the same address space, they have the same size, + // so we don't need to do any truncation, etc. This avoids introducing + // ptrtoint instructions for pointers that may be non-integral. + if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() && + cast<PointerType>(SrcVal->getType())->getAddressSpace() == + cast<PointerType>(LoadTy)->getAddressSpace()) { + return SrcVal; + } + uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8; uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8; // Compute which bits of the stored value are being used by the load. Convert diff --git a/contrib/llvm/lib/Transforms/Utils/ValueMapper.cpp b/contrib/llvm/lib/Transforms/Utils/ValueMapper.cpp index 84d89f103a2f..930972924c3c 100644 --- a/contrib/llvm/lib/Transforms/Utils/ValueMapper.cpp +++ b/contrib/llvm/lib/Transforms/Utils/ValueMapper.cpp @@ -949,11 +949,10 @@ void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, Constant *NewV; if (IsOldCtorDtor) { auto *S = cast<ConstantStruct>(V); - auto *E1 = mapValue(S->getOperand(0)); - auto *E2 = mapValue(S->getOperand(1)); - Value *Null = Constant::getNullValue(VoidPtrTy); - NewV = - ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr); + auto *E1 = cast<Constant>(mapValue(S->getOperand(0))); + auto *E2 = cast<Constant>(mapValue(S->getOperand(1))); + Constant *Null = Constant::getNullValue(VoidPtrTy); + NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null); } else { NewV = cast_or_null<Constant>(mapValue(V)); } diff --git a/contrib/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp b/contrib/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp index 97dcb40a1d72..9cf66382b581 100644 --- a/contrib/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp +++ b/contrib/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp @@ -346,7 +346,7 @@ bool Vectorizer::isConsecutiveAccess(Value *A, Value *B) { if (!Safe) { KnownBits Known(BitWidth); computeKnownBits(OpA, Known, DL, 0, nullptr, OpA, &DT); - if (Known.Zero.countTrailingZeros() < (BitWidth - 1)) + if (Known.countMaxTrailingOnes() < (BitWidth - 1)) Safe = true; } diff --git a/contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp index 3fde0a453962..516ab7d03a88 100644 --- a/contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp +++ b/contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp @@ -391,13 +391,14 @@ public: TripCount(nullptr), VectorTripCount(nullptr), Legal(LVL), Cost(CM), AddedSafetyChecks(false) {} - // Perform the actual loop widening (vectorization). - void vectorize() { - // Create a new empty loop. Unlink the old loop and connect the new one. - createEmptyLoop(); - // Widen each instruction in the old loop to a new one in the new loop. - vectorizeLoop(); - } + /// Create a new empty loop. Unlink the old loop and connect the new one. + void createVectorizedLoopSkeleton(); + + /// Vectorize a single instruction within the innermost loop. + void vectorizeInstruction(Instruction &I); + + /// Fix the vectorized code, taking care of header phi's, live-outs, and more. + void fixVectorizedLoop(); // Return true if any runtime check is added. bool areSafetyChecksAdded() { return AddedSafetyChecks; } @@ -425,9 +426,6 @@ protected: EdgeMaskCacheTy; typedef DenseMap<BasicBlock *, VectorParts> BlockMaskCacheTy; - /// Create an empty loop, based on the loop ranges of the old loop. - void createEmptyLoop(); - /// Set up the values of the IVs correctly when exiting the vector loop. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, Value *CountRoundDown, Value *EndValue, @@ -436,8 +434,6 @@ protected: /// Create a new induction variable inside L. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End, Value *Step, Instruction *DL); - /// Copy and widen the instructions from the old loop. - virtual void vectorizeLoop(); /// Handle all cross-iteration phis in the header. void fixCrossIterationPHIs(); @@ -450,10 +446,10 @@ protected: /// vectorizing this phi node. void fixReduction(PHINode *Phi); - /// \brief The Loop exit block may have single value PHI nodes where the - /// incoming value is 'Undef'. While vectorizing we only handled real values - /// that were defined inside the loop. Here we fix the 'undef case'. - /// See PR14725. + /// \brief The Loop exit block may have single value PHI nodes with some + /// incoming value. While vectorizing we only handled real values + /// that were defined inside the loop and we should have one value for + /// each predecessor of its parent basic block. See PR14725. void fixLCSSAPHIs(); /// Iteratively sink the scalarized operands of a predicated instruction into @@ -464,11 +460,6 @@ protected: /// respective conditions. void predicateInstructions(); - /// Collect the instructions from the original loop that would be trivially - /// dead in the vectorized loop if generated. - void collectTriviallyDeadInstructions( - SmallPtrSetImpl<Instruction *> &DeadInstructions); - /// Shrinks vector element sizes to the smallest bitwidth they can be legally /// represented as. void truncateToMinimalBitwidths(); @@ -481,10 +472,6 @@ protected: /// and DST. VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); - /// A helper function to vectorize a single instruction within the innermost - /// loop. - void vectorizeInstruction(Instruction &I); - /// Vectorize a single PHINode in a block. This method handles the induction /// variable canonicalization. It supports both VF = 1 for unrolled loops and /// arbitrary length vectors. @@ -1700,6 +1687,9 @@ public: /// access that can be widened. bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1); + // Returns true if the NoNaN attribute is set on the function. + bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; } + private: /// Check if a single basic block loop is vectorizable. /// At this point we know that this is a loop with a constant trip count @@ -2185,7 +2175,10 @@ public: /// passed Legality checks. class LoopVectorizationPlanner { public: - LoopVectorizationPlanner(LoopVectorizationCostModel &CM) : CM(CM) {} + LoopVectorizationPlanner(Loop *OrigLoop, LoopInfo *LI, + LoopVectorizationLegality *Legal, + LoopVectorizationCostModel &CM) + : OrigLoop(OrigLoop), LI(LI), Legal(Legal), CM(CM) {} ~LoopVectorizationPlanner() {} @@ -2193,7 +2186,25 @@ public: LoopVectorizationCostModel::VectorizationFactor plan(bool OptForSize, unsigned UserVF); + /// Generate the IR code for the vectorized loop. + void executePlan(InnerLoopVectorizer &ILV); + +protected: + /// Collect the instructions from the original loop that would be trivially + /// dead in the vectorized loop if generated. + void collectTriviallyDeadInstructions( + SmallPtrSetImpl<Instruction *> &DeadInstructions); + private: + /// The loop that we evaluate. + Loop *OrigLoop; + + /// Loop Info analysis. + LoopInfo *LI; + + /// The legality analysis. + LoopVectorizationLegality *Legal; + /// The profitablity analysis. LoopVectorizationCostModel &CM; }; @@ -3361,7 +3372,7 @@ void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) { LVer->prepareNoAliasMetadata(); } -void InnerLoopVectorizer::createEmptyLoop() { +void InnerLoopVectorizer::createVectorizedLoopSkeleton() { /* In this function we generate a new loop. The new loop will contain the vectorized instructions while the old loop will continue to run the @@ -3883,36 +3894,7 @@ void InnerLoopVectorizer::truncateToMinimalBitwidths() { } } -void InnerLoopVectorizer::vectorizeLoop() { - //===------------------------------------------------===// - // - // Notice: any optimization or new instruction that go - // into the code below should be also be implemented in - // the cost-model. - // - //===------------------------------------------------===// - - // Collect instructions from the original loop that will become trivially dead - // in the vectorized loop. We don't need to vectorize these instructions. For - // example, original induction update instructions can become dead because we - // separately emit induction "steps" when generating code for the new loop. - // Similarly, we create a new latch condition when setting up the structure - // of the new loop, so the old one can become dead. - SmallPtrSet<Instruction *, 4> DeadInstructions; - collectTriviallyDeadInstructions(DeadInstructions); - - // Scan the loop in a topological order to ensure that defs are vectorized - // before users. - LoopBlocksDFS DFS(OrigLoop); - DFS.perform(LI); - - // Vectorize all instructions in the original loop that will not become - // trivially dead when vectorized. - for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) - for (Instruction &I : *BB) - if (!DeadInstructions.count(&I)) - vectorizeInstruction(I); - +void InnerLoopVectorizer::fixVectorizedLoop() { // Insert truncates and extends for any truncated instructions as hints to // InstCombine. if (VF > 1) @@ -4049,8 +4031,11 @@ void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) { // Set the insertion point after the previous value if it is an instruction. // Note that the previous value may have been constant-folded so it is not - // guaranteed to be an instruction in the vector loop. - if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1])) + // guaranteed to be an instruction in the vector loop. Also, if the previous + // value is a phi node, we should insert after all the phi nodes to avoid + // breaking basic block verification. + if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1]) || + isa<PHINode>(PreviousParts[UF - 1])) Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt()); else Builder.SetInsertPoint( @@ -4258,39 +4243,9 @@ void InnerLoopVectorizer::fixReduction(PHINode *Phi) { } if (VF > 1) { - // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles - // and vector ops, reducing the set of values being computed by half each - // round. - assert(isPowerOf2_32(VF) && - "Reduction emission only supported for pow2 vectors!"); - Value *TmpVec = ReducedPartRdx; - SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); - for (unsigned i = VF; i != 1; i >>= 1) { - // Move the upper half of the vector to the lower half. - for (unsigned j = 0; j != i / 2; ++j) - ShuffleMask[j] = Builder.getInt32(i / 2 + j); - - // Fill the rest of the mask with undef. - std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), - UndefValue::get(Builder.getInt32Ty())); - - Value *Shuf = Builder.CreateShuffleVector( - TmpVec, UndefValue::get(TmpVec->getType()), - ConstantVector::get(ShuffleMask), "rdx.shuf"); - - if (Op != Instruction::ICmp && Op != Instruction::FCmp) - // Floating point operations had to be 'fast' to enable the reduction. - TmpVec = addFastMathFlag(Builder.CreateBinOp( - (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx")); - else - TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, - TmpVec, Shuf); - } - - // The result is in the first element of the vector. + bool NoNaN = Legal->hasFunNoNaNAttr(); ReducedPartRdx = - Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); - + createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN); // If the reduction can be performed in a smaller type, we need to extend // the reduction to the wider type before we branch to the original loop. if (Phi->getType() != RdxDesc.getRecurrenceType()) @@ -4345,33 +4300,11 @@ void InnerLoopVectorizer::fixLCSSAPHIs() { auto *LCSSAPhi = dyn_cast<PHINode>(&LEI); if (!LCSSAPhi) break; - if (LCSSAPhi->getNumIncomingValues() == 1) - LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), - LoopMiddleBlock); - } -} - -void InnerLoopVectorizer::collectTriviallyDeadInstructions( - SmallPtrSetImpl<Instruction *> &DeadInstructions) { - BasicBlock *Latch = OrigLoop->getLoopLatch(); - - // We create new control-flow for the vectorized loop, so the original - // condition will be dead after vectorization if it's only used by the - // branch. - auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); - if (Cmp && Cmp->hasOneUse()) - DeadInstructions.insert(Cmp); - - // We create new "steps" for induction variable updates to which the original - // induction variables map. An original update instruction will be dead if - // all its users except the induction variable are dead. - for (auto &Induction : *Legal->getInductionVars()) { - PHINode *Ind = Induction.first; - auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); - if (all_of(IndUpdate->users(), [&](User *U) -> bool { - return U == Ind || DeadInstructions.count(cast<Instruction>(U)); - })) - DeadInstructions.insert(IndUpdate); + if (LCSSAPhi->getNumIncomingValues() == 1) { + assert(OrigLoop->isLoopInvariant(LCSSAPhi->getIncomingValue(0)) && + "Incoming value isn't loop invariant"); + LCSSAPhi->addIncoming(LCSSAPhi->getIncomingValue(0), LoopMiddleBlock); + } } } @@ -7577,6 +7510,72 @@ LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) { return CM.selectVectorizationFactor(MaxVF); } +void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV) { + // Perform the actual loop transformation. + + // 1. Create a new empty loop. Unlink the old loop and connect the new one. + ILV.createVectorizedLoopSkeleton(); + + //===------------------------------------------------===// + // + // Notice: any optimization or new instruction that go + // into the code below should also be implemented in + // the cost-model. + // + //===------------------------------------------------===// + + // 2. Copy and widen instructions from the old loop into the new loop. + + // Collect instructions from the original loop that will become trivially dead + // in the vectorized loop. We don't need to vectorize these instructions. For + // example, original induction update instructions can become dead because we + // separately emit induction "steps" when generating code for the new loop. + // Similarly, we create a new latch condition when setting up the structure + // of the new loop, so the old one can become dead. + SmallPtrSet<Instruction *, 4> DeadInstructions; + collectTriviallyDeadInstructions(DeadInstructions); + + // Scan the loop in a topological order to ensure that defs are vectorized + // before users. + LoopBlocksDFS DFS(OrigLoop); + DFS.perform(LI); + + // Vectorize all instructions in the original loop that will not become + // trivially dead when vectorized. + for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) + for (Instruction &I : *BB) + if (!DeadInstructions.count(&I)) + ILV.vectorizeInstruction(I); + + // 3. Fix the vectorized code: take care of header phi's, live-outs, + // predication, updating analyses. + ILV.fixVectorizedLoop(); +} + +void LoopVectorizationPlanner::collectTriviallyDeadInstructions( + SmallPtrSetImpl<Instruction *> &DeadInstructions) { + BasicBlock *Latch = OrigLoop->getLoopLatch(); + + // We create new control-flow for the vectorized loop, so the original + // condition will be dead after vectorization if it's only used by the + // branch. + auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); + if (Cmp && Cmp->hasOneUse()) + DeadInstructions.insert(Cmp); + + // We create new "steps" for induction variable updates to which the original + // induction variables map. An original update instruction will be dead if + // all its users except the induction variable are dead. + for (auto &Induction : *Legal->getInductionVars()) { + PHINode *Ind = Induction.first; + auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); + if (all_of(IndUpdate->users(), [&](User *U) -> bool { + return U == Ind || DeadInstructions.count(cast<Instruction>(U)); + })) + DeadInstructions.insert(IndUpdate); + } +} + void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) { auto *SI = dyn_cast<StoreInst>(Instr); bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent())); @@ -7759,7 +7758,7 @@ bool LoopVectorizePass::processLoop(Loop *L) { CM.collectValuesToIgnore(); // Use the planner for vectorization. - LoopVectorizationPlanner LVP(CM); + LoopVectorizationPlanner LVP(L, LI, &LVL, CM); // Get user vectorization factor. unsigned UserVF = Hints.getWidth(); @@ -7853,7 +7852,7 @@ bool LoopVectorizePass::processLoop(Loop *L) { // interleave it. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, &CM); - Unroller.vectorize(); + LVP.executePlan(Unroller); ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(), L->getHeader()) @@ -7863,7 +7862,7 @@ bool LoopVectorizePass::processLoop(Loop *L) { // If we decided that it is *legal* to vectorize the loop, then do it. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC, &LVL, &CM); - LB.vectorize(); + LVP.executePlan(LB); ++LoopsVectorized; // Add metadata to disable runtime unrolling a scalar loop when there are diff --git a/contrib/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/contrib/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp index f112c555205c..64013d6d687d 100644 --- a/contrib/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp +++ b/contrib/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp @@ -40,7 +40,9 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/GraphWriter.h" +#include "llvm/Support/KnownBits.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/Transforms/Utils/LoopUtils.h" #include "llvm/Transforms/Vectorize.h" #include <algorithm> #include <memory> @@ -212,23 +214,6 @@ static unsigned getSameOpcode(ArrayRef<Value *> VL) { return Opcode; } -/// Get the intersection (logical and) of all of the potential IR flags -/// of each scalar operation (VL) that will be converted into a vector (I). -/// Flag set: NSW, NUW, exact, and all of fast-math. -static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) { - if (auto *VecOp = dyn_cast<Instruction>(I)) { - if (auto *I0 = dyn_cast<Instruction>(VL[0])) { - // VecOVp is initialized to the 0th scalar, so start counting from index - // '1'. - VecOp->copyIRFlags(I0); - for (int i = 1, e = VL.size(); i < e; ++i) { - if (auto *Scalar = dyn_cast<Instruction>(VL[i])) - VecOp->andIRFlags(Scalar); - } - } - } -} - /// \returns true if all of the values in \p VL have the same type or false /// otherwise. static bool allSameType(ArrayRef<Value *> VL) { @@ -315,10 +300,10 @@ public: BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, - const DataLayout *DL) + const DataLayout *DL, OptimizationRemarkEmitter *ORE) : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), DB(DB), - DL(DL), Builder(Se->getContext()) { + DL(DL), ORE(ORE), Builder(Se->getContext()) { CodeMetrics::collectEphemeralValues(F, AC, EphValues); // Use the vector register size specified by the target unless overridden // by a command-line option. @@ -331,7 +316,10 @@ public: else MaxVecRegSize = TTI->getRegisterBitWidth(true); - MinVecRegSize = MinVectorRegSizeOption; + if (MinVectorRegSizeOption.getNumOccurrences()) + MinVecRegSize = MinVectorRegSizeOption; + else + MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); } /// \brief Vectorize the tree that starts with the elements in \p VL. @@ -377,6 +365,8 @@ public: MinBWs.clear(); } + unsigned getTreeSize() const { return VectorizableTree.size(); } + /// \brief Perform LICM and CSE on the newly generated gather sequences. void optimizeGatherSequence(); @@ -415,6 +405,8 @@ public: /// vectorizable. We do not vectorize such trees. bool isTreeTinyAndNotFullyVectorizable(); + OptimizationRemarkEmitter *getORE() { return ORE; } + private: struct TreeEntry; @@ -944,6 +936,8 @@ private: AssumptionCache *AC; DemandedBits *DB; const DataLayout *DL; + OptimizationRemarkEmitter *ORE; + unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. unsigned MinVecRegSize; // Set by cl::opt (default: 128). /// Instruction builder to construct the vectorized tree. @@ -1835,11 +1829,13 @@ int BoUpSLP::getEntryCost(TreeEntry *E) { CInt->getValue().isPowerOf2()) Op2VP = TargetTransformInfo::OP_PowerOf2; - int ScalarCost = VecTy->getNumElements() * - TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, - Op2VK, Op1VP, Op2VP); + SmallVector<const Value *, 4> Operands(VL0->operand_values()); + int ScalarCost = + VecTy->getNumElements() * + TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK, Op1VP, + Op2VP, Operands); int VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK, - Op1VP, Op2VP); + Op1VP, Op2VP, Operands); return VecCost - ScalarCost; } case Instruction::GetElementPtr: { @@ -3703,10 +3699,8 @@ void BoUpSLP::computeMinimumValueSizes() { // Determine if the sign bit of all the roots is known to be zero. If not, // IsKnownPositive is set to False. IsKnownPositive = all_of(TreeRoot, [&](Value *R) { - bool KnownZero = false; - bool KnownOne = false; - ComputeSignBit(R, KnownZero, KnownOne, *DL); - return KnownZero; + KnownBits Known = computeKnownBits(R, *DL); + return Known.isNonNegative(); }); // Determine the maximum number of bits required to store the scalar @@ -3786,8 +3780,9 @@ struct SLPVectorizer : public FunctionPass { auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); + auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); - return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB); + return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); } void getAnalysisUsage(AnalysisUsage &AU) const override { @@ -3799,6 +3794,7 @@ struct SLPVectorizer : public FunctionPass { AU.addRequired<LoopInfoWrapperPass>(); AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<DemandedBitsWrapperPass>(); + AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); AU.addPreserved<LoopInfoWrapperPass>(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<AAResultsWrapperPass>(); @@ -3817,8 +3813,9 @@ PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &A auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); auto *AC = &AM.getResult<AssumptionAnalysis>(F); auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); + auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); - bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB); + bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); if (!Changed) return PreservedAnalyses::all(); @@ -3833,7 +3830,8 @@ bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, TargetTransformInfo *TTI_, TargetLibraryInfo *TLI_, AliasAnalysis *AA_, LoopInfo *LI_, DominatorTree *DT_, - AssumptionCache *AC_, DemandedBits *DB_) { + AssumptionCache *AC_, DemandedBits *DB_, + OptimizationRemarkEmitter *ORE_) { SE = SE_; TTI = TTI_; TLI = TLI_; @@ -3861,7 +3859,7 @@ bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, // Use the bottom up slp vectorizer to construct chains that start with // store instructions. - BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL); + BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to // delete instructions. @@ -3950,6 +3948,13 @@ bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n"); if (Cost < -SLPCostThreshold) { DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n"); + using namespace ore; + R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", + cast<StoreInst>(Chain[i])) + << "Stores SLP vectorized with cost " << NV("Cost", Cost) + << " and with tree size " + << NV("TreeSize", R.getTreeSize())); + R.vectorizeTree(); // Move to the next bundle. @@ -4163,6 +4168,12 @@ bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, if (Cost < -SLPCostThreshold) { DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); + R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", + cast<Instruction>(Ops[0])) + << "SLP vectorized with cost " << ore::NV("Cost", Cost) + << " and with tree size " + << ore::NV("TreeSize", R.getTreeSize())); + Value *VectorizedRoot = R.vectorizeTree(); // Reconstruct the build vector by extracting the vectorized root. This @@ -4506,6 +4517,12 @@ public: DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost << ". (HorRdx)\n"); + auto *I0 = cast<Instruction>(VL[0]); + V.getORE()->emit( + OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", I0) + << "Vectorized horizontal reduction with cost " + << ore::NV("Cost", Cost) << " and with tree size " + << ore::NV("TreeSize", V.getTreeSize())); // Vectorize a tree. DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); @@ -4513,7 +4530,7 @@ public: // Emit a reduction. Value *ReducedSubTree = - emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps); + emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI); if (VectorizedTree) { Builder.SetCurrentDebugLocation(Loc); VectorizedTree = Builder.CreateBinOp(ReductionOpcode, VectorizedTree, @@ -4583,33 +4600,31 @@ private: /// \brief Emit a horizontal reduction of the vectorized value. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, - unsigned ReduxWidth, ArrayRef<Value *> RedOps) { + unsigned ReduxWidth, ArrayRef<Value *> RedOps, + const TargetTransformInfo *TTI) { assert(VectorizedValue && "Need to have a vectorized tree node"); assert(isPowerOf2_32(ReduxWidth) && "We only handle power-of-two reductions for now"); + if (!IsPairwiseReduction) + return createSimpleTargetReduction( + Builder, TTI, ReductionOpcode, VectorizedValue, + TargetTransformInfo::ReductionFlags(), RedOps); + Value *TmpVec = VectorizedValue; for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) { - if (IsPairwiseReduction) { - Value *LeftMask = + Value *LeftMask = createRdxShuffleMask(ReduxWidth, i, true, true, Builder); - Value *RightMask = + Value *RightMask = createRdxShuffleMask(ReduxWidth, i, true, false, Builder); - Value *LeftShuf = Builder.CreateShuffleVector( + Value *LeftShuf = Builder.CreateShuffleVector( TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l"); - Value *RightShuf = Builder.CreateShuffleVector( + Value *RightShuf = Builder.CreateShuffleVector( TmpVec, UndefValue::get(TmpVec->getType()), (RightMask), "rdx.shuf.r"); - TmpVec = Builder.CreateBinOp(ReductionOpcode, LeftShuf, RightShuf, - "bin.rdx"); - } else { - Value *UpperHalf = - createRdxShuffleMask(ReduxWidth, i, false, false, Builder); - Value *Shuf = Builder.CreateShuffleVector( - TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf"); - TmpVec = Builder.CreateBinOp(ReductionOpcode, TmpVec, Shuf, "bin.rdx"); - } + TmpVec = + Builder.CreateBinOp(ReductionOpcode, LeftShuf, RightShuf, "bin.rdx"); propagateIRFlags(TmpVec, RedOps); } @@ -5162,6 +5177,7 @@ INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) INITIALIZE_PASS_DEPENDENCY(LoopSimplify) INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) +INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) namespace llvm { diff --git a/contrib/llvm/lib/XRay/Trace.cpp b/contrib/llvm/lib/XRay/Trace.cpp index d2984697c8a9..6677063f944f 100644 --- a/contrib/llvm/lib/XRay/Trace.cpp +++ b/contrib/llvm/lib/XRay/Trace.cpp @@ -115,6 +115,7 @@ struct FDRState { uint16_t CPUId; uint16_t ThreadId; uint64_t BaseTSC; + /// Encode some of the state transitions for the FDR log reader as explicit /// checks. These are expectations for the next Record in the stream. enum class Token { @@ -123,8 +124,10 @@ struct FDRState { NEW_CPU_ID_RECORD, FUNCTION_SEQUENCE, SCAN_TO_END_OF_THREAD_BUF, + CUSTOM_EVENT_DATA, }; Token Expects; + // Each threads buffer may have trailing garbage to scan over, so we track our // progress. uint64_t CurrentBufferSize; @@ -143,6 +146,8 @@ Twine fdrStateToTwine(const FDRState::Token &state) { return "FUNCTION_SEQUENCE"; case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF: return "SCAN_TO_END_OF_THREAD_BUF"; + case FDRState::Token::CUSTOM_EVENT_DATA: + return "CUSTOM_EVENT_DATA"; } return "UNKNOWN"; } @@ -212,13 +217,32 @@ Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte, return Error::success(); } +/// State transition when a CustomEventMarker is encountered. +Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte, + DataExtractor &RecordExtractor, + size_t &RecordSize) { + // We can encounter a CustomEventMarker anywhere in the log, so we can handle + // it regardless of the expectation. However, we do se the expectation to read + // a set number of fixed bytes, as described in the metadata. + uint32_t OffsetPtr = 1; // Read after the first byte. + uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr); + uint64_t TSC = RecordExtractor.getU64(&OffsetPtr); + + // FIXME: Actually represent the record through the API. For now we only skip + // through the data. + (void)TSC; + RecordSize = 16 + DataSize; + return Error::success(); +} + /// Advances the state machine for reading the FDR record type by reading one /// Metadata Record and updating the State appropriately based on the kind of /// record encountered. The RecordKind is encoded in the first byte of the /// Record, which the caller should pass in because they have already read it /// to determine that this is a metadata record as opposed to a function record. Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte, - DataExtractor &RecordExtractor) { + DataExtractor &RecordExtractor, + size_t &RecordSize) { // The remaining 7 bits are the RecordKind enum. uint8_t RecordKind = RecordFirstByte >> 1; switch (RecordKind) { @@ -247,6 +271,11 @@ Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte, processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor)) return E; break; + case 5: // CustomEventMarker + if (auto E = processCustomEventMarker(State, RecordFirstByte, + RecordExtractor, RecordSize)) + return E; + break; default: // Widen the record type to uint16_t to prevent conversion to char. return make_error<StringError>( @@ -400,7 +429,8 @@ Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader, bool isMetadataRecord = BitField & 0x01uL; if (isMetadataRecord) { RecordSize = 16; - if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor)) + if (auto E = processFDRMetadataRecord(State, BitField, RecordExtractor, + RecordSize)) return E; State.CurrentBufferConsumed += RecordSize; } else { // Process Function Record diff --git a/contrib/llvm/tools/bugpoint/ExtractFunction.cpp b/contrib/llvm/tools/bugpoint/ExtractFunction.cpp index 82c61b6e1be7..72872e83f792 100644 --- a/contrib/llvm/tools/bugpoint/ExtractFunction.cpp +++ b/contrib/llvm/tools/bugpoint/ExtractFunction.cpp @@ -232,8 +232,7 @@ static Constant *GetTorInit(std::vector<std::pair<Function *, int>> &TorList) { std::vector<Constant *> ArrayElts; Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext()); - StructType *STy = - StructType::get(Int32Ty, TorList[0].first->getType(), nullptr); + StructType *STy = StructType::get(Int32Ty, TorList[0].first->getType()); for (unsigned i = 0, e = TorList.size(); i != e; ++i) { Constant *Elts[] = {ConstantInt::get(Int32Ty, TorList[i].second), TorList[i].first}; diff --git a/contrib/llvm/tools/clang/include/clang-c/Index.h b/contrib/llvm/tools/clang/include/clang-c/Index.h index c50ac1b6d248..462d9269f7ad 100644 --- a/contrib/llvm/tools/clang/include/clang-c/Index.h +++ b/contrib/llvm/tools/clang/include/clang-c/Index.h @@ -32,7 +32,7 @@ * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable. */ #define CINDEX_VERSION_MAJOR 0 -#define CINDEX_VERSION_MINOR 38 +#define CINDEX_VERSION_MINOR 39 #define CINDEX_VERSION_ENCODE(major, minor) ( \ ((major) * 10000) \ @@ -4081,6 +4081,23 @@ CINDEX_LINKAGE unsigned clang_Cursor_isObjCOptional(CXCursor C); CINDEX_LINKAGE unsigned clang_Cursor_isVariadic(CXCursor C); /** + * \brief Returns non-zero if the given cursor points to a symbol marked with + * external_source_symbol attribute. + * + * \param language If non-NULL, and the attribute is present, will be set to + * the 'language' string from the attribute. + * + * \param definedIn If non-NULL, and the attribute is present, will be set to + * the 'definedIn' string from the attribute. + * + * \param isGenerated If non-NULL, and the attribute is present, will be set to + * non-zero if the 'generated_declaration' is set in the attribute. + */ +CINDEX_LINKAGE unsigned clang_Cursor_isExternalSymbol(CXCursor C, + CXString *language, CXString *definedIn, + unsigned *isGenerated); + +/** * \brief Given a cursor that represents a declaration, return the associated * comment's source range. The range may include multiple consecutive comments * with whitespace in between. diff --git a/contrib/llvm/tools/clang/include/clang/AST/CXXInheritance.h b/contrib/llvm/tools/clang/include/clang/AST/CXXInheritance.h index 3cf058f26bc6..a7961ebe8ce6 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/CXXInheritance.h +++ b/contrib/llvm/tools/clang/include/clang/AST/CXXInheritance.h @@ -161,7 +161,8 @@ class CXXBasePaths { void ComputeDeclsFound(); bool lookupInBases(ASTContext &Context, const CXXRecordDecl *Record, - CXXRecordDecl::BaseMatchesCallback BaseMatches); + CXXRecordDecl::BaseMatchesCallback BaseMatches, + bool LookupInDependent = false); public: typedef std::list<CXXBasePath>::iterator paths_iterator; diff --git a/contrib/llvm/tools/clang/include/clang/AST/Decl.h b/contrib/llvm/tools/clang/include/clang/AST/Decl.h index 573ea55de1fd..facef8e55f7a 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/Decl.h +++ b/contrib/llvm/tools/clang/include/clang/AST/Decl.h @@ -966,9 +966,16 @@ public: /// hasLocalStorage - Returns true if a variable with function scope /// is a non-static local variable. bool hasLocalStorage() const { - if (getStorageClass() == SC_None) + if (getStorageClass() == SC_None) { + // OpenCL v1.2 s6.5.3: The __constant or constant address space name is + // used to describe variables allocated in global memory and which are + // accessed inside a kernel(s) as read-only variables. As such, variables + // in constant address space cannot have local storage. + if (getType().getAddressSpace() == LangAS::opencl_constant) + return false; // Second check is for C++11 [dcl.stc]p4. return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; + } // Global Named Register (GNU extension) if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) @@ -2478,7 +2485,7 @@ public: void setCapturedVLAType(const VariableArrayType *VLAType); /// getParent - Returns the parent of this field declaration, which - /// is the struct in which this method is defined. + /// is the struct in which this field is defined. const RecordDecl *getParent() const { return cast<RecordDecl>(getDeclContext()); } diff --git a/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h b/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h index 13921a132cfb..6965e8143ff6 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h +++ b/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h @@ -1563,10 +1563,13 @@ public: /// \param Paths used to record the paths from this class to its base class /// subobjects that match the search criteria. /// + /// \param LookupInDependent can be set to true to extend the search to + /// dependent base classes. + /// /// \returns true if there exists any path from this class to a base class /// subobject that matches the search criteria. - bool lookupInBases(BaseMatchesCallback BaseMatches, - CXXBasePaths &Paths) const; + bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, + bool LookupInDependent = false) const; /// \brief Base-class lookup callback that determines whether the given /// base class specifier refers to a specific class declaration. @@ -1608,6 +1611,16 @@ public: CXXBasePath &Path, DeclarationName Name); /// \brief Base-class lookup callback that determines whether there exists + /// a member with the given name. + /// + /// This callback can be used with \c lookupInBases() to find members + /// of the given name within a C++ class hierarchy, including dependent + /// classes. + static bool + FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, DeclarationName Name); + + /// \brief Base-class lookup callback that determines whether there exists /// an OpenMP declare reduction member with the given name. /// /// This callback can be used with \c lookupInBases() to find members @@ -1633,6 +1646,14 @@ public: /// \brief Get the indirect primary bases for this class. void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const; + /// Performs an imprecise lookup of a dependent name in this class. + /// + /// This function does not follow strict semantic rules and should be used + /// only when lookup rules can be relaxed, e.g. indexing. + std::vector<const NamedDecl *> + lookupDependentName(const DeclarationName &Name, + llvm::function_ref<bool(const NamedDecl *ND)> Filter); + /// Renders and displays an inheritance diagram /// for this C++ class and all of its base classes (transitively) using /// GraphViz. diff --git a/contrib/llvm/tools/clang/include/clang/AST/ExternalASTMerger.h b/contrib/llvm/tools/clang/include/clang/AST/ExternalASTMerger.h index 51d0c30ad23b..55459df1fe6b 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/ExternalASTMerger.h +++ b/contrib/llvm/tools/clang/include/clang/AST/ExternalASTMerger.h @@ -44,6 +44,8 @@ public: FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl<Decl *> &Result) override; + + void CompleteType(TagDecl *Tag) override; }; } // end namespace clang diff --git a/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h b/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h index 1b5850a05b37..cd2a39449825 100644 --- a/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h +++ b/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h @@ -2326,7 +2326,7 @@ DEF_TRAVERSE_STMT(LambdaExpr, { } TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); - FunctionProtoTypeLoc Proto = TL.castAs<FunctionProtoTypeLoc>(); + FunctionProtoTypeLoc Proto = TL.getAsAdjusted<FunctionProtoTypeLoc>(); if (S->hasExplicitParameters() && S->hasExplicitResultType()) { // Visit the whole type. diff --git a/contrib/llvm/tools/clang/include/clang/Basic/Attr.td b/contrib/llvm/tools/clang/include/clang/Basic/Attr.td index 3eeeb1bdc971..4eb958e3f4d5 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/Attr.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/Attr.td @@ -652,6 +652,30 @@ def Availability : InheritableAttr { .Case("tvos_app_extension", "tvOS (App Extension)") .Case("watchos_app_extension", "watchOS (App Extension)") .Default(llvm::StringRef()); +} +static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) { + return llvm::StringSwitch<llvm::StringRef>(Platform) + .Case("ios", "iOS") + .Case("macos", "macOS") + .Case("tvos", "tvOS") + .Case("watchos", "watchOS") + .Case("ios_app_extension", "iOSApplicationExtension") + .Case("macos_app_extension", "macOSApplicationExtension") + .Case("tvos_app_extension", "tvOSApplicationExtension") + .Case("watchos_app_extension", "watchOSApplicationExtension") + .Default(Platform); +} +static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) { + return llvm::StringSwitch<llvm::StringRef>(Platform) + .Case("iOS", "ios") + .Case("macOS", "macos") + .Case("tvOS", "tvos") + .Case("watchOS", "watchos") + .Case("iOSApplicationExtension", "ios_app_extension") + .Case("macOSApplicationExtension", "macos_app_extension") + .Case("tvOSApplicationExtension", "tvos_app_extension") + .Case("watchOSApplicationExtension", "watchos_app_extension") + .Default(Platform); } }]; let HasCustomParsing = 1; let DuplicatesAllowedWhileMerging = 1; diff --git a/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def b/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def index 816ea156f979..a9ec172422ab 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def +++ b/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def @@ -1409,6 +1409,9 @@ LANGBUILTIN(to_private, "v*v*", "tn", OCLC20_LANG) BUILTIN(__builtin_os_log_format_buffer_size, "zcC*.", "p:0:nut") BUILTIN(__builtin_os_log_format, "v*v*cC*.", "p:0:nt") +// Builtins for XRay +BUILTIN(__xray_customevent, "vcC*z", "") + #undef BUILTIN #undef LIBBUILTIN #undef LANGBUILTIN diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td index 05e03fab40fa..e1a41584023c 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td @@ -486,6 +486,7 @@ def UnneededInternalDecl : DiagGroup<"unneeded-internal-declaration">; def UnneededMemberFunction : DiagGroup<"unneeded-member-function">; def UnusedPrivateField : DiagGroup<"unused-private-field">; def UnusedFunction : DiagGroup<"unused-function", [UnneededInternalDecl]>; +def UnusedTemplate : DiagGroup<"unused-template", [UnneededInternalDecl]>; def UnusedMemberFunction : DiagGroup<"unused-member-function", [UnneededMemberFunction]>; def UnusedLabel : DiagGroup<"unused-label">; @@ -627,6 +628,7 @@ def Conversion : DiagGroup<"conversion", def Unused : DiagGroup<"unused", [UnusedArgument, UnusedFunction, UnusedLabel, // UnusedParameter, (matches GCC's behavior) + // UnusedTemplate, (clean-up libc++ before enabling) // UnusedMemberFunction, (clean-up llvm before enabling) UnusedPrivateField, UnusedLambdaCapture, UnusedLocalTypedef, UnusedValue, UnusedVariable, diff --git a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td index a0c0e5f86449..1db6704f6d1f 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -303,6 +303,8 @@ def note_empty_parens_zero_initialize : Note< "replace parentheses with an initializer to declare a variable">; def warn_unused_function : Warning<"unused function %0">, InGroup<UnusedFunction>, DefaultIgnore; +def warn_unused_template : Warning<"unused %select{function|variable}0 template %1">, + InGroup<UnusedTemplate>, DefaultIgnore; def warn_unused_member_function : Warning<"unused member function %0">, InGroup<UnusedMemberFunction>, DefaultIgnore; def warn_used_but_marked_unused: Warning<"%0 was marked unused but was used">, @@ -2463,6 +2465,9 @@ def err_attribute_invalid_size : Error< "vector size not an integral multiple of component size">; def err_attribute_zero_size : Error<"zero vector size">; def err_attribute_size_too_large : Error<"vector size too large">; +def err_typecheck_vector_not_convertable_implict_truncation : Error< + "cannot convert between %select{scalar|vector}0 type %1 and vector type" + " %2 as implicit conversion would cause truncation">; def err_typecheck_vector_not_convertable : Error< "cannot convert between vector values of different size (%0 and %1)">; def err_typecheck_vector_not_convertable_non_scalar : Error< @@ -4607,6 +4612,8 @@ def err_abi_tag_on_redeclaration : Error< "cannot add 'abi_tag' attribute in a redeclaration">; def err_new_abi_tag_on_redeclaration : Error< "'abi_tag' %0 missing in original declaration">; +def note_use_ifdef_guards : Note< + "unguarded header; consider using #ifdef guards or #pragma once">; def note_deleted_dtor_no_operator_delete : Note< "virtual destructor requires an unambiguous, accessible 'operator delete'">; @@ -5775,6 +5782,9 @@ def err_objc_object_assignment : Error< "cannot assign to class object (%0 invalid)">; def err_typecheck_invalid_operands : Error< "invalid operands to binary expression (%0 and %1)">; +def err_typecheck_logical_vector_expr_gnu_cpp_restrict : Error< + "logical expression with vector %select{type %1 and non-vector type %2|types" + " %1 and %2}0 is only supported in C++">; def err_typecheck_sub_ptr_compatible : Error< "%diff{$ and $ are not pointers to compatible types|" "pointers to incompatible types}0,1">; @@ -8186,9 +8196,20 @@ def err_undeclared_use_suggest : Error< "use of undeclared %0; did you mean %1?">; def err_undeclared_var_use_suggest : Error< "use of undeclared identifier %0; did you mean %1?">; +def err_no_template : Error<"no template named %0">; def err_no_template_suggest : Error<"no template named %0; did you mean %1?">; +def err_no_member_template : Error<"no template named %0 in %1">; def err_no_member_template_suggest : Error< "no template named %0 in %1; did you mean %select{|simply }2%3?">; +def err_non_template_in_template_id : Error< + "%0 does not name a template but is followed by template arguments">; +def err_non_template_in_template_id_suggest : Error< + "%0 does not name a template but is followed by template arguments; " + "did you mean %1?">; +def err_non_template_in_member_template_id_suggest : Error< + "member %0 of %1 is not a template; did you mean %select{|simply }2%3?">; +def note_non_template_in_template_id_found : Note< + "non-template declaration found by name lookup">; def err_mem_init_not_member_or_class_suggest : Error< "initializer %0 does not name a non-static data member or base " "class; did you mean the %select{base class|member}1 %2?">; @@ -8875,6 +8896,13 @@ def ext_equivalent_internal_linkage_decl_in_modules : ExtWarn< InGroup<DiagGroup<"modules-ambiguous-internal-linkage">>; def note_equivalent_internal_linkage_decl : Note< "declared here%select{ in module '%1'|}0">; + +def note_redefinition_modules_same_file : Note< + "'%0' included multiple times, additional include site in header from module '%1'">; +def note_redefinition_modules_same_file_modulemap : Note< + "consider adding '%0' as part of '%1' definition">; +def note_redefinition_include_same_file : Note< + "'%0' included multiple times, additional include site here">; } let CategoryName = "Coroutines Issue" in { diff --git a/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h b/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h index 2889cce5963b..6ca1ba39c8fb 100644 --- a/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h +++ b/contrib/llvm/tools/clang/include/clang/Basic/TargetOptions.h @@ -24,8 +24,7 @@ namespace clang { /// \brief Options for controlling the target. class TargetOptions { public: - /// If given, the name of the target triple to compile for. If not given the - /// target will be selected to match the host. + /// The name of the target triple to compile for. std::string Triple; /// When compiling for the device side, contains the triple used to compile diff --git a/contrib/llvm/tools/clang/include/clang/Driver/Options.td b/contrib/llvm/tools/clang/include/clang/Driver/Options.td index 31015228f362..d812bd8ec032 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/Options.td +++ b/contrib/llvm/tools/clang/include/clang/Driver/Options.td @@ -827,6 +827,9 @@ def fno_sanitize_address_use_after_scope : Flag<["-"], "fno-sanitize-address-use Group<f_clang_Group>, Flags<[CoreOption, DriverOption]>, HelpText<"Disable use-after-scope detection in AddressSanitizer">; +def fsanitize_address_globals_dead_stripping : Flag<["-"], "fsanitize-address-globals-dead-stripping">, + Group<f_clang_Group>, + HelpText<"Enable linker dead stripping of globals in AddressSanitizer">; def fsanitize_recover : Flag<["-"], "fsanitize-recover">, Group<f_clang_Group>; def fno_sanitize_recover : Flag<["-"], "fno-sanitize-recover">, Flags<[CoreOption, DriverOption]>, diff --git a/contrib/llvm/tools/clang/include/clang/Driver/SanitizerArgs.h b/contrib/llvm/tools/clang/include/clang/Driver/SanitizerArgs.h index c7b3e8006dd5..a9645d463fa1 100644 --- a/contrib/llvm/tools/clang/include/clang/Driver/SanitizerArgs.h +++ b/contrib/llvm/tools/clang/include/clang/Driver/SanitizerArgs.h @@ -35,6 +35,7 @@ class SanitizerArgs { int AsanFieldPadding = 0; bool AsanSharedRuntime = false; bool AsanUseAfterScope = true; + bool AsanGlobalsDeadStripping = false; bool LinkCXXRuntimes = false; bool NeedPIE = false; bool Stats = false; diff --git a/contrib/llvm/tools/clang/include/clang/Format/Format.h b/contrib/llvm/tools/clang/include/clang/Format/Format.h index 9bed253baca2..a963c6369aa9 100644 --- a/contrib/llvm/tools/clang/include/clang/Format/Format.h +++ b/contrib/llvm/tools/clang/include/clang/Format/Format.h @@ -98,22 +98,39 @@ struct FormatStyle { /// \endcode bool AlignConsecutiveDeclarations; - /// \brief If ``true``, aligns escaped newlines as far left as possible. - /// Otherwise puts them into the right-most column. - /// \code - /// true: - /// #define A \ - /// int aaaa; \ - /// int b; \ - /// int dddddddddd; - /// - /// false: - /// #define A \ - /// int aaaa; \ - /// int b; \ - /// int dddddddddd; - /// \endcode - bool AlignEscapedNewlinesLeft; + /// \brief Different styles for aligning escaped newlines. + enum EscapedNewlineAlignmentStyle { + /// \brief Don't align escaped newlines. + /// \code + /// #define A \ + /// int aaaa; \ + /// int b; \ + /// int dddddddddd; + /// \endcode + ENAS_DontAlign, + /// \brief Align escaped newlines as far left as possible. + /// \code + /// true: + /// #define A \ + /// int aaaa; \ + /// int b; \ + /// int dddddddddd; + /// + /// false: + /// \endcode + ENAS_Left, + /// \brief Align escaped newlines in the right-most column. + /// \code + /// #define A \ + /// int aaaa; \ + /// int b; \ + /// int dddddddddd; + /// \endcode + ENAS_Right, + }; + + /// \brief Options for aligning backslashes in escaped newlines. + EscapedNewlineAlignmentStyle AlignEscapedNewlines; /// \brief If ``true``, horizontally align operands of binary and ternary /// expressions. @@ -1347,7 +1364,7 @@ struct FormatStyle { AlignAfterOpenBracket == R.AlignAfterOpenBracket && AlignConsecutiveAssignments == R.AlignConsecutiveAssignments && AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations && - AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft && + AlignEscapedNewlines == R.AlignEscapedNewlines && AlignOperands == R.AlignOperands && AlignTrailingComments == R.AlignTrailingComments && AllowAllParametersOfDeclarationOnNextLine == diff --git a/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def b/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def index 7495ad808c99..251441d38ff8 100644 --- a/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def +++ b/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.def @@ -137,6 +137,8 @@ CODEGENOPT(StructPathTBAA , 1, 0) ///< Whether or not to use struct-path TBAA CODEGENOPT(SaveTempLabels , 1, 0) ///< Save temporary labels. CODEGENOPT(SanitizeAddressUseAfterScope , 1, 0) ///< Enable use-after-scope detection ///< in AddressSanitizer +CODEGENOPT(SanitizeAddressGlobalsDeadStripping, 1, 0) ///< Enable linker dead stripping + ///< of globals in AddressSanitizer CODEGENOPT(SanitizeMemoryTrackOrigins, 2, 0) ///< Enable tracking origins in ///< MemorySanitizer CODEGENOPT(SanitizeMemoryUseAfterDtor, 1, 0) ///< Enable use-after-delete detection diff --git a/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h b/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h index 44b7b2e4a474..7da1e7b41ab8 100644 --- a/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h +++ b/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h @@ -105,9 +105,6 @@ class MacroInfo { /// \brief Must warn if the macro is unused at the end of translation unit. bool IsWarnIfUnused : 1; - /// \brief Whether this macro info was loaded from an AST file. - bool FromASTFile : 1; - /// \brief Whether this macro was used as header guard. bool UsedForHeaderGuard : 1; @@ -264,34 +261,16 @@ public: IsDisabled = true; } - /// \brief Determine whether this macro info came from an AST file (such as - /// a precompiled header or module) rather than having been parsed. - bool isFromASTFile() const { return FromASTFile; } - /// \brief Determine whether this macro was used for a header guard. bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; } void setUsedForHeaderGuard(bool Val) { UsedForHeaderGuard = Val; } - /// \brief Retrieve the global ID of the module that owns this particular - /// macro info. - unsigned getOwningModuleID() const { - if (isFromASTFile()) - return *(const unsigned *)(this + 1); - - return 0; - } - void dump() const; private: unsigned getDefinitionLengthSlow(const SourceManager &SM) const; - void setOwningModuleID(unsigned ID) { - assert(isFromASTFile()); - *(unsigned *)(this + 1) = ID; - } - friend class Preprocessor; }; diff --git a/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h b/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h index 0e3f563785d4..114bf70ad59a 100644 --- a/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h +++ b/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h @@ -644,14 +644,6 @@ class Preprocessor { /// of that list. MacroInfoChain *MIChainHead; - struct DeserializedMacroInfoChain { - MacroInfo MI; - unsigned OwningModuleID; // MUST be immediately after the MacroInfo object - // so it can be accessed by MacroInfo::getOwningModuleID(). - DeserializedMacroInfoChain *Next; - }; - DeserializedMacroInfoChain *DeserialMIChainHead; - void updateOutOfDateIdentifier(IdentifierInfo &II) const; public: @@ -1669,10 +1661,6 @@ public: /// \brief Allocate a new MacroInfo object with the provided SourceLocation. MacroInfo *AllocateMacroInfo(SourceLocation L); - /// \brief Allocate a new MacroInfo object loaded from an AST file. - MacroInfo *AllocateDeserializedMacroInfo(SourceLocation L, - unsigned SubModuleID); - /// \brief Turn the specified lexer token into a fully checked and spelled /// filename, e.g. as an operand of \#include. /// @@ -1764,9 +1752,6 @@ private: /// macro name. void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info); - /// \brief Allocate a new MacroInfo object. - MacroInfo *AllocateMacroInfo(); - DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc); UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc); diff --git a/contrib/llvm/tools/clang/include/clang/Parse/Parser.h b/contrib/llvm/tools/clang/include/clang/Parse/Parser.h index 8d0935dec1b6..f5a7e02941a7 100644 --- a/contrib/llvm/tools/clang/include/clang/Parse/Parser.h +++ b/contrib/llvm/tools/clang/include/clang/Parse/Parser.h @@ -1488,6 +1488,8 @@ private: K == tok::plusplus || K == tok::minusminus); } + bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); + ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); @@ -2723,10 +2725,7 @@ private: bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); - bool ParseTemplateIdAfterTemplateName(TemplateTy Template, - SourceLocation TemplateNameLoc, - const CXXScopeSpec &SS, - bool ConsumeLastToken, + bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); diff --git a/contrib/llvm/tools/clang/include/clang/Sema/Sema.h b/contrib/llvm/tools/clang/include/clang/Sema/Sema.h index e5961079f7c2..e910be14f969 100644 --- a/contrib/llvm/tools/clang/include/clang/Sema/Sema.h +++ b/contrib/llvm/tools/clang/include/clang/Sema/Sema.h @@ -1074,6 +1074,10 @@ public: /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; + /// Stack of types that correspond to the parameter entities that are + /// currently being copy-initialized. Can be empty. + llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; + void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); @@ -1456,6 +1460,11 @@ private: /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; + /// Get the module whose scope we are currently within. + Module *getCurrentModule() const { + return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; + } + VisibleModuleSet VisibleModules; Module *CachedFakeTopLevelModule; @@ -1466,7 +1475,7 @@ public: /// \brief Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. - void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc); + void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); } @@ -1593,7 +1602,7 @@ public: Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, - bool AllowClassTemplates = false); + bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we @@ -1738,6 +1747,23 @@ public: TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); + /// Determine whether it's plausible that E was intended to be a + /// template-name. + bool mightBeIntendedToBeTemplateName(ExprResult E) { + if (!getLangOpts().CPlusPlus || E.isInvalid()) + return false; + if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) + return !DRE->hasExplicitTemplateArgs(); + if (auto *ME = dyn_cast<MemberExpr>(E.get())) + return !ME->hasExplicitTemplateArgs(); + // Any additional cases recognized here should also be handled by + // diagnoseExprIntendedAsTemplateName. + return false; + } + void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, + SourceLocation Less, + SourceLocation Greater); + Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, @@ -2336,6 +2362,7 @@ public: void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); + void notePreviousDefinition(SourceLocation Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions @@ -2726,7 +2753,8 @@ public: resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); - bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr); + bool resolveAndFixAddressOfOnlyViableOverloadCandidate( + ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, @@ -3049,7 +3077,8 @@ public: bool IncludeGlobalScope = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, - bool IncludeGlobalScope = true); + bool IncludeGlobalScope = true, + bool IncludeDependentBases = false); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. @@ -6084,6 +6113,7 @@ public: TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); + void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation(Scope *S, @@ -9259,6 +9289,8 @@ public: /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); + QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, + ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); @@ -10008,6 +10040,7 @@ public: MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteNaturalLanguage(); + void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); diff --git a/contrib/llvm/tools/clang/include/clang/Tooling/RefactoringCallbacks.h b/contrib/llvm/tools/clang/include/clang/Tooling/RefactoringCallbacks.h index 6ef9ea11f0ae..9862951149a3 100644 --- a/contrib/llvm/tools/clang/include/clang/Tooling/RefactoringCallbacks.h +++ b/contrib/llvm/tools/clang/include/clang/Tooling/RefactoringCallbacks.h @@ -47,6 +47,33 @@ protected: Replacements Replace; }; +/// \brief Adaptor between \c ast_matchers::MatchFinder and \c +/// tooling::RefactoringTool. +/// +/// Runs AST matchers and stores the \c tooling::Replacements in a map. +class ASTMatchRefactorer { +public: + explicit ASTMatchRefactorer( + std::map<std::string, Replacements> &FileToReplaces); + + template <typename T> + void addMatcher(const T &Matcher, RefactoringCallback *Callback) { + MatchFinder.addMatcher(Matcher, Callback); + Callbacks.push_back(Callback); + } + + void addDynamicMatcher(const ast_matchers::internal::DynTypedMatcher &Matcher, + RefactoringCallback *Callback); + + std::unique_ptr<ASTConsumer> newASTConsumer(); + +private: + friend class RefactoringASTConsumer; + std::vector<RefactoringCallback *> Callbacks; + ast_matchers::MatchFinder MatchFinder; + std::map<std::string, Replacements> &FileToReplaces; +}; + /// \brief Replace the text of the statement bound to \c FromId with the text in /// \c ToText. class ReplaceStmtWithText : public RefactoringCallback { @@ -59,6 +86,29 @@ private: std::string ToText; }; +/// \brief Replace the text of an AST node bound to \c FromId with the result of +/// evaluating the template in \c ToTemplate. +/// +/// Expressions of the form ${NodeName} in \c ToTemplate will be +/// replaced by the text of the node bound to ${NodeName}. The string +/// "$$" will be replaced by "$". +class ReplaceNodeWithTemplate : public RefactoringCallback { +public: + static llvm::Expected<std::unique_ptr<ReplaceNodeWithTemplate>> + create(StringRef FromId, StringRef ToTemplate); + void run(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + struct TemplateElement { + enum { Literal, Identifier } Type; + std::string Value; + }; + ReplaceNodeWithTemplate(llvm::StringRef FromId, + std::vector<TemplateElement> Template); + std::string FromId; + std::vector<TemplateElement> Template; +}; + /// \brief Replace the text of the statement bound to \c FromId with the text of /// the statement bound to \c ToId. class ReplaceStmtWithStmt : public RefactoringCallback { diff --git a/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp b/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp index 4fb6051d6f58..847638b7bbeb 100644 --- a/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp @@ -1622,10 +1622,18 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { // We may already have a record of the same name; try to find and match it. RecordDecl *AdoptDecl = nullptr; + RecordDecl *PrevDecl = nullptr; if (!DC->isFunctionOrMethod()) { SmallVector<NamedDecl *, 4> ConflictingDecls; SmallVector<NamedDecl *, 2> FoundDecls; DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls); + + if (!FoundDecls.empty()) { + // We're going to have to compare D against potentially conflicting Decls, so complete it. + if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition()) + D->getASTContext().getExternalSource()->CompleteType(D); + } + for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (!FoundDecls[I]->isInIdentifierNamespace(IDNS)) continue; @@ -1652,6 +1660,8 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { } } + PrevDecl = FoundRecord; + if (RecordDecl *FoundDef = FoundRecord->getDefinition()) { if ((SearchName && !D->isCompleteDefinition()) || (D->isCompleteDefinition() && @@ -1744,6 +1754,10 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { LexicalDC->addDeclInternal(D2); if (D->isAnonymousStructOrUnion()) D2->setAnonymousStructOrUnion(true); + if (PrevDecl) { + // FIXME: do this for all Redeclarables, not just RecordDecls. + D2->setPreviousDecl(PrevDecl); + } } Importer.Imported(D, D2); diff --git a/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp b/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp index 8fe72eac4133..9376ee1d4ee4 100644 --- a/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp @@ -855,6 +855,11 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) { if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) { + if (D1CXX->hasExternalLexicalStorage() && + !D1CXX->isCompleteDefinition()) { + D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX); + } + if (D1CXX->getNumBases() != D2CXX->getNumBases()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent) diff --git a/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp b/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp index 56fb0464078f..746602d47be5 100644 --- a/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp +++ b/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp @@ -13,6 +13,7 @@ #include "clang/AST/CXXInheritance.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" +#include "clang/AST/DeclTemplate.h" #include "clang/AST/RecordLayout.h" #include "llvm/ADT/SetVector.h" #include <algorithm> @@ -174,9 +175,10 @@ bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches, return AllMatches; } -bool CXXBasePaths::lookupInBases( - ASTContext &Context, const CXXRecordDecl *Record, - CXXRecordDecl::BaseMatchesCallback BaseMatches) { +bool CXXBasePaths::lookupInBases(ASTContext &Context, + const CXXRecordDecl *Record, + CXXRecordDecl::BaseMatchesCallback BaseMatches, + bool LookupInDependent) { bool FoundPath = false; // The access of the path down to this record. @@ -194,7 +196,7 @@ bool CXXBasePaths::lookupInBases( // the base class scope is not examined during unqualified name lookup // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. - if (BaseType->isDependentType()) + if (!LookupInDependent && BaseType->isDependentType()) continue; // Determine whether we need to visit this base class at all, @@ -262,10 +264,28 @@ bool CXXBasePaths::lookupInBases( return FoundPath; } } else if (VisitBase) { - CXXRecordDecl *BaseRecord - = cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>() - ->getDecl()); - if (lookupInBases(Context, BaseRecord, BaseMatches)) { + CXXRecordDecl *BaseRecord; + if (LookupInDependent) { + BaseRecord = nullptr; + const TemplateSpecializationType *TST = + BaseSpec.getType()->getAs<TemplateSpecializationType>(); + if (!TST) { + if (auto *RT = BaseSpec.getType()->getAs<RecordType>()) + BaseRecord = cast<CXXRecordDecl>(RT->getDecl()); + } else { + TemplateName TN = TST->getTemplateName(); + if (auto *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) + BaseRecord = TD->getTemplatedDecl(); + } + if (BaseRecord && !BaseRecord->hasDefinition()) + BaseRecord = nullptr; + } else { + BaseRecord = cast<CXXRecordDecl>( + BaseSpec.getType()->castAs<RecordType>()->getDecl()); + } + if (BaseRecord && + lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { // C++ [class.member.lookup]p2: // A member name f in one sub-object B hides a member name f in // a sub-object A if A is a base class sub-object of B. Any @@ -299,9 +319,11 @@ bool CXXBasePaths::lookupInBases( } bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, - CXXBasePaths &Paths) const { + CXXBasePaths &Paths, + bool LookupInDependent) const { // If we didn't find anything, report that. - if (!Paths.lookupInBases(getASTContext(), this, BaseMatches)) + if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, + LookupInDependent)) return false; // If we're not recording paths or we won't ever find ambiguities, @@ -387,23 +409,49 @@ bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, return false; } -bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier, - CXXBasePath &Path, - DeclarationName Name) { - RecordDecl *BaseRecord = - Specifier->getType()->castAs<RecordType>()->getDecl(); - - const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member; +static bool findOrdinaryMember(RecordDecl *BaseRecord, CXXBasePath &Path, + DeclarationName Name) { + const unsigned IDNS = clang::Decl::IDNS_Ordinary | clang::Decl::IDNS_Tag | + clang::Decl::IDNS_Member; for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); Path.Decls = Path.Decls.slice(1)) { if (Path.Decls.front()->isInIdentifierNamespace(IDNS)) return true; } - + return false; } +bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier, + CXXBasePath &Path, + DeclarationName Name) { + RecordDecl *BaseRecord = + Specifier->getType()->castAs<RecordType>()->getDecl(); + return findOrdinaryMember(BaseRecord, Path, Name); +} + +bool CXXRecordDecl::FindOrdinaryMemberInDependentClasses( + const CXXBaseSpecifier *Specifier, CXXBasePath &Path, + DeclarationName Name) { + const TemplateSpecializationType *TST = + Specifier->getType()->getAs<TemplateSpecializationType>(); + if (!TST) { + auto *RT = Specifier->getType()->getAs<RecordType>(); + if (!RT) + return false; + return findOrdinaryMember(RT->getDecl(), Path, Name); + } + TemplateName TN = TST->getTemplateName(); + const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); + if (!TD) + return false; + CXXRecordDecl *RD = TD->getTemplatedDecl(); + if (!RD) + return false; + return findOrdinaryMember(RD, Path, Name); +} + bool CXXRecordDecl::FindOMPReductionMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { @@ -438,6 +486,36 @@ FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, return false; } +std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName( + const DeclarationName &Name, + llvm::function_ref<bool(const NamedDecl *ND)> Filter) { + std::vector<const NamedDecl *> Results; + // Lookup in the class. + DeclContext::lookup_result DirectResult = lookup(Name); + if (!DirectResult.empty()) { + for (const NamedDecl *ND : DirectResult) { + if (Filter(ND)) + Results.push_back(ND); + } + return Results; + } + // Perform lookup into our base classes. + CXXBasePaths Paths; + Paths.setOrigin(this); + if (!lookupInBases( + [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { + return CXXRecordDecl::FindOrdinaryMemberInDependentClasses( + Specifier, Path, Name); + }, + Paths, /*LookupInDependent=*/true)) + return Results; + for (const NamedDecl *ND : Paths.front().Decls) { + if (Filter(ND)) + Results.push_back(ND); + } + return Results; +} + void OverridingMethods::add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding) { SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides diff --git a/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp b/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp index dd8f768c5711..9f87fe12a9cd 100644 --- a/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp +++ b/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp @@ -1432,8 +1432,9 @@ bool CXXRecordDecl::isAnyDestructorNoReturn() const { // Check base classes destructor for noreturn. for (const auto &Base : bases()) - if (Base.getType()->getAsCXXRecordDecl()->isAnyDestructorNoReturn()) - return true; + if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) + if (RD->isAnyDestructorNoReturn()) + return true; // Check fields for noreturn. for (const auto *Field : fields()) diff --git a/contrib/llvm/tools/clang/lib/AST/ExternalASTMerger.cpp b/contrib/llvm/tools/clang/lib/AST/ExternalASTMerger.cpp index 8849cfc3c80b..1dc472a5f753 100644 --- a/contrib/llvm/tools/clang/lib/AST/ExternalASTMerger.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ExternalASTMerger.cpp @@ -178,3 +178,9 @@ void ExternalASTMerger::FindExternalLexicalDecls( } }); } + +void ExternalASTMerger::CompleteType(TagDecl *Tag) { + SmallVector<Decl *, 0> Result; + FindExternalLexicalDecls(Tag, [](Decl::Kind) { return true; }, Result); + Tag->setHasExternalLexicalStorage(false); +} diff --git a/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp b/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp index 83168d0924f6..f4d314a6dd0d 100644 --- a/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp +++ b/contrib/llvm/tools/clang/lib/AST/ODRHash.cpp @@ -411,7 +411,7 @@ public: void VisitTypedefType(const TypedefType *T) { AddDecl(T->getDecl()); - Hash.AddQualType(T->getDecl()->getUnderlyingType()); + AddQualType(T->getDecl()->getUnderlyingType().getCanonicalType()); VisitType(T); } }; diff --git a/contrib/llvm/tools/clang/lib/AST/Stmt.cpp b/contrib/llvm/tools/clang/lib/AST/Stmt.cpp index 69e65f558f89..2367cadf645c 100644 --- a/contrib/llvm/tools/clang/lib/AST/Stmt.cpp +++ b/contrib/llvm/tools/clang/lib/AST/Stmt.cpp @@ -1112,7 +1112,7 @@ void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) { bool CapturedStmt::capturesVariable(const VarDecl *Var) const { for (const auto &I : captures()) { - if (!I.capturesVariable()) + if (!I.capturesVariable() && !I.capturesVariableByCopy()) continue; // This does not handle variable redeclarations. This should be diff --git a/contrib/llvm/tools/clang/lib/AST/Type.cpp b/contrib/llvm/tools/clang/lib/AST/Type.cpp index df26233b4796..22d52bcd3f31 100644 --- a/contrib/llvm/tools/clang/lib/AST/Type.cpp +++ b/contrib/llvm/tools/clang/lib/AST/Type.cpp @@ -2114,18 +2114,15 @@ bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { if (hasNonTrivialObjCLifetime()) return false; - // C++11 [basic.types]p9 + // C++11 [basic.types]p9 - See Core 2094 // Scalar types, trivially copyable class types, arrays of such types, and - // non-volatile const-qualified versions of these types are collectively + // cv-qualified versions of these types are collectively // called trivially copyable types. QualType CanonicalType = getCanonicalType(); if (CanonicalType->isDependentType()) return false; - if (CanonicalType.isVolatileQualified()) - return false; - // Return false for incomplete types after skipping any incomplete array types // which are expressly allowed by the standard and thus our API. if (CanonicalType->isIncompleteType()) diff --git a/contrib/llvm/tools/clang/lib/Basic/Targets.cpp b/contrib/llvm/tools/clang/lib/Basic/Targets.cpp index 33eb0b05ddcd..92c561aa9413 100644 --- a/contrib/llvm/tools/clang/lib/Basic/Targets.cpp +++ b/contrib/llvm/tools/clang/lib/Basic/Targets.cpp @@ -6862,6 +6862,11 @@ public: case 'N': // Same as 'K' but zext (required for SIMode) case 'O': // The constant 4096 return true; + + case 'f': + case 'e': + info.setAllowsRegister(); + return true; } return false; } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp b/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp index 0d96f2efa60a..0f07169ac8b0 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp @@ -194,6 +194,8 @@ static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, // where this is not a factor). Also, on ELF this feature requires an assembler // extension that only works with -integrated-as at the moment. static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { + if (!CGOpts.SanitizeAddressGlobalsDeadStripping) + return false; switch (T.getObjectFormat()) { case Triple::MachO: case Triple::COFF: @@ -1071,7 +1073,8 @@ void clang::EmitBackendOutput(DiagnosticsEngine &Diags, // into memory and pass it into runThinLTOBackend, which will run the // function importer and invoke LTO passes. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = - llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile); + llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, + /*IgnoreEmptyThinLTOIndexFile*/true); if (!IndexOrErr) { logAllUnhandledErrors(IndexOrErr.takeError(), errs(), "Error loading index file '" + diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp index 2b2a92dd6019..f1c20e9df1f3 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp @@ -878,7 +878,8 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) { // If type is const-qualified, copy the value into the block field. } else if (type.isConstQualified() && - type.getObjCLifetime() == Qualifiers::OCL_Strong) { + type.getObjCLifetime() == Qualifiers::OCL_Strong && + CGM.getCodeGenOpts().OptimizationLevel != 0) { llvm::Value *value = Builder.CreateLoad(src, "captured"); Builder.CreateStore(value, blockField); @@ -960,9 +961,8 @@ llvm::Type *CodeGenModule::getBlockDescriptorType() { // const char *signature; // the block signature // const char *layout; // reserved // }; - BlockDescriptorType = - llvm::StructType::create("struct.__block_descriptor", - UnsignedLongTy, UnsignedLongTy, nullptr); + BlockDescriptorType = llvm::StructType::create( + "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy); // Now form a pointer to that. unsigned AddrSpace = 0; @@ -986,9 +986,8 @@ llvm::Type *CodeGenModule::getGenericBlockLiteralType() { // struct __block_descriptor *__descriptor; // }; GenericBlockLiteralType = - llvm::StructType::create("struct.__block_literal_generic", - VoidPtrTy, IntTy, IntTy, VoidPtrTy, - BlockDescPtrTy, nullptr); + llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy, + IntTy, IntTy, VoidPtrTy, BlockDescPtrTy); return GenericBlockLiteralType; } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp index 2f05c0e910e5..50c9e22801c7 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp @@ -2769,6 +2769,32 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, return RValue::get(ConstantInt::get(ConvertType(E->getType()), Layout.size().getQuantity())); } + + case Builtin::BI__xray_customevent: { + if (!ShouldXRayInstrumentFunction()) + return RValue::getIgnored(); + if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>()) { + if (XRayAttr->neverXRayInstrument()) + return RValue::getIgnored(); + } + Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent); + auto FTy = F->getFunctionType(); + auto Arg0 = E->getArg(0); + auto Arg0Val = EmitScalarExpr(Arg0); + auto Arg0Ty = Arg0->getType(); + auto PTy0 = FTy->getParamType(0); + if (PTy0 != Arg0Val->getType()) { + if (Arg0Ty->isArrayType()) + Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer(); + else + Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0); + } + auto Arg1 = EmitScalarExpr(E->getArg(1)); + auto PTy1 = FTy->getParamType(1); + if (PTy1 != Arg1->getType()) + Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1); + return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1})); + } } // If this is an alias for a lib function (e.g. __builtin_sin), emit @@ -4545,7 +4571,7 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID, Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI__builtin_arm_stlex ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd); - llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, nullptr); + llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty); Address Tmp = CreateMemTemp(E->getArg(0)->getType()); Value *Val = EmitScalarExpr(E->getArg(0)); @@ -5375,7 +5401,7 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID, Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_stlex ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp); - llvm::Type *STy = llvm::StructType::get(Int64Ty, Int64Ty, nullptr); + llvm::Type *STy = llvm::StructType::get(Int64Ty, Int64Ty); Address Tmp = CreateMemTemp(E->getArg(0)->getType()); EmitAnyExprToMem(E->getArg(0), Tmp, Qualifiers(), /*init*/ true); @@ -7347,8 +7373,8 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, // unsigned int __cpu_type; // unsigned int __cpu_subtype; // unsigned int __cpu_features[1]; - llvm::Type *STy = llvm::StructType::get( - Int32Ty, Int32Ty, Int32Ty, llvm::ArrayType::get(Int32Ty, 1), nullptr); + llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, Int32Ty, + llvm::ArrayType::get(Int32Ty, 1)); // Grab the global __cpu_model. llvm::Constant *CpuModel = CGM.CreateRuntimeVariable(STy, "__cpu_model"); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGCUDANV.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGCUDANV.cpp index 813cd7400186..d24ef0a8a974 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGCUDANV.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGCUDANV.cpp @@ -265,7 +265,7 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() { "__cudaRegisterFatBinary"); // struct { int magic, int version, void * gpu_binary, void * dont_care }; llvm::StructType *FatbinWrapperTy = - llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy, nullptr); + llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy); llvm::Function *ModuleCtorFunc = llvm::Function::Create( llvm::FunctionType::get(VoidTy, VoidPtrTy, false), diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp index 437ab7dd4649..e8bcf0a3ac56 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp @@ -51,8 +51,7 @@ DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) { if (rv.isComplex()) { CodeGenFunction::ComplexPairTy V = rv.getComplexVal(); llvm::Type *ComplexTy = - llvm::StructType::get(V.first->getType(), V.second->getType(), - (void*) nullptr); + llvm::StructType::get(V.first->getType(), V.second->getType()); Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex"); CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0, CharUnits())); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp index 3e5434660567..9d77c61bd52c 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp @@ -209,7 +209,7 @@ llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context, // Check namespace. if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context)) - return getOrCreateNameSpace(NSDecl); + return getOrCreateNamespace(NSDecl); if (const auto *RDecl = dyn_cast<RecordDecl>(Context)) if (!RDecl->isDependentType()) @@ -2860,8 +2860,8 @@ void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, if (DebugKind >= codegenoptions::LimitedDebugInfo) { if (const NamespaceDecl *NSDecl = - dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) - FDContext = getOrCreateNameSpace(NSDecl); + dyn_cast_or_null<NamespaceDecl>(FD->getLexicalDeclContext())) + FDContext = getOrCreateNamespace(NSDecl); else if (const RecordDecl *RDecl = dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { llvm::DIScope *Mod = getParentModuleOrNull(RDecl); @@ -3961,7 +3961,7 @@ void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { CGM.getCodeGenOpts().DebugExplicitImport) { DBuilder.createImportedModule( getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), - getOrCreateNameSpace(NSDecl), + getOrCreateNamespace(NSDecl), getLineNumber(UD.getLocation())); } } @@ -4021,23 +4021,26 @@ CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { else R = DBuilder.createImportedDeclaration( getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), - getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), + getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())), getLineNumber(NA.getLocation()), NA.getName()); VH.reset(R); return R; } llvm::DINamespace * -CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { - NSDecl = NSDecl->getCanonicalDecl(); - auto I = NameSpaceCache.find(NSDecl); - if (I != NameSpaceCache.end()) +CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { + // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued + // if necessary, and this way multiple declarations of the same namespace in + // different parent modules stay distinct. + auto I = NamespaceCache.find(NSDecl); + if (I != NamespaceCache.end()) return cast<llvm::DINamespace>(I->second); llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); + // Don't trust the context if it is a DIModule (see comment above). llvm::DINamespace *NS = DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline()); - NameSpaceCache[NSDecl].reset(NS); + NamespaceCache[NSDecl].reset(NS); return NS; } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h b/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h index 5050ca0ad3fa..7de48f278994 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h @@ -125,7 +125,7 @@ class CGDebugInfo { /// Cache declarations relevant to DW_TAG_imported_declarations (C++ /// using declarations) that aren't covered by other more specific caches. llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache; - llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NameSpaceCache; + llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache; llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef> NamespaceAliasCache; llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>> @@ -194,8 +194,9 @@ class CGDebugInfo { getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F); /// \return debug info descriptor for vtable. llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F); + /// \return namespace descriptor for the given namespace decl. - llvm::DINamespace *getOrCreateNameSpace(const NamespaceDecl *N); + llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N); llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty, QualType PointeeTy, llvm::DIFile *F); llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp index 10a0b46d9028..0fa8eeb1c3e1 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp @@ -152,7 +152,14 @@ void CodeGenFunction::EmitDecl(const Decl &D) { /// EmitVarDecl - This method handles emission of any variable declaration /// inside a function, including static vars etc. void CodeGenFunction::EmitVarDecl(const VarDecl &D) { - if (D.isStaticLocal()) { + if (D.hasExternalStorage()) + // Don't emit it now, allow it to be emitted lazily on its first use. + return; + + // Some function-scope variable does not have static storage but still + // needs to be emitted like a static variable, e.g. a function-scope + // variable in constant address space in OpenCL. + if (D.getStorageDuration() != SD_Automatic) { llvm::GlobalValue::LinkageTypes Linkage = CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false); @@ -163,10 +170,6 @@ void CodeGenFunction::EmitVarDecl(const VarDecl &D) { return EmitStaticVarDecl(D, Linkage); } - if (D.hasExternalStorage()) - // Don't emit it now, allow it to be emitted lazily on its first use. - return; - if (D.getType().getAddressSpace() == LangAS::opencl_local) return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp index ca1535182ec1..e65fa863fe31 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp @@ -765,8 +765,8 @@ llvm::BasicBlock *CodeGenFunction::EmitLandingPad() { llvm::BasicBlock *lpad = createBasicBlock("lpad"); EmitBlock(lpad); - llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad( - llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0); + llvm::LandingPadInst *LPadInst = + Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0); llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0); Builder.CreateStore(LPadExn, getExceptionSlot()); @@ -1310,8 +1310,8 @@ llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() { if (!CurFn->hasPersonalityFn()) CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality)); - llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad( - llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0); + llvm::LandingPadInst *LPadInst = + Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0); LPadInst->addClause(getCatchAllValue(*this)); llvm::Value *Exn = nullptr; @@ -1387,8 +1387,7 @@ llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) { llvm::Value *Exn = getExceptionFromSlot(); llvm::Value *Sel = getSelectorFromSlot(); - llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), - Sel->getType(), nullptr); + llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType()); llvm::Value *LPadVal = llvm::UndefValue::get(LPadType); LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val"); LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val"); @@ -1747,7 +1746,7 @@ void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, // }; // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode; llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo(); - llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr); + llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy); llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo()); llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0); Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign()); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp index 863b4380da47..cef6292c0e4d 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp @@ -2859,9 +2859,9 @@ void CodeGenFunction::EmitCfiCheckFail() { EmitTrapCheck(DataIsNotNullPtr); llvm::StructType *SourceLocationTy = - llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr); + llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); llvm::StructType *CfiCheckFailDataTy = - llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr); + llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); llvm::Value *V = Builder.CreateConstGEP2_32( CfiCheckFailDataTy, diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp index 49bbb4808eaa..a05a088f0919 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp @@ -512,12 +512,20 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, currentElement->addIncoming(element, entryBB); // Emit the actual filler expression. - LValue elementLV = - CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType); - if (filler) - EmitInitializationToLValue(filler, elementLV); - else - EmitNullInitializationToLValue(elementLV); + { + // C++1z [class.temporary]p5: + // when a default constructor is called to initialize an element of + // an array with no corresponding initializer [...] the destruction of + // every temporary created in a default argument is sequenced before + // the construction of the next array element, if any + CodeGenFunction::RunCleanupsScope CleanupsScope(CGF); + LValue elementLV = + CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType); + if (filler) + EmitInitializationToLValue(filler, elementLV); + else + EmitNullInitializationToLValue(elementLV); + } // Move on to the next element. llvm::Value *nextElement = diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp index 53c184130709..6b72774c10a5 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp @@ -1361,9 +1361,8 @@ llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value, Value.getComplexIntImag()); // FIXME: the target may want to specify that this is packed. - llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), - Complex[1]->getType(), - nullptr); + llvm::StructType *STy = + llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); return llvm::ConstantStruct::get(STy, Complex); } case APValue::Float: { @@ -1384,9 +1383,8 @@ llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value, Value.getComplexFloatImag()); // FIXME: the target may want to specify that this is packed. - llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), - Complex[1]->getType(), - nullptr); + llvm::StructType *STy = + llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); return llvm::ConstantStruct::get(STy, Complex); } case APValue::Vector: { diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp index 70b741651fd1..b8d830ee9f3f 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp @@ -89,14 +89,14 @@ struct BinOpInfo { } /// Check if the binop computes a division or a remainder. - bool isDivisionLikeOperation() const { + bool isDivremOp() const { return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign || Opcode == BO_RemAssign; } /// Check if the binop can result in an integer division by zero. bool mayHaveIntegerDivisionByZero() const { - if (isDivisionLikeOperation()) + if (isDivremOp()) if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS)) return CI->isZero(); return true; @@ -104,7 +104,7 @@ struct BinOpInfo { /// Check if the binop can result in a float division by zero. bool mayHaveFloatDivisionByZero() const { - if (isDivisionLikeOperation()) + if (isDivremOp()) if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS)) return CFP->isZero(); return true; @@ -2552,6 +2552,7 @@ Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { if (isSigned) OpID |= 1; + CodeGenFunction::SanitizerScope SanScope(&CGF); llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty); llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy); @@ -2567,7 +2568,6 @@ Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) { // If the signed-integer-overflow sanitizer is enabled, emit a call to its // runtime. Otherwise, this is a -ftrapv check, so just emit a trap. if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) { - CodeGenFunction::SanitizerScope SanScope(&CGF); llvm::Value *NotOverflow = Builder.CreateNot(overflow); SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow : SanitizerKind::UnsignedIntegerOverflow; diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp index 821629c50d4a..c8b8be7f4552 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp @@ -34,7 +34,6 @@ #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/Compiler.h" -#include <cstdarg> using namespace clang; using namespace CodeGen; @@ -58,18 +57,19 @@ public: /// Initialises the lazy function with the name, return type, and the types /// of the arguments. - LLVM_END_WITH_NULL - void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) { + template <typename... Tys> + void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, + Tys *... Types) { CGM = Mod; FunctionName = name; Function = nullptr; - std::vector<llvm::Type *> ArgTys; - va_list Args; - va_start(Args, RetTy); - while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *)) - ArgTys.push_back(ArgTy); - va_end(Args); - FTy = llvm::FunctionType::get(RetTy, ArgTys, false); + if(sizeof...(Tys)) { + SmallVector<llvm::Type *, 8> ArgTys({Types...}); + FTy = llvm::FunctionType::get(RetTy, ArgTys, false); + } + else { + FTy = llvm::FunctionType::get(RetTy, None, false); + } } llvm::FunctionType *getType() { return FTy; } @@ -603,11 +603,10 @@ protected: public: CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) { // IMP objc_msg_lookup(id, SEL); - MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, - nullptr); + MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); // IMP objc_msg_lookup_super(struct objc_super*, SEL); MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, - PtrToObjCSuperTy, SelectorTy, nullptr); + PtrToObjCSuperTy, SelectorTy); } }; @@ -702,52 +701,51 @@ class CGObjCGNUstep : public CGObjCGNU { CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) { const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime; - llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy, - PtrTy, PtrTy, IntTy, IMPTy, nullptr); + llvm::StructType *SlotStructTy = + llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy); SlotTy = llvm::PointerType::getUnqual(SlotStructTy); // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender); SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy, - SelectorTy, IdTy, nullptr); + SelectorTy, IdTy); // Slot_t objc_msg_lookup_super(struct objc_super*, SEL); SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, - PtrToObjCSuperTy, SelectorTy, nullptr); + PtrToObjCSuperTy, SelectorTy); // If we're in ObjC++ mode, then we want to make if (CGM.getLangOpts().CPlusPlus) { llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); // void *__cxa_begin_catch(void *e) - EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr); + EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy); // void __cxa_end_catch(void) - ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr); + ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy); // void _Unwind_Resume_or_Rethrow(void*) ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy, - PtrTy, nullptr); + PtrTy); } else if (R.getVersion() >= VersionTuple(1, 7)) { llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); // id objc_begin_catch(void *e) - EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr); + EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy); // void objc_end_catch(void) - ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr); + ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy); // void _Unwind_Resume_or_Rethrow(void*) - ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, - PtrTy, nullptr); + ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy); } llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy, - SelectorTy, IdTy, PtrDiffTy, nullptr); + SelectorTy, IdTy, PtrDiffTy); SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy, - IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); + IdTy, SelectorTy, IdTy, PtrDiffTy); SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy, - IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); + IdTy, SelectorTy, IdTy, PtrDiffTy); SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy", - VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr); + VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy); // void objc_setCppObjectAtomic(void *dest, const void *src, void // *helper); CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy, - PtrTy, PtrTy, nullptr); + PtrTy, PtrTy); // void objc_getCppObjectAtomic(void *dest, const void *src, void // *helper); CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy, - PtrTy, PtrTy, nullptr); + PtrTy, PtrTy); } llvm::Constant *GetCppAtomicObjectGetFunction() override { @@ -849,14 +847,14 @@ protected: public: CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) { // IMP objc_msg_lookup(id, SEL); - MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr); + MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy); MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy, - SelectorTy, nullptr); + SelectorTy); // IMP objc_msg_lookup_super(struct objc_super*, SEL); MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy, - PtrToObjCSuperTy, SelectorTy, nullptr); + PtrToObjCSuperTy, SelectorTy); MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy, - PtrToObjCSuperTy, SelectorTy, nullptr); + PtrToObjCSuperTy, SelectorTy); } }; } // end anonymous namespace @@ -945,35 +943,34 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, } PtrToIdTy = llvm::PointerType::getUnqual(IdTy); - ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr); + ObjCSuperTy = llvm::StructType::get(IdTy, IdTy); PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy); llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); // void objc_exception_throw(id); - ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr); - ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr); + ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); + ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy); // int objc_sync_enter(id); - SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr); + SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy); // int objc_sync_exit(id); - SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr); + SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy); // void objc_enumerationMutation (id) - EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, - IdTy, nullptr); + EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy); // id objc_getProperty(id, SEL, ptrdiff_t, BOOL) GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy, - PtrDiffTy, BoolTy, nullptr); + PtrDiffTy, BoolTy); // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL) SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy, - PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr); + PtrDiffTy, IdTy, BoolTy, BoolTy); // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) - GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, - PtrDiffTy, BoolTy, BoolTy, nullptr); + GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy, + PtrDiffTy, BoolTy, BoolTy); // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL) - SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, - PtrDiffTy, BoolTy, BoolTy, nullptr); + SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy, + PtrDiffTy, BoolTy, BoolTy); // IMP type llvm::Type *IMPArgs[] = { IdTy, SelectorTy }; @@ -997,21 +994,19 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion, // Get functions needed in GC mode // id objc_assign_ivar(id, id, ptrdiff_t); - IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy, - nullptr); + IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy); // id objc_assign_strongCast (id, id*) StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy, - PtrToIdTy, nullptr); + PtrToIdTy); // id objc_assign_global(id, id*); - GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy, - nullptr); + GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy); // id objc_assign_weak(id, id*); - WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr); + WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy); // id objc_read_weak(id*); - WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr); + WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy); // void *objc_memmove_collectable(void*, void *, size_t); MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy, - SizeTy, nullptr); + SizeTy); } } @@ -1317,7 +1312,7 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF, } } // Cast the pointer to a simplified version of the class structure - llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr); + llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy); ReceiverClass = Builder.CreateBitCast(ReceiverClass, llvm::PointerType::getUnqual(CastTy)); // Get the superclass pointer @@ -1326,8 +1321,8 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF, ReceiverClass = Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign()); // Construct the structure used to look up the IMP - llvm::StructType *ObjCSuperTy = llvm::StructType::get( - Receiver->getType(), IdTy, nullptr); + llvm::StructType *ObjCSuperTy = + llvm::StructType::get(Receiver->getType(), IdTy); // FIXME: Is this really supposed to be a dynamic alloca? Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy), @@ -1565,11 +1560,8 @@ GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames, IvarList.addInt(IntTy, (int)IvarNames.size()); // Get the ivar structure type. - llvm::StructType *ObjCIvarTy = llvm::StructType::get( - PtrToInt8Ty, - PtrToInt8Ty, - IntTy, - nullptr); + llvm::StructType *ObjCIvarTy = + llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy); // Array of ivar structures. auto Ivars = IvarList.beginArray(ObjCIvarTy); @@ -1611,7 +1603,7 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( // anyway; the classes will still work with the GNU runtime, they will just // be ignored. llvm::StructType *ClassTy = llvm::StructType::get( - PtrToInt8Ty, // isa + PtrToInt8Ty, // isa PtrToInt8Ty, // super_class PtrToInt8Ty, // name LongTy, // version @@ -1620,18 +1612,18 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( IVars->getType(), // ivars Methods->getType(), // methods // These are all filled in by the runtime, so we pretend - PtrTy, // dtable - PtrTy, // subclass_list - PtrTy, // sibling_class - PtrTy, // protocols - PtrTy, // gc_object_type + PtrTy, // dtable + PtrTy, // subclass_list + PtrTy, // sibling_class + PtrTy, // protocols + PtrTy, // gc_object_type // New ABI: LongTy, // abi_version IvarOffsets->getType(), // ivar_offsets Properties->getType(), // properties IntPtrTy, // strong_pointers - IntPtrTy, // weak_pointers - nullptr); + IntPtrTy // weak_pointers + ); ConstantInitBuilder Builder(CGM); auto Elements = Builder.beginStruct(ClassTy); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp index 70d24b791334..9c048423285b 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp @@ -105,8 +105,8 @@ private: llvm::Constant *getMessageSendFp2retFn() const { llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext); - llvm::Type *resultType = - llvm::StructType::get(longDoubleType, longDoubleType, nullptr); + llvm::Type *resultType = + llvm::StructType::get(longDoubleType, longDoubleType); return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType, params, true), @@ -5506,17 +5506,15 @@ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) // char *name; // char *attributes; // } - PropertyTy = llvm::StructType::create("struct._prop_t", - Int8PtrTy, Int8PtrTy, nullptr); + PropertyTy = llvm::StructType::create("struct._prop_t", Int8PtrTy, Int8PtrTy); // struct _prop_list_t { // uint32_t entsize; // sizeof(struct _prop_t) // uint32_t count_of_properties; // struct _prop_t prop_list[count_of_properties]; // } - PropertyListTy = - llvm::StructType::create("struct._prop_list_t", IntTy, IntTy, - llvm::ArrayType::get(PropertyTy, 0), nullptr); + PropertyListTy = llvm::StructType::create( + "struct._prop_list_t", IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0)); // struct _prop_list_t * PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); @@ -5525,9 +5523,8 @@ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) // char *method_type; // char *_imp; // } - MethodTy = llvm::StructType::create("struct._objc_method", - SelectorPtrTy, Int8PtrTy, Int8PtrTy, - nullptr); + MethodTy = llvm::StructType::create("struct._objc_method", SelectorPtrTy, + Int8PtrTy, Int8PtrTy); // struct _objc_cache * CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache"); @@ -5540,17 +5537,16 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // SEL name; // char *types; // } - MethodDescriptionTy = - llvm::StructType::create("struct._objc_method_description", - SelectorPtrTy, Int8PtrTy, nullptr); + MethodDescriptionTy = llvm::StructType::create( + "struct._objc_method_description", SelectorPtrTy, Int8PtrTy); // struct _objc_method_description_list { // int count; // struct _objc_method_description[1]; // } - MethodDescriptionListTy = llvm::StructType::create( - "struct._objc_method_description_list", IntTy, - llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr); + MethodDescriptionListTy = + llvm::StructType::create("struct._objc_method_description_list", IntTy, + llvm::ArrayType::get(MethodDescriptionTy, 0)); // struct _objc_method_description_list * MethodDescriptionListPtrTy = @@ -5566,11 +5562,10 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // const char ** extendedMethodTypes; // struct _objc_property_list *class_properties; // } - ProtocolExtensionTy = - llvm::StructType::create("struct._objc_protocol_extension", - IntTy, MethodDescriptionListPtrTy, - MethodDescriptionListPtrTy, PropertyListPtrTy, - Int8PtrPtrTy, PropertyListPtrTy, nullptr); + ProtocolExtensionTy = llvm::StructType::create( + "struct._objc_protocol_extension", IntTy, MethodDescriptionListPtrTy, + MethodDescriptionListPtrTy, PropertyListPtrTy, Int8PtrPtrTy, + PropertyListPtrTy); // struct _objc_protocol_extension * ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); @@ -5582,10 +5577,8 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) ProtocolListTy = llvm::StructType::create(VMContext, "struct._objc_protocol_list"); - ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), - LongTy, - llvm::ArrayType::get(ProtocolTy, 0), - nullptr); + ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), LongTy, + llvm::ArrayType::get(ProtocolTy, 0)); // struct _objc_protocol { // struct _objc_protocol_extension *isa; @@ -5596,9 +5589,7 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // } ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy, llvm::PointerType::getUnqual(ProtocolListTy), - MethodDescriptionListPtrTy, - MethodDescriptionListPtrTy, - nullptr); + MethodDescriptionListPtrTy, MethodDescriptionListPtrTy); // struct _objc_protocol_list * ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); @@ -5612,8 +5603,8 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // char *ivar_type; // int ivar_offset; // } - IvarTy = llvm::StructType::create("struct._objc_ivar", - Int8PtrTy, Int8PtrTy, IntTy, nullptr); + IvarTy = llvm::StructType::create("struct._objc_ivar", Int8PtrTy, Int8PtrTy, + IntTy); // struct _objc_ivar_list * IvarListTy = @@ -5626,9 +5617,8 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); // struct _objc_class_extension * - ClassExtensionTy = - llvm::StructType::create("struct._objc_class_extension", - IntTy, Int8PtrTy, PropertyListPtrTy, nullptr); + ClassExtensionTy = llvm::StructType::create( + "struct._objc_class_extension", IntTy, Int8PtrTy, PropertyListPtrTy); ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); ClassTy = llvm::StructType::create(VMContext, "struct._objc_class"); @@ -5648,18 +5638,9 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // struct _objc_class_ext *ext; // }; ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy), - llvm::PointerType::getUnqual(ClassTy), - Int8PtrTy, - LongTy, - LongTy, - LongTy, - IvarListPtrTy, - MethodListPtrTy, - CachePtrTy, - ProtocolListPtrTy, - Int8PtrTy, - ClassExtensionPtrTy, - nullptr); + llvm::PointerType::getUnqual(ClassTy), Int8PtrTy, LongTy, + LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy, + ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy); ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); @@ -5673,12 +5654,10 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // struct _objc_property_list *instance_properties;// category's @property // struct _objc_property_list *class_properties; // } - CategoryTy = - llvm::StructType::create("struct._objc_category", - Int8PtrTy, Int8PtrTy, MethodListPtrTy, - MethodListPtrTy, ProtocolListPtrTy, - IntTy, PropertyListPtrTy, PropertyListPtrTy, - nullptr); + CategoryTy = llvm::StructType::create( + "struct._objc_category", Int8PtrTy, Int8PtrTy, MethodListPtrTy, + MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy, + PropertyListPtrTy); // Global metadata structures @@ -5689,10 +5668,9 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // short cat_def_cnt; // char *defs[cls_def_cnt + cat_def_cnt]; // } - SymtabTy = - llvm::StructType::create("struct._objc_symtab", - LongTy, SelectorPtrTy, ShortTy, ShortTy, - llvm::ArrayType::get(Int8PtrTy, 0), nullptr); + SymtabTy = llvm::StructType::create("struct._objc_symtab", LongTy, + SelectorPtrTy, ShortTy, ShortTy, + llvm::ArrayType::get(Int8PtrTy, 0)); SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); // struct _objc_module { @@ -5701,10 +5679,8 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // char *name; // struct _objc_symtab* symtab; // } - ModuleTy = - llvm::StructType::create("struct._objc_module", - LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr); - + ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy, + Int8PtrTy, SymtabPtrTy); // FIXME: This is the size of the setjmp buffer and should be target // specific. 18 is what's used on 32-bit X86. @@ -5713,10 +5689,9 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) // Exceptions llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4); - ExceptionDataTy = - llvm::StructType::create("struct._objc_exception_data", - llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize), - StackPtrTy, nullptr); + ExceptionDataTy = llvm::StructType::create( + "struct._objc_exception_data", + llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy); } ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) @@ -5727,8 +5702,8 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // struct _objc_method method_list[method_count]; // } MethodListnfABITy = - llvm::StructType::create("struct.__method_list_t", IntTy, IntTy, - llvm::ArrayType::get(MethodTy, 0), nullptr); + llvm::StructType::create("struct.__method_list_t", IntTy, IntTy, + llvm::ArrayType::get(MethodTy, 0)); // struct method_list_t * MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); @@ -5752,14 +5727,12 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul ProtocolListnfABITy = llvm::StructType::create(VMContext, "struct._objc_protocol_list"); - ProtocolnfABITy = - llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy, - llvm::PointerType::getUnqual(ProtocolListnfABITy), - MethodListnfABIPtrTy, MethodListnfABIPtrTy, - MethodListnfABIPtrTy, MethodListnfABIPtrTy, - PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, - Int8PtrTy, PropertyListPtrTy, - nullptr); + ProtocolnfABITy = llvm::StructType::create( + "struct._protocol_t", ObjectPtrTy, Int8PtrTy, + llvm::PointerType::getUnqual(ProtocolListnfABITy), MethodListnfABIPtrTy, + MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, + PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, Int8PtrTy, + PropertyListPtrTy); // struct _protocol_t* ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); @@ -5769,8 +5742,7 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // struct _protocol_t *[protocol_count]; // } ProtocolListnfABITy->setBody(LongTy, - llvm::ArrayType::get(ProtocolnfABIPtrTy, 0), - nullptr); + llvm::ArrayType::get(ProtocolnfABIPtrTy, 0)); // struct _objc_protocol_list* ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); @@ -5784,7 +5756,7 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // } IvarnfABITy = llvm::StructType::create( "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy), - Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr); + Int8PtrTy, Int8PtrTy, IntTy, IntTy); // struct _ivar_list_t { // uint32 entsize; // sizeof(struct _ivar_t) @@ -5792,8 +5764,8 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // struct _iver_t list[count]; // } IvarListnfABITy = - llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy, - llvm::ArrayType::get(IvarnfABITy, 0), nullptr); + llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy, + llvm::ArrayType::get(IvarnfABITy, 0)); IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); @@ -5812,13 +5784,10 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // } // FIXME. Add 'reserved' field in 64bit abi mode! - ClassRonfABITy = llvm::StructType::create("struct._class_ro_t", - IntTy, IntTy, IntTy, Int8PtrTy, - Int8PtrTy, MethodListnfABIPtrTy, - ProtocolListnfABIPtrTy, - IvarListnfABIPtrTy, - Int8PtrTy, PropertyListPtrTy, - nullptr); + ClassRonfABITy = llvm::StructType::create( + "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy, + MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy, + Int8PtrTy, PropertyListPtrTy); // ImpnfABITy - LLVM for id (*)(id, SEL, ...) llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; @@ -5835,11 +5804,9 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t"); ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy), - llvm::PointerType::getUnqual(ClassnfABITy), - CachePtrTy, + llvm::PointerType::getUnqual(ClassnfABITy), CachePtrTy, llvm::PointerType::getUnqual(ImpnfABITy), - llvm::PointerType::getUnqual(ClassRonfABITy), - nullptr); + llvm::PointerType::getUnqual(ClassRonfABITy)); // LLVM for struct _class_t * ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); @@ -5854,15 +5821,10 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // const struct _prop_list_t * const class_properties; // const uint32_t size; // } - CategorynfABITy = llvm::StructType::create("struct._category_t", - Int8PtrTy, ClassnfABIPtrTy, - MethodListnfABIPtrTy, - MethodListnfABIPtrTy, - ProtocolListnfABIPtrTy, - PropertyListPtrTy, - PropertyListPtrTy, - IntTy, - nullptr); + CategorynfABITy = llvm::StructType::create( + "struct._category_t", Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy, + MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy, + PropertyListPtrTy, IntTy); // New types for nonfragile abi messaging. CodeGen::CodeGenTypes &Types = CGM.getTypes(); @@ -5899,9 +5861,8 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // SUPER_IMP messenger; // SEL name; // }; - SuperMessageRefTy = - llvm::StructType::create("struct._super_message_ref_t", - ImpnfABITy, SelectorPtrTy, nullptr); + SuperMessageRefTy = llvm::StructType::create("struct._super_message_ref_t", + ImpnfABITy, SelectorPtrTy); // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); @@ -5912,10 +5873,9 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // const char* name; // c++ typeinfo string // Class cls; // }; - EHTypeTy = - llvm::StructType::create("struct._objc_typeinfo", - llvm::PointerType::getUnqual(Int8PtrTy), - Int8PtrTy, ClassnfABIPtrTy, nullptr); + EHTypeTy = llvm::StructType::create("struct._objc_typeinfo", + llvm::PointerType::getUnqual(Int8PtrTy), + Int8PtrTy, ClassnfABIPtrTy); EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); } diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp index d1a706b8821e..b256a88c47ad 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -728,7 +728,7 @@ CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) IdentTy = llvm::StructType::create( "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */, CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */, - CGM.Int8PtrTy /* psource */, nullptr); + CGM.Int8PtrTy /* psource */); KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8); loadOffloadInfoMetadata(); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp index f57cbe86c413..c7e30fad7575 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp @@ -548,9 +548,9 @@ void BackendConsumer::UnsupportedDiagHandler( StringRef Filename; unsigned Line, Column; - bool BadDebugInfo; - FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, - Line, Column); + bool BadDebugInfo = false; + FullSourceLoc Loc = + getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str(); @@ -572,8 +572,8 @@ void BackendConsumer::EmitOptimizationMessage( StringRef Filename; unsigned Line, Column; bool BadDebugInfo = false; - FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, - Line, Column); + FullSourceLoc Loc = + getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); std::string Msg; raw_string_ostream MsgStream(Msg); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp index ff26d80fe2b6..a0254797ea43 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp @@ -751,7 +751,7 @@ void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { // Get the type of a ctor entry, { i32, void ()*, i8* }. llvm::StructType *CtorStructTy = llvm::StructType::get( - Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); + Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); // Construct the constructor and destructor arrays. ConstantInitBuilder builder(*this); diff --git a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp index dc24b2040f04..5ed929135880 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp @@ -490,7 +490,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { llvm_unreachable("Unexpected undeduced type!"); case Type::Complex: { llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType()); - ResultType = llvm::StructType::get(EltTy, EltTy, nullptr); + ResultType = llvm::StructType::get(EltTy, EltTy); break; } case Type::LValueReference: diff --git a/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp b/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp index dac2d15fa406..66f51305430a 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -499,7 +499,7 @@ llvm::Type * ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { if (MPT->isMemberDataPointer()) return CGM.PtrDiffTy; - return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr); + return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy); } /// In the Itanium and ARM ABIs, method pointers have the form: diff --git a/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp b/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp index 4ebbef7dfb5b..18367d1602ba 100644 --- a/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp +++ b/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp @@ -3159,8 +3159,7 @@ GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, } } - llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr); - + llvm::StructType *Result = llvm::StructType::get(Lo, Hi); // Verify that the second element is at an 8-byte offset. assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && @@ -3235,8 +3234,7 @@ classifyReturnType(QualType RetTy) const { case ComplexX87: assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), - llvm::Type::getX86_FP80Ty(getVMContext()), - nullptr); + llvm::Type::getX86_FP80Ty(getVMContext())); break; } @@ -3732,7 +3730,7 @@ Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, CharUnits::fromQuantity(16)); llvm::Type *DoubleTy = CGF.DoubleTy; - llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr); + llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy); llvm::Value *V; Address Tmp = CGF.CreateMemTemp(Ty); Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); @@ -4637,7 +4635,7 @@ PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { llvm::Type *CoerceTy; if (Bits > GPRBits) { CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); - CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr); + CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); } else CoerceTy = llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); @@ -6695,6 +6693,14 @@ MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); } + // Use indirect if the aggregate cannot fit into registers for + // passing arguments according to the ABI + unsigned Threshold = IsO32 ? 16 : 64; + + if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold)) + return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true, + getContext().getTypeAlign(Ty) / 8 > Align); + // If we have reached here, aggregates are passed directly by coercing to // another structure type. Padding is inserted if the offset of the // aggregate is unaligned. @@ -7037,13 +7043,13 @@ ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); } + if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) + return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); + // Ignore empty records. if (isEmptyRecord(getContext(), Ty, true)) return ABIArgInfo::getIgnore(); - if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) - return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); - uint64_t Size = getContext().getTypeSize(Ty); if (Size > 64) return getNaturalAlignIndirect(Ty, /*ByVal=*/true); diff --git a/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp index c298302c477c..9ab2e176845c 100644 --- a/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.cpp @@ -563,12 +563,18 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, } } - if (Arg *A = Args.getLastArg( - options::OPT_fsanitize_address_use_after_scope, - options::OPT_fno_sanitize_address_use_after_scope)) { - AsanUseAfterScope = A->getOption().getID() == - options::OPT_fsanitize_address_use_after_scope; - } + AsanUseAfterScope = Args.hasFlag( + options::OPT_fsanitize_address_use_after_scope, + options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope); + + // As a workaround for a bug in gold 2.26 and earlier, dead stripping of + // globals in ASan is disabled by default on ELF targets. + // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002 + AsanGlobalsDeadStripping = + !TC.getTriple().isOSBinFormatELF() || + Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping); + } else { + AsanUseAfterScope = false; } // Parse -link-cxx-sanitizer flag. @@ -634,7 +640,7 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune")}; for (auto F : CoverageFlags) { if (CoverageFeatures & F.first) - CmdArgs.push_back(Args.MakeArgString(F.second)); + CmdArgs.push_back(F.second); } if (TC.getTriple().isOSWindows() && needsUbsanRt()) { @@ -687,7 +693,7 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::utostr(MsanTrackOrigins))); if (MsanUseAfterDtor) - CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-use-after-dtor")); + CmdArgs.push_back("-fsanitize-memory-use-after-dtor"); // FIXME: Pass these parameters as function attributes, not as -llvm flags. if (!TsanMemoryAccess) { @@ -706,17 +712,20 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, } if (CfiCrossDso) - CmdArgs.push_back(Args.MakeArgString("-fsanitize-cfi-cross-dso")); + CmdArgs.push_back("-fsanitize-cfi-cross-dso"); if (Stats) - CmdArgs.push_back(Args.MakeArgString("-fsanitize-stats")); + CmdArgs.push_back("-fsanitize-stats"); if (AsanFieldPadding) CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" + llvm::utostr(AsanFieldPadding))); if (AsanUseAfterScope) - CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-use-after-scope")); + CmdArgs.push_back("-fsanitize-address-use-after-scope"); + + if (AsanGlobalsDeadStripping) + CmdArgs.push_back("-fsanitize-address-globals-dead-stripping"); // MSan: Workaround for PR16386. // ASan: This is mainly to help LSan with cases such as @@ -724,7 +733,7 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, // We can't make this conditional on -fsanitize=leak, as that flag shouldn't // affect compilation. if (Sanitizers.has(Memory) || Sanitizers.has(Address)) - CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new")); + CmdArgs.push_back("-fno-assume-sane-operator-new"); // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is // enabled. diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp index cd791af83220..f33542477fb5 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Arch/Mips.cpp @@ -282,18 +282,18 @@ void mips::getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple, if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx, options::OPT_mfp64)) { if (A->getOption().matches(options::OPT_mfp32)) - Features.push_back(Args.MakeArgString("-fp64")); + Features.push_back("-fp64"); else if (A->getOption().matches(options::OPT_mfpxx)) { - Features.push_back(Args.MakeArgString("+fpxx")); - Features.push_back(Args.MakeArgString("+nooddspreg")); + Features.push_back("+fpxx"); + Features.push_back("+nooddspreg"); } else - Features.push_back(Args.MakeArgString("+fp64")); + Features.push_back("+fp64"); } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) { - Features.push_back(Args.MakeArgString("+fpxx")); - Features.push_back(Args.MakeArgString("+nooddspreg")); + Features.push_back("+fpxx"); + Features.push_back("+nooddspreg"); } else if (mips::isFP64ADefault(Triple, CPUName)) { - Features.push_back(Args.MakeArgString("+fp64")); - Features.push_back(Args.MakeArgString("+nooddspreg")); + Features.push_back("+fp64"); + Features.push_back("+nooddspreg"); } AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg, diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Myriad.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Myriad.cpp index 2935755c12be..f70ce93c45ce 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/Myriad.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/Myriad.cpp @@ -43,15 +43,17 @@ void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA, } CmdArgs.push_back("-DMYRIAD2"); - // Append all -I, -iquote, -isystem paths, defines/undefines, - // 'f' flags, optimize flags, and warning options. + // Append all -I, -iquote, -isystem paths, defines/undefines, 'f' + // flags, 'g' flags, 'M' flags, optimize flags, warning options, + // mcpu flags, mllvm flags, and Xclang flags. // These are spelled the same way in clang and moviCompile. Args.AddAllArgsExcept( CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group, options::OPT_std_EQ, options::OPT_D, options::OPT_U, options::OPT_f_Group, options::OPT_f_clang_Group, options::OPT_g_Group, options::OPT_M_Group, - options::OPT_O_Group, options::OPT_W_Group, options::OPT_mcpu_EQ}, + options::OPT_O_Group, options::OPT_W_Group, options::OPT_mcpu_EQ, + options::OPT_mllvm, options::OPT_Xclang}, {options::OPT_fno_split_dwarf_inlining}); Args.hasArg(options::OPT_fno_split_dwarf_inlining); // Claim it if present. diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp index 123a1516f1e7..3471569b6884 100644 --- a/contrib/llvm/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains/WebAssembly.cpp @@ -42,7 +42,7 @@ void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA, const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); ArgStringList CmdArgs; CmdArgs.push_back("-flavor"); - CmdArgs.push_back("ld"); + CmdArgs.push_back("wasm"); // Enable garbage collection of unused input sections by default, since code // size is of particular importance. This is significantly facilitated by @@ -101,6 +101,9 @@ WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple, : ToolChain(D, Triple, Args) { assert(Triple.isArch32Bit() != Triple.isArch64Bit()); + + getProgramPaths().push_back(getDriver().getInstalledDir()); + getFilePaths().push_back( getDriver().SysRoot + "/lib" + (Triple.isArch32Bit() ? "32" : "64")); } diff --git a/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp b/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp index 3adb72c11da8..488f9dd582f9 100644 --- a/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp +++ b/contrib/llvm/tools/clang/lib/Format/ContinuationIndenter.cpp @@ -674,6 +674,8 @@ unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { return State.Stack[State.Stack.size() - 2].LastSpace; return State.FirstIndent; } + if (Current.is(tok::r_paren) && State.Stack.size() > 1) + return State.Stack[State.Stack.size() - 2].LastSpace; if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope()) return State.Stack[State.Stack.size() - 2].LastSpace; if (Current.is(tok::identifier) && Current.Next && @@ -920,6 +922,10 @@ void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, NewParenState.NoLineBreak = NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand; + // Don't propagate AvoidBinPacking into subexpressions of arg/param lists. + if (*I > prec::Comma) + NewParenState.AvoidBinPacking = false; + // Indent from 'LastSpace' unless these are fake parentheses encapsulating // a builder type call after 'return' or, if the alignment after opening // brackets is disabled. @@ -1034,13 +1040,20 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, NestedBlockIndent = Column; } + bool EndsInComma = + Current.MatchingParen && + Current.MatchingParen->getPreviousNonComment() && + Current.MatchingParen->getPreviousNonComment()->is(tok::comma); + AvoidBinPacking = + (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) || (State.Line->MustBeDeclaration && !Style.BinPackParameters) || (!State.Line->MustBeDeclaration && !Style.BinPackArguments) || (Style.ExperimentalAutoDetectBinPacking && (Current.PackingKind == PPK_OnePerLine || (!BinPackInconclusiveFunctions && Current.PackingKind == PPK_Inconclusive))); + if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) { if (Style.ColumnLimit) { // If this '[' opens an ObjC call, determine whether all parameters fit @@ -1061,6 +1074,9 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, } } } + + if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) + BreakBeforeParameter = true; } // Generally inherit NoLineBreak from the current scope to nested scope. // However, don't do this for non-empty nested blocks, dict literals and diff --git a/contrib/llvm/tools/clang/lib/Format/Format.cpp b/contrib/llvm/tools/clang/lib/Format/Format.cpp index f55a623a8d1f..c8677e805179 100644 --- a/contrib/llvm/tools/clang/lib/Format/Format.cpp +++ b/contrib/llvm/tools/clang/lib/Format/Format.cpp @@ -171,6 +171,18 @@ template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> { } }; +template <> struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> { + static void enumeration(IO &IO, FormatStyle::EscapedNewlineAlignmentStyle &Value) { + IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign); + IO.enumCase(Value, "Left", FormatStyle::ENAS_Left); + IO.enumCase(Value, "Right", FormatStyle::ENAS_Right); + + // For backward compatibility. + IO.enumCase(Value, "true", FormatStyle::ENAS_Left); + IO.enumCase(Value, "false", FormatStyle::ENAS_Right); + } +}; + template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> { static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) { IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle); @@ -233,6 +245,7 @@ template <> struct MappingTraits<FormatStyle> { // For backward compatibility. if (!IO.outputting()) { + IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines); IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment); IO.mapOptional("IndentFunctionDeclarationAfterType", Style.IndentWrappedFunctionNames); @@ -247,7 +260,7 @@ template <> struct MappingTraits<FormatStyle> { Style.AlignConsecutiveAssignments); IO.mapOptional("AlignConsecutiveDeclarations", Style.AlignConsecutiveDeclarations); - IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft); + IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines); IO.mapOptional("AlignOperands", Style.AlignOperands); IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", @@ -498,7 +511,7 @@ FormatStyle getLLVMStyle() { FormatStyle LLVMStyle; LLVMStyle.Language = FormatStyle::LK_Cpp; LLVMStyle.AccessModifierOffset = -2; - LLVMStyle.AlignEscapedNewlinesLeft = false; + LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right; LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align; LLVMStyle.AlignOperands = true; LLVMStyle.AlignTrailingComments = true; @@ -587,7 +600,7 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { GoogleStyle.Language = Language; GoogleStyle.AccessModifierOffset = -1; - GoogleStyle.AlignEscapedNewlinesLeft = true; + GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left; GoogleStyle.AllowShortIfStatementsOnASingleLine = true; GoogleStyle.AllowShortLoopsOnASingleLine = true; GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; @@ -624,9 +637,10 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.BreakBeforeTernaryOperators = false; - // taze:, @tag followed by { for a lot of JSDoc tags, and @see, which is - // commonly followed by overlong URLs. - GoogleStyle.CommentPragmas = "(taze:|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)"; + // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot + // of JSDoc tags, and @see, which is commonly followed by overlong URLs. + GoogleStyle.CommentPragmas = + "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)"; GoogleStyle.MaxEmptyLinesToKeep = 3; GoogleStyle.NamespaceIndentation = FormatStyle::NI_All; GoogleStyle.SpacesInContainerLiterals = false; diff --git a/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp b/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp index c274d7bf07f8..387768a6ee56 100644 --- a/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp +++ b/contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp @@ -576,9 +576,12 @@ private: } break; case tok::kw_for: - if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous && - Tok->Previous->is(tok::period)) - break; + if (Style.Language == FormatStyle::LK_JavaScript) + if (Tok->Previous && Tok->Previous->is(tok::period)) + break; + // JS' for async ( ... + if (CurrentToken->is(Keywords.kw_async)) + next(); Contexts.back().ColonIsForRangeExpr = true; next(); if (!parseParens()) @@ -1034,8 +1037,9 @@ private: if (Style.Language == FormatStyle::LK_JavaScript) { if (Current.is(tok::exclaim)) { if (Current.Previous && - (Current.Previous->isOneOf(tok::identifier, tok::r_paren, - tok::r_square, tok::r_brace) || + (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace, + tok::r_paren, tok::r_square, + tok::r_brace) || Current.Previous->Tok.isLiteral())) { Current.Type = TT_JsNonNullAssertion; return; @@ -2248,6 +2252,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, } else if (Style.Language == FormatStyle::LK_JavaScript) { if (Left.is(TT_JsFatArrow)) return true; + // for async ( ... + if (Right.is(tok::l_paren) && Left.is(Keywords.kw_async) && + Left.Previous && Left.Previous->is(tok::kw_for)) + return true; if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && Right.MatchingParen) { const FormatToken *Next = Right.MatchingParen->getNextNonComment(); @@ -2462,16 +2470,20 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, return true; } - // If the last token before a '}' is a comma or a trailing comment, the - // intention is to insert a line break after it in order to make shuffling - // around entries easier. + // If the last token before a '}', ']', or ')' is a comma or a trailing + // comment, the intention is to insert a line break after it in order to make + // shuffling around entries easier. const FormatToken *BeforeClosingBrace = nullptr; - if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && + if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_JavaScript && + Left.is(tok::l_paren))) && Left.BlockKind != BK_Block && Left.MatchingParen) BeforeClosingBrace = Left.MatchingParen->Previous; else if (Right.MatchingParen && - Right.MatchingParen->isOneOf(tok::l_brace, - TT_ArrayInitializerLSquare)) + (Right.MatchingParen->isOneOf(tok::l_brace, + TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_JavaScript && + Right.MatchingParen->is(tok::l_paren)))) BeforeClosingBrace = &Left; if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || BeforeClosingBrace->isTrailingComment())) diff --git a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp index 2d788b52dfda..31c66ffb00a1 100644 --- a/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp +++ b/contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp @@ -368,9 +368,10 @@ void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) { (Style.Language == FormatStyle::LK_JavaScript && NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in, Keywords.kw_as)) || + (Style.isCpp() && NextTok->is(tok::l_paren)) || NextTok->isOneOf(tok::comma, tok::period, tok::colon, tok::r_paren, tok::r_square, tok::l_brace, - tok::l_square, tok::l_paren, tok::ellipsis) || + tok::l_square, tok::ellipsis) || (NextTok->is(tok::identifier) && !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) || (NextTok->is(tok::semi) && @@ -476,6 +477,24 @@ static bool isGoogScope(const UnwrappedLine &Line) { return I->Tok->is(tok::l_paren); } +static bool isIIFE(const UnwrappedLine &Line, + const AdditionalKeywords &Keywords) { + // Look for the start of an immediately invoked anonymous function. + // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression + // This is commonly done in JavaScript to create a new, anonymous scope. + // Example: (function() { ... })() + if (Line.Tokens.size() < 3) + return false; + auto I = Line.Tokens.begin(); + if (I->Tok->isNot(tok::l_paren)) + return false; + ++I; + if (I->Tok->isNot(Keywords.kw_function)) + return false; + ++I; + return I->Tok->is(tok::l_paren); +} + static bool ShouldBreakBeforeBrace(const FormatStyle &Style, const FormatToken &InitialToken) { if (InitialToken.is(tok::kw_namespace)) @@ -493,15 +512,16 @@ void UnwrappedLineParser::parseChildBlock() { FormatTok->BlockKind = BK_Block; nextToken(); { - bool GoogScope = - Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line); + bool SkipIndent = + (Style.Language == FormatStyle::LK_JavaScript && + (isGoogScope(*Line) || isIIFE(*Line, Keywords))); ScopedLineState LineState(*this); ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack, /*MustBeDeclaration=*/false); - Line->Level += GoogScope ? 0 : 1; + Line->Level += SkipIndent ? 0 : 1; parseLevel(/*HasOpeningBrace=*/true); flushComments(isOnNewLine(*FormatTok)); - Line->Level -= GoogScope ? 0 : 1; + Line->Level -= SkipIndent ? 0 : 1; } nextToken(); } @@ -1615,6 +1635,10 @@ void UnwrappedLineParser::parseForOrWhileLoop() { assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) && "'for', 'while' or foreach macro expected"); nextToken(); + // JS' for async ( ... + if (Style.Language == FormatStyle::LK_JavaScript && + FormatTok->is(Keywords.kw_async)) + nextToken(); if (FormatTok->Tok.is(tok::l_paren)) parseParens(); if (FormatTok->Tok.is(tok::l_brace)) { diff --git a/contrib/llvm/tools/clang/lib/Format/WhitespaceManager.cpp b/contrib/llvm/tools/clang/lib/Format/WhitespaceManager.cpp index 2c1f59324971..3b6311d15487 100644 --- a/contrib/llvm/tools/clang/lib/Format/WhitespaceManager.cpp +++ b/contrib/llvm/tools/clang/lib/Format/WhitespaceManager.cpp @@ -517,8 +517,11 @@ void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End, } void WhitespaceManager::alignEscapedNewlines() { - unsigned MaxEndOfLine = - Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit; + if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign) + return; + + bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left; + unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; unsigned StartOfMacro = 0; for (unsigned i = 1, e = Changes.size(); i < e; ++i) { Change &C = Changes[i]; @@ -527,7 +530,7 @@ void WhitespaceManager::alignEscapedNewlines() { MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine); } else { alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine); - MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit; + MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit; StartOfMacro = i; } } @@ -602,7 +605,7 @@ void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines, unsigned EscapedNewlineColumn) { if (Newlines > 0) { unsigned Offset = - std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn); + std::min<int>(EscapedNewlineColumn - 2, PreviousEndOfTokenColumn); for (unsigned i = 0; i < Newlines; ++i) { Text.append(EscapedNewlineColumn - Offset - 1, ' '); Text.append(UseCRLF ? "\\\r\n" : "\\\n"); diff --git a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp index 96854b8fbc1a..51147b6f9499 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp @@ -778,6 +778,8 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.SanitizeAddressUseAfterScope = A->getOption().getID() == OPT_fsanitize_address_use_after_scope; } + Opts.SanitizeAddressGlobalsDeadStripping = + Args.hasArg(OPT_fsanitize_address_globals_dead_stripping); Opts.SSPBufferSize = getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); Opts.StackRealignment = Args.hasArg(OPT_mstackrealign); diff --git a/contrib/llvm/tools/clang/lib/Headers/avxintrin.h b/contrib/llvm/tools/clang/lib/Headers/avxintrin.h index cdb7aa4fb626..15d28259dcc0 100644 --- a/contrib/llvm/tools/clang/lib/Headers/avxintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/avxintrin.h @@ -1458,12 +1458,13 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Computes two dot products in parallel, using the lower and upper /// halves of two [8 x float] vectors as input to the two computations, and /// returning the two dot products in the lower and upper halves of the -/// [8 x float] result. The immediate integer operand controls which input -/// elements will contribute to the dot product, and where the final results -/// are returned. In general, for each dot product, the four corresponding -/// elements of the input vectors are multiplied; the first two and second -/// two products are summed, then the two sums are added to form the final -/// result. +/// [8 x float] result. +/// +/// The immediate integer operand controls which input elements will +/// contribute to the dot product, and where the final results are returned. +/// In general, for each dot product, the four corresponding elements of the +/// input vectors are multiplied; the first two and second two products are +/// summed, then the two sums are added to form the final result. /// /// \headerfile <x86intrin.h> /// @@ -1497,15 +1498,16 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /* Vector shuffle */ /// \brief Selects 8 float values from the 256-bit operands of [8 x float], as -/// specified by the immediate value operand. The four selected elements in -/// each operand are copied to the destination according to the bits -/// specified in the immediate operand. The selected elements from the first -/// 256-bit operand are copied to bits [63:0] and bits [191:128] of the -/// destination, and the selected elements from the second 256-bit operand -/// are copied to bits [127:64] and bits [255:192] of the destination. For -/// example, if bits [7:0] of the immediate operand contain a value of 0xFF, -/// the 256-bit destination vector would contain the following values: b[7], -/// b[7], a[7], a[7], b[3], b[3], a[3], a[3]. +/// specified by the immediate value operand. +/// +/// The four selected elements in each operand are copied to the destination +/// according to the bits specified in the immediate operand. The selected +/// elements from the first 256-bit operand are copied to bits [63:0] and +/// bits [191:128] of the destination, and the selected elements from the +/// second 256-bit operand are copied to bits [127:64] and bits [255:192] of +/// the destination. For example, if bits [7:0] of the immediate operand +/// contain a value of 0xFF, the 256-bit destination vector would contain the +/// following values: b[7], b[7], a[7], a[7], b[3], b[3], a[3], a[3]. /// /// \headerfile <x86intrin.h> /// @@ -1557,13 +1559,14 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) 12 + (((mask) >> 6) & 0x3)); }) /// \brief Selects four double-precision values from the 256-bit operands of -/// [4 x double], as specified by the immediate value operand. The selected -/// elements from the first 256-bit operand are copied to bits [63:0] and -/// bits [191:128] in the destination, and the selected elements from the -/// second 256-bit operand are copied to bits [127:64] and bits [255:192] in -/// the destination. For example, if bits [3:0] of the immediate operand -/// contain a value of 0xF, the 256-bit destination vector would contain the -/// following values: b[3], a[3], b[1], a[1]. +/// [4 x double], as specified by the immediate value operand. +/// +/// The selected elements from the first 256-bit operand are copied to bits +/// [63:0] and bits [191:128] in the destination, and the selected elements +/// from the second 256-bit operand are copied to bits [127:64] and bits +/// [255:192] in the destination. For example, if bits [3:0] of the immediate +/// operand contain a value of 0xF, the 256-bit destination vector would +/// contain the following values: b[3], a[3], b[1], a[1]. /// /// \headerfile <x86intrin.h> /// @@ -1641,9 +1644,11 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding double-precision values of two /// 128-bit vectors of [2 x double], using the operation specified by the -/// immediate integer operand. Returns a [2 x double] vector consisting of -/// two doubles corresponding to the two comparison results: zero if the -/// comparison is false, and all 1's if the comparison is true. +/// immediate integer operand. +/// +/// Returns a [2 x double] vector consisting of two doubles corresponding to +/// the two comparison results: zero if the comparison is false, and all 1's +/// if the comparison is true. /// /// \headerfile <x86intrin.h> /// @@ -1699,9 +1704,11 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding values of two 128-bit vectors of /// [4 x float], using the operation specified by the immediate integer -/// operand. Returns a [4 x float] vector consisting of four floats -/// corresponding to the four comparison results: zero if the comparison is -/// false, and all 1's if the comparison is true. +/// operand. +/// +/// Returns a [4 x float] vector consisting of four floats corresponding to +/// the four comparison results: zero if the comparison is false, and all 1's +/// if the comparison is true. /// /// \headerfile <x86intrin.h> /// @@ -1757,9 +1764,11 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding double-precision values of two /// 256-bit vectors of [4 x double], using the operation specified by the -/// immediate integer operand. Returns a [4 x double] vector consisting of -/// four doubles corresponding to the four comparison results: zero if the -/// comparison is false, and all 1's if the comparison is true. +/// immediate integer operand. +/// +/// Returns a [4 x double] vector consisting of four doubles corresponding to +/// the four comparison results: zero if the comparison is false, and all 1's +/// if the comparison is true. /// /// \headerfile <x86intrin.h> /// @@ -1815,9 +1824,11 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding values of two 256-bit vectors of /// [8 x float], using the operation specified by the immediate integer -/// operand. Returns a [8 x float] vector consisting of eight floats -/// corresponding to the eight comparison results: zero if the comparison is -/// false, and all 1's if the comparison is true. +/// operand. +/// +/// Returns a [8 x float] vector consisting of eight floats corresponding to +/// the eight comparison results: zero if the comparison is false, and all +/// 1's if the comparison is true. /// /// \headerfile <x86intrin.h> /// @@ -1873,8 +1884,10 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding scalar double-precision values of /// two 128-bit vectors of [2 x double], using the operation specified by the -/// immediate integer operand. If the result is true, all 64 bits of the -/// destination vector are set; otherwise they are cleared. +/// immediate integer operand. +/// +/// If the result is true, all 64 bits of the destination vector are set; +/// otherwise they are cleared. /// /// \headerfile <x86intrin.h> /// @@ -1930,8 +1943,10 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) /// \brief Compares each of the corresponding scalar values of two 128-bit /// vectors of [4 x float], using the operation specified by the immediate -/// integer operand. If the result is true, all 32 bits of the destination -/// vector are set; otherwise they are cleared. +/// integer operand. +/// +/// If the result is true, all 32 bits of the destination vector are set; +/// otherwise they are cleared. /// /// \headerfile <x86intrin.h> /// @@ -2536,7 +2551,9 @@ _mm256_unpacklo_ps(__m256 __a, __m256 __b) /// \brief Given two 128-bit floating-point vectors of [2 x double], perform an /// element-by-element comparison of the double-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2563,7 +2580,9 @@ _mm_testz_pd(__m128d __a, __m128d __b) /// \brief Given two 128-bit floating-point vectors of [2 x double], perform an /// element-by-element comparison of the double-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2590,7 +2609,9 @@ _mm_testc_pd(__m128d __a, __m128d __b) /// \brief Given two 128-bit floating-point vectors of [2 x double], perform an /// element-by-element comparison of the double-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2618,7 +2639,9 @@ _mm_testnzc_pd(__m128d __a, __m128d __b) /// \brief Given two 128-bit floating-point vectors of [4 x float], perform an /// element-by-element comparison of the single-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2645,7 +2668,9 @@ _mm_testz_ps(__m128 __a, __m128 __b) /// \brief Given two 128-bit floating-point vectors of [4 x float], perform an /// element-by-element comparison of the single-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2672,7 +2697,9 @@ _mm_testc_ps(__m128 __a, __m128 __b) /// \brief Given two 128-bit floating-point vectors of [4 x float], perform an /// element-by-element comparison of the single-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2700,7 +2727,9 @@ _mm_testnzc_ps(__m128 __a, __m128 __b) /// \brief Given two 256-bit floating-point vectors of [4 x double], perform an /// element-by-element comparison of the double-precision elements in the /// first source vector and the corresponding elements in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2727,7 +2756,9 @@ _mm256_testz_pd(__m256d __a, __m256d __b) /// \brief Given two 256-bit floating-point vectors of [4 x double], perform an /// element-by-element comparison of the double-precision elements in the /// first source vector and the corresponding elements in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2754,7 +2785,9 @@ _mm256_testc_pd(__m256d __a, __m256d __b) /// \brief Given two 256-bit floating-point vectors of [4 x double], perform an /// element-by-element comparison of the double-precision elements in the /// first source vector and the corresponding elements in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of double-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2782,7 +2815,9 @@ _mm256_testnzc_pd(__m256d __a, __m256d __b) /// \brief Given two 256-bit floating-point vectors of [8 x float], perform an /// element-by-element comparison of the single-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2809,7 +2844,9 @@ _mm256_testz_ps(__m256 __a, __m256 __b) /// \brief Given two 256-bit floating-point vectors of [8 x float], perform an /// element-by-element comparison of the single-precision element in the /// first source vector and the corresponding element in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2836,7 +2873,9 @@ _mm256_testc_ps(__m256 __a, __m256 __b) /// \brief Given two 256-bit floating-point vectors of [8 x float], perform an /// element-by-element comparison of the single-precision elements in the /// first source vector and the corresponding elements in the second source -/// vector. The EFLAGS register is updated as follows: \n +/// vector. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of single-precision elements where the /// sign-bits of both elements are 1, the ZF flag is set to 0. Otherwise the /// ZF flag is set to 1. \n @@ -2862,7 +2901,9 @@ _mm256_testnzc_ps(__m256 __a, __m256 __b) } /// \brief Given two 256-bit integer vectors, perform a bit-by-bit comparison -/// of the two source vectors and update the EFLAGS register as follows: \n +/// of the two source vectors. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of bits where both bits are 1, the ZF flag /// is set to 0. Otherwise the ZF flag is set to 1. \n /// If there is at least one pair of bits where the bit from the first source @@ -2886,7 +2927,9 @@ _mm256_testz_si256(__m256i __a, __m256i __b) } /// \brief Given two 256-bit integer vectors, perform a bit-by-bit comparison -/// of the two source vectors and update the EFLAGS register as follows: \n +/// of the two source vectors. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of bits where both bits are 1, the ZF flag /// is set to 0. Otherwise the ZF flag is set to 1. \n /// If there is at least one pair of bits where the bit from the first source @@ -2910,7 +2953,9 @@ _mm256_testc_si256(__m256i __a, __m256i __b) } /// \brief Given two 256-bit integer vectors, perform a bit-by-bit comparison -/// of the two source vectors and update the EFLAGS register as follows: \n +/// of the two source vectors. +/// +/// The EFLAGS register is updated as follows: \n /// If there is at least one pair of bits where both bits are 1, the ZF flag /// is set to 0. Otherwise the ZF flag is set to 1. \n /// If there is at least one pair of bits where the bit from the first source @@ -4466,9 +4511,10 @@ _mm256_castsi256_si128(__m256i __a) } /// \brief Constructs a 256-bit floating-point vector of [4 x double] from a -/// 128-bit floating-point vector of [2 x double]. The lower 128 bits -/// contain the value of the source vector. The contents of the upper 128 -/// bits are undefined. +/// 128-bit floating-point vector of [2 x double]. +/// +/// The lower 128 bits contain the value of the source vector. The contents +/// of the upper 128 bits are undefined. /// /// \headerfile <x86intrin.h> /// @@ -4486,9 +4532,10 @@ _mm256_castpd128_pd256(__m128d __a) } /// \brief Constructs a 256-bit floating-point vector of [8 x float] from a -/// 128-bit floating-point vector of [4 x float]. The lower 128 bits contain -/// the value of the source vector. The contents of the upper 128 bits are -/// undefined. +/// 128-bit floating-point vector of [4 x float]. +/// +/// The lower 128 bits contain the value of the source vector. The contents +/// of the upper 128 bits are undefined. /// /// \headerfile <x86intrin.h> /// @@ -4506,6 +4553,7 @@ _mm256_castps128_ps256(__m128 __a) } /// \brief Constructs a 256-bit integer vector from a 128-bit integer vector. +/// /// The lower 128 bits contain the value of the source vector. The contents /// of the upper 128 bits are undefined. /// @@ -4586,8 +4634,10 @@ _mm256_zextsi128_si256(__m128i __a) /// \brief Constructs a new 256-bit vector of [8 x float] by first duplicating /// a 256-bit vector of [8 x float] given in the first parameter, and then /// replacing either the upper or the lower 128 bits with the contents of a -/// 128-bit vector of [4 x float] in the second parameter. The immediate -/// integer parameter determines between the upper or the lower 128 bits. +/// 128-bit vector of [4 x float] in the second parameter. +/// +/// The immediate integer parameter determines between the upper or the lower +/// 128 bits. /// /// \headerfile <x86intrin.h> /// @@ -4631,8 +4681,10 @@ _mm256_zextsi128_si256(__m128i __a) /// \brief Constructs a new 256-bit vector of [4 x double] by first duplicating /// a 256-bit vector of [4 x double] given in the first parameter, and then /// replacing either the upper or the lower 128 bits with the contents of a -/// 128-bit vector of [2 x double] in the second parameter. The immediate -/// integer parameter determines between the upper or the lower 128 bits. +/// 128-bit vector of [2 x double] in the second parameter. +/// +/// The immediate integer parameter determines between the upper or the lower +/// 128 bits. /// /// \headerfile <x86intrin.h> /// @@ -4672,8 +4724,10 @@ _mm256_zextsi128_si256(__m128i __a) /// \brief Constructs a new 256-bit integer vector by first duplicating a /// 256-bit integer vector given in the first parameter, and then replacing /// either the upper or the lower 128 bits with the contents of a 128-bit -/// integer vector in the second parameter. The immediate integer parameter -/// determines between the upper or the lower 128 bits. +/// integer vector in the second parameter. +/// +/// The immediate integer parameter determines between the upper or the lower +/// 128 bits. /// /// \headerfile <x86intrin.h> /// diff --git a/contrib/llvm/tools/clang/lib/Headers/emmintrin.h b/contrib/llvm/tools/clang/lib/Headers/emmintrin.h index 13b0db22ec44..fa5cefadc52c 100644 --- a/contrib/llvm/tools/clang/lib/Headers/emmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/emmintrin.h @@ -462,8 +462,9 @@ _mm_cmplt_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are less than or equal to those in the second operand. Each -/// comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are less than or equal to those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -482,8 +483,9 @@ _mm_cmple_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are greater than those in the second operand. Each comparison -/// yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are greater than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -502,8 +504,9 @@ _mm_cmpgt_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are greater than or equal to those in the second operand. Each -/// comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are greater than or equal to those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -522,9 +525,10 @@ _mm_cmpge_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are ordered with respect to those in the second operand. A pair -/// of double-precision values are "ordered" with respect to each other if -/// neither value is a NaN. Each comparison yields 0h for false, +/// operand are ordered with respect to those in the second operand. +/// +/// A pair of double-precision values are "ordered" with respect to each +/// other if neither value is a NaN. Each comparison yields 0h for false, /// FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> @@ -544,9 +548,10 @@ _mm_cmpord_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are unordered with respect to those in the second operand. A pair -/// of double-precision values are "unordered" with respect to each other if -/// one or both values are NaN. Each comparison yields 0h for false, +/// operand are unordered with respect to those in the second operand. +/// +/// A pair of double-precision values are "unordered" with respect to each +/// other if one or both values are NaN. Each comparison yields 0h for false, /// FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> @@ -567,8 +572,9 @@ _mm_cmpunord_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are unequal to those in the second operand. Each comparison -/// yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are unequal to those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -587,8 +593,9 @@ _mm_cmpneq_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are not less than those in the second operand. Each comparison -/// yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are not less than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -607,8 +614,9 @@ _mm_cmpnlt_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are not less than or equal to those in the second operand. Each -/// comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are not less than or equal to those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -627,8 +635,9 @@ _mm_cmpnle_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first -/// operand are not greater than those in the second operand. Each -/// comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// operand are not greater than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -648,6 +657,7 @@ _mm_cmpngt_pd(__m128d __a, __m128d __b) /// \brief Compares each of the corresponding double-precision values of the /// 128-bit vectors of [2 x double] to determine if the values in the first /// operand are not greater than or equal to those in the second operand. +/// /// Each comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> @@ -666,8 +676,9 @@ _mm_cmpnge_pd(__m128d __a, __m128d __b) } /// \brief Compares the lower double-precision floating-point values in each of -/// the two 128-bit floating-point vectors of [2 x double] for equality. The -/// comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. +/// the two 128-bit floating-point vectors of [2 x double] for equality. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -690,8 +701,9 @@ _mm_cmpeq_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than the corresponding value in -/// the second parameter. The comparison yields 0h for false, -/// FFFFFFFFFFFFFFFFh for true. +/// the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -714,8 +726,9 @@ _mm_cmplt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than or equal to the -/// corresponding value in the second parameter. The comparison yields 0h for -/// false, FFFFFFFFFFFFFFFFh for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -738,8 +751,9 @@ _mm_cmple_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than the corresponding value -/// in the second parameter. The comparison yields 0h for false, -/// FFFFFFFFFFFFFFFFh for true. +/// in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -763,8 +777,9 @@ _mm_cmpgt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than or equal to the -/// corresponding value in the second parameter. The comparison yields 0h for -/// false, FFFFFFFFFFFFFFFFh for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -788,9 +803,11 @@ _mm_cmpge_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is "ordered" with respect to the -/// corresponding value in the second parameter. The comparison yields 0h for -/// false, FFFFFFFFFFFFFFFFh for true. A pair of double-precision values are -/// "ordered" with respect to each other if neither value is a NaN. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. A pair of +/// double-precision values are "ordered" with respect to each other if +/// neither value is a NaN. /// /// \headerfile <x86intrin.h> /// @@ -813,9 +830,11 @@ _mm_cmpord_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is "unordered" with respect to the -/// corresponding value in the second parameter. The comparison yields 0h -/// for false, FFFFFFFFFFFFFFFFh for true. A pair of double-precision values -/// are "unordered" with respect to each other if one or both values are NaN. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. A pair of +/// double-precision values are "unordered" with respect to each other if one +/// or both values are NaN. /// /// \headerfile <x86intrin.h> /// @@ -839,8 +858,9 @@ _mm_cmpunord_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is unequal to the corresponding value in -/// the second parameter. The comparison yields 0h for false, -/// FFFFFFFFFFFFFFFFh for true. +/// the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -863,8 +883,9 @@ _mm_cmpneq_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is not less than the corresponding -/// value in the second parameter. The comparison yields 0h for false, -/// FFFFFFFFFFFFFFFFh for true. +/// value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -887,8 +908,9 @@ _mm_cmpnlt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is not less than or equal to the -/// corresponding value in the second parameter. The comparison yields 0h -/// for false, FFFFFFFFFFFFFFFFh for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -911,8 +933,9 @@ _mm_cmpnle_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is not greater than the corresponding -/// value in the second parameter. The comparison yields 0h for false, -/// FFFFFFFFFFFFFFFFh for true. +/// value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -936,8 +959,9 @@ _mm_cmpngt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is not greater than or equal to the -/// corresponding value in the second parameter. The comparison yields 0h -/// for false, FFFFFFFFFFFFFFFFh for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0h for false, FFFFFFFFFFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -982,7 +1006,9 @@ _mm_comieq_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than the corresponding value in -/// the second parameter. The comparison yields 0 for false, 1 for true. +/// the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. /// /// \headerfile <x86intrin.h> /// @@ -1004,8 +1030,9 @@ _mm_comilt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than or equal to the -/// corresponding value in the second parameter. The comparison yields 0 for -/// false, 1 for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. /// /// \headerfile <x86intrin.h> /// @@ -1027,7 +1054,9 @@ _mm_comile_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than the corresponding value -/// in the second parameter. The comparison yields 0 for false, 1 for true. +/// in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. /// /// \headerfile <x86intrin.h> /// @@ -1049,8 +1078,9 @@ _mm_comigt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than or equal to the -/// corresponding value in the second parameter. The comparison yields 0 for -/// false, 1 for true. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. /// /// \headerfile <x86intrin.h> /// @@ -1072,7 +1102,9 @@ _mm_comige_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is unequal to the corresponding value in -/// the second parameter. The comparison yields 0 for false, 1 for true. +/// the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. /// /// \headerfile <x86intrin.h> /// @@ -1093,8 +1125,9 @@ _mm_comineq_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] for equality. The -/// comparison yields 0 for false, 1 for true. If either of the two lower -/// double-precision values is NaN, 1 is returned. +/// comparison yields 0 for false, 1 for true. +/// +/// If either of the two lower double-precision values is NaN, 1 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1117,8 +1150,10 @@ _mm_ucomieq_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than the corresponding value in -/// the second parameter. The comparison yields 0 for false, 1 for true. If -/// either of the two lower double-precision values is NaN, 1 is returned. +/// the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. If either of the two lower +/// double-precision values is NaN, 1 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1141,9 +1176,10 @@ _mm_ucomilt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is less than or equal to the -/// corresponding value in the second parameter. The comparison yields 0 for -/// false, 1 for true. If either of the two lower double-precision values is -/// NaN, 1 is returned. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. If either of the two lower +/// double-precision values is NaN, 1 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1166,8 +1202,10 @@ _mm_ucomile_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than the corresponding value -/// in the second parameter. The comparison yields 0 for false, 1 for true. -/// If either of the two lower double-precision values is NaN, 0 is returned. +/// in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. If either of the two lower +/// double-precision values is NaN, 0 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1190,9 +1228,10 @@ _mm_ucomigt_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is greater than or equal to the -/// corresponding value in the second parameter. The comparison yields 0 for -/// false, 1 for true. If either of the two lower double-precision values -/// is NaN, 0 is returned. +/// corresponding value in the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. If either of the two +/// lower double-precision values is NaN, 0 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1215,8 +1254,10 @@ _mm_ucomige_sd(__m128d __a, __m128d __b) /// \brief Compares the lower double-precision floating-point values in each of /// the two 128-bit floating-point vectors of [2 x double] to determine if /// the value in the first parameter is unequal to the corresponding value in -/// the second parameter. The comparison yields 0 for false, 1 for true. If -/// either of the two lower double-precision values is NaN, 0 is returned. +/// the second parameter. +/// +/// The comparison yields 0 for false, 1 for true. If either of the two lower +/// double-precision values is NaN, 0 is returned. /// /// \headerfile <x86intrin.h> /// @@ -1278,8 +1319,9 @@ _mm_cvtps_pd(__m128 __a) /// \brief Converts the lower two integer elements of a 128-bit vector of /// [4 x i32] into two double-precision floating-point values, returned in a -/// 128-bit vector of [2 x double]. The upper two elements of the input -/// vector are unused. +/// 128-bit vector of [2 x double]. +/// +/// The upper two elements of the input vector are unused. /// /// \headerfile <x86intrin.h> /// @@ -1287,7 +1329,9 @@ _mm_cvtps_pd(__m128 __a) /// /// \param __a /// A 128-bit integer vector of [4 x i32]. The lower two integer elements are -/// converted to double-precision values. The upper two elements are unused. +/// converted to double-precision values. +/// +/// The upper two elements are unused. /// \returns A 128-bit vector of [2 x double] containing the converted values. static __inline__ __m128d __DEFAULT_FN_ATTRS _mm_cvtepi32_pd(__m128i __a) @@ -1409,10 +1453,11 @@ _mm_cvtss_sd(__m128d __a, __m128 __b) /// \brief Converts the two double-precision floating-point elements of a /// 128-bit vector of [2 x double] into two signed 32-bit integer values, -/// returned in the lower 64 bits of a 128-bit vector of [4 x i32]. If the -/// result of either conversion is inexact, the result is truncated (rounded -/// towards zero) regardless of the current MXCSR setting. The upper 64 bits -/// of the result vector are set to zero. +/// returned in the lower 64 bits of a 128-bit vector of [4 x i32]. +/// +/// If the result of either conversion is inexact, the result is truncated +/// (rounded towards zero) regardless of the current MXCSR setting. The upper +/// 64 bits of the result vector are set to zero. /// /// \headerfile <x86intrin.h> /// @@ -1466,9 +1511,10 @@ _mm_cvtpd_pi32(__m128d __a) /// \brief Converts the two double-precision floating-point elements of a /// 128-bit vector of [2 x double] into two signed 32-bit integer values, -/// returned in a 64-bit vector of [2 x i32]. If the result of either -/// conversion is inexact, the result is truncated (rounded towards zero) -/// regardless of the current MXCSR setting. +/// returned in a 64-bit vector of [2 x i32]. +/// +/// If the result of either conversion is inexact, the result is truncated +/// (rounded towards zero) regardless of the current MXCSR setting. /// /// \headerfile <x86intrin.h> /// @@ -1980,8 +2026,9 @@ _mm_storel_pd(double *__dp, __m128d __a) /// \brief Adds the corresponding elements of two 128-bit vectors of [16 x i8], /// saving the lower 8 bits of each sum in the corresponding element of a -/// 128-bit result vector of [16 x i8]. The integer elements of both -/// parameters can be either signed or unsigned. +/// 128-bit result vector of [16 x i8]. +/// +/// The integer elements of both parameters can be either signed or unsigned. /// /// \headerfile <x86intrin.h> /// @@ -2001,8 +2048,9 @@ _mm_add_epi8(__m128i __a, __m128i __b) /// \brief Adds the corresponding elements of two 128-bit vectors of [8 x i16], /// saving the lower 16 bits of each sum in the corresponding element of a -/// 128-bit result vector of [8 x i16]. The integer elements of both -/// parameters can be either signed or unsigned. +/// 128-bit result vector of [8 x i16]. +/// +/// The integer elements of both parameters can be either signed or unsigned. /// /// \headerfile <x86intrin.h> /// @@ -2022,8 +2070,9 @@ _mm_add_epi16(__m128i __a, __m128i __b) /// \brief Adds the corresponding elements of two 128-bit vectors of [4 x i32], /// saving the lower 32 bits of each sum in the corresponding element of a -/// 128-bit result vector of [4 x i32]. The integer elements of both -/// parameters can be either signed or unsigned. +/// 128-bit result vector of [4 x i32]. +/// +/// The integer elements of both parameters can be either signed or unsigned. /// /// \headerfile <x86intrin.h> /// @@ -2061,8 +2110,9 @@ _mm_add_si64(__m64 __a, __m64 __b) /// \brief Adds the corresponding elements of two 128-bit vectors of [2 x i64], /// saving the lower 64 bits of each sum in the corresponding element of a -/// 128-bit result vector of [2 x i64]. The integer elements of both -/// parameters can be either signed or unsigned. +/// 128-bit result vector of [2 x i64]. +/// +/// The integer elements of both parameters can be either signed or unsigned. /// /// \headerfile <x86intrin.h> /// @@ -2208,10 +2258,12 @@ _mm_avg_epu16(__m128i __a, __m128i __b) /// \brief Multiplies the corresponding elements of two 128-bit signed [8 x i16] /// vectors, producing eight intermediate 32-bit signed integer products, and /// adds the consecutive pairs of 32-bit products to form a 128-bit signed -/// [4 x i32] vector. For example, bits [15:0] of both parameters are -/// multiplied producing a 32-bit product, bits [31:16] of both parameters -/// are multiplied producing a 32-bit product, and the sum of those two -/// products becomes bits [31:0] of the result. +/// [4 x i32] vector. +/// +/// For example, bits [15:0] of both parameters are multiplied producing a +/// 32-bit product, bits [31:16] of both parameters are multiplied producing +/// a 32-bit product, and the sum of those two products becomes bits [31:0] +/// of the result. /// /// \headerfile <x86intrin.h> /// @@ -3146,8 +3198,9 @@ _mm_cmpgt_epi8(__m128i __a, __m128i __b) /// \brief Compares each of the corresponding signed 16-bit values of the /// 128-bit integer vectors to determine if the values in the first operand -/// are greater than those in the second operand. Each comparison yields 0h -/// for false, FFFFh for true. +/// are greater than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -3166,8 +3219,9 @@ _mm_cmpgt_epi16(__m128i __a, __m128i __b) /// \brief Compares each of the corresponding signed 32-bit values of the /// 128-bit integer vectors to determine if the values in the first operand -/// are greater than those in the second operand. Each comparison yields 0h -/// for false, FFFFFFFFh for true. +/// are greater than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -3186,8 +3240,9 @@ _mm_cmpgt_epi32(__m128i __a, __m128i __b) /// \brief Compares each of the corresponding signed 8-bit values of the 128-bit /// integer vectors to determine if the values in the first operand are less -/// than those in the second operand. Each comparison yields 0h for false, -/// FFh for true. +/// than those in the second operand. +/// +/// Each comparison yields 0h for false, FFh for true. /// /// \headerfile <x86intrin.h> /// @@ -3206,8 +3261,9 @@ _mm_cmplt_epi8(__m128i __a, __m128i __b) /// \brief Compares each of the corresponding signed 16-bit values of the /// 128-bit integer vectors to determine if the values in the first operand -/// are less than those in the second operand. Each comparison yields 0h for -/// false, FFFFh for true. +/// are less than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -3226,8 +3282,9 @@ _mm_cmplt_epi16(__m128i __a, __m128i __b) /// \brief Compares each of the corresponding signed 32-bit values of the /// 128-bit integer vectors to determine if the values in the first operand -/// are less than those in the second operand. Each comparison yields 0h for -/// false, FFFFFFFFh for true. +/// are less than those in the second operand. +/// +/// Each comparison yields 0h for false, FFFFFFFFh for true. /// /// \headerfile <x86intrin.h> /// @@ -3925,10 +3982,11 @@ _mm_storeu_si128(__m128i *__p, __m128i __b) /// \brief Moves bytes selected by the mask from the first operand to the /// specified unaligned memory location. When a mask bit is 1, the -/// corresponding byte is written, otherwise it is not written. To minimize -/// caching, the date is flagged as non-temporal (unlikely to be used again -/// soon). Exception and trap behavior for elements not selected for storage -/// to memory are implementation dependent. +/// corresponding byte is written, otherwise it is not written. +/// +/// To minimize caching, the date is flagged as non-temporal (unlikely to be +/// used again soon). Exception and trap behavior for elements not selected +/// for storage to memory are implementation dependent. /// /// \headerfile <x86intrin.h> /// @@ -3972,8 +4030,10 @@ _mm_storel_epi64(__m128i *__p, __m128i __a) } /// \brief Stores a 128-bit floating point vector of [2 x double] to a 128-bit -/// aligned memory location. To minimize caching, the data is flagged as -/// non-temporal (unlikely to be used again soon). +/// aligned memory location. +/// +/// To minimize caching, the data is flagged as non-temporal (unlikely to be +/// used again soon). /// /// \headerfile <x86intrin.h> /// @@ -3990,6 +4050,7 @@ _mm_stream_pd(double *__p, __m128d __a) } /// \brief Stores a 128-bit integer vector to a 128-bit aligned memory location. +/// /// To minimize caching, the data is flagged as non-temporal (unlikely to be /// used again soon). /// @@ -4007,8 +4068,9 @@ _mm_stream_si128(__m128i *__p, __m128i __a) __builtin_nontemporal_store((__v2di)__a, (__v2di*)__p); } -/// \brief Stores a 32-bit integer value in the specified memory location. To -/// minimize caching, the data is flagged as non-temporal (unlikely to be +/// \brief Stores a 32-bit integer value in the specified memory location. +/// +/// To minimize caching, the data is flagged as non-temporal (unlikely to be /// used again soon). /// /// \headerfile <x86intrin.h> @@ -4026,8 +4088,9 @@ _mm_stream_si32(int *__p, int __a) } #ifdef __x86_64__ -/// \brief Stores a 64-bit integer value in the specified memory location. To -/// minimize caching, the data is flagged as non-temporal (unlikely to be +/// \brief Stores a 64-bit integer value in the specified memory location. +/// +/// To minimize caching, the data is flagged as non-temporal (unlikely to be /// used again soon). /// /// \headerfile <x86intrin.h> diff --git a/contrib/llvm/tools/clang/lib/Headers/intrin.h b/contrib/llvm/tools/clang/lib/Headers/intrin.h index 38d9407abed9..881d05c0d164 100644 --- a/contrib/llvm/tools/clang/lib/Headers/intrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/intrin.h @@ -85,9 +85,6 @@ void __inwordstring(unsigned short, unsigned short *, unsigned long); void __lidt(void *); unsigned __int64 __ll_lshift(unsigned __int64, int); __int64 __ll_rshift(__int64, int); -void __llwpcb(void *); -unsigned char __lwpins32(unsigned int, unsigned int, unsigned int); -void __lwpval32(unsigned int, unsigned int, unsigned int); unsigned int __lzcnt(unsigned int); unsigned short __lzcnt16(unsigned short); static __inline__ @@ -126,7 +123,6 @@ unsigned __int64 __readmsr(unsigned long); unsigned __int64 __readpmc(unsigned long); unsigned long __segmentlimit(unsigned long); void __sidt(void *); -void *__slwpcb(void); static __inline__ void __stosb(unsigned char *, unsigned char, size_t); static __inline__ @@ -227,8 +223,6 @@ void __incgsbyte(unsigned long); void __incgsdword(unsigned long); void __incgsqword(unsigned long); void __incgsword(unsigned long); -unsigned char __lwpins64(unsigned __int64, unsigned int, unsigned int); -void __lwpval64(unsigned __int64, unsigned int, unsigned int); unsigned __int64 __lzcnt64(unsigned __int64); static __inline__ void __movsq(unsigned long long *, unsigned long long const *, size_t); diff --git a/contrib/llvm/tools/clang/lib/Headers/mmintrin.h b/contrib/llvm/tools/clang/lib/Headers/mmintrin.h index 2b3618398cbf..5a7968bec842 100644 --- a/contrib/llvm/tools/clang/lib/Headers/mmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/mmintrin.h @@ -608,10 +608,11 @@ _mm_subs_pi16(__m64 __m1, __m64 __m2) /// \brief Subtracts each 8-bit unsigned integer element of the second 64-bit /// integer vector of [8 x i8] from the corresponding 8-bit unsigned integer -/// element of the first 64-bit integer vector of [8 x i8]. If an element of -/// the first vector is less than the corresponding element of the second -/// vector, the result is saturated to 0. The results are packed into a -/// 64-bit integer vector of [8 x i8]. +/// element of the first 64-bit integer vector of [8 x i8]. +/// +/// If an element of the first vector is less than the corresponding element +/// of the second vector, the result is saturated to 0. The results are +/// packed into a 64-bit integer vector of [8 x i8]. /// /// \headerfile <x86intrin.h> /// @@ -631,10 +632,11 @@ _mm_subs_pu8(__m64 __m1, __m64 __m2) /// \brief Subtracts each 16-bit unsigned integer element of the second 64-bit /// integer vector of [4 x i16] from the corresponding 16-bit unsigned -/// integer element of the first 64-bit integer vector of [4 x i16]. If an -/// element of the first vector is less than the corresponding element of the -/// second vector, the result is saturated to 0. The results are packed into -/// a 64-bit integer vector of [4 x i16]. +/// integer element of the first 64-bit integer vector of [4 x i16]. +/// +/// If an element of the first vector is less than the corresponding element +/// of the second vector, the result is saturated to 0. The results are +/// packed into a 64-bit integer vector of [4 x i16]. /// /// \headerfile <x86intrin.h> /// @@ -657,9 +659,11 @@ _mm_subs_pu16(__m64 __m1, __m64 __m2) /// element of the second 64-bit integer vector of [4 x i16] and get four /// 32-bit products. Adds adjacent pairs of products to get two 32-bit sums. /// The lower 32 bits of these two sums are packed into a 64-bit integer -/// vector of [2 x i32]. For example, bits [15:0] of both parameters are -/// multiplied, bits [31:16] of both parameters are multiplied, and the sum -/// of both results is written to bits [31:0] of the result. +/// vector of [2 x i32]. +/// +/// For example, bits [15:0] of both parameters are multiplied, bits [31:16] +/// of both parameters are multiplied, and the sum of both results is written +/// to bits [31:0] of the result. /// /// \headerfile <x86intrin.h> /// @@ -851,10 +855,11 @@ _mm_slli_si64(__m64 __m, int __count) /// \brief Right-shifts each 16-bit integer element of the first parameter, /// which is a 64-bit integer vector of [4 x i16], by the number of bits -/// specified by the second parameter, which is a 64-bit integer. High-order -/// bits are filled with the sign bit of the initial value of each 16-bit -/// element. The 16-bit results are packed into a 64-bit integer vector of -/// [4 x i16]. +/// specified by the second parameter, which is a 64-bit integer. +/// +/// High-order bits are filled with the sign bit of the initial value of each +/// 16-bit element. The 16-bit results are packed into a 64-bit integer +/// vector of [4 x i16]. /// /// \headerfile <x86intrin.h> /// @@ -874,6 +879,7 @@ _mm_sra_pi16(__m64 __m, __m64 __count) /// \brief Right-shifts each 16-bit integer element of a 64-bit integer vector /// of [4 x i16] by the number of bits specified by a 32-bit integer. +/// /// High-order bits are filled with the sign bit of the initial value of each /// 16-bit element. The 16-bit results are packed into a 64-bit integer /// vector of [4 x i16]. @@ -896,10 +902,11 @@ _mm_srai_pi16(__m64 __m, int __count) /// \brief Right-shifts each 32-bit integer element of the first parameter, /// which is a 64-bit integer vector of [2 x i32], by the number of bits -/// specified by the second parameter, which is a 64-bit integer. High-order -/// bits are filled with the sign bit of the initial value of each 32-bit -/// element. The 32-bit results are packed into a 64-bit integer vector of -/// [2 x i32]. +/// specified by the second parameter, which is a 64-bit integer. +/// +/// High-order bits are filled with the sign bit of the initial value of each +/// 32-bit element. The 32-bit results are packed into a 64-bit integer +/// vector of [2 x i32]. /// /// \headerfile <x86intrin.h> /// @@ -919,6 +926,7 @@ _mm_sra_pi32(__m64 __m, __m64 __count) /// \brief Right-shifts each 32-bit integer element of a 64-bit integer vector /// of [2 x i32] by the number of bits specified by a 32-bit integer. +/// /// High-order bits are filled with the sign bit of the initial value of each /// 32-bit element. The 32-bit results are packed into a 64-bit integer /// vector of [2 x i32]. @@ -941,9 +949,10 @@ _mm_srai_pi32(__m64 __m, int __count) /// \brief Right-shifts each 16-bit integer element of the first parameter, /// which is a 64-bit integer vector of [4 x i16], by the number of bits -/// specified by the second parameter, which is a 64-bit integer. High-order -/// bits are cleared. The 16-bit results are packed into a 64-bit integer -/// vector of [4 x i16]. +/// specified by the second parameter, which is a 64-bit integer. +/// +/// High-order bits are cleared. The 16-bit results are packed into a 64-bit +/// integer vector of [4 x i16]. /// /// \headerfile <x86intrin.h> /// @@ -963,6 +972,7 @@ _mm_srl_pi16(__m64 __m, __m64 __count) /// \brief Right-shifts each 16-bit integer element of a 64-bit integer vector /// of [4 x i16] by the number of bits specified by a 32-bit integer. +/// /// High-order bits are cleared. The 16-bit results are packed into a 64-bit /// integer vector of [4 x i16]. /// @@ -984,9 +994,10 @@ _mm_srli_pi16(__m64 __m, int __count) /// \brief Right-shifts each 32-bit integer element of the first parameter, /// which is a 64-bit integer vector of [2 x i32], by the number of bits -/// specified by the second parameter, which is a 64-bit integer. High-order -/// bits are cleared. The 32-bit results are packed into a 64-bit integer -/// vector of [2 x i32]. +/// specified by the second parameter, which is a 64-bit integer. +/// +/// High-order bits are cleared. The 32-bit results are packed into a 64-bit +/// integer vector of [2 x i32]. /// /// \headerfile <x86intrin.h> /// @@ -1006,6 +1017,7 @@ _mm_srl_pi32(__m64 __m, __m64 __count) /// \brief Right-shifts each 32-bit integer element of a 64-bit integer vector /// of [2 x i32] by the number of bits specified by a 32-bit integer. +/// /// High-order bits are cleared. The 32-bit results are packed into a 64-bit /// integer vector of [2 x i32]. /// @@ -1026,8 +1038,9 @@ _mm_srli_pi32(__m64 __m, int __count) } /// \brief Right-shifts the first 64-bit integer parameter by the number of bits -/// specified by the second 64-bit integer parameter. High-order bits are -/// cleared. +/// specified by the second 64-bit integer parameter. +/// +/// High-order bits are cleared. /// /// \headerfile <x86intrin.h> /// @@ -1046,7 +1059,9 @@ _mm_srl_si64(__m64 __m, __m64 __count) /// \brief Right-shifts the first parameter, which is a 64-bit integer, by the /// number of bits specified by the second parameter, which is a 32-bit -/// integer. High-order bits are cleared. +/// integer. +/// +/// High-order bits are cleared. /// /// \headerfile <x86intrin.h> /// @@ -1140,8 +1155,9 @@ _mm_xor_si64(__m64 __m1, __m64 __m2) /// \brief Compares the 8-bit integer elements of two 64-bit integer vectors of /// [8 x i8] to determine if the element of the first vector is equal to the -/// corresponding element of the second vector. The comparison yields 0 for -/// false, 0xFF for true. +/// corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFF for true. /// /// \headerfile <x86intrin.h> /// @@ -1161,8 +1177,9 @@ _mm_cmpeq_pi8(__m64 __m1, __m64 __m2) /// \brief Compares the 16-bit integer elements of two 64-bit integer vectors of /// [4 x i16] to determine if the element of the first vector is equal to the -/// corresponding element of the second vector. The comparison yields 0 for -/// false, 0xFFFF for true. +/// corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFFFF for true. /// /// \headerfile <x86intrin.h> /// @@ -1182,8 +1199,9 @@ _mm_cmpeq_pi16(__m64 __m1, __m64 __m2) /// \brief Compares the 32-bit integer elements of two 64-bit integer vectors of /// [2 x i32] to determine if the element of the first vector is equal to the -/// corresponding element of the second vector. The comparison yields 0 for -/// false, 0xFFFFFFFF for true. +/// corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFFFFFFFF for true. /// /// \headerfile <x86intrin.h> /// @@ -1203,8 +1221,9 @@ _mm_cmpeq_pi32(__m64 __m1, __m64 __m2) /// \brief Compares the 8-bit integer elements of two 64-bit integer vectors of /// [8 x i8] to determine if the element of the first vector is greater than -/// the corresponding element of the second vector. The comparison yields 0 -/// for false, 0xFF for true. +/// the corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFF for true. /// /// \headerfile <x86intrin.h> /// @@ -1224,8 +1243,9 @@ _mm_cmpgt_pi8(__m64 __m1, __m64 __m2) /// \brief Compares the 16-bit integer elements of two 64-bit integer vectors of /// [4 x i16] to determine if the element of the first vector is greater than -/// the corresponding element of the second vector. The comparison yields 0 -/// for false, 0xFFFF for true. +/// the corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFFFF for true. /// /// \headerfile <x86intrin.h> /// @@ -1245,8 +1265,9 @@ _mm_cmpgt_pi16(__m64 __m1, __m64 __m2) /// \brief Compares the 32-bit integer elements of two 64-bit integer vectors of /// [2 x i32] to determine if the element of the first vector is greater than -/// the corresponding element of the second vector. The comparison yields 0 -/// for false, 0xFFFFFFFF for true. +/// the corresponding element of the second vector. +/// +/// The comparison yields 0 for false, 0xFFFFFFFF for true. /// /// \headerfile <x86intrin.h> /// diff --git a/contrib/llvm/tools/clang/lib/Headers/opencl-c.h b/contrib/llvm/tools/clang/lib/Headers/opencl-c.h index 6452d5c987f0..58c8daf3a536 100644 --- a/contrib/llvm/tools/clang/lib/Headers/opencl-c.h +++ b/contrib/llvm/tools/clang/lib/Headers/opencl-c.h @@ -14962,6 +14962,7 @@ float __purefn __ovld read_imagef(read_only image2d_array_msaa_depth_t image, in #endif //cl_khr_gl_msaa_sharing // OpenCL Extension v2.0 s9.18 - Mipmaps +#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 #ifdef cl_khr_mipmap_image float4 __purefn __ovld read_imagef(read_only image1d_t image, sampler_t sampler, float coord, float lod); @@ -15037,6 +15038,7 @@ int4 __purefn __ovld read_imagei(read_only image3d_t image, sampler_t sampler, f uint4 __purefn __ovld read_imageui(read_only image3d_t image, sampler_t sampler, float4 coord, float lod); #endif //cl_khr_mipmap_image +#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 /** * Sampler-less Image Access @@ -15135,6 +15137,7 @@ float __purefn __ovld read_imagef(read_write image2d_msaa_depth_t image, int2 co float __purefn __ovld read_imagef(read_write image2d_array_msaa_depth_t image, int4 coord, int sample); #endif //cl_khr_gl_msaa_sharing +#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 #ifdef cl_khr_mipmap_image float4 __purefn __ovld read_imagef(read_write image1d_t image, sampler_t sampler, float coord, float lod); int4 __purefn __ovld read_imagei(read_write image1d_t image, sampler_t sampler, float coord, float lod); @@ -15208,6 +15211,7 @@ float4 __purefn __ovld read_imagef(read_write image3d_t image, sampler_t sampler int4 __purefn __ovld read_imagei(read_write image3d_t image, sampler_t sampler, float4 coord, float lod); uint4 __purefn __ovld read_imageui(read_write image3d_t image, sampler_t sampler, float4 coord, float lod); #endif //cl_khr_mipmap_image +#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 // Image read functions returning half4 type #ifdef cl_khr_fp16 @@ -15319,6 +15323,7 @@ void __ovld write_imagef(write_only image2d_array_depth_t image, int4 coord, flo #endif //cl_khr_depth_images // OpenCL Extension v2.0 s9.18 - Mipmaps +#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 #ifdef cl_khr_mipmap_image void __ovld write_imagef(write_only image1d_t image, int coord, int lod, float4 color); void __ovld write_imagei(write_only image1d_t image, int coord, int lod, int4 color); @@ -15345,6 +15350,7 @@ void __ovld write_imagei(write_only image3d_t image, int4 coord, int lod, int4 c void __ovld write_imageui(write_only image3d_t image, int4 coord, int lod, uint4 color); #endif #endif //cl_khr_mipmap_image +#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 // Image write functions for half4 type #ifdef cl_khr_fp16 @@ -15391,6 +15397,7 @@ void __ovld write_imagef(read_write image2d_depth_t image, int2 coord, float col void __ovld write_imagef(read_write image2d_array_depth_t image, int4 coord, float color); #endif //cl_khr_depth_images +#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 #ifdef cl_khr_mipmap_image void __ovld write_imagef(read_write image1d_t image, int coord, int lod, float4 color); void __ovld write_imagei(read_write image1d_t image, int coord, int lod, int4 color); @@ -15417,6 +15424,7 @@ void __ovld write_imagei(read_write image3d_t image, int4 coord, int lod, int4 c void __ovld write_imageui(read_write image3d_t image, int4 coord, int lod, uint4 color); #endif #endif //cl_khr_mipmap_image +#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 // Image write functions for half4 type #ifdef cl_khr_fp16 @@ -15559,6 +15567,7 @@ int __ovld __cnfn get_image_depth(read_write image3d_t image); #endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 // OpenCL Extension v2.0 s9.18 - Mipmaps +#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 #ifdef cl_khr_mipmap_image /** * Return the image miplevels. @@ -15574,11 +15583,9 @@ int __ovld get_image_num_mip_levels(write_only image2d_t image); int __ovld get_image_num_mip_levels(write_only image3d_t image); #endif -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 int __ovld get_image_num_mip_levels(read_write image1d_t image); int __ovld get_image_num_mip_levels(read_write image2d_t image); int __ovld get_image_num_mip_levels(read_write image3d_t image); -#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 int __ovld get_image_num_mip_levels(read_only image1d_array_t image); int __ovld get_image_num_mip_levels(read_only image2d_array_t image); @@ -15590,14 +15597,13 @@ int __ovld get_image_num_mip_levels(write_only image2d_array_t image); int __ovld get_image_num_mip_levels(write_only image2d_array_depth_t image); int __ovld get_image_num_mip_levels(write_only image2d_depth_t image); -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0 int __ovld get_image_num_mip_levels(read_write image1d_array_t image); int __ovld get_image_num_mip_levels(read_write image2d_array_t image); int __ovld get_image_num_mip_levels(read_write image2d_array_depth_t image); int __ovld get_image_num_mip_levels(read_write image2d_depth_t image); -#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 #endif //cl_khr_mipmap_image +#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0 /** * Return the channel data type. Valid values are: diff --git a/contrib/llvm/tools/clang/lib/Headers/pmmintrin.h b/contrib/llvm/tools/clang/lib/Headers/pmmintrin.h index a479d9ed2911..559ece2e3974 100644 --- a/contrib/llvm/tools/clang/lib/Headers/pmmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/pmmintrin.h @@ -31,9 +31,11 @@ __attribute__((__always_inline__, __nodebug__, __target__("sse3"))) /// \brief Loads data from an unaligned memory location to elements in a 128-bit -/// vector. If the address of the data is not 16-byte aligned, the -/// instruction may read two adjacent aligned blocks of memory to retrieve -/// the requested data. +/// vector. +/// +/// If the address of the data is not 16-byte aligned, the instruction may +/// read two adjacent aligned blocks of memory to retrieve the requested +/// data. /// /// \headerfile <x86intrin.h> /// diff --git a/contrib/llvm/tools/clang/lib/Headers/prfchwintrin.h b/contrib/llvm/tools/clang/lib/Headers/prfchwintrin.h index a3789126ef07..b52f31da2706 100644 --- a/contrib/llvm/tools/clang/lib/Headers/prfchwintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/prfchwintrin.h @@ -50,8 +50,10 @@ _m_prefetch(void *__P) /// the L1 data cache and sets the cache-coherency to modified. This /// provides a hint to the processor that the cache line will be modified. /// It is intended for use when the cache line will be written to shortly -/// after the prefetch is performed. Note that the effect of this intrinsic -/// is dependent on the processor implementation. +/// after the prefetch is performed. +/// +/// Note that the effect of this intrinsic is dependent on the processor +/// implementation. /// /// \headerfile <x86intrin.h> /// diff --git a/contrib/llvm/tools/clang/lib/Headers/smmintrin.h b/contrib/llvm/tools/clang/lib/Headers/smmintrin.h index 1c94aca69381..c2fa5a452bce 100644 --- a/contrib/llvm/tools/clang/lib/Headers/smmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/smmintrin.h @@ -586,7 +586,9 @@ _mm_mul_epi32 (__m128i __V1, __m128i __V2) /* SSE4 Floating Point Dot Product Instructions. */ /// \brief Computes the dot product of the two 128-bit vectors of [4 x float] /// and returns it in the elements of the 128-bit result vector of -/// [4 x float]. The immediate integer operand controls which input elements +/// [4 x float]. +/// +/// The immediate integer operand controls which input elements /// will contribute to the dot product, and where the final results are /// returned. /// @@ -620,7 +622,9 @@ _mm_mul_epi32 (__m128i __V1, __m128i __V2) /// \brief Computes the dot product of the two 128-bit vectors of [2 x double] /// and returns it in the elements of the 128-bit result vector of -/// [2 x double]. The immediate integer operand controls which input +/// [2 x double]. +/// +/// The immediate integer operand controls which input /// elements will contribute to the dot product, and where the final results /// are returned. /// @@ -875,7 +879,7 @@ _mm_max_epu32 (__m128i __V1, __m128i __V2) /// int _mm_extract_ps(__m128 X, const int N); /// \endcode /// -/// This intrinsic corresponds to the <c> VEXTRACTPS / EXTRACTPS </c> +/// This intrinsic corresponds to the <c> VEXTRACTPS / EXTRACTPS </c> /// instruction. /// /// \param X diff --git a/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h b/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h index 80664043a06f..042bfc7e3b0d 100644 --- a/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h @@ -469,10 +469,11 @@ _mm_hsubs_pi16(__m64 __a, __m64 __b) /// values contained in the first source operand and packed 8-bit signed /// integer values contained in the second source operand, adds pairs of /// contiguous products with signed saturation, and writes the 16-bit sums to -/// the corresponding bits in the destination. For example, bits [7:0] of -/// both operands are multiplied, bits [15:8] of both operands are -/// multiplied, and the sum of both results is written to bits [15:0] of the -/// destination. +/// the corresponding bits in the destination. +/// +/// For example, bits [7:0] of both operands are multiplied, bits [15:8] of +/// both operands are multiplied, and the sum of both results is written to +/// bits [15:0] of the destination. /// /// \headerfile <x86intrin.h> /// @@ -502,10 +503,11 @@ _mm_maddubs_epi16(__m128i __a, __m128i __b) /// values contained in the first source operand and packed 8-bit signed /// integer values contained in the second source operand, adds pairs of /// contiguous products with signed saturation, and writes the 16-bit sums to -/// the corresponding bits in the destination. For example, bits [7:0] of -/// both operands are multiplied, bits [15:8] of both operands are -/// multiplied, and the sum of both results is written to bits [15:0] of the -/// destination. +/// the corresponding bits in the destination. +/// +/// For example, bits [7:0] of both operands are multiplied, bits [15:8] of +/// both operands are multiplied, and the sum of both results is written to +/// bits [15:0] of the destination. /// /// \headerfile <x86intrin.h> /// @@ -619,13 +621,14 @@ _mm_shuffle_pi8(__m64 __a, __m64 __b) } /// \brief For each 8-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// byte in the second source is negative, calculate the two's complement of -/// the corresponding byte in the first source, and write that value to the -/// destination. If the byte in the second source is positive, copy the -/// corresponding byte from the first source to the destination. If the byte -/// in the second source is zero, clear the corresponding byte in the -/// destination. +/// the following actions as specified by the second source operand. +/// +/// If the byte in the second source is negative, calculate the two's +/// complement of the corresponding byte in the first source, and write that +/// value to the destination. If the byte in the second source is positive, +/// copy the corresponding byte from the first source to the destination. If +/// the byte in the second source is zero, clear the corresponding byte in +/// the destination. /// /// \headerfile <x86intrin.h> /// @@ -644,13 +647,14 @@ _mm_sign_epi8(__m128i __a, __m128i __b) } /// \brief For each 16-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// word in the second source is negative, calculate the two's complement of -/// the corresponding word in the first source, and write that value to the -/// destination. If the word in the second source is positive, copy the -/// corresponding word from the first source to the destination. If the word -/// in the second source is zero, clear the corresponding word in the -/// destination. +/// the following actions as specified by the second source operand. +/// +/// If the word in the second source is negative, calculate the two's +/// complement of the corresponding word in the first source, and write that +/// value to the destination. If the word in the second source is positive, +/// copy the corresponding word from the first source to the destination. If +/// the word in the second source is zero, clear the corresponding word in +/// the destination. /// /// \headerfile <x86intrin.h> /// @@ -669,8 +673,9 @@ _mm_sign_epi16(__m128i __a, __m128i __b) } /// \brief For each 32-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// doubleword in the second source is negative, calculate the two's +/// the following actions as specified by the second source operand. +/// +/// If the doubleword in the second source is negative, calculate the two's /// complement of the corresponding word in the first source, and write that /// value to the destination. If the doubleword in the second source is /// positive, copy the corresponding word from the first source to the @@ -694,13 +699,14 @@ _mm_sign_epi32(__m128i __a, __m128i __b) } /// \brief For each 8-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// byte in the second source is negative, calculate the two's complement of -/// the corresponding byte in the first source, and write that value to the -/// destination. If the byte in the second source is positive, copy the -/// corresponding byte from the first source to the destination. If the byte -/// in the second source is zero, clear the corresponding byte in the -/// destination. +/// the following actions as specified by the second source operand. +/// +/// If the byte in the second source is negative, calculate the two's +/// complement of the corresponding byte in the first source, and write that +/// value to the destination. If the byte in the second source is positive, +/// copy the corresponding byte from the first source to the destination. If +/// the byte in the second source is zero, clear the corresponding byte in +/// the destination. /// /// \headerfile <x86intrin.h> /// @@ -719,13 +725,14 @@ _mm_sign_pi8(__m64 __a, __m64 __b) } /// \brief For each 16-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// word in the second source is negative, calculate the two's complement of -/// the corresponding word in the first source, and write that value to the -/// destination. If the word in the second source is positive, copy the -/// corresponding word from the first source to the destination. If the word -/// in the second source is zero, clear the corresponding word in the -/// destination. +/// the following actions as specified by the second source operand. +/// +/// If the word in the second source is negative, calculate the two's +/// complement of the corresponding word in the first source, and write that +/// value to the destination. If the word in the second source is positive, +/// copy the corresponding word from the first source to the destination. If +/// the word in the second source is zero, clear the corresponding word in +/// the destination. /// /// \headerfile <x86intrin.h> /// @@ -744,8 +751,9 @@ _mm_sign_pi16(__m64 __a, __m64 __b) } /// \brief For each 32-bit integer in the first source operand, perform one of -/// the following actions as specified by the second source operand: If the -/// doubleword in the second source is negative, calculate the two's +/// the following actions as specified by the second source operand. +/// +/// If the doubleword in the second source is negative, calculate the two's /// complement of the corresponding doubleword in the first source, and /// write that value to the destination. If the doubleword in the second /// source is positive, copy the corresponding doubleword from the first diff --git a/contrib/llvm/tools/clang/lib/Headers/x86intrin.h b/contrib/llvm/tools/clang/lib/Headers/x86intrin.h index ef1d02948c8b..31ee7b82dd53 100644 --- a/contrib/llvm/tools/clang/lib/Headers/x86intrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/x86intrin.h @@ -88,6 +88,4 @@ #include <clzerointrin.h> #endif -/* FIXME: LWP */ - #endif /* __X86INTRIN_H */ diff --git a/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h b/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h index 5c312c08efb6..9773acb840a5 100644 --- a/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h +++ b/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h @@ -2331,8 +2331,10 @@ _mm_mulhi_pu16(__m64 __a, __m64 __b) /// \brief Conditionally copies the values from each 8-bit element in the first /// 64-bit integer vector operand to the specified memory location, as /// specified by the most significant bit in the corresponding element in the -/// second 64-bit integer vector operand. To minimize caching, the data is -/// flagged as non-temporal (unlikely to be used again soon). +/// second 64-bit integer vector operand. +/// +/// To minimize caching, the data is flagged as non-temporal +/// (unlikely to be used again soon). /// /// \headerfile <x86intrin.h> /// @@ -2815,11 +2817,12 @@ _mm_cvtpi32x2_ps(__m64 __a, __m64 __b) /// \brief Converts each single-precision floating-point element of a 128-bit /// floating-point vector of [4 x float] into a 16-bit signed integer, and -/// packs the results into a 64-bit integer vector of [4 x i16]. If the -/// floating-point element is NaN or infinity, or if the floating-point -/// element is greater than 0x7FFFFFFF or less than -0x8000, it is converted -/// to 0x8000. Otherwise if the floating-point element is greater than -/// 0x7FFF, it is converted to 0x7FFF. +/// packs the results into a 64-bit integer vector of [4 x i16]. +/// +/// If the floating-point element is NaN or infinity, or if the +/// floating-point element is greater than 0x7FFFFFFF or less than -0x8000, +/// it is converted to 0x8000. Otherwise if the floating-point element is +/// greater than 0x7FFF, it is converted to 0x7FFF. /// /// \headerfile <x86intrin.h> /// @@ -2845,11 +2848,12 @@ _mm_cvtps_pi16(__m128 __a) /// \brief Converts each single-precision floating-point element of a 128-bit /// floating-point vector of [4 x float] into an 8-bit signed integer, and /// packs the results into the lower 32 bits of a 64-bit integer vector of -/// [8 x i8]. The upper 32 bits of the vector are set to 0. If the -/// floating-point element is NaN or infinity, or if the floating-point -/// element is greater than 0x7FFFFFFF or less than -0x80, it is converted -/// to 0x80. Otherwise if the floating-point element is greater than 0x7F, -/// it is converted to 0x7F. +/// [8 x i8]. The upper 32 bits of the vector are set to 0. +/// +/// If the floating-point element is NaN or infinity, or if the +/// floating-point element is greater than 0x7FFFFFFF or less than -0x80, it +/// is converted to 0x80. Otherwise if the floating-point element is greater +/// than 0x7F, it is converted to 0x7F. /// /// \headerfile <x86intrin.h> /// diff --git a/contrib/llvm/tools/clang/lib/Index/IndexBody.cpp b/contrib/llvm/tools/clang/lib/Index/IndexBody.cpp index 7f09290de40f..08d233fb83e0 100644 --- a/contrib/llvm/tools/clang/lib/Index/IndexBody.cpp +++ b/contrib/llvm/tools/clang/lib/Index/IndexBody.cpp @@ -150,6 +150,53 @@ public: Parent, ParentDC, Roles, Relations, E); } + bool indexDependentReference( + const Expr *E, const Type *T, const DeclarationNameInfo &NameInfo, + llvm::function_ref<bool(const NamedDecl *ND)> Filter) { + if (!T) + return true; + const TemplateSpecializationType *TST = + T->getAs<TemplateSpecializationType>(); + if (!TST) + return true; + TemplateName TN = TST->getTemplateName(); + const ClassTemplateDecl *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); + if (!TD) + return true; + CXXRecordDecl *RD = TD->getTemplatedDecl(); + if (!RD->hasDefinition()) + return true; + RD = RD->getDefinition(); + std::vector<const NamedDecl *> Symbols = + RD->lookupDependentName(NameInfo.getName(), Filter); + // FIXME: Improve overload handling. + if (Symbols.size() != 1) + return true; + SourceLocation Loc = NameInfo.getLoc(); + if (Loc.isInvalid()) + Loc = E->getLocStart(); + SmallVector<SymbolRelation, 4> Relations; + SymbolRoleSet Roles = getRolesForRef(E, Relations); + return IndexCtx.handleReference(Symbols[0], Loc, Parent, ParentDC, Roles, + Relations, E); + } + + bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { + const DeclarationNameInfo &Info = E->getMemberNameInfo(); + return indexDependentReference( + E, E->getBaseType().getTypePtrOrNull(), Info, + [](const NamedDecl *D) { return D->isCXXInstanceMember(); }); + } + + bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { + const DeclarationNameInfo &Info = E->getNameInfo(); + const NestedNameSpecifier *NNS = E->getQualifier(); + return indexDependentReference( + E, NNS->getAsType(), Info, + [](const NamedDecl *D) { return !D->isCXXInstanceMember(); }); + } + bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator() && D.getField()) diff --git a/contrib/llvm/tools/clang/lib/Index/IndexDecl.cpp b/contrib/llvm/tools/clang/lib/Index/IndexDecl.cpp index 7de70a10b692..203862c46e98 100644 --- a/contrib/llvm/tools/clang/lib/Index/IndexDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Index/IndexDecl.cpp @@ -52,6 +52,22 @@ public: return MD && !MD->isImplicit() && MD->isThisDeclarationADefinition(); } + void handleTemplateArgumentLoc(const TemplateArgumentLoc &TALoc, + const NamedDecl *Parent, + const DeclContext *DC) { + const TemplateArgumentLocInfo &LocInfo = TALoc.getLocInfo(); + switch (TALoc.getArgument().getKind()) { + case TemplateArgument::Expression: + IndexCtx.indexBody(LocInfo.getAsExpr(), Parent, DC); + break; + case TemplateArgument::Type: + IndexCtx.indexTypeSourceInfo(LocInfo.getAsTypeSourceInfo(), Parent, DC); + break; + default: + break; + } + } + void handleDeclarator(const DeclaratorDecl *D, const NamedDecl *Parent = nullptr, bool isIBType = false) { @@ -233,6 +249,12 @@ public: Dtor->getParent(), Dtor->getDeclContext()); } } + // Template specialization arguments. + if (const ASTTemplateArgumentListInfo *TemplateArgInfo = + D->getTemplateSpecializationArgsAsWritten()) { + for (const auto &Arg : TemplateArgInfo->arguments()) + handleTemplateArgumentLoc(Arg, D, D->getLexicalDeclContext()); + } if (D->isThisDeclarationADefinition()) { const Stmt *Body = D->getBody(); @@ -522,6 +544,14 @@ public: return true; } + bool VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) { + TRY_DECL(D, IndexCtx.handleDecl(D)); + IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), D); + IndexCtx.handleReference(D->getAliasedNamespace(), D->getTargetNameLoc(), D, + D->getLexicalDeclContext()); + return true; + } + bool VisitUsingDecl(const UsingDecl *D) { const DeclContext *DC = D->getDeclContext()->getRedeclContext(); const NamedDecl *Parent = dyn_cast<NamedDecl>(DC); diff --git a/contrib/llvm/tools/clang/lib/Index/IndexTypeSourceInfo.cpp b/contrib/llvm/tools/clang/lib/Index/IndexTypeSourceInfo.cpp index 44d1241fb930..ae27ebe6ea4c 100644 --- a/contrib/llvm/tools/clang/lib/Index/IndexTypeSourceInfo.cpp +++ b/contrib/llvm/tools/clang/lib/Index/IndexTypeSourceInfo.cpp @@ -141,6 +141,34 @@ public: return true; } + bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { + const DependentNameType *DNT = TL.getTypePtr(); + const NestedNameSpecifier *NNS = DNT->getQualifier(); + const Type *T = NNS->getAsType(); + if (!T) + return true; + const TemplateSpecializationType *TST = + T->getAs<TemplateSpecializationType>(); + if (!TST) + return true; + TemplateName TN = TST->getTemplateName(); + const ClassTemplateDecl *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); + if (!TD) + return true; + CXXRecordDecl *RD = TD->getTemplatedDecl(); + if (!RD->hasDefinition()) + return true; + RD = RD->getDefinition(); + DeclarationName Name(DNT->getIdentifier()); + std::vector<const NamedDecl *> Symbols = RD->lookupDependentName( + Name, [](const NamedDecl *ND) { return isa<TypeDecl>(ND); }); + if (Symbols.size() != 1) + return true; + return IndexCtx.handleReference(Symbols[0], TL.getNameLoc(), Parent, + ParentDC, SymbolRoleSet(), Relations); + } + bool TraverseStmt(Stmt *S) { IndexCtx.indexBody(S, Parent, ParentDC); return true; @@ -184,7 +212,7 @@ void IndexingContext::indexNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, if (!DC) DC = Parent->getLexicalDeclContext(); - SourceLocation Loc = NNS.getSourceRange().getBegin(); + SourceLocation Loc = NNS.getLocalBeginLoc(); switch (NNS.getNestedNameSpecifier()->getKind()) { case NestedNameSpecifier::Identifier: diff --git a/contrib/llvm/tools/clang/lib/Index/IndexingContext.cpp b/contrib/llvm/tools/clang/lib/Index/IndexingContext.cpp index 709a23657b07..5cebb198460f 100644 --- a/contrib/llvm/tools/clang/lib/Index/IndexingContext.cpp +++ b/contrib/llvm/tools/clang/lib/Index/IndexingContext.cpp @@ -124,6 +124,10 @@ bool IndexingContext::isTemplateImplicitInstantiation(const Decl *D) { TKind = FD->getTemplateSpecializationKind(); } else if (auto *VD = dyn_cast<VarDecl>(D)) { TKind = VD->getTemplateSpecializationKind(); + } else if (isa<FieldDecl>(D)) { + if (const auto *Parent = + dyn_cast<ClassTemplateSpecializationDecl>(D->getDeclContext())) + TKind = Parent->getSpecializationKind(); } switch (TKind) { case TSK_Undeclared: @@ -159,6 +163,17 @@ static const Decl *adjustTemplateImplicitInstantiation(const Decl *D) { return FD->getTemplateInstantiationPattern(); } else if (auto *VD = dyn_cast<VarDecl>(D)) { return VD->getTemplateInstantiationPattern(); + } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { + if (const auto *Parent = + dyn_cast<ClassTemplateSpecializationDecl>(D->getDeclContext())) { + const CXXRecordDecl *Pattern = Parent->getTemplateInstantiationPattern(); + for (const NamedDecl *ND : Pattern->lookup(FD->getDeclName())) { + if (ND->isImplicit()) + continue; + if (isa<FieldDecl>(ND)) + return ND; + } + } } return nullptr; } diff --git a/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp b/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp index bec434085e3a..1e5deeb1919b 100644 --- a/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp @@ -29,7 +29,6 @@ MacroInfo::MacroInfo(SourceLocation DefLoc) IsUsed(false), IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false), - FromASTFile(false), UsedForHeaderGuard(false) { } @@ -137,7 +136,6 @@ LLVM_DUMP_METHOD void MacroInfo::dump() const { if (IsAllowRedefinitionsWithoutWarning) Out << " allow_redefinitions_without_warning"; if (IsWarnIfUnused) Out << " warn_if_unused"; - if (FromASTFile) Out << " imported"; if (UsedForHeaderGuard) Out << " header_guard"; Out << "\n #define <macro>"; diff --git a/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp b/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp index 70d37d3d7082..6f44dc757e85 100644 --- a/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/ModuleMap.cpp @@ -1485,7 +1485,19 @@ void ModuleMapParser::parseModuleDecl() { // Determine whether this (sub)module has already been defined. if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { - if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) { + // We might see a (re)definition of a module that we already have a + // definition for in two cases: + // - If we loaded one definition from an AST file and we've just found a + // corresponding definition in a module map file, or + bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid(); + // - If we're building a (preprocessed) module and we've just loaded the + // module map file from which it was created. + bool ParsedAsMainInput = + Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap && + Map.LangOpts.CurrentModule == ModuleName && + SourceMgr.getDecomposedLoc(ModuleNameLoc).first != + SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first; + if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) { // Skip the module definition. skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) @@ -1901,8 +1913,10 @@ void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, // 'framework module FrameworkName.Private', since a 'Private.Framework' // does not usually exist. However, since both are currently widely used // for private modules, make sure we find the right path in both cases. - RelativePathName.resize(ActiveModule->IsFramework ? 0 - : RelativePathLength); + if (ActiveModule->IsFramework && ActiveModule->Name == "Private") + RelativePathName.clear(); + else + RelativePathName.resize(RelativePathLength); FullPathName.resize(FullPathLength); llvm::sys::path::append(RelativePathName, "PrivateHeaders", Header.FileName); diff --git a/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp b/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp index 06fee8e5b0a8..faf8809e4eb4 100644 --- a/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp @@ -54,35 +54,12 @@ using namespace clang; // Utility Methods for Preprocessor Directive Handling. //===----------------------------------------------------------------------===// -MacroInfo *Preprocessor::AllocateMacroInfo() { - MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>(); - MIChain->Next = MIChainHead; +MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { + auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead}; MIChainHead = MIChain; return &MIChain->MI; } -MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { - MacroInfo *MI = AllocateMacroInfo(); - new (MI) MacroInfo(L); - return MI; -} - -MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L, - unsigned SubModuleID) { - static_assert(alignof(MacroInfo) >= sizeof(SubModuleID), - "alignment for MacroInfo is less than the ID"); - DeserializedMacroInfoChain *MIChain = - BP.Allocate<DeserializedMacroInfoChain>(); - MIChain->Next = DeserialMIChainHead; - DeserialMIChainHead = MIChain; - - MacroInfo *MI = &MIChain->MI; - new (MI) MacroInfo(L); - MI->FromASTFile = true; - MI->setOwningModuleID(SubModuleID); - return MI; -} - DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc) { return new (BP) DefMacroDirective(MI, Loc); diff --git a/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp b/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp index e409ab036535..dce8c1efda23 100644 --- a/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp +++ b/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp @@ -88,7 +88,7 @@ Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurLexerSubmodule(nullptr), Callbacks(nullptr), CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr), - Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) { + Record(nullptr), MIChainHead(nullptr) { OwnsHeaderSearch = OwnsHeaders; CounterValue = 0; // __COUNTER__ starts at 0. @@ -169,11 +169,6 @@ Preprocessor::~Preprocessor() { std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr); CurTokenLexer.reset(); - while (DeserializedMacroInfoChain *I = DeserialMIChainHead) { - DeserialMIChainHead = I->Next; - I->~DeserializedMacroInfoChain(); - } - // Free any cached MacroArgs. for (MacroArgs *ArgList = MacroArgCache; ArgList;) ArgList = ArgList->deallocate(); diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp index 1465d21ac5ee..4ccee74eaa90 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp @@ -2577,9 +2577,9 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, // and attempt to recover. ParsedType T; IdentifierInfo *II = Tok.getIdentifierInfo(); + bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less); Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T, - getLangOpts().CPlusPlus && - NextToken().is(tok::less)); + IsTemplateName); if (T) { // The action has suggested that the type T could be used. Set that as // the type in the declaration specifiers, consume the would-be type @@ -2604,6 +2604,13 @@ bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); + // Eat any following template arguments. + if (IsTemplateName) { + SourceLocation LAngle, RAngle; + TemplateArgList Args; + ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle); + } + // TODO: Could inject an invalid typedef decl in an enclosing scope to // avoid rippling error messages on subsequent uses of the same type, // could be useful if #include was forgotten. diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp index ad7b319676e9..e6cf65e36cfa 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp @@ -1137,8 +1137,8 @@ TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, if (!Template) { TemplateArgList TemplateArgs; SourceLocation LAngleLoc, RAngleLoc; - ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc, - TemplateArgs, RAngleLoc); + ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, + RAngleLoc); return true; } @@ -1530,8 +1530,8 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, // a class (or template thereof). TemplateArgList TemplateArgs; SourceLocation LAngleLoc, RAngleLoc; - if (ParseTemplateIdAfterTemplateName( - nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) { + if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, + RAngleLoc)) { // We couldn't parse the template argument list at all, so don't // try to give any location information for the list. LAngleLoc = RAngleLoc = SourceLocation(); diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp index 3e02e46ddc7d..727fd3500991 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp @@ -235,6 +235,30 @@ bool Parser::isNotExpressionStart() { return isKnownToBeDeclarationSpecifier(); } +/// We've parsed something that could plausibly be intended to be a template +/// name (\p LHS) followed by a '<' token, and the following code can't possibly +/// be an expression. Determine if this is likely to be a template-id and if so, +/// diagnose it. +bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) { + TentativeParsingAction TPA(*this); + // FIXME: We could look at the token sequence in a lot more detail here. + if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater, + StopAtSemi | StopBeforeMatch)) { + TPA.Commit(); + + SourceLocation Greater; + ParseGreaterThanInTemplateList(Greater, true, false); + Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS, + Less, Greater); + return true; + } + + // There's no matching '>' token, this probably isn't supposed to be + // interpreted as a template-id. Parse it as an (ill-formed) comparison. + TPA.Revert(); + return false; +} + static bool isFoldOperator(prec::Level Level) { return Level > prec::Unknown && Level != prec::Conditional; } @@ -276,6 +300,16 @@ Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { return LHS; } + // If a '<' token is followed by a type that can be a template argument and + // cannot be an expression, then this is ill-formed, but might be intended + // to be a template-id. + if (OpToken.is(tok::less) && Actions.mightBeIntendedToBeTemplateName(LHS) && + (isKnownToBeDeclarationSpecifier() || + Tok.isOneOf(tok::greater, tok::greatergreater, + tok::greatergreatergreater)) && + diagnoseUnknownTemplateId(LHS, OpToken.getLocation())) + return ExprError(); + // If the next token is an ellipsis, then this is a fold-expression. Leave // it alone so we can handle it in the paren expression. if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) { @@ -2989,6 +3023,11 @@ Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() { return AvailabilitySpec(ConsumeToken()); } else { // Parse the platform name. + if (Tok.is(tok::code_completion)) { + Actions.CodeCompleteAvailabilityPlatformName(); + cutOffParsing(); + return None; + } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_avail_query_expected_platform_name); return None; @@ -3001,12 +3040,14 @@ Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() { if (Version.empty()) return None; - StringRef Platform = PlatformIdentifier->Ident->getName(); + StringRef GivenPlatform = PlatformIdentifier->Ident->getName(); + StringRef Platform = + AvailabilityAttr::canonicalizePlatformName(GivenPlatform); if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) { Diag(PlatformIdentifier->Loc, diag::err_avail_query_unrecognized_platform_name) - << Platform; + << GivenPlatform; return None; } diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp index 671a815911f3..56093f685617 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp @@ -2114,11 +2114,8 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; - if (Tok.is(tok::less) && - ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, - SS, true, LAngleLoc, - TemplateArgs, - RAngleLoc)) + if (Tok.is(tok::less) && ParseTemplateIdAfterTemplateName( + true, LAngleLoc, TemplateArgs, RAngleLoc)) return true; if (Id.getKind() == UnqualifiedId::IK_Identifier || diff --git a/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp b/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp index d2b18e7c0a81..6a81e14ed496 100644 --- a/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp +++ b/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp @@ -886,22 +886,12 @@ bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, /// list ('<' template-parameter-list [opt] '>') and placing the /// results into a form that can be transferred to semantic analysis. /// -/// \param Template the template declaration produced by isTemplateName -/// -/// \param TemplateNameLoc the source location of the template name -/// -/// \param SS if non-NULL, the nested-name-specifier preceding the -/// template name. -/// /// \param ConsumeLastToken if true, then we will consume the last /// token that forms the template-id. Otherwise, we will leave the /// last token in the stream (e.g., so that it can be replaced with an /// annotation token). bool -Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, - SourceLocation TemplateNameLoc, - const CXXScopeSpec &SS, - bool ConsumeLastToken, +Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc) { @@ -983,9 +973,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; - bool Invalid = ParseTemplateIdAfterTemplateName(Template, - TemplateNameLoc, - SS, false, LAngleLoc, + bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc, TemplateArgs, RAngleLoc); diff --git a/contrib/llvm/tools/clang/lib/Sema/Sema.cpp b/contrib/llvm/tools/clang/lib/Sema/Sema.cpp index 2f493fa5fbef..ca1d27e9505f 100644 --- a/contrib/llvm/tools/clang/lib/Sema/Sema.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/Sema.cpp @@ -477,6 +477,13 @@ static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { return true; if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { + // If this is a function template and none of its specializations is used, + // we should warn. + if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) + for (const auto *Spec : Template->specializations()) + if (ShouldRemoveFromUnused(SemaRef, Spec)) + return true; + // UnusedFileScopedDecls stores the first declaration. // The declaration may have become definition so check again. const FunctionDecl *DeclToCheck; @@ -500,6 +507,13 @@ static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { VD->isUsableInConstantExpressions(SemaRef->Context)) return true; + if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) + // If this is a variable template and none of its specializations is used, + // we should warn. + for (const auto *Spec : Template->specializations()) + if (ShouldRemoveFromUnused(SemaRef, Spec)) + return true; + // UnusedFileScopedDecls stores the first declaration. // The declaration may have become definition so check again. const VarDecl *DeclToCheck = VD->getDefinition(); @@ -905,10 +919,14 @@ void Sema::ActOnEndOfTranslationUnit() { << /*function*/0 << DiagD->getDeclName(); } } else { - Diag(DiagD->getLocation(), - isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function - : diag::warn_unused_function) - << DiagD->getDeclName(); + if (FD->getDescribedFunctionTemplate()) + Diag(DiagD->getLocation(), diag::warn_unused_template) + << /*function*/0 << DiagD->getDeclName(); + else + Diag(DiagD->getLocation(), + isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function + : diag::warn_unused_function) + << DiagD->getDeclName(); } } else { const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); @@ -924,7 +942,11 @@ void Sema::ActOnEndOfTranslationUnit() { Diag(DiagD->getLocation(), diag::warn_unused_const_variable) << DiagD->getDeclName(); } else { - Diag(DiagD->getLocation(), diag::warn_unused_variable) + if (DiagD->getDescribedVarTemplate()) + Diag(DiagD->getLocation(), diag::warn_unused_template) + << /*variable*/1 << DiagD->getDeclName(); + else + Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD->getDeclName(); } } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp index 7e91709e67da..7d534263f468 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp @@ -1871,7 +1871,8 @@ static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization // preserves Result. Result = E; - if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) + if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate( + Result, /*DoFunctionPointerConversion=*/true)) return false; return Result.isUsable(); } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp index cfac3f1dc1de..8fb2f4139236 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp @@ -3869,6 +3869,41 @@ static void AddObjCProperties( } } +static void AddRecordMembersCompletionResults(Sema &SemaRef, + ResultBuilder &Results, Scope *S, + QualType BaseType, + RecordDecl *RD) { + // Indicate that we are performing a member access, and the cv-qualifiers + // for the base object type. + Results.setObjectTypeQualifiers(BaseType.getQualifiers()); + + // Access to a C/C++ class, struct, or union. + Results.allowNestedNameSpecifiers(); + CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); + SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, + SemaRef.CodeCompleter->includeGlobals(), + /*IncludeDependentBases=*/true); + + if (SemaRef.getLangOpts().CPlusPlus) { + if (!Results.empty()) { + // The "template" keyword can follow "->" or "." in the grammar. + // However, we only want to suggest the template keyword if something + // is dependent. + bool IsDependent = BaseType->isDependentType(); + if (!IsDependent) { + for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) + if (DeclContext *Ctx = DepScope->getEntity()) { + IsDependent = Ctx->isDependentContext(); + break; + } + } + + if (IsDependent) + Results.AddResult(CodeCompletionResult("template")); + } + } +} + void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement) { @@ -3879,8 +3914,6 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, if (ConvertedBase.isInvalid()) return; Base = ConvertedBase.get(); - - typedef CodeCompletionResult Result; QualType BaseType = Base->getType(); @@ -3915,34 +3948,18 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, &ResultBuilder::IsMember); Results.EnterNewScope(); if (const RecordType *Record = BaseType->getAs<RecordType>()) { - // Indicate that we are performing a member access, and the cv-qualifiers - // for the base object type. - Results.setObjectTypeQualifiers(BaseType.getQualifiers()); - - // Access to a C/C++ class, struct, or union. - Results.allowNestedNameSpecifiers(); - CodeCompletionDeclConsumer Consumer(Results, CurContext); - LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer, - CodeCompleter->includeGlobals()); - - if (getLangOpts().CPlusPlus) { - if (!Results.empty()) { - // The "template" keyword can follow "->" or "." in the grammar. - // However, we only want to suggest the template keyword if something - // is dependent. - bool IsDependent = BaseType->isDependentType(); - if (!IsDependent) { - for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) - if (DeclContext *Ctx = DepScope->getEntity()) { - IsDependent = Ctx->isDependentContext(); - break; - } - } - - if (IsDependent) - Results.AddResult(Result("template")); - } - } + AddRecordMembersCompletionResults(*this, Results, S, BaseType, + Record->getDecl()); + } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { + TemplateName TN = TST->getTemplateName(); + if (const auto *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { + CXXRecordDecl *RD = TD->getTemplatedDecl(); + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD); + } + } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { + if (auto *RD = ICNT->getDecl()) + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD); } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { // Objective-C property reference. AddedPropertiesSet AddedProperties; @@ -7811,6 +7828,23 @@ void Sema::CodeCompleteNaturalLanguage() { nullptr, 0); } +void Sema::CodeCompleteAvailabilityPlatformName() { + ResultBuilder Results(*this, CodeCompleter->getAllocator(), + CodeCompleter->getCodeCompletionTUInfo(), + CodeCompletionContext::CCC_Other); + Results.EnterNewScope(); + static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; + for (const char *Platform : llvm::makeArrayRef(Platforms)) { + Results.AddResult(CodeCompletionResult(Platform)); + Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( + Twine(Platform) + "ApplicationExtension"))); + } + Results.ExitScope(); + HandleCodeCompleteResults(this, CodeCompleter, + CodeCompletionContext::CCC_Other, Results.data(), + Results.size()); +} + void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results) { diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp index 2612023f59db..2e069a9defaa 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp @@ -64,22 +64,45 @@ namespace { class TypeNameValidatorCCC : public CorrectionCandidateCallback { public: - TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, - bool AllowTemplates=false) - : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), - AllowTemplates(AllowTemplates) { - WantExpressionKeywords = false; - WantCXXNamedCasts = false; - WantRemainingKeywords = false; + TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, + bool AllowTemplates = false, + bool AllowNonTemplates = true) + : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), + AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { + WantExpressionKeywords = false; + WantCXXNamedCasts = false; + WantRemainingKeywords = false; } bool ValidateCandidate(const TypoCorrection &candidate) override { if (NamedDecl *ND = candidate.getCorrectionDecl()) { + if (!AllowInvalidDecl && ND->isInvalidDecl()) + return false; + + if (getAsTypeTemplateDecl(ND)) + return AllowTemplates; + bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); - bool AllowedTemplate = AllowTemplates && getAsTypeTemplateDecl(ND); - return (IsType || AllowedTemplate) && - (AllowInvalidDecl || !ND->isInvalidDecl()); + if (!IsType) + return false; + + if (AllowNonTemplates) + return true; + + // An injected-class-name of a class template (specialization) is valid + // as a template or as a non-template. + if (AllowTemplates) { + auto *RD = dyn_cast<CXXRecordDecl>(ND); + if (!RD || !RD->isInjectedClassName()) + return false; + RD = cast<CXXRecordDecl>(RD->getDeclContext()); + return RD->getDescribedClassTemplate() || + isa<ClassTemplateSpecializationDecl>(RD); + } + + return false; } + return !WantClassName && candidate.isKeyword(); } @@ -87,6 +110,7 @@ class TypeNameValidatorCCC : public CorrectionCandidateCallback { bool AllowInvalidDecl; bool WantClassName; bool AllowTemplates; + bool AllowNonTemplates; }; } // end anonymous namespace @@ -627,7 +651,7 @@ void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, - bool AllowClassTemplates) { + bool IsTemplateName) { // Don't report typename errors for editor placeholders. if (II->isEditorPlaceholder()) return; @@ -639,28 +663,41 @@ void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, llvm::make_unique<TypeNameValidatorCCC>( - false, false, AllowClassTemplates), + false, false, IsTemplateName, !IsTemplateName), CTK_ErrorRecovery)) { + // FIXME: Support error recovery for the template-name case. + bool CanRecover = !IsTemplateName; if (Corrected.isKeyword()) { // We corrected to a keyword. - diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); + diagnoseTypo(Corrected, + PDiag(IsTemplateName ? diag::err_no_template_suggest + : diag::err_unknown_typename_suggest) + << II); II = Corrected.getCorrectionAsIdentifierInfo(); } else { // We found a similarly-named type or interface; suggest that. if (!SS || !SS->isSet()) { diagnoseTypo(Corrected, - PDiag(diag::err_unknown_typename_suggest) << II); + PDiag(IsTemplateName ? diag::err_no_template_suggest + : diag::err_unknown_typename_suggest) + << II, CanRecover); } else if (DeclContext *DC = computeDeclContext(*SS, false)) { std::string CorrectedStr(Corrected.getAsString(getLangOpts())); bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && II->getName().equals(CorrectedStr); diagnoseTypo(Corrected, - PDiag(diag::err_unknown_nested_typename_suggest) - << II << DC << DroppedSpecifier << SS->getRange()); + PDiag(IsTemplateName + ? diag::err_no_member_template_suggest + : diag::err_unknown_nested_typename_suggest) + << II << DC << DroppedSpecifier << SS->getRange(), + CanRecover); } else { llvm_unreachable("could not have corrected a typo here"); } + if (!CanRecover) + return; + CXXScopeSpec tmpSS; if (Corrected.getCorrectionSpecifier()) tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), @@ -675,7 +712,7 @@ void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, return; } - if (getLangOpts().CPlusPlus) { + if (getLangOpts().CPlusPlus && !IsTemplateName) { // See if II is a class template that the user forgot to pass arguments to. UnqualifiedId Name; Name.setIdentifier(II, IILoc); @@ -700,10 +737,13 @@ void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, // (struct, union, enum) from Parser::ParseImplicitInt here, instead? if (!SS || (!SS->isSet() && !SS->isInvalid())) - Diag(IILoc, diag::err_unknown_typename) << II; + Diag(IILoc, IsTemplateName ? diag::err_no_template + : diag::err_unknown_typename) + << II; else if (DeclContext *DC = computeDeclContext(*SS, false)) - Diag(IILoc, diag::err_typename_nested_not_found) - << II << DC << SS->getRange(); + Diag(IILoc, IsTemplateName ? diag::err_no_member_template + : diag::err_typename_nested_not_found) + << II << DC << SS->getRange(); else if (isDependentScopeSpecifier(*SS)) { unsigned DiagID = diag::err_typename_missing; if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) @@ -1488,6 +1528,11 @@ bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return false; + // A non-out-of-line declaration of a member specialization was implicitly + // instantiated; it's the out-of-line declaration that we're interested in. + if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && + FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) + return false; if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) @@ -1514,6 +1559,10 @@ bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { if (VD->isStaticDataMember() && VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return false; + if (VD->isStaticDataMember() && + VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && + VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) + return false; if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) return false; @@ -1972,7 +2021,7 @@ bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) << Kind << NewType; if (Old->getLocation().isValid()) - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); New->setInvalidDecl(); return true; } @@ -1985,7 +2034,7 @@ bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { Diag(New->getLocation(), diag::err_redefinition_different_typedef) << Kind << NewType << OldType; if (Old->getLocation().isValid()) - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); New->setInvalidDecl(); return true; } @@ -2052,7 +2101,7 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, NamedDecl *OldD = OldDecls.getRepresentativeDecl(); if (OldD->getLocation().isValid()) - Diag(OldD->getLocation(), diag::note_previous_definition); + notePreviousDefinition(OldD->getLocation(), New->getLocation()); return New->setInvalidDecl(); } @@ -2078,7 +2127,7 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); // Make the old tag definition visible. - makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); + makeMergedDefinitionVisible(Hidden); // If this was an unscoped enumeration, yank all of its enumerators // out of the scope. @@ -2144,7 +2193,7 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); return New->setInvalidDecl(); } @@ -2165,7 +2214,7 @@ void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, Diag(New->getLocation(), diag::ext_redefinition_of_typedef) << New->getDeclName(); - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); } /// DeclhasAttr - returns true if decl Declaration already has the target @@ -2452,7 +2501,10 @@ static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { ? diag::err_alias_after_tentative : diag::err_redefinition; S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); - S.Diag(Def->getLocation(), diag::note_previous_definition); + if (Diag == diag::err_redefinition) + S.notePreviousDefinition(Def->getLocation(), VD->getLocation()); + else + S.Diag(Def->getLocation(), diag::note_previous_definition); VD->setInvalidDecl(); } ++I; @@ -2839,7 +2891,7 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, } else { Diag(New->getLocation(), diag::err_redefinition_different_kind) << New->getDeclName(); - Diag(OldD->getLocation(), diag::note_previous_definition); + notePreviousDefinition(OldD->getLocation(), New->getLocation()); return true; } } @@ -2876,7 +2928,7 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, !Old->hasAttr<InternalLinkageAttr>()) { Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) << New->getDeclName(); - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); New->dropAttr<InternalLinkageAttr>(); } @@ -3604,9 +3656,9 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { } if (!Old) { Diag(New->getLocation(), diag::err_redefinition_different_kind) - << New->getDeclName(); - Diag(Previous.getRepresentativeDecl()->getLocation(), - diag::note_previous_definition); + << New->getDeclName(); + notePreviousDefinition(Previous.getRepresentativeDecl()->getLocation(), + New->getLocation()); return New->setInvalidDecl(); } @@ -3635,7 +3687,7 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { Old->getStorageClass() == SC_None && !Old->hasAttr<WeakImportAttr>()) { Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); // Remove weak_import attribute on new declaration. New->dropAttr<WeakImportAttr>(); } @@ -3644,7 +3696,7 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { !Old->hasAttr<InternalLinkageAttr>()) { Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) << New->getDeclName(); - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); New->dropAttr<InternalLinkageAttr>(); } @@ -3801,6 +3853,67 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { New->setImplicitlyInline(); } +void Sema::notePreviousDefinition(SourceLocation Old, SourceLocation New) { + SourceManager &SrcMgr = getSourceManager(); + auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); + auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old); + auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); + auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); + auto &HSI = PP.getHeaderSearchInfo(); + StringRef HdrFilename = SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old)); + + auto noteFromModuleOrInclude = [&](SourceLocation &Loc, + SourceLocation &IncLoc) -> bool { + Module *Mod = nullptr; + // Redefinition errors with modules are common with non modular mapped + // headers, example: a non-modular header H in module A that also gets + // included directly in a TU. Pointing twice to the same header/definition + // is confusing, try to get better diagnostics when modules is on. + if (getLangOpts().Modules) { + auto ModLoc = SrcMgr.getModuleImportLoc(Old); + if (!ModLoc.first.isInvalid()) + Mod = HSI.getModuleMap().inferModuleFromLocation( + FullSourceLoc(Loc, SrcMgr)); + } + + if (IncLoc.isValid()) { + if (Mod) { + Diag(IncLoc, diag::note_redefinition_modules_same_file) + << HdrFilename.str() << Mod->getFullModuleName(); + if (!Mod->DefinitionLoc.isInvalid()) + Diag(Mod->DefinitionLoc, diag::note_defined_here) + << Mod->getFullModuleName(); + } else { + Diag(IncLoc, diag::note_redefinition_include_same_file) + << HdrFilename.str(); + } + return true; + } + + return false; + }; + + // Is it the same file and same offset? Provide more information on why + // this leads to a redefinition error. + bool EmittedDiag = false; + if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { + SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); + SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); + EmittedDiag = noteFromModuleOrInclude(Old, OldIncLoc); + EmittedDiag |= noteFromModuleOrInclude(New, NewIncLoc); + + // If the header has no guards, emit a note suggesting one. + if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) + Diag(Old, diag::note_use_ifdef_guards); + + if (EmittedDiag) + return; + } + + // Redefinition coming from different files or couldn't do better above. + Diag(Old, diag::note_previous_definition); +} + /// We've just determined that \p Old and \p New both appear to be definitions /// of the same variable. Either diagnose or fix the problem. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { @@ -3816,12 +3929,12 @@ bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { // Make the canonical definition visible. if (auto *OldTD = Old->getDescribedVarTemplate()) - makeMergedDefinitionVisible(OldTD, New->getLocation()); - makeMergedDefinitionVisible(Old, New->getLocation()); + makeMergedDefinitionVisible(OldTD); + makeMergedDefinitionVisible(Old); return false; } else { Diag(New->getLocation(), diag::err_redefinition) << New; - Diag(Old->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Old->getLocation(), New->getLocation()); New->setInvalidDecl(); return true; } @@ -6706,6 +6819,9 @@ NamedDecl *Sema::ActOnVariableDeclarator( return NewTemplate; } + if (IsMemberSpecialization && !NewVD->isInvalidDecl()) + CompleteMemberSpecialization(NewVD, Previous); + return NewVD; } @@ -8919,12 +9035,17 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, } } + MarkUnusedFileScopedDecl(NewFD); + if (getLangOpts().CPlusPlus) { if (FunctionTemplate) { if (NewFD->isInvalidDecl()) FunctionTemplate->setInvalidDecl(); return FunctionTemplate; } + + if (isMemberSpecialization && !NewFD->isInvalidDecl()) + CompleteMemberSpecialization(NewFD, Previous); } if (NewFD->hasAttr<OpenCLKernelAttr>()) { @@ -8964,8 +9085,6 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, } } - MarkUnusedFileScopedDecl(NewFD); - // Here we have an function template explicit specialization at class scope. // The actually specialization will be postponed to template instatiation // time via the ClassScopeFunctionSpecializationDecl node. @@ -9182,7 +9301,9 @@ bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { FunctionDecl *const OldTemplatedDecl = OldTemplateDecl->getTemplatedDecl(); + // FIXME: This assert will not hold in the presence of modules. assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); + // FIXME: We need an update record for this AST mutation. OldTemplatedDecl->setDeletedAsWritten(false); } } @@ -10273,23 +10394,36 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { VDecl->setInit(Init); if (VDecl->isLocalVarDecl()) { + // Don't check the initializer if the declaration is malformed. + if (VDecl->isInvalidDecl()) { + // do nothing + + // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. + // This is true even in OpenCL C++. + } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { + CheckForConstantInitializer(Init, DclT); + + // Otherwise, C++ does not restrict the initializer. + } else if (getLangOpts().CPlusPlus) { + // do nothing + // C99 6.7.8p4: All the expressions in an initializer for an object that has // static storage duration shall be constant expressions or string literals. - // C++ does not have this restriction. - if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { + } else if (VDecl->getStorageClass() == SC_Static) { + CheckForConstantInitializer(Init, DclT); + + // C89 is stricter than C99 for aggregate initializers. + // C89 6.5.7p3: All the expressions [...] in an initializer list + // for an object that has aggregate or union type shall be + // constant expressions. + } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && + isa<InitListExpr>(Init)) { const Expr *Culprit; - if (VDecl->getStorageClass() == SC_Static) - CheckForConstantInitializer(Init, DclT); - // C89 is stricter than C99 for non-static aggregate types. - // C89 6.5.7p3: All the expressions [...] in an initializer list - // for an object that has aggregate or union type shall be - // constant expressions. - else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && - isa<InitListExpr>(Init) && - !Init->isConstantInitializer(Context, false, &Culprit)) + if (!Init->isConstantInitializer(Context, false, &Culprit)) { Diag(Culprit->getExprLoc(), diag::ext_aggregate_init_not_constant) << Culprit->getSourceRange(); + } } } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && VDecl->getLexicalDeclContext()->isRecord()) { @@ -11023,8 +11157,7 @@ static bool hasDependentAlignment(VarDecl *VD) { /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform /// any semantic actions necessary after any initializer has been attached. -void -Sema::FinalizeDeclaration(Decl *ThisDecl) { +void Sema::FinalizeDeclaration(Decl *ThisDecl) { // Note that we are no longer parsing the initializer for this declaration. ParsingInitForAutoVars.erase(ThisDecl); @@ -11189,9 +11322,8 @@ Sema::FinalizeDeclaration(Decl *ThisDecl) { if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) AddPushedVisibilityAttribute(VD); - // FIXME: Warn on unused templates. - if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && - !isa<VarTemplatePartialSpecializationDecl>(VD)) + // FIXME: Warn on unused var template partial specializations. + if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) MarkUnusedFileScopedDecl(VD); // Now we have parsed the initializer and can update the table of magic @@ -11765,9 +11897,8 @@ Sema::CheckForFunctionRedefinition(FunctionDecl *FD, Definition->getNumTemplateParameterLists())) { SkipBody->ShouldSkip = true; if (auto *TD = Definition->getDescribedFunctionTemplate()) - makeMergedDefinitionVisible(TD, FD->getLocation()); - makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), - FD->getLocation()); + makeMergedDefinitionVisible(TD); + makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); return; } @@ -13421,7 +13552,7 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, // we already have. Make the existing definition visible and // use it in place of this one. SkipBody->ShouldSkip = true; - makeMergedDefinitionVisible(Hidden, KWLoc); + makeMergedDefinitionVisible(Hidden); return Def; } else if (!IsExplicitSpecializationAfterInstantiation) { // A redeclaration in function prototype scope in C isn't @@ -13430,7 +13561,8 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; else Diag(NameLoc, diag::err_redefinition) << Name; - Diag(Def->getLocation(), diag::note_previous_definition); + notePreviousDefinition(Def->getLocation(), + NameLoc.isValid() ? NameLoc : KWLoc); // If this is a redefinition, recover by making this // struct be anonymous, which will make any later // references get the previous definition. @@ -13520,7 +13652,7 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, // The tag name clashes with something else in the target scope, // issue an error and recover by making this tag be anonymous. Diag(NameLoc, diag::err_redefinition_different_kind) << Name; - Diag(PrevDecl->getLocation(), diag::note_previous_definition); + notePreviousDefinition(PrevDecl->getLocation(), NameLoc); Name = nullptr; Invalid = true; } @@ -13753,6 +13885,9 @@ CreateNewDecl: // record. AddPushedVisibilityAttribute(New); + if (isMemberSpecialization && !New->isInvalidDecl()) + CompleteMemberSpecialization(New, Previous); + OwnedDecl = true; // In C++, don't return an invalid declaration. We can't recover well from // the cases where we make the type anonymous. @@ -15221,7 +15356,7 @@ Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; else Diag(IdLoc, diag::err_redefinition) << Id; - Diag(PrevDecl->getLocation(), diag::note_previous_definition); + notePreviousDefinition(PrevDecl->getLocation(), IdLoc); return nullptr; } } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp index 97d273f6ddb6..3de792e4e406 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp @@ -7230,6 +7230,13 @@ public: SemaRef.Context.getTargetInfo().getPlatformMinVersion()); } + bool TraverseDecl(Decl *D) { + // Avoid visiting nested functions to prevent duplicate warnings. + if (!D || isa<FunctionDecl>(D)) + return true; + return Base::TraverseDecl(D); + } + bool TraverseStmt(Stmt *S) { if (!S) return true; @@ -7243,6 +7250,8 @@ public: bool TraverseIfStmt(IfStmt *If); + bool TraverseLambdaExpr(LambdaExpr *E) { return true; } + bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) { if (ObjCMethodDecl *D = Msg->getMethodDecl()) DiagnoseDeclAvailability( @@ -7346,7 +7355,9 @@ void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability( llvm::raw_string_ostream FixItOS(FixItString); FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available" : "__builtin_available") - << "(" << SemaRef.getASTContext().getTargetInfo().getPlatformName() + << "(" + << AvailabilityAttr::getPlatformNameSourceSpelling( + SemaRef.getASTContext().getTargetInfo().getPlatformName()) << " " << Introduced.getAsString() << ", *)) {\n" << Indentation << ExtraIndentation; FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str()); diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp index 849e978e2d86..14efc9672061 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp @@ -5277,6 +5277,9 @@ ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, // We aren't supposed to apply this logic if there's an '&' involved. if (!find.HasFormOfMemberPointer) { + if (Expr::hasAnyTypeDependentArguments(ArgExprs)) + return new (Context) CallExpr( + Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); OverloadExpr *ovl = find.Expression; if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) return BuildOverloadedCallExpr( @@ -8028,6 +8031,33 @@ QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, return QualType(); } +// Diagnose cases where a scalar was implicitly converted to a vector and +// diagnose the underlying types. Otherwise, diagnose the error +// as invalid vector logical operands for non-C++ cases. +QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, + ExprResult &RHS) { + QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); + QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); + + bool LHSNatVec = LHSType->isVectorType(); + bool RHSNatVec = RHSType->isVectorType(); + + if (!(LHSNatVec && RHSNatVec)) { + Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); + Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); + Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) + << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() + << Vector->getSourceRange(); + return QualType(); + } + + Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) + << 1 << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); + + return QualType(); +} + /// Try to convert a value of non-vector type to a vector type by converting /// the type to the element type of the vector and then performing a splat. /// If the language is OpenCL, we only use conversions that promote scalar @@ -8075,6 +8105,162 @@ static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, return false; } +/// Test if a (constant) integer Int can be casted to another integer type +/// IntTy without losing precision. +static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, + QualType OtherIntTy) { + QualType IntTy = Int->get()->getType().getUnqualifiedType(); + + // Reject cases where the value of the Int is unknown as that would + // possibly cause truncation, but accept cases where the scalar can be + // demoted without loss of precision. + llvm::APSInt Result; + bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); + int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); + bool IntSigned = IntTy->hasSignedIntegerRepresentation(); + bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); + + if (CstInt) { + // If the scalar is constant and is of a higher order and has more active + // bits that the vector element type, reject it. + unsigned NumBits = IntSigned + ? (Result.isNegative() ? Result.getMinSignedBits() + : Result.getActiveBits()) + : Result.getActiveBits(); + if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) + return true; + + // If the signedness of the scalar type and the vector element type + // differs and the number of bits is greater than that of the vector + // element reject it. + return (IntSigned != OtherIntSigned && + NumBits > S.Context.getIntWidth(OtherIntTy)); + } + + // Reject cases where the value of the scalar is not constant and it's + // order is greater than that of the vector element type. + return (Order < 0); +} + +/// Test if a (constant) integer Int can be casted to floating point type +/// FloatTy without losing precision. +static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, + QualType FloatTy) { + QualType IntTy = Int->get()->getType().getUnqualifiedType(); + + // Determine if the integer constant can be expressed as a floating point + // number of the appropiate type. + llvm::APSInt Result; + bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); + uint64_t Bits = 0; + if (CstInt) { + // Reject constants that would be truncated if they were converted to + // the floating point type. Test by simple to/from conversion. + // FIXME: Ideally the conversion to an APFloat and from an APFloat + // could be avoided if there was a convertFromAPInt method + // which could signal back if implicit truncation occurred. + llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); + Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), + llvm::APFloat::rmTowardZero); + llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), + !IntTy->hasSignedIntegerRepresentation()); + bool Ignored = false; + Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, + &Ignored); + if (Result != ConvertBack) + return true; + } else { + // Reject types that cannot be fully encoded into the mantissa of + // the float. + Bits = S.Context.getTypeSize(IntTy); + unsigned FloatPrec = llvm::APFloat::semanticsPrecision( + S.Context.getFloatTypeSemantics(FloatTy)); + if (Bits > FloatPrec) + return true; + } + + return false; +} + +/// Attempt to convert and splat Scalar into a vector whose types matches +/// Vector following GCC conversion rules. The rule is that implicit +/// conversion can occur when Scalar can be casted to match Vector's element +/// type without causing truncation of Scalar. +static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, + ExprResult *Vector) { + QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); + QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); + const VectorType *VT = VectorTy->getAs<VectorType>(); + + assert(!isa<ExtVectorType>(VT) && + "ExtVectorTypes should not be handled here!"); + + QualType VectorEltTy = VT->getElementType(); + + // Reject cases where the vector element type or the scalar element type are + // not integral or floating point types. + if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) + return true; + + // The conversion to apply to the scalar before splatting it, + // if necessary. + CastKind ScalarCast = CK_NoOp; + + // Accept cases where the vector elements are integers and the scalar is + // an integer. + // FIXME: Notionally if the scalar was a floating point value with a precise + // integral representation, we could cast it to an appropriate integer + // type and then perform the rest of the checks here. GCC will perform + // this conversion in some cases as determined by the input language. + // We should accept it on a language independent basis. + if (VectorEltTy->isIntegralType(S.Context) && + ScalarTy->isIntegralType(S.Context) && + S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { + + if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) + return true; + + ScalarCast = CK_IntegralCast; + } else if (VectorEltTy->isRealFloatingType()) { + if (ScalarTy->isRealFloatingType()) { + + // Reject cases where the scalar type is not a constant and has a higher + // Order than the vector element type. + llvm::APFloat Result(0.0); + bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); + int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); + if (!CstScalar && Order < 0) + return true; + + // If the scalar cannot be safely casted to the vector element type, + // reject it. + if (CstScalar) { + bool Truncated = false; + Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), + llvm::APFloat::rmNearestTiesToEven, &Truncated); + if (Truncated) + return true; + } + + ScalarCast = CK_FloatingCast; + } else if (ScalarTy->isIntegralType(S.Context)) { + if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) + return true; + + ScalarCast = CK_IntegralToFloating; + } else + return true; + } + + // Adjust scalar if desired. + if (Scalar) { + if (ScalarCast != CK_NoOp) + *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); + *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); + } + return false; +} + QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, @@ -8143,19 +8329,29 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, } } - // If there's an ext-vector type and a scalar, try to convert the scalar to + // If there's a vector type and a scalar, try to convert the scalar to // the vector element type and splat. - // FIXME: this should also work for regular vector types as supported in GCC. - if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { - if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, - LHSVecType->getElementType(), LHSType)) - return LHSType; + if (!RHSVecType) { + if (isa<ExtVectorType>(LHSVecType)) { + if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, + LHSVecType->getElementType(), LHSType)) + return LHSType; + } else { + if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) + return LHSType; + } } - if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { - if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), - LHSType, RHSVecType->getElementType(), - RHSType)) - return RHSType; + if (!LHSVecType) { + if (isa<ExtVectorType>(RHSVecType)) { + if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), + LHSType, RHSVecType->getElementType(), + RHSType)) + return RHSType; + } else { + if (LHS.get()->getValueKind() == VK_LValue || + !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) + return RHSType; + } } // FIXME: The code below also handles conversion between vectors and @@ -8208,6 +8404,22 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, return QualType(); } + + // If there is a vector type that is not a ExtVector and a scalar, we reach + // this point if scalar could not be converted to the vector's element type + // without truncation. + if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || + (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { + QualType Scalar = LHSVecType ? RHSType : LHSType; + QualType Vector = LHSVecType ? LHSType : RHSType; + unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; + Diag(Loc, + diag::err_typecheck_vector_not_convertable_implict_truncation) + << ScalarOrVector << Scalar << Vector; + + return QualType(); + } + // Otherwise, use the generic diagnostic. Diag(Loc, diag::err_typecheck_vector_not_convertable) << LHSType << RHSType @@ -9827,6 +10039,12 @@ QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && vType->hasFloatingRepresentation()) return InvalidOperands(Loc, LHS, RHS); + // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the + // usage of the logical operators && and || with vectors in C. This + // check could be notionally dropped. + if (!getLangOpts().CPlusPlus && + !(isa<ExtVectorType>(vType->getAs<VectorType>()))) + return InvalidLogicalVectorOperands(Loc, LHS, RHS); return GetSignedVectorType(LHS.get()->getType()); } @@ -11770,6 +11988,8 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, resultType = GetSignedVectorType(resultType); break; } else { + // FIXME: GCC's vector extension permits the usage of '!' with a vector + // type in C++. We should allow that here too. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input.get()->getSourceRange()); } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp index 9b88cddbc969..8500b748a3ec 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp @@ -4720,10 +4720,24 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, // regard to cv-qualifiers. const RecordType *lhsRecord = LhsT->getAs<RecordType>(); - if (!lhsRecord) return false; - const RecordType *rhsRecord = RhsT->getAs<RecordType>(); - if (!rhsRecord) return false; + if (!rhsRecord || !lhsRecord) { + const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); + const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); + if (!LHSObjTy || !RHSObjTy) + return false; + + ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); + ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); + if (!BaseInterface || !DerivedInterface) + return false; + + if (Self.RequireCompleteType( + KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) + return false; + + return BaseInterface->isSuperClassOf(DerivedInterface); + } assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)); @@ -5342,6 +5356,15 @@ QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, // C++11 [expr.cond]p1 // The first expression is contextually converted to bool. + // + // FIXME; GCC's vector extension permits the use of a?b:c where the type of + // a is that of a integer vector with the same number of elements and + // size as the vectors of b and c. If one of either b or c is a scalar + // it is implicitly converted to match the type of the vector. + // Otherwise the expression is ill-formed. If both b and c are scalars, + // then b and c are checked and converted to the type of a if possible. + // Unlike the OpenCL ?: operator, the expression is evaluated as + // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). if (!Cond.get()->isTypeDependent()) { ExprResult CondRes = CheckCXXBooleanCondition(Cond.get()); if (CondRes.isInvalid()) diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp index a44e9243e3c5..28581bad1a7a 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp @@ -4241,8 +4241,7 @@ void Sema::diagnoseARCUnbridgedCast(Expr *e) { castType = cast->getTypeAsWritten(); CCK = CCK_OtherCast; } else { - castType = cast->getType(); - CCK = CCK_ImplicitConversion; + llvm_unreachable("Unexpected ImplicitCastExpr"); } ARCConversionTypeClass castACTC = diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp index d0f530010a0d..32024cb335dc 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp @@ -1209,7 +1209,7 @@ void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, } else { assert((ElemType->isRecordType() || ElemType->isVectorType() || - ElemType->isClkEventT()) && "Unexpected type"); + ElemType->isOpenCLSpecificType()) && "Unexpected type"); // C99 6.7.8p13: // @@ -8296,8 +8296,46 @@ Sema::PerformCopyInitialization(const InitializedEntity &Entity, AllowExplicit); InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); + // Prevent infinite recursion when performing parameter copy-initialization. + const bool ShouldTrackCopy = + Entity.isParameterKind() && Seq.isConstructorInitialization(); + if (ShouldTrackCopy) { + if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != + CurrentParameterCopyTypes.end()) { + Seq.SetOverloadFailure( + InitializationSequence::FK_ConstructorOverloadFailed, + OR_No_Viable_Function); + + // Try to give a meaningful diagnostic note for the problematic + // constructor. + const auto LastStep = Seq.step_end() - 1; + assert(LastStep->Kind == + InitializationSequence::SK_ConstructorInitialization); + const FunctionDecl *Function = LastStep->Function.Function; + auto Candidate = + llvm::find_if(Seq.getFailedCandidateSet(), + [Function](const OverloadCandidate &Candidate) -> bool { + return Candidate.Viable && + Candidate.Function == Function && + Candidate.Conversions.size() > 0; + }); + if (Candidate != Seq.getFailedCandidateSet().end() && + Function->getNumParams() > 0) { + Candidate->Viable = false; + Candidate->FailureKind = ovl_fail_bad_conversion; + Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, + InitE, + Function->getParamDecl(0)->getType()); + } + } + CurrentParameterCopyTypes.push_back(Entity.getType()); + } + ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); + if (ShouldTrackCopy) + CurrentParameterCopyTypes.pop_back(); + return Result; } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp index ce76e14982db..c5b579a4b2e9 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp @@ -1382,8 +1382,8 @@ Module *Sema::getOwningModule(Decl *Entity) { return M; } -void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) { - if (auto *M = PP.getModuleContainingLocation(Loc)) +void Sema::makeMergedDefinitionVisible(NamedDecl *ND) { + if (auto *M = getCurrentModule()) Context.mergeDefinitionIntoModule(ND, M); else // We're not building a module; just make the definition visible. @@ -1393,7 +1393,7 @@ void Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) { // visible too. They're not (necessarily) within a mergeable DeclContext. if (auto *TD = dyn_cast<TemplateDecl>(ND)) for (auto *Param : *TD->getTemplateParameters()) - makeMergedDefinitionVisible(Param, Loc); + makeMergedDefinitionVisible(Param); } /// \brief Find the module in which the given declaration was defined. @@ -3445,7 +3445,8 @@ static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, bool QualifiedNameLookup, bool InBaseClass, VisibleDeclConsumer &Consumer, - VisibleDeclsRecord &Visited) { + VisibleDeclsRecord &Visited, + bool IncludeDependentBases = false) { if (!Ctx) return; @@ -3501,7 +3502,8 @@ static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, ShadowContextRAII Shadow(Visited); for (auto I : Ctx->using_directives()) { LookupVisibleDecls(I->getNominatedNamespace(), Result, - QualifiedNameLookup, InBaseClass, Consumer, Visited); + QualifiedNameLookup, InBaseClass, Consumer, Visited, + IncludeDependentBases); } } @@ -3513,14 +3515,28 @@ static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, for (const auto &B : Record->bases()) { QualType BaseType = B.getType(); - // Don't look into dependent bases, because name lookup can't look - // there anyway. - if (BaseType->isDependentType()) - continue; - - const RecordType *Record = BaseType->getAs<RecordType>(); - if (!Record) - continue; + RecordDecl *RD; + if (BaseType->isDependentType()) { + if (!IncludeDependentBases) { + // Don't look into dependent bases, because name lookup can't look + // there anyway. + continue; + } + const auto *TST = BaseType->getAs<TemplateSpecializationType>(); + if (!TST) + continue; + TemplateName TN = TST->getTemplateName(); + const auto *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); + if (!TD) + continue; + RD = TD->getTemplatedDecl(); + } else { + const auto *Record = BaseType->getAs<RecordType>(); + if (!Record) + continue; + RD = Record->getDecl(); + } // FIXME: It would be nice to be able to determine whether referencing // a particular member would be ambiguous. For example, given @@ -3543,8 +3559,8 @@ static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, // Find results in this base class (and its bases). ShadowContextRAII Shadow(Visited); - LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, - true, Consumer, Visited); + LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer, + Visited, IncludeDependentBases); } } @@ -3713,7 +3729,8 @@ void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, - bool IncludeGlobalScope) { + bool IncludeGlobalScope, + bool IncludeDependentBases) { LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); Result.setAllowHidden(Consumer.includeHiddenDecls()); VisibleDeclsRecord Visited; @@ -3721,7 +3738,8 @@ void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, Visited.visitedContext(Context.getTranslationUnitDecl()); ShadowContextRAII Shadow(Visited); ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, - /*InBaseClass=*/false, Consumer, Visited); + /*InBaseClass=*/false, Consumer, Visited, + IncludeDependentBases); } /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp index 782c377e3202..51794160278c 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp @@ -11210,12 +11210,12 @@ Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, /// \brief Given an overloaded function, tries to turn it into a non-overloaded /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This /// will perform access checks, diagnose the use of the resultant decl, and, if -/// necessary, perform a function-to-pointer decay. +/// requested, potentially perform a function-to-pointer decay. /// /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. /// Otherwise, returns true. This may emit diagnostics and return true. bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( - ExprResult &SrcExpr) { + ExprResult &SrcExpr, bool DoFunctionPointerConverion) { Expr *E = SrcExpr.get(); assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); @@ -11230,7 +11230,7 @@ bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( DiagnoseUseOfDecl(Found, E->getExprLoc()); CheckAddressOfMemberAccess(E, DAP); Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); - if (Fixed->getType()->isFunctionType()) + if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); else SrcExpr = Fixed; diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp index 5d7eada28717..33a8f9c4afa3 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp @@ -2268,9 +2268,57 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, BoundExpr = IntegerLiteral::Create( Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc); else if (const VariableArrayType *VAT = - dyn_cast<VariableArrayType>(UnqAT)) - BoundExpr = VAT->getSizeExpr(); - else { + dyn_cast<VariableArrayType>(UnqAT)) { + // For a variably modified type we can't just use the expression within + // the array bounds, since we don't want that to be re-evaluated here. + // Rather, we need to determine what it was when the array was first + // created - so we resort to using sizeof(vla)/sizeof(element). + // For e.g. + // void f(int b) { + // int vla[b]; + // b = -1; <-- This should not affect the num of iterations below + // for (int &c : vla) { .. } + // } + + // FIXME: This results in codegen generating IR that recalculates the + // run-time number of elements (as opposed to just using the IR Value + // that corresponds to the run-time value of each bound that was + // generated when the array was created.) If this proves too embarassing + // even for unoptimized IR, consider passing a magic-value/cookie to + // codegen that then knows to simply use that initial llvm::Value (that + // corresponds to the bound at time of array creation) within + // getelementptr. But be prepared to pay the price of increasing a + // customized form of coupling between the two components - which could + // be hard to maintain as the codebase evolves. + + ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr( + EndVar->getLocation(), UETT_SizeOf, + /*isType=*/true, + CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( + VAT->desugar(), RangeLoc)) + .getAsOpaquePtr(), + EndVar->getSourceRange()); + if (SizeOfVLAExprR.isInvalid()) + return StmtError(); + + ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( + EndVar->getLocation(), UETT_SizeOf, + /*isType=*/true, + CreateParsedType(VAT->desugar(), + Context.getTrivialTypeSourceInfo( + VAT->getElementType(), RangeLoc)) + .getAsOpaquePtr(), + EndVar->getSourceRange()); + if (SizeOfEachElementExprR.isInvalid()) + return StmtError(); + + BoundExpr = + ActOnBinOp(S, EndVar->getLocation(), tok::slash, + SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); + if (BoundExpr.isInvalid()) + return StmtError(); + + } else { // Can't be a DependentSizedArrayType or an IncompleteArrayType since // UnqAT is not incomplete and Range is not type-dependent. llvm_unreachable("Unexpected array type in for-range"); diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp index 61b4df40964c..a479d1027533 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp @@ -455,6 +455,85 @@ void Sema::LookupTemplateName(LookupResult &Found, } } +void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, + SourceLocation Less, + SourceLocation Greater) { + if (TemplateName.isInvalid()) + return; + + DeclarationNameInfo NameInfo; + CXXScopeSpec SS; + LookupNameKind LookupKind; + + DeclContext *LookupCtx = nullptr; + NamedDecl *Found = nullptr; + + // Figure out what name we looked up. + if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { + NameInfo = ME->getMemberNameInfo(); + SS.Adopt(ME->getQualifierLoc()); + LookupKind = LookupMemberName; + LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); + Found = ME->getMemberDecl(); + } else { + auto *DRE = cast<DeclRefExpr>(TemplateName.get()); + NameInfo = DRE->getNameInfo(); + SS.Adopt(DRE->getQualifierLoc()); + LookupKind = LookupOrdinaryName; + Found = DRE->getFoundDecl(); + } + + // Try to correct the name by looking for templates and C++ named casts. + struct TemplateCandidateFilter : CorrectionCandidateCallback { + TemplateCandidateFilter() { + WantTypeSpecifiers = false; + WantExpressionKeywords = false; + WantRemainingKeywords = false; + WantCXXNamedCasts = true; + }; + bool ValidateCandidate(const TypoCorrection &Candidate) override { + if (auto *ND = Candidate.getCorrectionDecl()) + return isAcceptableTemplateName(ND->getASTContext(), ND, true); + return Candidate.isKeyword(); + } + }; + + DeclarationName Name = NameInfo.getName(); + if (TypoCorrection Corrected = + CorrectTypo(NameInfo, LookupKind, S, &SS, + llvm::make_unique<TemplateCandidateFilter>(), + CTK_ErrorRecovery, LookupCtx)) { + auto *ND = Corrected.getFoundDecl(); + if (ND) + ND = isAcceptableTemplateName(Context, ND, + /*AllowFunctionTemplates*/ true); + if (ND || Corrected.isKeyword()) { + if (LookupCtx) { + std::string CorrectedStr(Corrected.getAsString(getLangOpts())); + bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && + Name.getAsString() == CorrectedStr; + diagnoseTypo(Corrected, + PDiag(diag::err_non_template_in_member_template_id_suggest) + << Name << LookupCtx << DroppedSpecifier + << SS.getRange(), false); + } else { + diagnoseTypo(Corrected, + PDiag(diag::err_non_template_in_template_id_suggest) + << Name, false); + } + if (Found) + Diag(Found->getLocation(), + diag::note_non_template_in_template_id_found); + return; + } + } + + Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) + << Name << SourceRange(Less, Greater); + if (Found) + Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); +} + /// ActOnDependentIdExpression - Handle a dependent id-expression that /// was just parsed. This is only possible with an explicit scope /// specifier naming a dependent type. @@ -1251,8 +1330,8 @@ Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); assert(Tmpl && "original definition of a class template is not a " "class template?"); - makeMergedDefinitionVisible(Hidden, KWLoc); - makeMergedDefinitionVisible(Tmpl, KWLoc); + makeMergedDefinitionVisible(Hidden); + makeMergedDefinitionVisible(Tmpl); return Def; } @@ -7352,7 +7431,7 @@ Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, NamedDecl *Hidden = nullptr; if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { SkipBody->ShouldSkip = true; - makeMergedDefinitionVisible(Hidden, KWLoc); + makeMergedDefinitionVisible(Hidden); // From here on out, treat this as just a redeclaration. TUK = TUK_Declaration; } else if (Def) { @@ -7825,6 +7904,9 @@ bool Sema::CheckFunctionTemplateSpecialization( // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr // function can differ from the template declaration with respect to // the constexpr specifier. + // FIXME: We need an update record for this AST mutation. + // FIXME: What if there are multiple such prior declarations (for instance, + // from different modules)? Specialization->setConstexpr(FD->isConstexpr()); } @@ -7872,9 +7954,11 @@ bool Sema::CheckFunctionTemplateSpecialization( // flag to not-deleted, so that we can inherit that information from 'FD'. if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && !Specialization->getCanonicalDecl()->isReferenced()) { + // FIXME: This assert will not hold in the presence of modules. assert( Specialization->getCanonicalDecl() == Specialization && "This must be the only existing declaration of this specialization"); + // FIXME: We need an update record for this AST mutation. Specialization->setDeletedAsWritten(false); } SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); @@ -7987,8 +8071,11 @@ Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { return false; } - // If this is a friend, just bail out here before we start turning - // things into explicit specializations. + // A member specialization in a friend declaration isn't really declaring + // an explicit specialization, just identifying a specific (possibly implicit) + // specialization. Don't change the template specialization kind. + // + // FIXME: Is this really valid? Other compilers reject. if (Member->getFriendObjectKind() != Decl::FOK_None) { // Preserve instantiation information. if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { @@ -8038,66 +8125,36 @@ Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { false)) return true; - // Note that this is an explicit instantiation of a member. - // the original declaration to note that it is an explicit specialization - // (if it was previously an implicit instantiation). This latter step - // makes bookkeeping easier. - if (isa<FunctionDecl>(Member)) { + // Note that this member specialization is an "instantiation of" the + // corresponding member of the original template. + if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) { FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); if (InstantiationFunction->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) { - InstantiationFunction->setTemplateSpecializationKind( - TSK_ExplicitSpecialization); - InstantiationFunction->setLocation(Member->getLocation()); // Explicit specializations of member functions of class templates do not // inherit '=delete' from the member function they are specializing. if (InstantiationFunction->isDeleted()) { + // FIXME: This assert will not hold in the presence of modules. assert(InstantiationFunction->getCanonicalDecl() == InstantiationFunction); + // FIXME: We need an update record for this AST mutation. InstantiationFunction->setDeletedAsWritten(false); } } - cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( - cast<CXXMethodDecl>(InstantiatedFrom), - TSK_ExplicitSpecialization); - MarkUnusedFileScopedDecl(InstantiationFunction); - } else if (isa<VarDecl>(Member)) { - VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); - if (InstantiationVar->getTemplateSpecializationKind() == - TSK_ImplicitInstantiation) { - InstantiationVar->setTemplateSpecializationKind( - TSK_ExplicitSpecialization); - InstantiationVar->setLocation(Member->getLocation()); - } - - cast<VarDecl>(Member)->setInstantiationOfStaticDataMember( + MemberFunction->setInstantiationOfMemberFunction( + cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); + } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) { + MemberVar->setInstantiationOfStaticDataMember( cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); - MarkUnusedFileScopedDecl(InstantiationVar); - } else if (isa<CXXRecordDecl>(Member)) { - CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); - if (InstantiationClass->getTemplateSpecializationKind() == - TSK_ImplicitInstantiation) { - InstantiationClass->setTemplateSpecializationKind( - TSK_ExplicitSpecialization); - InstantiationClass->setLocation(Member->getLocation()); - } - - cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( - cast<CXXRecordDecl>(InstantiatedFrom), - TSK_ExplicitSpecialization); - } else { - assert(isa<EnumDecl>(Member) && "Only member enums remain"); - EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation); - if (InstantiationEnum->getTemplateSpecializationKind() == - TSK_ImplicitInstantiation) { - InstantiationEnum->setTemplateSpecializationKind( - TSK_ExplicitSpecialization); - InstantiationEnum->setLocation(Member->getLocation()); - } - - cast<EnumDecl>(Member)->setInstantiationOfMemberEnum( + } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) { + MemberClass->setInstantiationOfMemberClass( + cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); + } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) { + MemberEnum->setInstantiationOfMemberEnum( cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); + } else { + llvm_unreachable("unknown member specialization kind"); } // Save the caller the trouble of having to figure out which declaration @@ -8107,6 +8164,43 @@ Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { return false; } +/// Complete the explicit specialization of a member of a class template by +/// updating the instantiated member to be marked as an explicit specialization. +/// +/// \param OrigD The member declaration instantiated from the template. +/// \param Loc The location of the explicit specialization of the member. +template<typename DeclT> +static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, + SourceLocation Loc) { + if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) + return; + + // FIXME: Inform AST mutation listeners of this AST mutation. + // FIXME: If there are multiple in-class declarations of the member (from + // multiple modules, or a declaration and later definition of a member type), + // should we update all of them? + OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); + OrigD->setLocation(Loc); +} + +void Sema::CompleteMemberSpecialization(NamedDecl *Member, + LookupResult &Previous) { + NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); + if (Instantiation == Member) + return; + + if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) + completeMemberSpecializationImpl(*this, Function, Member->getLocation()); + else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) + completeMemberSpecializationImpl(*this, Var, Member->getLocation()); + else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) + completeMemberSpecializationImpl(*this, Record, Member->getLocation()); + else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) + completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); + else + llvm_unreachable("unknown member specialization kind"); +} + /// \brief Check the scope of an explicit instantiation. /// /// \returns true if a serious error occurs, false otherwise. diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp index 9a71a17561c7..03df6fde6c80 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -1849,6 +1849,19 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, } } } + + // Check the template parameter list against the previous declaration. The + // goal here is to pick up default arguments added since the friend was + // declared; we know the template parameter lists match, since otherwise + // we would not have picked this template as the previous declaration. + if (TemplateParams && FunctionTemplate->getPreviousDecl()) { + SemaRef.CheckTemplateParameterList( + TemplateParams, + FunctionTemplate->getPreviousDecl()->getTemplateParameters(), + Function->isThisDeclarationADefinition() + ? Sema::TPC_FriendFunctionTemplateDefinition + : Sema::TPC_FriendFunctionTemplate); + } } if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) @@ -3660,6 +3673,7 @@ TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, New->setType(SemaRef.Context.getFunctionType( NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); } else { + Sema::ContextRAII SwitchContext(SemaRef, New); SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); } } diff --git a/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp b/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp index bcc66bbd1c0a..3992179fabae 100644 --- a/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp +++ b/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp @@ -2285,8 +2285,9 @@ bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { // Methods cannot return interface types. All ObjC objects are // passed by reference. if (T->isObjCObjectType()) { - Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; - return 0; + Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) + << 0 << T << FixItHint::CreateInsertion(Loc, "*"); + return true; } return false; diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp index 61b5a822c552..ef8481488302 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp @@ -1534,9 +1534,8 @@ MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { return Macro; unsigned NextIndex = 1; // Skip identifier ID. - SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]); SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); - MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID); + MacroInfo *MI = PP.AllocateMacroInfo(Loc); MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); MI->setIsUsed(Record[NextIndex++]); MI->setUsedForHeaderGuard(Record[NextIndex++]); diff --git a/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp b/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp index 8e4b217a44cd..b6c0cb2815fb 100644 --- a/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp +++ b/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp @@ -2413,7 +2413,6 @@ void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { } AddIdentifierRef(Name, Record); - Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc())); AddSourceLocation(MI->getDefinitionLoc(), Record); AddSourceLocation(MI->getDefinitionEndLoc(), Record); Record.push_back(MI->isUsed()); diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp index 1ea85d60c9e9..371187747f03 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -233,19 +233,16 @@ void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg, if (StringSelectors.empty()) { ASTContext &Ctx = C.getASTContext(); Selector Sels[] = { - getKeywordSelector(Ctx, "caseInsensitiveCompare", nullptr), - getKeywordSelector(Ctx, "compare", nullptr), - getKeywordSelector(Ctx, "compare", "options", nullptr), - getKeywordSelector(Ctx, "compare", "options", "range", nullptr), - getKeywordSelector(Ctx, "compare", "options", "range", "locale", - nullptr), - getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet", - nullptr), - getKeywordSelector(Ctx, "initWithFormat", - nullptr), - getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare", nullptr), - getKeywordSelector(Ctx, "localizedCompare", nullptr), - getKeywordSelector(Ctx, "localizedStandardCompare", nullptr), + getKeywordSelector(Ctx, "caseInsensitiveCompare"), + getKeywordSelector(Ctx, "compare"), + getKeywordSelector(Ctx, "compare", "options"), + getKeywordSelector(Ctx, "compare", "options", "range"), + getKeywordSelector(Ctx, "compare", "options", "range", "locale"), + getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet"), + getKeywordSelector(Ctx, "initWithFormat"), + getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare"), + getKeywordSelector(Ctx, "localizedCompare"), + getKeywordSelector(Ctx, "localizedStandardCompare"), }; for (Selector KnownSel : Sels) StringSelectors[KnownSel] = 0; @@ -262,16 +259,15 @@ void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg, if (ArrayWithObjectSel.isNull()) { ASTContext &Ctx = C.getASTContext(); - ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject", nullptr); - AddObjectSel = getKeywordSelector(Ctx, "addObject", nullptr); + ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject"); + AddObjectSel = getKeywordSelector(Ctx, "addObject"); InsertObjectAtIndexSel = - getKeywordSelector(Ctx, "insertObject", "atIndex", nullptr); + getKeywordSelector(Ctx, "insertObject", "atIndex"); ReplaceObjectAtIndexWithObjectSel = - getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject", nullptr); + getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject"); SetObjectAtIndexedSubscriptSel = - getKeywordSelector(Ctx, "setObject", "atIndexedSubscript", nullptr); - ArrayByAddingObjectSel = - getKeywordSelector(Ctx, "arrayByAddingObject", nullptr); + getKeywordSelector(Ctx, "setObject", "atIndexedSubscript"); + ArrayByAddingObjectSel = getKeywordSelector(Ctx, "arrayByAddingObject"); } if (S == ArrayWithObjectSel || S == AddObjectSel || @@ -292,13 +288,11 @@ void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg, if (DictionaryWithObjectForKeySel.isNull()) { ASTContext &Ctx = C.getASTContext(); DictionaryWithObjectForKeySel = - getKeywordSelector(Ctx, "dictionaryWithObject", "forKey", nullptr); - SetObjectForKeySel = - getKeywordSelector(Ctx, "setObject", "forKey", nullptr); + getKeywordSelector(Ctx, "dictionaryWithObject", "forKey"); + SetObjectForKeySel = getKeywordSelector(Ctx, "setObject", "forKey"); SetObjectForKeyedSubscriptSel = - getKeywordSelector(Ctx, "setObject", "forKeyedSubscript", nullptr); - RemoveObjectForKeySel = - getKeywordSelector(Ctx, "removeObjectForKey", nullptr); + getKeywordSelector(Ctx, "setObject", "forKeyedSubscript"); + RemoveObjectForKeySel = getKeywordSelector(Ctx, "removeObjectForKey"); } if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) { diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp index 8c2aef21b3ca..48d6cd8a527c 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp @@ -41,6 +41,22 @@ bool BuiltinFunctionChecker::evalCall(const CallExpr *CE, default: return false; + case Builtin::BI__builtin_assume: { + assert (CE->arg_begin() != CE->arg_end()); + SVal ArgSVal = state->getSVal(CE->getArg(0), LCtx); + if (ArgSVal.isUndef()) + return true; // Return true to model purity. + + state = state->assume(ArgSVal.castAs<DefinedOrUnknownSVal>(), true); + // FIXME: do we want to warn here? Not right now. The most reports might + // come from infeasible paths, thus being false positives. + if (!state) + return true; + + C.addTransition(state); + return true; + } + case Builtin::BI__builtin_unpredictable: case Builtin::BI__builtin_expect: case Builtin::BI__builtin_assume_aligned: diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp index c1deadef4202..8a5c769b6b50 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunctionChecker.cpp @@ -123,14 +123,14 @@ void NoReturnFunctionChecker::checkPostObjCMessage(const ObjCMethodCall &Msg, case 4: lazyInitKeywordSelector(HandleFailureInFunctionSel, C.getASTContext(), "handleFailureInFunction", "file", "lineNumber", - "description", nullptr); + "description"); if (Sel != HandleFailureInFunctionSel) return; break; case 5: lazyInitKeywordSelector(HandleFailureInMethodSel, C.getASTContext(), "handleFailureInMethod", "object", "file", - "lineNumber", "description", nullptr); + "lineNumber", "description"); if (Sel != HandleFailureInMethodSel) return; break; diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp index 3f6ae6222ce0..89b1291c4f46 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp @@ -703,31 +703,30 @@ private: ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } + template <typename... Keywords> void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries, - const RetainSummary *Summ, va_list argp) { - Selector S = getKeywordSelector(Ctx, argp); + const RetainSummary *Summ, Keywords *... Kws) { + Selector S = getKeywordSelector(Ctx, Kws...); Summaries[ObjCSummaryKey(ClsII, S)] = Summ; } - void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) { - va_list argp; - va_start(argp, Summ); - addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); - va_end(argp); + template <typename... Keywords> + void addInstMethSummary(const char *Cls, const RetainSummary *Summ, + Keywords *... Kws) { + addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, Kws...); } - void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) { - va_list argp; - va_start(argp, Summ); - addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); - va_end(argp); + template <typename... Keywords> + void addClsMethSummary(const char *Cls, const RetainSummary *Summ, + Keywords *... Kws) { + addMethodSummary(&Ctx.Idents.get(Cls), ObjCClassMethodSummaries, Summ, + Kws...); } - void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) { - va_list argp; - va_start(argp, Summ); - addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp); - va_end(argp); + template <typename... Keywords> + void addClsMethSummary(IdentifierInfo *II, const RetainSummary *Summ, + Keywords *... Kws) { + addMethodSummary(II, ObjCClassMethodSummaries, Summ, Kws...); } public: @@ -1640,20 +1639,16 @@ void RetainSummaryManager::InitializeMethodSummaries() { addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet); // Create summaries QCRenderer/QCView -createSnapShotImageOfType: - addInstMethSummary("QCRenderer", AllocSumm, - "createSnapshotImageOfType", nullptr); - addInstMethSummary("QCView", AllocSumm, - "createSnapshotImageOfType", nullptr); + addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType"); + addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType"); // Create summaries for CIContext, 'createCGImage' and // 'createCGLayerWithSize'. These objects are CF objects, and are not // automatically garbage collected. - addInstMethSummary("CIContext", CFAllocSumm, - "createCGImage", "fromRect", nullptr); + addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect"); addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect", - "format", "colorSpace", nullptr); - addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info", - nullptr); + "format", "colorSpace"); + addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info"); } //===----------------------------------------------------------------------===// diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h index 41f70d7d5b69..b11d070c629b 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h @@ -11,48 +11,26 @@ #define LLVM_CLANG_LIB_STATICANALYZER_CHECKERS_SELECTOREXTRAS_H #include "clang/AST/ASTContext.h" -#include <cstdarg> namespace clang { namespace ento { -static inline Selector getKeywordSelectorImpl(ASTContext &Ctx, - const char *First, - va_list argp) { - SmallVector<IdentifierInfo*, 10> II; - II.push_back(&Ctx.Idents.get(First)); - - while (const char *s = va_arg(argp, const char *)) - II.push_back(&Ctx.Idents.get(s)); +template <typename... IdentifierInfos> +static inline Selector getKeywordSelector(ASTContext &Ctx, + IdentifierInfos *... IIs) { + static_assert(sizeof...(IdentifierInfos), + "keyword selectors must have at least one argument"); + SmallVector<IdentifierInfo *, 10> II({&Ctx.Idents.get(IIs)...}); return Ctx.Selectors.getSelector(II.size(), &II[0]); } -static inline Selector getKeywordSelector(ASTContext &Ctx, va_list argp) { - const char *First = va_arg(argp, const char *); - assert(First && "keyword selectors must have at least one argument"); - return getKeywordSelectorImpl(Ctx, First, argp); -} - -LLVM_END_WITH_NULL -static inline Selector getKeywordSelector(ASTContext &Ctx, - const char *First, ...) { - va_list argp; - va_start(argp, First); - Selector result = getKeywordSelectorImpl(Ctx, First, argp); - va_end(argp); - return result; -} - -LLVM_END_WITH_NULL +template <typename... IdentifierInfos> static inline void lazyInitKeywordSelector(Selector &Sel, ASTContext &Ctx, - const char *First, ...) { + IdentifierInfos *... IIs) { if (!Sel.isNull()) return; - va_list argp; - va_start(argp, First); - Sel = getKeywordSelectorImpl(Ctx, First, argp); - va_end(argp); + Sel = getKeywordSelector(Ctx, IIs...); } static inline void lazyInitNullarySelector(Selector &Sel, ASTContext &Ctx, diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp index 93ad17cffb34..2f9f5d2d9cf8 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp @@ -440,7 +440,10 @@ StdLibraryFunctionsChecker::findFunctionSummary(const FunctionDecl *FD, BasicValueFactory &BVF = SVB.getBasicValueFactory(); initFunctionSummaries(BVF); - std::string Name = FD->getQualifiedNameAsString(); + IdentifierInfo *II = FD->getIdentifier(); + if (!II) + return None; + StringRef Name = II->getName(); if (Name.empty() || !C.isCLibraryFunction(FD, Name)) return None; diff --git a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp index 39d88bfda148..caf86b26b66d 100644 --- a/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp +++ b/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp @@ -447,6 +447,7 @@ bool ExprEngine::inlineCall(const CallEvent &Call, const Decl *D, Bldr.takeNodes(Pred); NumInlinedCalls++; + Engine.FunctionSummaries->bumpNumTimesInlined(D); // Mark the decl as visited. if (VisitedCallees) @@ -868,8 +869,6 @@ bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D, || IsRecursive)) return false; - Engine.FunctionSummaries->bumpNumTimesInlined(D); - return true; } diff --git a/contrib/llvm/tools/clang/lib/Tooling/RefactoringCallbacks.cpp b/contrib/llvm/tools/clang/lib/Tooling/RefactoringCallbacks.cpp index e900c23e4f64..9fd333ca554e 100644 --- a/contrib/llvm/tools/clang/lib/Tooling/RefactoringCallbacks.cpp +++ b/contrib/llvm/tools/clang/lib/Tooling/RefactoringCallbacks.cpp @@ -9,8 +9,13 @@ // // //===----------------------------------------------------------------------===// -#include "clang/Lex/Lexer.h" #include "clang/Tooling/RefactoringCallbacks.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Lex/Lexer.h" + +using llvm::StringError; +using llvm::make_error; namespace clang { namespace tooling { @@ -20,18 +25,62 @@ tooling::Replacements &RefactoringCallback::getReplacements() { return Replace; } -static Replacement replaceStmtWithText(SourceManager &Sources, - const Stmt &From, +ASTMatchRefactorer::ASTMatchRefactorer( + std::map<std::string, Replacements> &FileToReplaces) + : FileToReplaces(FileToReplaces) {} + +void ASTMatchRefactorer::addDynamicMatcher( + const ast_matchers::internal::DynTypedMatcher &Matcher, + RefactoringCallback *Callback) { + MatchFinder.addDynamicMatcher(Matcher, Callback); + Callbacks.push_back(Callback); +} + +class RefactoringASTConsumer : public ASTConsumer { +public: + explicit RefactoringASTConsumer(ASTMatchRefactorer &Refactoring) + : Refactoring(Refactoring) {} + + void HandleTranslationUnit(ASTContext &Context) override { + // The ASTMatchRefactorer is re-used between translation units. + // Clear the matchers so that each Replacement is only emitted once. + for (const auto &Callback : Refactoring.Callbacks) { + Callback->getReplacements().clear(); + } + Refactoring.MatchFinder.matchAST(Context); + for (const auto &Callback : Refactoring.Callbacks) { + for (const auto &Replacement : Callback->getReplacements()) { + llvm::Error Err = + Refactoring.FileToReplaces[Replacement.getFilePath()].add( + Replacement); + if (Err) { + llvm::errs() << "Skipping replacement " << Replacement.toString() + << " due to this error:\n" + << toString(std::move(Err)) << "\n"; + } + } + } + } + +private: + ASTMatchRefactorer &Refactoring; +}; + +std::unique_ptr<ASTConsumer> ASTMatchRefactorer::newASTConsumer() { + return llvm::make_unique<RefactoringASTConsumer>(*this); +} + +static Replacement replaceStmtWithText(SourceManager &Sources, const Stmt &From, StringRef Text) { - return tooling::Replacement(Sources, CharSourceRange::getTokenRange( - From.getSourceRange()), Text); + return tooling::Replacement( + Sources, CharSourceRange::getTokenRange(From.getSourceRange()), Text); } -static Replacement replaceStmtWithStmt(SourceManager &Sources, - const Stmt &From, +static Replacement replaceStmtWithStmt(SourceManager &Sources, const Stmt &From, const Stmt &To) { - return replaceStmtWithText(Sources, From, Lexer::getSourceText( - CharSourceRange::getTokenRange(To.getSourceRange()), - Sources, LangOptions())); + return replaceStmtWithText( + Sources, From, + Lexer::getSourceText(CharSourceRange::getTokenRange(To.getSourceRange()), + Sources, LangOptions())); } ReplaceStmtWithText::ReplaceStmtWithText(StringRef FromId, StringRef ToText) @@ -103,5 +152,90 @@ void ReplaceIfStmtWithItsBody::run( } } +ReplaceNodeWithTemplate::ReplaceNodeWithTemplate( + llvm::StringRef FromId, std::vector<TemplateElement> Template) + : FromId(FromId), Template(std::move(Template)) {} + +llvm::Expected<std::unique_ptr<ReplaceNodeWithTemplate>> +ReplaceNodeWithTemplate::create(StringRef FromId, StringRef ToTemplate) { + std::vector<TemplateElement> ParsedTemplate; + for (size_t Index = 0; Index < ToTemplate.size();) { + if (ToTemplate[Index] == '$') { + if (ToTemplate.substr(Index, 2) == "$$") { + Index += 2; + ParsedTemplate.push_back( + TemplateElement{TemplateElement::Literal, "$"}); + } else if (ToTemplate.substr(Index, 2) == "${") { + size_t EndOfIdentifier = ToTemplate.find("}", Index); + if (EndOfIdentifier == std::string::npos) { + return make_error<StringError>( + "Unterminated ${...} in replacement template near " + + ToTemplate.substr(Index), + llvm::inconvertibleErrorCode()); + } + std::string SourceNodeName = + ToTemplate.substr(Index + 2, EndOfIdentifier - Index - 2); + ParsedTemplate.push_back( + TemplateElement{TemplateElement::Identifier, SourceNodeName}); + Index = EndOfIdentifier + 1; + } else { + return make_error<StringError>( + "Invalid $ in replacement template near " + + ToTemplate.substr(Index), + llvm::inconvertibleErrorCode()); + } + } else { + size_t NextIndex = ToTemplate.find('$', Index + 1); + ParsedTemplate.push_back( + TemplateElement{TemplateElement::Literal, + ToTemplate.substr(Index, NextIndex - Index)}); + Index = NextIndex; + } + } + return std::unique_ptr<ReplaceNodeWithTemplate>( + new ReplaceNodeWithTemplate(FromId, std::move(ParsedTemplate))); +} + +void ReplaceNodeWithTemplate::run( + const ast_matchers::MatchFinder::MatchResult &Result) { + const auto &NodeMap = Result.Nodes.getMap(); + + std::string ToText; + for (const auto &Element : Template) { + switch (Element.Type) { + case TemplateElement::Literal: + ToText += Element.Value; + break; + case TemplateElement::Identifier: { + auto NodeIter = NodeMap.find(Element.Value); + if (NodeIter == NodeMap.end()) { + llvm::errs() << "Node " << Element.Value + << " used in replacement template not bound in Matcher \n"; + llvm::report_fatal_error("Unbound node in replacement template."); + } + CharSourceRange Source = + CharSourceRange::getTokenRange(NodeIter->second.getSourceRange()); + ToText += Lexer::getSourceText(Source, *Result.SourceManager, + Result.Context->getLangOpts()); + break; + } + } + } + if (NodeMap.count(FromId) == 0) { + llvm::errs() << "Node to be replaced " << FromId + << " not bound in query.\n"; + llvm::report_fatal_error("FromId node not bound in MatchResult"); + } + auto Replacement = + tooling::Replacement(*Result.SourceManager, &NodeMap.at(FromId), ToText, + Result.Context->getLangOpts()); + llvm::Error Err = Replace.add(Replacement); + if (Err) { + llvm::errs() << "Query and replace failed in " << Replacement.getFilePath() + << "! " << llvm::toString(std::move(Err)) << "\n"; + llvm::report_fatal_error("Replacement failed"); + } +} + } // end namespace tooling } // end namespace clang diff --git a/contrib/llvm/tools/llc/llc.cpp b/contrib/llvm/tools/llc/llc.cpp index 7c81abaed755..8c786950036f 100644 --- a/contrib/llvm/tools/llc/llc.cpp +++ b/contrib/llvm/tools/llc/llc.cpp @@ -301,6 +301,8 @@ int main(int argc, char **argv) { initializeConstantHoistingLegacyPassPass(*Registry); initializeScalarOpts(*Registry); initializeVectorization(*Registry); + initializeScalarizeMaskedMemIntrinPass(*Registry); + initializeExpandReductionsPass(*Registry); // Register the target printer for --version. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); diff --git a/contrib/llvm/tools/lld/COFF/Driver.cpp b/contrib/llvm/tools/lld/COFF/Driver.cpp index 5a15b5b11507..4c0ea44b875e 100644 --- a/contrib/llvm/tools/lld/COFF/Driver.cpp +++ b/contrib/llvm/tools/lld/COFF/Driver.cpp @@ -18,7 +18,6 @@ #include "lld/Driver/Driver.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringSwitch.h" -#include "llvm/LibDriver/LibDriver.h" #include "llvm/Object/ArchiveWriter.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" @@ -29,6 +28,7 @@ #include "llvm/Support/TarWriter.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/ToolDrivers/llvm-lib/LibDriver.h" #include <algorithm> #include <memory> diff --git a/contrib/llvm/tools/lld/COFF/ICF.cpp b/contrib/llvm/tools/lld/COFF/ICF.cpp index 9a43f2bd43f5..3b7cc424f0a2 100644 --- a/contrib/llvm/tools/lld/COFF/ICF.cpp +++ b/contrib/llvm/tools/lld/COFF/ICF.cpp @@ -21,9 +21,9 @@ #include "Chunks.h" #include "Error.h" #include "Symbols.h" -#include "lld/Core/Parallel.h" #include "llvm/ADT/Hashing.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/Parallel.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <atomic> @@ -192,7 +192,7 @@ void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) { // Split sections into 256 shards and call Fn in parallel. size_t NumShards = 256; size_t Step = Chunks.size() / NumShards; - parallel_for(size_t(0), NumShards, [&](size_t I) { + for_each_n(parallel::par, size_t(0), NumShards, [&](size_t I) { forEachClassRange(I * Step, (I + 1) * Step, Fn); }); forEachClassRange(Step * NumShards, Chunks.size(), Fn); diff --git a/contrib/llvm/tools/lld/COFF/MapFile.cpp b/contrib/llvm/tools/lld/COFF/MapFile.cpp index 4e596e602fee..b63d4672c7d5 100644 --- a/contrib/llvm/tools/lld/COFF/MapFile.cpp +++ b/contrib/llvm/tools/lld/COFF/MapFile.cpp @@ -25,7 +25,7 @@ #include "Symbols.h" #include "Writer.h" -#include "lld/Core/Parallel.h" +#include "llvm/Support/Parallel.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; @@ -76,7 +76,7 @@ static SymbolMapTy getSectionSyms(ArrayRef<DefinedRegular *> Syms) { static DenseMap<DefinedRegular *, std::string> getSymbolStrings(ArrayRef<DefinedRegular *> Syms) { std::vector<std::string> Str(Syms.size()); - parallel_for((size_t)0, Syms.size(), [&](size_t I) { + for_each_n(parallel::par, (size_t)0, Syms.size(), [&](size_t I) { raw_string_ostream OS(Str[I]); writeHeader(OS, Syms[I]->getRVA(), 0, 0); OS << indent(2) << toString(*Syms[I]); diff --git a/contrib/llvm/tools/lld/COFF/Writer.cpp b/contrib/llvm/tools/lld/COFF/Writer.cpp index 8762b88c4d6b..5c9c8375dadc 100644 --- a/contrib/llvm/tools/lld/COFF/Writer.cpp +++ b/contrib/llvm/tools/lld/COFF/Writer.cpp @@ -17,13 +17,13 @@ #include "PDB.h" #include "SymbolTable.h" #include "Symbols.h" -#include "lld/Core/Parallel.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileOutputBuffer.h" +#include "llvm/Support/Parallel.h" #include "llvm/Support/RandomNumberGenerator.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> @@ -745,8 +745,8 @@ void Writer::writeSections() { // ADD instructions). if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE) memset(SecBuf, 0xCC, Sec->getRawSize()); - parallel_for_each(Sec->getChunks().begin(), Sec->getChunks().end(), - [&](Chunk *C) { C->writeTo(SecBuf); }); + for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(), + [&](Chunk *C) { C->writeTo(SecBuf); }); } } @@ -760,16 +760,14 @@ void Writer::sortExceptionTable() { uint8_t *End = Begin + Sec->getVirtualSize(); if (Config->Machine == AMD64) { struct Entry { ulittle32_t Begin, End, Unwind; }; - parallel_sort( - (Entry *)Begin, (Entry *)End, - [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); + sort(parallel::par, (Entry *)Begin, (Entry *)End, + [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); return; } if (Config->Machine == ARMNT) { struct Entry { ulittle32_t Begin, Unwind; }; - parallel_sort( - (Entry *)Begin, (Entry *)End, - [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); + sort(parallel::par, (Entry *)Begin, (Entry *)End, + [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); return; } errs() << "warning: don't know how to handle .pdata.\n"; diff --git a/contrib/llvm/tools/lld/ELF/Config.h b/contrib/llvm/tools/lld/ELF/Config.h index 0321c84e7106..57a0e5a5ec73 100644 --- a/contrib/llvm/tools/lld/ELF/Config.h +++ b/contrib/llvm/tools/lld/ELF/Config.h @@ -73,7 +73,6 @@ struct VersionDefinition { // Most fields are initialized by the driver. struct Configuration { InputFile *FirstElf = nullptr; - bool HasStaticTlsModel = false; uint8_t OSABI = 0; llvm::CachePruningPolicy ThinLTOCachePolicy; llvm::StringMap<uint64_t> SectionStartMap; diff --git a/contrib/llvm/tools/lld/ELF/Driver.cpp b/contrib/llvm/tools/lld/ELF/Driver.cpp index c2cfe3c4129e..737c6a6bf114 100644 --- a/contrib/llvm/tools/lld/ELF/Driver.cpp +++ b/contrib/llvm/tools/lld/ELF/Driver.cpp @@ -284,7 +284,7 @@ static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) { int V = Default; if (auto *Arg = Args.getLastArg(Key)) { StringRef S = Arg->getValue(); - if (S.getAsInteger(10, V)) + if (!to_integer(S, V, 10)) error(Arg->getSpelling() + ": number expected, but got " + S); } return V; @@ -311,7 +311,7 @@ static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key, if (Pos != StringRef::npos && Key == Value.substr(0, Pos)) { Value = Value.substr(Pos + 1); uint64_t Result; - if (Value.getAsInteger(0, Result)) + if (!to_integer(Value, Result)) error("invalid " + Key + ": " + Value); return Result; } @@ -522,7 +522,7 @@ static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) { uint64_t VA = 0; if (S.startswith("0x")) S = S.drop_front(2); - if (S.getAsInteger(16, VA)) + if (!to_integer(S, VA, 16)) error("invalid argument: " + toString(Arg)); return VA; } @@ -886,7 +886,7 @@ static uint64_t getImageBase(opt::InputArgList &Args) { StringRef S = Arg->getValue(); uint64_t V; - if (S.getAsInteger(0, V)) { + if (!to_integer(S, V)) { error("-image-base: number expected, but got " + S); return 0; } diff --git a/contrib/llvm/tools/lld/ELF/GdbIndex.h b/contrib/llvm/tools/lld/ELF/GdbIndex.h index a36b92714def..03fec64f9bd5 100644 --- a/contrib/llvm/tools/lld/ELF/GdbIndex.h +++ b/contrib/llvm/tools/lld/ELF/GdbIndex.h @@ -21,7 +21,7 @@ class InputSection; // Struct represents single entry of address area of gdb index. struct AddressEntry { - InputSectionBase *Section; + InputSection *Section; uint64_t LowAddress; uint64_t HighAddress; size_t CuIndex; diff --git a/contrib/llvm/tools/lld/ELF/ICF.cpp b/contrib/llvm/tools/lld/ELF/ICF.cpp index dcf01ea80011..3722d4e3ed2f 100644 --- a/contrib/llvm/tools/lld/ELF/ICF.cpp +++ b/contrib/llvm/tools/lld/ELF/ICF.cpp @@ -325,7 +325,7 @@ void ICF<ELFT>::forEachClass(std::function<void(size_t, size_t)> Fn) { // Split sections into 256 shards and call Fn in parallel. size_t NumShards = 256; size_t Step = Sections.size() / NumShards; - parallelFor(0, NumShards, [&](size_t I) { + parallelForEachN(0, NumShards, [&](size_t I) { forEachClassRange(I * Step, (I + 1) * Step, Fn); }); forEachClassRange(Step * NumShards, Sections.size(), Fn); diff --git a/contrib/llvm/tools/lld/ELF/InputFiles.cpp b/contrib/llvm/tools/lld/ELF/InputFiles.cpp index 5f94fc9338a4..fe036a644f41 100644 --- a/contrib/llvm/tools/lld/ELF/InputFiles.cpp +++ b/contrib/llvm/tools/lld/ELF/InputFiles.cpp @@ -383,9 +383,9 @@ elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec, // we see. The eglibc ARM dynamic loaders require the presence of an // attribute section for dlopen to work. // In a full implementation we would merge all attribute sections. - if (In<ELFT>::ARMAttributes == nullptr) { - In<ELFT>::ARMAttributes = make<InputSection>(this, &Sec, Name); - return In<ELFT>::ARMAttributes; + if (InX::ARMAttributes == nullptr) { + InX::ARMAttributes = make<InputSection>(this, &Sec, Name); + return InX::ARMAttributes; } return &InputSection::Discarded; case SHT_RELA: diff --git a/contrib/llvm/tools/lld/ELF/InputSection.cpp b/contrib/llvm/tools/lld/ELF/InputSection.cpp index c082f128a9bc..87896ec96b29 100644 --- a/contrib/llvm/tools/lld/ELF/InputSection.cpp +++ b/contrib/llvm/tools/lld/ELF/InputSection.cpp @@ -324,7 +324,7 @@ void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) { // section, but for --emit-relocs it is an virtual address. P->r_offset = RelocatedSection->OutSec->Addr + RelocatedSection->getOffset(Rel.r_offset); - P->setSymbolAndType(In<ELFT>::SymTab->getSymbolIndex(&Body), Type, + P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type, Config->IsMips64EL); if (Body.Type == STT_SECTION) { @@ -400,40 +400,40 @@ getRelocTargetVA(uint32_t Type, int64_t A, typename ELFT::uint P, return Body.getVA(A); case R_GOT: case R_RELAX_TLS_GD_TO_IE_ABS: - return Body.getGotVA<ELFT>() + A; + return Body.getGotVA() + A; case R_GOTONLY_PC: - return In<ELFT>::Got->getVA() + A - P; + return InX::Got->getVA() + A - P; case R_GOTONLY_PC_FROM_END: - return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize(); + return InX::Got->getVA() + A - P + InX::Got->getSize(); case R_GOTREL: - return Body.getVA(A) - In<ELFT>::Got->getVA(); + return Body.getVA(A) - InX::Got->getVA(); case R_GOTREL_FROM_END: - return Body.getVA(A) - In<ELFT>::Got->getVA() - In<ELFT>::Got->getSize(); + return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize(); case R_GOT_FROM_END: case R_RELAX_TLS_GD_TO_IE_END: - return Body.getGotOffset() + A - In<ELFT>::Got->getSize(); + return Body.getGotOffset() + A - InX::Got->getSize(); case R_GOT_OFF: return Body.getGotOffset() + A; case R_GOT_PAGE_PC: case R_RELAX_TLS_GD_TO_IE_PAGE_PC: - return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P); + return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P); case R_GOT_PC: case R_RELAX_TLS_GD_TO_IE: - return Body.getGotVA<ELFT>() + A - P; + return Body.getGotVA() + A - P; case R_HINT: case R_NONE: case R_TLSDESC_CALL: llvm_unreachable("cannot relocate hint relocs"); case R_MIPS_GOTREL: - return Body.getVA(A) - In<ELFT>::MipsGot->getGp(); + return Body.getVA(A) - InX::MipsGot->getGp(); case R_MIPS_GOT_GP: - return In<ELFT>::MipsGot->getGp() + A; + return InX::MipsGot->getGp() + A; case R_MIPS_GOT_GP_PC: { // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target // is _gp_disp symbol. In that case we should use the following // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf - uint64_t V = In<ELFT>::MipsGot->getGp() + A - P; + uint64_t V = InX::MipsGot->getGp() + A - P; if (Type == R_MIPS_LO16) V += 4; return V; @@ -442,24 +442,21 @@ getRelocTargetVA(uint32_t Type, int64_t A, typename ELFT::uint P, // If relocation against MIPS local symbol requires GOT entry, this entry // should be initialized by 'page address'. This address is high 16-bits // of sum the symbol's value and the addend. - return In<ELFT>::MipsGot->getVA() + - In<ELFT>::MipsGot->getPageEntryOffset(Body, A) - - In<ELFT>::MipsGot->getGp(); + return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) - + InX::MipsGot->getGp(); case R_MIPS_GOT_OFF: case R_MIPS_GOT_OFF32: // In case of MIPS if a GOT relocation has non-zero addend this addend // should be applied to the GOT entry content not to the GOT entry offset. // That is why we use separate expression type. - return In<ELFT>::MipsGot->getVA() + - In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) - - In<ELFT>::MipsGot->getGp(); + return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) - + InX::MipsGot->getGp(); case R_MIPS_TLSGD: - return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() + - In<ELFT>::MipsGot->getGlobalDynOffset(Body) - - In<ELFT>::MipsGot->getGp(); + return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() + + InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp(); case R_MIPS_TLSLD: - return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() + - In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp(); + return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() + + InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp(); case R_PAGE_PC: case R_PLT_PAGE_PC: if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) @@ -523,19 +520,18 @@ getRelocTargetVA(uint32_t Type, int64_t A, typename ELFT::uint P, case R_SIZE: return Body.getSize<ELFT>() + A; case R_TLSDESC: - return In<ELFT>::Got->getGlobalDynAddr(Body) + A; + return InX::Got->getGlobalDynAddr(Body) + A; case R_TLSDESC_PAGE: - return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) - + return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) - getAArch64Page(P); case R_TLSGD: - return In<ELFT>::Got->getGlobalDynOffset(Body) + A - - In<ELFT>::Got->getSize(); + return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize(); case R_TLSGD_PC: - return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P; + return InX::Got->getGlobalDynAddr(Body) + A - P; case R_TLSLD: - return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize(); + return InX::Got->getTlsIndexOff() + A - InX::Got->getSize(); case R_TLSLD_PC: - return In<ELFT>::Got->getTlsIndexVA() + A - P; + return InX::Got->getTlsIndexVA() + A - P; } llvm_unreachable("Invalid expression"); } diff --git a/contrib/llvm/tools/lld/ELF/LinkerScript.cpp b/contrib/llvm/tools/lld/ELF/LinkerScript.cpp index d7858e173c7b..161909abf00d 100644 --- a/contrib/llvm/tools/lld/ELF/LinkerScript.cpp +++ b/contrib/llvm/tools/lld/ELF/LinkerScript.cpp @@ -48,8 +48,12 @@ using namespace lld::elf; LinkerScript *elf::Script; uint64_t ExprValue::getValue() const { - if (Sec) - return Sec->getOffset(Val) + Sec->getOutputSection()->Addr; + if (Sec) { + if (Sec->getOutputSection()) + return Sec->getOffset(Val) + Sec->getOutputSection()->Addr; + error("unable to evaluate expression: input section " + Sec->Name + + " has no output section assigned"); + } return Val; } @@ -411,6 +415,7 @@ void LinkerScript::processCommands(OutputSectionFactory &Factory) { if (OutputSection *Sec = Cmd->Sec) { assert(Sec->SectionIndex == INT_MAX); Sec->SectionIndex = I; + SecToCommand[Sec] = Cmd; } } } @@ -440,6 +445,7 @@ void LinkerScript::fabricateDefaultCommands() { auto *OSCmd = make<OutputSectionCommand>(Sec->Name); OSCmd->Sec = Sec; + SecToCommand[Sec] = OSCmd; // Prefer user supplied address over additional alignment constraint auto I = Config->SectionStartMap.find(Sec->Name); @@ -484,6 +490,7 @@ void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) { auto *Cmd = cast<OutputSectionCommand>(*I); Factory.addInputSec(S, Name, Cmd->Sec); if (OutputSection *Sec = Cmd->Sec) { + SecToCommand[Sec] = Cmd; unsigned Index = std::distance(Opt.Commands.begin(), I); assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index); Sec->SectionIndex = Index; @@ -699,6 +706,7 @@ void LinkerScript::adjustSectionsBeforeSorting() { OutSec->SectionIndex = I; OutputSections->push_back(OutSec); Cmd->Sec = OutSec; + SecToCommand[OutSec] = Cmd; } } @@ -822,16 +830,14 @@ void LinkerScript::placeOrphanSections() { // If there is no command corresponding to this output section, // create one and put a InputSectionDescription in it so that both // representations agree on which input sections to use. - auto Pos = std::find_if(CmdIter, E, [&](BaseCommand *Base) { - auto *Cmd = dyn_cast<OutputSectionCommand>(Base); - return Cmd && Cmd->Name == Name; - }); - if (Pos == E) { - auto *Cmd = make<OutputSectionCommand>(Name); + OutputSectionCommand *Cmd = getCmd(Sec); + if (!Cmd) { + Cmd = make<OutputSectionCommand>(Name); Opt.Commands.insert(CmdIter, Cmd); ++CmdIndex; Cmd->Sec = Sec; + SecToCommand[Sec] = Cmd; auto *ISD = make<InputSectionDescription>(""); for (InputSection *IS : Sec->Sections) ISD->Sections.push_back(IS); @@ -841,7 +847,11 @@ void LinkerScript::placeOrphanSections() { } // Continue from where we found it. - CmdIndex = (Pos - Opt.Commands.begin()) + 1; + while (*CmdIter != Cmd) { + ++CmdIter; + ++CmdIndex; + } + ++CmdIndex; } } @@ -1000,7 +1010,7 @@ std::vector<PhdrEntry> LinkerScript::createPhdrs() { break; // Assign headers specified by linker script - for (size_t Id : getPhdrIndices(Sec->Name)) { + for (size_t Id : getPhdrIndices(Sec)) { Ret[Id].add(Sec); if (Opt.PhdrsCommands[Id].Flags == UINT_MAX) Ret[Id].p_flags |= Sec->getPhdrFlags(); @@ -1020,11 +1030,16 @@ bool LinkerScript::ignoreInterpSection() { return true; } -Optional<uint32_t> LinkerScript::getFiller(StringRef Name) { - for (BaseCommand *Base : Opt.Commands) - if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) - if (Cmd->Name == Name) - return Cmd->Filler; +OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const { + auto I = SecToCommand.find(Sec); + if (I == SecToCommand.end()) + return nullptr; + return I->second; +} + +Optional<uint32_t> LinkerScript::getFiller(OutputSection *Sec) { + if (OutputSectionCommand *Cmd = getCmd(Sec)) + return Cmd->Filler; return None; } @@ -1042,26 +1057,16 @@ static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { } void LinkerScript::writeDataBytes(OutputSection *Sec, uint8_t *Buf) { - auto I = std::find_if(Opt.Commands.begin(), Opt.Commands.end(), - [=](BaseCommand *Base) { - if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) - if (Cmd->Sec == Sec) - return true; - return false; - }); - if (I == Opt.Commands.end()) - return; - auto *Cmd = cast<OutputSectionCommand>(*I); - for (BaseCommand *Base : Cmd->Commands) - if (auto *Data = dyn_cast<BytesDataCommand>(Base)) - writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size); + if (OutputSectionCommand *Cmd = getCmd(Sec)) + for (BaseCommand *Base : Cmd->Commands) + if (auto *Data = dyn_cast<BytesDataCommand>(Base)) + writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size); } -bool LinkerScript::hasLMA(StringRef Name) { - for (BaseCommand *Base : Opt.Commands) - if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) - if (Cmd->LMAExpr && Cmd->Name == Name) - return true; +bool LinkerScript::hasLMA(OutputSection *Sec) { + if (OutputSectionCommand *Cmd = getCmd(Sec)) + if (Cmd->LMAExpr) + return true; return false; } @@ -1080,15 +1085,10 @@ ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) { bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; } -// Returns indices of ELF headers containing specific section, identified -// by Name. Each index is a zero based number of ELF header listed within -// PHDRS {} script block. -std::vector<size_t> LinkerScript::getPhdrIndices(StringRef SectionName) { - for (BaseCommand *Base : Opt.Commands) { - auto *Cmd = dyn_cast<OutputSectionCommand>(Base); - if (!Cmd || Cmd->Name != SectionName) - continue; - +// Returns indices of ELF headers containing specific section. Each index is a +// zero based number of ELF header listed within PHDRS {} script block. +std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) { + if (OutputSectionCommand *Cmd = getCmd(Sec)) { std::vector<size_t> Ret; for (StringRef PhdrName : Cmd->Phdrs) Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName)); diff --git a/contrib/llvm/tools/lld/ELF/LinkerScript.h b/contrib/llvm/tools/lld/ELF/LinkerScript.h index 7bcd21c87602..d0a4d83d72b0 100644 --- a/contrib/llvm/tools/lld/ELF/LinkerScript.h +++ b/contrib/llvm/tools/lld/ELF/LinkerScript.h @@ -211,8 +211,9 @@ struct ScriptConfiguration { std::vector<llvm::StringRef> ReferencedSymbols; }; -class LinkerScript { -protected: +class LinkerScript final { + llvm::DenseMap<OutputSection *, OutputSectionCommand *> SecToCommand; + OutputSectionCommand *getCmd(OutputSection *Sec) const; void assignSymbol(SymbolAssignment *Cmd, bool InSec); void setDot(Expr E, const Twine &Loc, bool InSec); @@ -222,7 +223,7 @@ protected: std::vector<InputSectionBase *> createInputSectionList(OutputSectionCommand &Cmd); - std::vector<size_t> getPhdrIndices(StringRef SectionName); + std::vector<size_t> getPhdrIndices(OutputSection *Sec); size_t getPhdrIndex(const Twine &Loc, StringRef PhdrName); MemoryRegion *findMemoryRegion(OutputSectionCommand *Cmd); @@ -262,8 +263,8 @@ public: std::vector<PhdrEntry> createPhdrs(); bool ignoreInterpSection(); - llvm::Optional<uint32_t> getFiller(StringRef Name); - bool hasLMA(StringRef Name); + llvm::Optional<uint32_t> getFiller(OutputSection *Sec); + bool hasLMA(OutputSection *Sec); bool shouldKeep(InputSectionBase *S); void assignOffsets(OutputSectionCommand *Cmd); void placeOrphanSections(); diff --git a/contrib/llvm/tools/lld/ELF/MapFile.cpp b/contrib/llvm/tools/lld/ELF/MapFile.cpp index af5bc3c2c813..23c63e845c9a 100644 --- a/contrib/llvm/tools/lld/ELF/MapFile.cpp +++ b/contrib/llvm/tools/lld/ELF/MapFile.cpp @@ -84,7 +84,7 @@ template <class ELFT> DenseMap<DefinedRegular *, std::string> getSymbolStrings(ArrayRef<DefinedRegular *> Syms) { std::vector<std::string> Str(Syms.size()); - parallelFor(0, Syms.size(), [&](size_t I) { + parallelForEachN(0, Syms.size(), [&](size_t I) { raw_string_ostream OS(Str[I]); writeHeader<ELFT>(OS, Syms[I]->getVA(), Syms[I]->template getSize<ELFT>(), 0); diff --git a/contrib/llvm/tools/lld/ELF/OutputSections.cpp b/contrib/llvm/tools/lld/ELF/OutputSections.cpp index cb9c57657af3..dcefd03766d7 100644 --- a/contrib/llvm/tools/lld/ELF/OutputSections.cpp +++ b/contrib/llvm/tools/lld/ELF/OutputSections.cpp @@ -133,7 +133,7 @@ template <class ELFT> void OutputSection::finalize() { if (isa<SyntheticSection>(First)) return; - this->Link = In<ELFT>::SymTab->OutSec->SectionIndex; + this->Link = InX::SymTab->OutSec->SectionIndex; // sh_info for SHT_REL[A] sections should contain the section header index of // the section to which the relocation applies. InputSectionBase *S = First->getRelocatedSection(); @@ -273,7 +273,7 @@ uint32_t OutputSection::getFiller() { // linker script. If nothing is specified and this is an executable section, // fall back to trap instructions to prevent bad diassembly and detect invalid // jumps to padding. - if (Optional<uint32_t> Filler = Script->getFiller(Name)) + if (Optional<uint32_t> Filler = Script->getFiller(this)) return *Filler; if (Flags & SHF_EXECINSTR) return Target->TrapInstr; @@ -297,7 +297,7 @@ template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) { if (Filler) fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler); - parallelFor(0, Sections.size(), [=](size_t I) { + parallelForEachN(0, Sections.size(), [=](size_t I) { InputSection *Sec = Sections[I]; Sec->writeTo<ELFT>(Buf); @@ -429,8 +429,11 @@ void OutputSectionFactory::addInputSec(InputSectionBase *IS, if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type)) Sec->Type = SHT_PROGBITS; else - error("Section has different type from others with the same name " + - toString(IS)); + error("section type mismatch for " + IS->Name + + "\n>>> " + toString(IS) + ": " + + getELFSectionTypeName(Config->EMachine, IS->Type) + + "\n>>> output section " + Sec->Name + ": " + + getELFSectionTypeName(Config->EMachine, Sec->Type)); } Sec->Flags |= Flags; } else { diff --git a/contrib/llvm/tools/lld/ELF/OutputSections.h b/contrib/llvm/tools/lld/ELF/OutputSections.h index 6405fb38c6d6..413871b60cf7 100644 --- a/contrib/llvm/tools/lld/ELF/OutputSections.h +++ b/contrib/llvm/tools/lld/ELF/OutputSections.h @@ -50,6 +50,7 @@ public: template <typename ELFT> void writeHeaderTo(typename ELFT::Shdr *SHdr); unsigned SectionIndex; + unsigned SortRank; uint32_t getPhdrFlags() const; diff --git a/contrib/llvm/tools/lld/ELF/Relocations.cpp b/contrib/llvm/tools/lld/ELF/Relocations.cpp index f5db931e9755..ea7477e03842 100644 --- a/contrib/llvm/tools/lld/ELF/Relocations.cpp +++ b/contrib/llvm/tools/lld/ELF/Relocations.cpp @@ -106,21 +106,21 @@ static unsigned handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, uint64_t Offset, int64_t Addend, RelExpr Expr) { if (Expr == R_MIPS_TLSLD) { - if (In<ELFT>::MipsGot->addTlsIndex() && Config->Pic) - In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::MipsGot, - In<ELFT>::MipsGot->getTlsIndexOff(), false, + if (InX::MipsGot->addTlsIndex() && Config->Pic) + In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::MipsGot, + InX::MipsGot->getTlsIndexOff(), false, nullptr, 0}); C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); return 1; } if (Expr == R_MIPS_TLSGD) { - if (In<ELFT>::MipsGot->addDynTlsEntry(Body) && Body.isPreemptible()) { - uint64_t Off = In<ELFT>::MipsGot->getGlobalDynOffset(Body); + if (InX::MipsGot->addDynTlsEntry(Body) && Body.isPreemptible()) { + uint64_t Off = InX::MipsGot->getGlobalDynOffset(Body); In<ELFT>::RelaDyn->addReloc( - {Target->TlsModuleIndexRel, In<ELFT>::MipsGot, Off, false, &Body, 0}); + {Target->TlsModuleIndexRel, InX::MipsGot, Off, false, &Body, 0}); if (Body.isPreemptible()) - In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::MipsGot, + In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, InX::MipsGot, Off + Config->Wordsize, false, &Body, 0}); } C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); @@ -156,17 +156,17 @@ static unsigned handleARMTlsRelocation(uint32_t Type, SymbolBody &Body, auto AddTlsReloc = [&](uint64_t Off, uint32_t Type, SymbolBody *Dest, bool Dyn) { if (Dyn) - In<ELFT>::RelaDyn->addReloc({Type, In<ELFT>::Got, Off, false, Dest, 0}); + In<ELFT>::RelaDyn->addReloc({Type, InX::Got, Off, false, Dest, 0}); else - In<ELFT>::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest}); + InX::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest}); }; // Local Dynamic is for access to module local TLS variables, while still // being suitable for being dynamically loaded via dlopen. // GOT[e0] is the module index, with a special value of 0 for the current // module. GOT[e1] is unused. There only needs to be one module index entry. - if (Expr == R_TLSLD_PC && In<ELFT>::Got->addTlsIndex()) { - AddTlsReloc(In<ELFT>::Got->getTlsIndexOff(), Target->TlsModuleIndexRel, + if (Expr == R_TLSLD_PC && InX::Got->addTlsIndex()) { + AddTlsReloc(InX::Got->getTlsIndexOff(), Target->TlsModuleIndexRel, NeedDynId ? nullptr : &Body, NeedDynId); C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); return 1; @@ -176,8 +176,8 @@ static unsigned handleARMTlsRelocation(uint32_t Type, SymbolBody &Body, // the module index and offset of symbol in TLS block we can fill these in // using static GOT relocations. if (Expr == R_TLSGD_PC) { - if (In<ELFT>::Got->addDynTlsEntry(Body)) { - uint64_t Off = In<ELFT>::Got->getGlobalDynOffset(Body); + if (InX::Got->addDynTlsEntry(Body)) { + uint64_t Off = InX::Got->getGlobalDynOffset(Body); AddTlsReloc(Off, Target->TlsModuleIndexRel, &Body, NeedDynId); AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Body, NeedDynOff); @@ -207,10 +207,10 @@ handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, bool IsPreemptible = isPreemptible(Body, Type); if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) && Config->Shared) { - if (In<ELFT>::Got->addDynTlsEntry(Body)) { - uint64_t Off = In<ELFT>::Got->getGlobalDynOffset(Body); - In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off, - !IsPreemptible, &Body, 0}); + if (InX::Got->addDynTlsEntry(Body)) { + uint64_t Off = InX::Got->getGlobalDynOffset(Body); + In<ELFT>::RelaDyn->addReloc( + {Target->TlsDescRel, InX::Got, Off, !IsPreemptible, &Body, 0}); } if (Expr != R_TLSDESC_CALL) C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); @@ -224,10 +224,10 @@ handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body}); return 2; } - if (In<ELFT>::Got->addTlsIndex()) - In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got, - In<ELFT>::Got->getTlsIndexOff(), false, - nullptr, 0}); + if (InX::Got->addTlsIndex()) + In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::Got, + InX::Got->getTlsIndexOff(), false, nullptr, + 0}); C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); return 1; } @@ -242,19 +242,19 @@ handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD, R_TLSGD_PC>(Expr)) { if (Config->Shared) { - if (In<ELFT>::Got->addDynTlsEntry(Body)) { - uint64_t Off = In<ELFT>::Got->getGlobalDynOffset(Body); + if (InX::Got->addDynTlsEntry(Body)) { + uint64_t Off = InX::Got->getGlobalDynOffset(Body); In<ELFT>::RelaDyn->addReloc( - {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0}); + {Target->TlsModuleIndexRel, InX::Got, Off, false, &Body, 0}); // If the symbol is preemptible we need the dynamic linker to write // the offset too. uint64_t OffsetOff = Off + Config->Wordsize; if (IsPreemptible) - In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got, - OffsetOff, false, &Body, 0}); + In<ELFT>::RelaDyn->addReloc( + {Target->TlsOffsetRel, InX::Got, OffsetOff, false, &Body, 0}); else - In<ELFT>::Got->Relocations.push_back( + InX::Got->Relocations.push_back( {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body}); } C.Relocations.push_back({Expr, Type, Offset, Addend, &Body}); @@ -268,8 +268,8 @@ handleTlsRelocation(uint32_t Type, SymbolBody &Body, InputSectionBase &C, {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type, Offset, Addend, &Body}); if (!Body.isInGot()) { - In<ELFT>::Got->addEntry(Body); - In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got, + InX::Got->addEntry(Body); + In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::Got, Body.getGotOffset(), false, &Body, 0}); } } else { @@ -518,7 +518,7 @@ template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) { // See if this symbol is in a read-only segment. If so, preserve the symbol's // memory protection by reserving space in the .bss.rel.ro section. bool IsReadOnly = isReadOnly<ELFT>(SS); - BssSection *Sec = IsReadOnly ? In<ELFT>::BssRelRo : In<ELFT>::Bss; + BssSection *Sec = IsReadOnly ? InX::BssRelRo : InX::Bss; uint64_t Off = Sec->reserveSpace(SymSize, SS->getAlignment<ELFT>()); // Look through the DSO's dynamic symbol table for aliases and create a @@ -774,7 +774,7 @@ static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt, template <class ELFT> static void addGotEntry(SymbolBody &Sym, bool Preemptible) { - In<ELFT>::Got->addEntry(Sym); + InX::Got->addEntry(Sym); uint64_t Off = Sym.getGotOffset(); uint32_t DynType; @@ -792,10 +792,10 @@ static void addGotEntry(SymbolBody &Sym, bool Preemptible) { bool Constant = !Preemptible && !(Config->Pic && !isAbsolute(Sym)); if (!Constant) In<ELFT>::RelaDyn->addReloc( - {DynType, In<ELFT>::Got, Off, !Preemptible, &Sym, 0}); + {DynType, InX::Got, Off, !Preemptible, &Sym, 0}); if (Constant || (!Config->IsRela && !Preemptible)) - In<ELFT>::Got->Relocations.push_back({Expr, DynType, Off, 0, &Sym}); + InX::Got->Relocations.push_back({Expr, DynType, Off, 0, &Sym}); } // The reason we have to do this early scan is as follows @@ -856,7 +856,7 @@ static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { // needs it to be created. Here we request for that. if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL, R_GOTREL_FROM_END, R_PPC_TOC>(Expr)) - In<ELFT>::Got->HasGotOffRel = true; + InX::Got->HasGotOffRel = true; // Read an addend. int64_t Addend = computeAddend<ELFT>(Rel, Sec.Data.data()); @@ -874,11 +874,11 @@ static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol. if (needsPlt(Expr) && !Body.isInPlt()) { if (Body.isGnuIFunc() && !Preemptible) - addPltEntry(InX::Iplt, In<ELFT>::IgotPlt, In<ELFT>::RelaIplt, + addPltEntry(InX::Iplt, InX::IgotPlt, In<ELFT>::RelaIplt, Target->IRelativeRel, Body, true); else - addPltEntry(InX::Plt, In<ELFT>::GotPlt, In<ELFT>::RelaPlt, - Target->PltRel, Body, !Preemptible); + addPltEntry(InX::Plt, InX::GotPlt, In<ELFT>::RelaPlt, Target->PltRel, + Body, !Preemptible); } // Create a GOT slot if a relocation needs GOT. @@ -891,9 +891,9 @@ static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { // See "Global Offset Table" in Chapter 5 in the following document // for detailed description: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf - In<ELFT>::MipsGot->addEntry(Body, Addend, Expr); + InX::MipsGot->addEntry(Body, Addend, Expr); if (Body.isTls() && Body.isPreemptible()) - In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::MipsGot, + In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::MipsGot, Body.getGotOffset(), false, &Body, 0}); } else if (!Body.isInGot()) { addGotEntry<ELFT>(Body, Preemptible); @@ -927,7 +927,7 @@ static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) { // a dynamic relocation. // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 if (Config->EMachine == EM_MIPS) - In<ELFT>::MipsGot->addEntry(Body, Addend, Expr); + InX::MipsGot->addEntry(Body, Addend, Expr); continue; } diff --git a/contrib/llvm/tools/lld/ELF/ScriptParser.cpp b/contrib/llvm/tools/lld/ELF/ScriptParser.cpp index 032ecd50f3e3..f1bc245c9256 100644 --- a/contrib/llvm/tools/lld/ELF/ScriptParser.cpp +++ b/contrib/llvm/tools/lld/ELF/ScriptParser.cpp @@ -639,7 +639,7 @@ ScriptParser::readOutputSectionDescription(StringRef OutSec) { // We are compatible with ld.gold because it's easier to implement. uint32_t ScriptParser::parseFill(StringRef Tok) { uint32_t V = 0; - if (Tok.getAsInteger(0, V)) + if (!to_integer(Tok, V)) setError("invalid filler expression: " + Tok); uint32_t Buf; @@ -778,23 +778,23 @@ static Optional<uint64_t> parseInt(StringRef Tok) { // Hexadecimal uint64_t Val; - if (Tok.startswith_lower("0x") && !Tok.substr(2).getAsInteger(16, Val)) + if (Tok.startswith_lower("0x") && to_integer(Tok.substr(2), Val, 16)) return Val; - if (Tok.endswith_lower("H") && !Tok.drop_back().getAsInteger(16, Val)) + if (Tok.endswith_lower("H") && to_integer(Tok.drop_back(), Val, 16)) return Val; // Decimal if (Tok.endswith_lower("K")) { - if (Tok.drop_back().getAsInteger(10, Val)) + if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024; } if (Tok.endswith_lower("M")) { - if (Tok.drop_back().getAsInteger(10, Val)) + if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024 * 1024; } - if (Tok.getAsInteger(10, Val)) + if (!to_integer(Tok, Val, 10)) return None; return Val; } @@ -900,10 +900,22 @@ Expr ScriptParser::readPrimary() { StringRef Name = readParenLiteral(); return [=] { return Script->isDefined(Name) ? 1 : 0; }; } + if (Tok == "LENGTH") { + StringRef Name = readParenLiteral(); + if (Script->Opt.MemoryRegions.count(Name) == 0) + setError("memory region not defined: " + Name); + return [=] { return Script->Opt.MemoryRegions[Name].Length; }; + } if (Tok == "LOADADDR") { StringRef Name = readParenLiteral(); return [=] { return Script->getOutputSection(Location, Name)->getLMA(); }; } + if (Tok == "ORIGIN") { + StringRef Name = readParenLiteral(); + if (Script->Opt.MemoryRegions.count(Name) == 0) + setError("memory region not defined: " + Name); + return [=] { return Script->Opt.MemoryRegions[Name].Origin; }; + } if (Tok == "SEGMENT_START") { expect("("); skip(); diff --git a/contrib/llvm/tools/lld/ELF/Strings.cpp b/contrib/llvm/tools/lld/ELF/Strings.cpp index 29760b492ba9..2e88bfba0fc1 100644 --- a/contrib/llvm/tools/lld/ELF/Strings.cpp +++ b/contrib/llvm/tools/lld/ELF/Strings.cpp @@ -46,7 +46,7 @@ int elf::getPriority(StringRef S) { if (Pos == StringRef::npos) return 65536; int V; - if (S.substr(Pos + 1).getAsInteger(10, V)) + if (!to_integer(S.substr(Pos + 1), V, 10)) return 65536; return V; } @@ -68,7 +68,7 @@ std::vector<uint8_t> elf::parseHex(StringRef S) { StringRef B = S.substr(0, 2); S = S.substr(2); uint8_t H; - if (B.getAsInteger(16, H)) { + if (!to_integer(B, H, 16)) { error("not a hexadecimal value: " + B); return {}; } diff --git a/contrib/llvm/tools/lld/ELF/Symbols.cpp b/contrib/llvm/tools/lld/ELF/Symbols.cpp index 2090b33e8cd6..7ce1f5354b1b 100644 --- a/contrib/llvm/tools/lld/ELF/Symbols.cpp +++ b/contrib/llvm/tools/lld/ELF/Symbols.cpp @@ -163,8 +163,8 @@ uint64_t SymbolBody::getVA(int64_t Addend) const { return OutVA + Addend; } -template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const { - return In<ELFT>::Got->getVA() + getGotOffset(); +uint64_t SymbolBody::getGotVA() const { + return InX::Got->getVA() + getGotOffset(); } uint64_t SymbolBody::getGotOffset() const { @@ -370,11 +370,6 @@ std::string lld::toString(const SymbolBody &B) { return B.getName(); } -template uint32_t SymbolBody::template getGotVA<ELF32LE>() const; -template uint32_t SymbolBody::template getGotVA<ELF32BE>() const; -template uint64_t SymbolBody::template getGotVA<ELF64LE>() const; -template uint64_t SymbolBody::template getGotVA<ELF64BE>() const; - template uint32_t SymbolBody::template getSize<ELF32LE>() const; template uint32_t SymbolBody::template getSize<ELF32BE>() const; template uint64_t SymbolBody::template getSize<ELF64LE>() const; diff --git a/contrib/llvm/tools/lld/ELF/Symbols.h b/contrib/llvm/tools/lld/ELF/Symbols.h index 39a0c0f7b4df..030527f63744 100644 --- a/contrib/llvm/tools/lld/ELF/Symbols.h +++ b/contrib/llvm/tools/lld/ELF/Symbols.h @@ -78,7 +78,7 @@ public: uint64_t getVA(int64_t Addend = 0) const; uint64_t getGotOffset() const; - template <class ELFT> typename ELFT::uint getGotVA() const; + uint64_t getGotVA() const; uint64_t getGotPltOffset() const; uint64_t getGotPltVA() const; uint64_t getPltVA() const; diff --git a/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp b/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp index 9c585e41e9f0..5a2c2c37efd8 100644 --- a/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp +++ b/contrib/llvm/tools/lld/ELF/SyntheticSections.cpp @@ -186,7 +186,7 @@ template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) { Options->size = getSize(); if (!Config->Relocatable) - Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp(); + Reginfo.ri_gp_value = InX::MipsGot->getGp(); memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo)); } @@ -244,7 +244,7 @@ MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo) template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) { if (!Config->Relocatable) - Reginfo.ri_gp_value = In<ELFT>::MipsGot->getGp(); + Reginfo.ri_gp_value = InX::MipsGot->getGp(); memcpy(Buf, &Reginfo, sizeof(Reginfo)); } @@ -293,13 +293,12 @@ InputSection *elf::createInterpSection() { return Sec; } -template <class ELFT> SymbolBody *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, uint64_t Size, InputSectionBase *Section) { auto *S = make<DefinedRegular>(Name, /*IsLocal*/ true, STV_DEFAULT, Type, Value, Size, Section, nullptr); - if (In<ELFT>::SymTab) - In<ELFT>::SymTab->addSymbol(S); + if (InX::SymTab) + InX::SymTab->addSymbol(S); return S; } @@ -356,7 +355,7 @@ void BuildIdSection::computeHash( std::vector<uint8_t> Hashes(Chunks.size() * HashSize); // Compute hash values. - parallelFor(0, Chunks.size(), [&](size_t I) { + parallelForEachN(0, Chunks.size(), [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); }); @@ -618,17 +617,16 @@ template <class ELFT> void EhFrameSection<ELFT>::writeTo(uint8_t *Buf) { } } -template <class ELFT> -GotSection<ELFT>::GotSection() +GotBaseSection::GotBaseSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Target->GotEntrySize, ".got") {} -template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) { +void GotBaseSection::addEntry(SymbolBody &Sym) { Sym.GotIndex = NumEntries; ++NumEntries; } -template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) { +bool GotBaseSection::addDynTlsEntry(SymbolBody &Sym) { if (Sym.GlobalDynIndex != -1U) return false; Sym.GlobalDynIndex = NumEntries; @@ -639,7 +637,7 @@ template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) { // Reserves TLS entries for a TLS module ID and a TLS block offset. // In total it takes two GOT slots. -template <class ELFT> bool GotSection<ELFT>::addTlsIndex() { +bool GotBaseSection::addTlsIndex() { if (TlsIndexOff != uint32_t(-1)) return false; TlsIndexOff = NumEntries * Config->Wordsize; @@ -647,21 +645,19 @@ template <class ELFT> bool GotSection<ELFT>::addTlsIndex() { return true; } -template <class ELFT> -uint64_t GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const { +uint64_t GotBaseSection::getGlobalDynAddr(const SymbolBody &B) const { return this->getVA() + B.GlobalDynIndex * Config->Wordsize; } -template <class ELFT> -uint64_t GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const { +uint64_t GotBaseSection::getGlobalDynOffset(const SymbolBody &B) const { return B.GlobalDynIndex * Config->Wordsize; } -template <class ELFT> void GotSection<ELFT>::finalizeContents() { +void GotBaseSection::finalizeContents() { Size = NumEntries * Config->Wordsize; } -template <class ELFT> bool GotSection<ELFT>::empty() const { +bool GotBaseSection::empty() const { // If we have a relocation that is relative to GOT (such as GOTOFFREL), // we need to emit a GOT even if it's empty. return NumEntries == 0 && !HasGotOffRel; @@ -1028,24 +1024,15 @@ template <class ELFT> void DynamicSection<ELFT>::addEntries() { // Add strings to .dynstr early so that .dynstr's size will be // fixed early. for (StringRef S : Config->AuxiliaryList) - add({DT_AUXILIARY, In<ELFT>::DynStrTab->addString(S)}); + add({DT_AUXILIARY, InX::DynStrTab->addString(S)}); if (!Config->Rpath.empty()) add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, - In<ELFT>::DynStrTab->addString(Config->Rpath)}); + InX::DynStrTab->addString(Config->Rpath)}); for (SharedFile<ELFT> *F : Symtab<ELFT>::X->getSharedFiles()) if (F->isNeeded()) - add({DT_NEEDED, In<ELFT>::DynStrTab->addString(F->SoName)}); + add({DT_NEEDED, InX::DynStrTab->addString(F->SoName)}); if (!Config->SoName.empty()) - add({DT_SONAME, In<ELFT>::DynStrTab->addString(Config->SoName)}); - - if (!Config->Shared && !Config->Relocatable) - add({DT_DEBUG, (uint64_t)0}); -} - -// Add remaining entries to complete .dynamic contents. -template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { - if (this->Size) - return; // Already finalized. + add({DT_SONAME, InX::DynStrTab->addString(Config->SoName)}); // Set DT_FLAGS and DT_FLAGS_1. uint32_t DtFlags = 0; @@ -1064,15 +1051,22 @@ template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { DtFlags |= DF_ORIGIN; DtFlags1 |= DF_1_ORIGIN; } - if (Config->HasStaticTlsModel) - DtFlags |= DF_STATIC_TLS; if (DtFlags) add({DT_FLAGS, DtFlags}); if (DtFlags1) add({DT_FLAGS_1, DtFlags1}); - this->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex; + if (!Config->Shared && !Config->Relocatable) + add({DT_DEBUG, (uint64_t)0}); +} + +// Add remaining entries to complete .dynamic contents. +template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { + if (this->Size) + return; // Already finalized. + + this->Link = InX::DynStrTab->OutSec->SectionIndex; if (In<ELFT>::RelaDyn->OutSec->Size > 0) { bool IsRela = Config->IsRela; add({IsRela ? DT_RELA : DT_REL, In<ELFT>::RelaDyn}); @@ -1093,18 +1087,18 @@ template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { add({DT_JMPREL, In<ELFT>::RelaPlt}); add({DT_PLTRELSZ, In<ELFT>::RelaPlt->OutSec->Size}); add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT, - In<ELFT>::GotPlt}); + InX::GotPlt}); add({DT_PLTREL, uint64_t(Config->IsRela ? DT_RELA : DT_REL)}); } - add({DT_SYMTAB, In<ELFT>::DynSymTab}); + add({DT_SYMTAB, InX::DynSymTab}); add({DT_SYMENT, sizeof(Elf_Sym)}); - add({DT_STRTAB, In<ELFT>::DynStrTab}); - add({DT_STRSZ, In<ELFT>::DynStrTab->getSize()}); + add({DT_STRTAB, InX::DynStrTab}); + add({DT_STRSZ, InX::DynStrTab->getSize()}); if (!Config->ZText) add({DT_TEXTREL, (uint64_t)0}); - if (In<ELFT>::GnuHashTab) - add({DT_GNU_HASH, In<ELFT>::GnuHashTab}); + if (InX::GnuHashTab) + add({DT_GNU_HASH, InX::GnuHashTab}); if (In<ELFT>::HashTab) add({DT_HASH, In<ELFT>::HashTab}); @@ -1142,15 +1136,15 @@ template <class ELFT> void DynamicSection<ELFT>::finalizeContents() { add({DT_MIPS_RLD_VERSION, 1}); add({DT_MIPS_FLAGS, RHF_NOTPOT}); add({DT_MIPS_BASE_ADDRESS, Config->ImageBase}); - add({DT_MIPS_SYMTABNO, In<ELFT>::DynSymTab->getNumSymbols()}); - add({DT_MIPS_LOCAL_GOTNO, In<ELFT>::MipsGot->getLocalEntriesNum()}); - if (const SymbolBody *B = In<ELFT>::MipsGot->getFirstGlobalEntry()) + add({DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()}); + add({DT_MIPS_LOCAL_GOTNO, InX::MipsGot->getLocalEntriesNum()}); + if (const SymbolBody *B = InX::MipsGot->getFirstGlobalEntry()) add({DT_MIPS_GOTSYM, B->DynsymIndex}); else - add({DT_MIPS_GOTSYM, In<ELFT>::DynSymTab->getNumSymbols()}); - add({DT_PLTGOT, In<ELFT>::MipsGot}); - if (In<ELFT>::MipsRldMap) - add({DT_MIPS_RLD_MAP, In<ELFT>::MipsRldMap}); + add({DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()}); + add({DT_PLTGOT, InX::MipsGot}); + if (InX::MipsRldMap) + add({DT_MIPS_RLD_MAP, InX::MipsRldMap}); } this->OutSec->Link = this->Link; @@ -1235,11 +1229,11 @@ template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) { if (Config->IsRela) P->r_addend = Rel.getAddend(); P->r_offset = Rel.getOffset(); - if (Config->EMachine == EM_MIPS && Rel.getInputSec() == In<ELFT>::MipsGot) + if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot) // Dynamic relocation against MIPS GOT section make deal TLS entries // allocated in the end of the GOT. We need to adjust the offset to take // in account 'local' and 'global' GOT entries. - P->r_offset += In<ELFT>::MipsGot->getTlsOffset(); + P->r_offset += InX::MipsGot->getTlsOffset(); P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL); } @@ -1259,22 +1253,19 @@ template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() { } template <class ELFT> void RelocationSection<ELFT>::finalizeContents() { - this->Link = In<ELFT>::DynSymTab ? In<ELFT>::DynSymTab->OutSec->SectionIndex - : In<ELFT>::SymTab->OutSec->SectionIndex; + this->Link = InX::DynSymTab ? InX::DynSymTab->OutSec->SectionIndex + : InX::SymTab->OutSec->SectionIndex; // Set required output section properties. this->OutSec->Link = this->Link; } -template <class ELFT> -SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec) +SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec) : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0, StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, Config->Wordsize, StrTabSec.isDynamic() ? ".dynsym" : ".symtab"), - StrTabSec(StrTabSec) { - this->Entsize = sizeof(Elf_Sym); -} + StrTabSec(StrTabSec) {} // Orders symbols according to their positions in the GOT, // in compliance with MIPS ABI rules. @@ -1296,7 +1287,7 @@ static bool sortMipsSymbols(const SymbolTableEntry &L, // symbols precede global symbols, so we sort symbol entries in this // function. (For .dynsym, we don't do that because symbols for // dynamic linking are inherently all globals.) -template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() { +void SymbolTableBaseSection::finalizeContents() { this->OutSec->Link = StrTabSec.OutSec->SectionIndex; // If it is a .dynsym, there should be no local symbols, but we need @@ -1306,9 +1297,9 @@ template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() { // Because the first symbol entry is a null entry, 1 is the first. this->OutSec->Info = 1; - if (In<ELFT>::GnuHashTab) { + if (InX::GnuHashTab) { // NB: It also sorts Symbols to meet the GNU hash table requirements. - In<ELFT>::GnuHashTab->addSymbols(Symbols); + InX::GnuHashTab->addSymbols(Symbols); } else if (Config->EMachine == EM_MIPS) { std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols); } @@ -1320,7 +1311,7 @@ template <class ELFT> void SymbolTableSection<ELFT>::finalizeContents() { } } -template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() { +void SymbolTableBaseSection::postThunkContents() { if (this->Type == SHT_DYNSYM) return; // move all local symbols before global symbols. @@ -1333,7 +1324,7 @@ template <class ELFT> void SymbolTableSection<ELFT>::postThunkContents() { this->OutSec->Info = NumLocals + 1; } -template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) { +void SymbolTableBaseSection::addSymbol(SymbolBody *B) { // Adding a local symbol to a .dynsym is a bug. assert(this->Type != SHT_DYNSYM || !B->isLocal()); @@ -1341,8 +1332,7 @@ template <class ELFT> void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) { Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)}); } -template <class ELFT> -size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) { +size_t SymbolTableBaseSection::getSymbolIndex(SymbolBody *Body) { auto I = llvm::find_if(Symbols, [&](const SymbolTableEntry &E) { if (E.Symbol == Body) return true; @@ -1358,6 +1348,12 @@ size_t SymbolTableSection<ELFT>::getSymbolIndex(SymbolBody *Body) { return I - Symbols.begin() + 1; } +template <class ELFT> +SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec) + : SymbolTableBaseSection(StrTabSec) { + this->Entsize = sizeof(Elf_Sym); +} + // Write the internal symbol table contents to the output symbol table. template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { // The first entry is a null entry as per the ELF spec. @@ -1450,13 +1446,12 @@ template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) { // DSOs very quickly. If you are sure that your dynamic linker knows // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a // safe bet is to specify -hash-style=both for backward compatibilty. -template <class ELFT> -GnuHashTableSection<ELFT>::GnuHashTableSection() +GnuHashTableSection::GnuHashTableSection() : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") { } -template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() { - this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex; +void GnuHashTableSection::finalizeContents() { + this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex; // Computes bloom filter size in word size. We want to allocate 8 // bits for each symbol. It must be a power of two. @@ -1471,11 +1466,10 @@ template <class ELFT> void GnuHashTableSection<ELFT>::finalizeContents() { Size += Symbols.size() * 4; // Hash values } -template <class ELFT> -void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) { +void GnuHashTableSection::writeTo(uint8_t *Buf) { // Write a header. write32(Buf, NBuckets, Config->Endianness); - write32(Buf + 4, In<ELFT>::DynSymTab->getNumSymbols() - Symbols.size(), + write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size(), Config->Endianness); write32(Buf + 8, MaskWords, Config->Endianness); write32(Buf + 12, getShift2(), Config->Endianness); @@ -1494,8 +1488,7 @@ void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) { // // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2), // p.9, https://www.akkadia.org/drepper/dsohowto.pdf -template <class ELFT> -void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) { +void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) { const unsigned C = Config->Wordsize * 8; for (const Entry &Sym : Symbols) { size_t I = (Sym.Hash / C) & (MaskWords - 1); @@ -1506,8 +1499,7 @@ void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *Buf) { } } -template <class ELFT> -void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) { +void GnuHashTableSection::writeHashTable(uint8_t *Buf) { // Group symbols by hash value. std::vector<std::vector<Entry>> Syms(NBuckets); for (const Entry &Ent : Symbols) @@ -1560,8 +1552,7 @@ static size_t getBucketSize(size_t NumSymbols) { // Add symbols to this symbol hash table. Note that this function // destructively sort a given vector -- which is needed because // GNU-style hash table places some sorting requirements. -template <class ELFT> -void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolTableEntry> &V) { +void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) { // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce // its type correctly. std::vector<SymbolTableEntry>::iterator Mid = @@ -1594,15 +1585,15 @@ HashTableSection<ELFT>::HashTableSection() } template <class ELFT> void HashTableSection<ELFT>::finalizeContents() { - this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex; + this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex; unsigned NumEntries = 2; // nbucket and nchain. - NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); // The chain entries. + NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries. // Create as many buckets as there are symbols. // FIXME: This is simplistic. We can try to optimize it, but implementing // support for SHT_GNU_HASH is probably even more profitable. - NumEntries += In<ELFT>::DynSymTab->getNumSymbols(); + NumEntries += InX::DynSymTab->getNumSymbols(); this->Size = NumEntries * 4; } @@ -1610,7 +1601,7 @@ template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { // A 32-bit integer type in the target endianness. typedef typename ELFT::Word Elf_Word; - unsigned NumSymbols = In<ELFT>::DynSymTab->getNumSymbols(); + unsigned NumSymbols = InX::DynSymTab->getNumSymbols(); auto *P = reinterpret_cast<Elf_Word *>(Buf); *P++ = NumSymbols; // nbucket @@ -1619,7 +1610,7 @@ template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) { Elf_Word *Buckets = P; Elf_Word *Chains = P + NumSymbols; - for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) { + for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { SymbolBody *Body = S.Symbol; StringRef Name = Body->getName(); unsigned I = Body->DynsymIndex; @@ -1706,13 +1697,14 @@ readCuList(DWARFContext &Dwarf, InputSection *Sec) { return Ret; } -static InputSectionBase *findSection(ArrayRef<InputSectionBase *> Arr, - uint64_t Offset) { +static InputSection *findSection(ArrayRef<InputSectionBase *> Arr, + uint64_t Offset) { for (InputSectionBase *S : Arr) - if (S && S != &InputSection::Discarded) - if (Offset >= S->getOffsetInFile() && - Offset < S->getOffsetInFile() + S->getSize()) - return S; + if (auto *IS = dyn_cast_or_null<InputSection>(S)) + if (IS != &InputSection::Discarded && IS->Live && + Offset >= IS->getOffsetInFile() && + Offset < IS->getOffsetInFile() + IS->getSize()) + return IS; return nullptr; } @@ -1725,10 +1717,10 @@ readAddressArea(DWARFContext &Dwarf, InputSection *Sec, size_t CurrentCU) { CU->collectAddressRanges(Ranges); ArrayRef<InputSectionBase *> Sections = Sec->File->getSections(); - for (std::pair<uint64_t, uint64_t> &R : Ranges) - if (InputSectionBase *S = findSection(Sections, R.first)) - Ret.push_back({S, R.first - S->getOffsetInFile(), - R.second - S->getOffsetInFile(), CurrentCU}); + for (DWARFAddressRange &R : Ranges) + if (InputSection *S = findSection(Sections, R.LowPC)) + Ret.push_back({S, R.LowPC - S->getOffsetInFile(), + R.HighPC - S->getOffsetInFile(), CurrentCU}); ++CurrentCU; } return Ret; @@ -1951,11 +1943,11 @@ static StringRef getFileDefName() { } template <class ELFT> void VersionDefinitionSection<ELFT>::finalizeContents() { - FileDefNameOff = In<ELFT>::DynStrTab->addString(getFileDefName()); + FileDefNameOff = InX::DynStrTab->addString(getFileDefName()); for (VersionDefinition &V : Config->VersionDefinitions) - V.NameOff = In<ELFT>::DynStrTab->addString(V.Name); + V.NameOff = InX::DynStrTab->addString(V.Name); - this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex; + this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex; // sh_info should be set to the number of definitions. This fact is missed in // documentation, but confirmed by binutils community: @@ -2008,16 +2000,16 @@ VersionTableSection<ELFT>::VersionTableSection() template <class ELFT> void VersionTableSection<ELFT>::finalizeContents() { // At the moment of june 2016 GNU docs does not mention that sh_link field // should be set, but Sun docs do. Also readelf relies on this field. - this->OutSec->Link = In<ELFT>::DynSymTab->OutSec->SectionIndex; + this->OutSec->Link = InX::DynSymTab->OutSec->SectionIndex; } template <class ELFT> size_t VersionTableSection<ELFT>::getSize() const { - return sizeof(Elf_Versym) * (In<ELFT>::DynSymTab->getSymbols().size() + 1); + return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1); } template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) { auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1; - for (const SymbolTableEntry &S : In<ELFT>::DynSymTab->getSymbols()) { + for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { OutVersym->vs_index = S.Symbol->symbol()->VersionId; ++OutVersym; } @@ -2051,14 +2043,14 @@ void VersionNeedSection<ELFT>::addSymbol(SharedSymbol *SS) { // to create one by adding it to our needed list and creating a dynstr entry // for the soname. if (File->VerdefMap.empty()) - Needed.push_back({File, In<ELFT>::DynStrTab->addString(File->SoName)}); + Needed.push_back({File, InX::DynStrTab->addString(File->SoName)}); typename SharedFile<ELFT>::NeededVer &NV = File->VerdefMap[Ver]; // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, // prepare to create one by allocating a version identifier and creating a // dynstr entry for the version name. if (NV.Index == 0) { - NV.StrTab = In<ELFT>::DynStrTab->addString(File->getStringTable().data() + - Ver->getAux()->vda_name); + NV.StrTab = InX::DynStrTab->addString(File->getStringTable().data() + + Ver->getAux()->vda_name); NV.Index = NextIndex++; } SS->symbol()->VersionId = NV.Index; @@ -2100,7 +2092,7 @@ template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) { } template <class ELFT> void VersionNeedSection<ELFT>::finalizeContents() { - this->OutSec->Link = In<ELFT>::DynStrTab->OutSec->SectionIndex; + this->OutSec->Link = InX::DynStrTab->OutSec->SectionIndex; this->OutSec->Info = Needed.size(); } @@ -2187,7 +2179,7 @@ MipsRldMapSection::MipsRldMapSection() void MipsRldMapSection::writeTo(uint8_t *Buf) { // Apply filler from linker script. - Optional<uint32_t> Fill = Script->getFiller(this->Name); + Optional<uint32_t> Fill = Script->getFiller(this->OutSec); if (!Fill || *Fill == 0) return; @@ -2245,10 +2237,14 @@ BssSection *InX::Bss; BssSection *InX::BssRelRo; BuildIdSection *InX::BuildId; InputSection *InX::Common; +SyntheticSection *InX::Dynamic; StringTableSection *InX::DynStrTab; +SymbolTableBaseSection *InX::DynSymTab; InputSection *InX::Interp; GdbIndexSection *InX::GdbIndex; +GotBaseSection *InX::Got; GotPltSection *InX::GotPlt; +GnuHashTableSection *InX::GnuHashTab; IgotPltSection *InX::IgotPlt; MipsGotSection *InX::MipsGot; MipsRldMapSection *InX::MipsRldMap; @@ -2256,6 +2252,7 @@ PltSection *InX::Plt; PltSection *InX::Iplt; StringTableSection *InX::ShStrTab; StringTableSection *InX::StrTab; +SymbolTableBaseSection *InX::SymTab; template void PltSection::addEntry<ELF32LE>(SymbolBody &Sym); template void PltSection::addEntry<ELF32BE>(SymbolBody &Sym); @@ -2272,19 +2269,6 @@ template MergeInputSection *elf::createCommentSection<ELF32BE>(); template MergeInputSection *elf::createCommentSection<ELF64LE>(); template MergeInputSection *elf::createCommentSection<ELF64BE>(); -template SymbolBody *elf::addSyntheticLocal<ELF32LE>(StringRef, uint8_t, - uint64_t, uint64_t, - InputSectionBase *); -template SymbolBody *elf::addSyntheticLocal<ELF32BE>(StringRef, uint8_t, - uint64_t, uint64_t, - InputSectionBase *); -template SymbolBody *elf::addSyntheticLocal<ELF64LE>(StringRef, uint8_t, - uint64_t, uint64_t, - InputSectionBase *); -template SymbolBody *elf::addSyntheticLocal<ELF64BE>(StringRef, uint8_t, - uint64_t, uint64_t, - InputSectionBase *); - template class elf::MipsAbiFlagsSection<ELF32LE>; template class elf::MipsAbiFlagsSection<ELF32BE>; template class elf::MipsAbiFlagsSection<ELF64LE>; @@ -2320,11 +2304,6 @@ template class elf::SymbolTableSection<ELF32BE>; template class elf::SymbolTableSection<ELF64LE>; template class elf::SymbolTableSection<ELF64BE>; -template class elf::GnuHashTableSection<ELF32LE>; -template class elf::GnuHashTableSection<ELF32BE>; -template class elf::GnuHashTableSection<ELF64LE>; -template class elf::GnuHashTableSection<ELF64BE>; - template class elf::HashTableSection<ELF32LE>; template class elf::HashTableSection<ELF32BE>; template class elf::HashTableSection<ELF64LE>; diff --git a/contrib/llvm/tools/lld/ELF/SyntheticSections.h b/contrib/llvm/tools/lld/ELF/SyntheticSections.h index 1098c58a3baf..0477c601a7df 100644 --- a/contrib/llvm/tools/lld/ELF/SyntheticSections.h +++ b/contrib/llvm/tools/lld/ELF/SyntheticSections.h @@ -104,10 +104,9 @@ private: llvm::DenseMap<std::pair<ArrayRef<uint8_t>, SymbolBody *>, CieRecord> CieMap; }; -template <class ELFT> class GotSection final : public SyntheticSection { +class GotBaseSection : public SyntheticSection { public: - GotSection(); - void writeTo(uint8_t *Buf) override; + GotBaseSection(); size_t getSize() const override { return Size; } void finalizeContents() override; bool empty() const override; @@ -125,12 +124,17 @@ public: // that relies on its address. bool HasGotOffRel = false; -private: +protected: size_t NumEntries = 0; uint32_t TlsIndexOff = -1; uint64_t Size = 0; }; +template <class ELFT> class GotSection final : public GotBaseSection { +public: + void writeTo(uint8_t *Buf) override; +}; + // .note.gnu.build-id section. class BuildIdSection : public SyntheticSection { // First 16 bytes are a header. @@ -401,31 +405,35 @@ struct SymbolTableEntry { size_t StrTabOffset; }; -template <class ELFT> class SymbolTableSection final : public SyntheticSection { +class SymbolTableBaseSection : public SyntheticSection { public: - typedef typename ELFT::Sym Elf_Sym; - - SymbolTableSection(StringTableSection &StrTabSec); - + SymbolTableBaseSection(StringTableSection &StrTabSec); void finalizeContents() override; void postThunkContents() override; - void writeTo(uint8_t *Buf) override; - size_t getSize() const override { return getNumSymbols() * sizeof(Elf_Sym); } + size_t getSize() const override { return getNumSymbols() * Entsize; } void addSymbol(SymbolBody *Body); unsigned getNumSymbols() const { return Symbols.size() + 1; } size_t getSymbolIndex(SymbolBody *Body); ArrayRef<SymbolTableEntry> getSymbols() const { return Symbols; } -private: +protected: // A vector of symbols and their string table offsets. std::vector<SymbolTableEntry> Symbols; StringTableSection &StrTabSec; }; +template <class ELFT> +class SymbolTableSection final : public SymbolTableBaseSection { + typedef typename ELFT::Sym Elf_Sym; + +public: + SymbolTableSection(StringTableSection &StrTabSec); + void writeTo(uint8_t *Buf) override; +}; + // Outputs GNU Hash section. For detailed explanation see: // https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections -template <class ELFT> class GnuHashTableSection final : public SyntheticSection { public: GnuHashTableSection(); @@ -739,7 +747,7 @@ private: template <class ELFT> InputSection *createCommonSection(); InputSection *createInterpSection(); template <class ELFT> MergeInputSection *createCommentSection(); -template <class ELFT> + SymbolBody *addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, uint64_t Size, InputSectionBase *Section); @@ -750,9 +758,13 @@ struct InX { static BssSection *BssRelRo; static BuildIdSection *BuildId; static InputSection *Common; + static SyntheticSection *Dynamic; static StringTableSection *DynStrTab; + static SymbolTableBaseSection *DynSymTab; + static GnuHashTableSection *GnuHashTab; static InputSection *Interp; static GdbIndexSection *GdbIndex; + static GotBaseSection *Got; static GotPltSection *GotPlt; static IgotPltSection *IgotPlt; static MipsGotSection *MipsGot; @@ -761,36 +773,27 @@ struct InX { static PltSection *Iplt; static StringTableSection *ShStrTab; static StringTableSection *StrTab; + static SymbolTableBaseSection *SymTab; }; template <class ELFT> struct In : public InX { - static DynamicSection<ELFT> *Dynamic; - static SymbolTableSection<ELFT> *DynSymTab; static EhFrameHeader<ELFT> *EhFrameHdr; - static GnuHashTableSection<ELFT> *GnuHashTab; - static GotSection<ELFT> *Got; static EhFrameSection<ELFT> *EhFrame; static HashTableSection<ELFT> *HashTab; static RelocationSection<ELFT> *RelaDyn; static RelocationSection<ELFT> *RelaPlt; static RelocationSection<ELFT> *RelaIplt; - static SymbolTableSection<ELFT> *SymTab; static VersionDefinitionSection<ELFT> *VerDef; static VersionTableSection<ELFT> *VerSym; static VersionNeedSection<ELFT> *VerNeed; }; -template <class ELFT> DynamicSection<ELFT> *In<ELFT>::Dynamic; -template <class ELFT> SymbolTableSection<ELFT> *In<ELFT>::DynSymTab; template <class ELFT> EhFrameHeader<ELFT> *In<ELFT>::EhFrameHdr; -template <class ELFT> GnuHashTableSection<ELFT> *In<ELFT>::GnuHashTab; -template <class ELFT> GotSection<ELFT> *In<ELFT>::Got; template <class ELFT> EhFrameSection<ELFT> *In<ELFT>::EhFrame; template <class ELFT> HashTableSection<ELFT> *In<ELFT>::HashTab; template <class ELFT> RelocationSection<ELFT> *In<ELFT>::RelaDyn; template <class ELFT> RelocationSection<ELFT> *In<ELFT>::RelaPlt; template <class ELFT> RelocationSection<ELFT> *In<ELFT>::RelaIplt; -template <class ELFT> SymbolTableSection<ELFT> *In<ELFT>::SymTab; template <class ELFT> VersionDefinitionSection<ELFT> *In<ELFT>::VerDef; template <class ELFT> VersionTableSection<ELFT> *In<ELFT>::VerSym; template <class ELFT> VersionNeedSection<ELFT> *In<ELFT>::VerNeed; diff --git a/contrib/llvm/tools/lld/ELF/Target.cpp b/contrib/llvm/tools/lld/ELF/Target.cpp index 4643c1a919aa..781d7fe3bc3f 100644 --- a/contrib/llvm/tools/lld/ELF/Target.cpp +++ b/contrib/llvm/tools/lld/ELF/Target.cpp @@ -351,15 +351,6 @@ X86TargetInfo::X86TargetInfo() { RelExpr X86TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S, const uint8_t *Loc) const { - // There are 4 different TLS variable models with varying degrees of - // flexibility and performance. LocalExec and InitialExec models are fast but - // less-flexible models. They cannot be used for dlopen(). If they are in use, - // we set DF_STATIC_TLS in the ELF header so that the runtime can reject such - // DSOs. - if (Type == R_386_TLS_LE || Type == R_386_TLS_LE_32 || Type == R_386_TLS_IE || - Type == R_386_TLS_GOTIE) - Config->HasStaticTlsModel = true; - switch (Type) { case R_386_8: case R_386_16: @@ -429,7 +420,7 @@ RelExpr X86TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data, } void X86TargetInfo::writeGotPltHeader(uint8_t *Buf) const { - write32le(Buf, In<ELF32LE>::Dynamic->getVA()); + write32le(Buf, InX::Dynamic->getVA()); } void X86TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &S) const { @@ -460,8 +451,8 @@ void X86TargetInfo::writePltHeader(uint8_t *Buf) const { }; memcpy(Buf, V, sizeof(V)); - uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize(); - uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA() - Ebx; + uint32_t Ebx = InX::Got->getVA() + InX::Got->getSize(); + uint32_t GotPlt = InX::GotPlt->getVA() - Ebx; write32le(Buf + 2, GotPlt + 4); write32le(Buf + 8, GotPlt + 8); return; @@ -473,7 +464,7 @@ void X86TargetInfo::writePltHeader(uint8_t *Buf) const { 0x90, 0x90, 0x90, 0x90 // nop }; memcpy(Buf, PltData, sizeof(PltData)); - uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA(); + uint32_t GotPlt = InX::GotPlt->getVA(); write32le(Buf + 2, GotPlt + 4); write32le(Buf + 8, GotPlt + 8); } @@ -490,7 +481,7 @@ void X86TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, if (Config->Pic) { // jmp *foo@GOT(%ebx) - uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize(); + uint32_t Ebx = InX::Got->getVA() + InX::Got->getSize(); Buf[1] = 0xa3; write32le(Buf + 2, GotPltEntryAddr - Ebx); } else { @@ -718,7 +709,7 @@ void X86_64TargetInfo<ELFT>::writeGotPltHeader(uint8_t *Buf) const { // required, but it is documented in the psabi and the glibc dynamic linker // seems to use it (note that this is relevant for linking ld.so, not any // other program). - write64le(Buf, In<ELFT>::Dynamic->getVA()); + write64le(Buf, InX::Dynamic->getVA()); } template <class ELFT> @@ -736,8 +727,8 @@ void X86_64TargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const { 0x0f, 0x1f, 0x40, 0x00 // nop }; memcpy(Buf, PltData, sizeof(PltData)); - uint64_t GotPlt = In<ELFT>::GotPlt->getVA(); - uint64_t Plt = In<ELFT>::Plt->getVA(); + uint64_t GotPlt = InX::GotPlt->getVA(); + uint64_t Plt = InX::Plt->getVA(); write32le(Buf + 2, GotPlt - Plt + 2); // GOTPLT+8 write32le(Buf + 8, GotPlt - Plt + 4); // GOTPLT+16 } @@ -760,7 +751,8 @@ void X86_64TargetInfo<ELFT>::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, template <class ELFT> bool X86_64TargetInfo<ELFT>::isPicRel(uint32_t Type) const { - return Type != R_X86_64_PC32 && Type != R_X86_64_32; + return Type != R_X86_64_PC32 && Type != R_X86_64_32 && + Type != R_X86_64_TPOFF32; } template <class ELFT> @@ -1140,7 +1132,7 @@ uint64_t getPPC64TocBase() { // TOC starts where the first of these sections starts. We always create a // .got when we see a relocation that uses it, so for us the start is always // the .got. - uint64_t TocVA = In<ELF64BE>::Got->getVA(); + uint64_t TocVA = InX::Got->getVA(); // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000 // thus permitting a full 64 Kbytes segment. Note that the glibc startup @@ -1369,7 +1361,7 @@ bool AArch64TargetInfo::isPicRel(uint32_t Type) const { } void AArch64TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const { - write64le(Buf, In<ELF64LE>::Plt->getVA()); + write64le(Buf, InX::Plt->getVA()); } // Page(Expr) is the page address of the expression Expr, defined @@ -1392,8 +1384,8 @@ void AArch64TargetInfo::writePltHeader(uint8_t *Buf) const { }; memcpy(Buf, PltData, sizeof(PltData)); - uint64_t Got = In<ELF64LE>::GotPlt->getVA(); - uint64_t Plt = In<ELF64LE>::Plt->getVA(); + uint64_t Got = InX::GotPlt->getVA(); + uint64_t Plt = InX::Plt->getVA(); relocateOne(Buf + 4, R_AARCH64_ADR_PREL_PG_HI21, getAArch64Page(Got + 16) - getAArch64Page(Plt + 4)); relocateOne(Buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, Got + 16); @@ -1746,7 +1738,7 @@ uint32_t ARMTargetInfo::getDynRel(uint32_t Type) const { } void ARMTargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const { - write32le(Buf, In<ELF32LE>::Plt->getVA()); + write32le(Buf, InX::Plt->getVA()); } void ARMTargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const { @@ -1763,15 +1755,15 @@ void ARMTargetInfo::writePltHeader(uint8_t *Buf) const { 0x00, 0x00, 0x00, 0x00, // L2: .word &(.got.plt) - L1 - 8 }; memcpy(Buf, PltData, sizeof(PltData)); - uint64_t GotPlt = In<ELF32LE>::GotPlt->getVA(); - uint64_t L1 = In<ELF32LE>::Plt->getVA() + 8; + uint64_t GotPlt = InX::GotPlt->getVA(); + uint64_t L1 = InX::Plt->getVA() + 8; write32le(Buf + 16, GotPlt - L1 - 8); } void ARMTargetInfo::addPltHeaderSymbols(InputSectionBase *ISD) const { auto *IS = cast<InputSection>(ISD); - addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, 0, 0, IS); - addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, 16, 0, IS); + addSyntheticLocal("$a", STT_NOTYPE, 0, 0, IS); + addSyntheticLocal("$d", STT_NOTYPE, 16, 0, IS); } void ARMTargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, @@ -1793,8 +1785,8 @@ void ARMTargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, void ARMTargetInfo::addPltSymbols(InputSectionBase *ISD, uint64_t Off) const { auto *IS = cast<InputSection>(ISD); - addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, Off, 0, IS); - addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, Off + 12, 0, IS); + addSyntheticLocal("$a", STT_NOTYPE, Off, 0, IS); + addSyntheticLocal("$d", STT_NOTYPE, Off + 12, 0, IS); } bool ARMTargetInfo::needsThunk(RelExpr Expr, uint32_t RelocType, @@ -1874,7 +1866,8 @@ void ARMTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type, // BLX (always unconditional) instruction to an ARM Target, select an // unconditional BL. write32le(Loc, 0xeb000000 | (read32le(Loc) & 0x00ffffff)); - // fall through as BL encoding is shared with B + // fall through as BL encoding is shared with B + LLVM_FALLTHROUGH; case R_ARM_JUMP24: case R_ARM_PC24: case R_ARM_PLT32: @@ -1908,7 +1901,8 @@ void ARMTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type, } // Bit 12 is 0 for BLX, 1 for BL write16le(Loc + 2, (read16le(Loc + 2) & ~0x1000) | (Val & 1) << 12); - // Fall through as rest of encoding is the same as B.W + // Fall through as rest of encoding is the same as B.W + LLVM_FALLTHROUGH; case R_ARM_THM_JUMP24: // Encoding B T4, BL T1, BLX T2: Val = S:I1:I2:imm10:imm11:0 // FIXME: Use of I1 and I2 require v6T2ops @@ -2132,7 +2126,7 @@ uint32_t MipsTargetInfo<ELFT>::getDynRel(uint32_t Type) const { template <class ELFT> void MipsTargetInfo<ELFT>::writeGotPlt(uint8_t *Buf, const SymbolBody &) const { - write32<ELFT::TargetEndianness>(Buf, In<ELFT>::Plt->getVA()); + write32<ELFT::TargetEndianness>(Buf, InX::Plt->getVA()); } template <endianness E, uint8_t BSIZE, uint8_t SHIFT> @@ -2201,7 +2195,7 @@ void MipsTargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const { write32<E>(Buf + 24, 0x0320f809); // jalr $25 write32<E>(Buf + 28, 0x2718fffe); // subu $24, $24, 2 - uint64_t GotPlt = In<ELFT>::GotPlt->getVA(); + uint64_t GotPlt = InX::GotPlt->getVA(); writeMipsHi16<E>(Buf, GotPlt); writeMipsLo16<E>(Buf + 4, GotPlt); writeMipsLo16<E>(Buf + 8, GotPlt); diff --git a/contrib/llvm/tools/lld/ELF/Threads.h b/contrib/llvm/tools/lld/ELF/Threads.h index 897432e69f8e..e01afd4d3fc9 100644 --- a/contrib/llvm/tools/lld/ELF/Threads.h +++ b/contrib/llvm/tools/lld/ELF/Threads.h @@ -61,8 +61,7 @@ #include "Config.h" -#include "lld/Core/Parallel.h" -#include <algorithm> +#include "llvm/Support/Parallel.h" #include <functional> namespace lld { @@ -71,19 +70,17 @@ namespace elf { template <class IterTy, class FuncTy> void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn) { if (Config->Threads) - parallel_for_each(Begin, End, Fn); + for_each(llvm::parallel::par, Begin, End, Fn); else - std::for_each(Begin, End, Fn); + for_each(llvm::parallel::seq, Begin, End, Fn); } -inline void parallelFor(size_t Begin, size_t End, - std::function<void(size_t)> Fn) { - if (Config->Threads) { - parallel_for(Begin, End, Fn); - } else { - for (size_t I = Begin; I < End; ++I) - Fn(I); - } +inline void parallelForEachN(size_t Begin, size_t End, + std::function<void(size_t)> Fn) { + if (Config->Threads) + for_each_n(llvm::parallel::par, Begin, End, Fn); + else + for_each_n(llvm::parallel::seq, Begin, End, Fn); } } } diff --git a/contrib/llvm/tools/lld/ELF/Thunks.cpp b/contrib/llvm/tools/lld/ELF/Thunks.cpp index 307ca5df2288..80ea69663c01 100644 --- a/contrib/llvm/tools/lld/ELF/Thunks.cpp +++ b/contrib/llvm/tools/lld/ELF/Thunks.cpp @@ -124,10 +124,10 @@ void ARMV7ABSLongThunk<ELFT>::writeTo(uint8_t *Buf, ThunkSection &IS) const { template <class ELFT> void ARMV7ABSLongThunk<ELFT>::addSymbols(ThunkSection &IS) { - this->ThunkSym = addSyntheticLocal<ELFT>( + this->ThunkSym = addSyntheticLocal( Saver.save("__ARMv7ABSLongThunk_" + this->Destination.getName()), STT_FUNC, this->Offset, size(), &IS); - addSyntheticLocal<ELFT>("$a", STT_NOTYPE, this->Offset, 0, &IS); + addSyntheticLocal("$a", STT_NOTYPE, this->Offset, 0, &IS); } template <class ELFT> @@ -145,10 +145,10 @@ void ThumbV7ABSLongThunk<ELFT>::writeTo(uint8_t *Buf, ThunkSection &IS) const { template <class ELFT> void ThumbV7ABSLongThunk<ELFT>::addSymbols(ThunkSection &IS) { - this->ThunkSym = addSyntheticLocal<ELFT>( + this->ThunkSym = addSyntheticLocal( Saver.save("__Thumbv7ABSLongThunk_" + this->Destination.getName()), STT_FUNC, this->Offset, size(), &IS); - addSyntheticLocal<ELFT>("$t", STT_NOTYPE, this->Offset, 0, &IS); + addSyntheticLocal("$t", STT_NOTYPE, this->Offset, 0, &IS); } template <class ELFT> @@ -168,10 +168,10 @@ void ARMV7PILongThunk<ELFT>::writeTo(uint8_t *Buf, ThunkSection &IS) const { template <class ELFT> void ARMV7PILongThunk<ELFT>::addSymbols(ThunkSection &IS) { - this->ThunkSym = addSyntheticLocal<ELFT>( + this->ThunkSym = addSyntheticLocal( Saver.save("__ARMV7PILongThunk_" + this->Destination.getName()), STT_FUNC, this->Offset, size(), &IS); - addSyntheticLocal<ELFT>("$a", STT_NOTYPE, this->Offset, 0, &IS); + addSyntheticLocal("$a", STT_NOTYPE, this->Offset, 0, &IS); } template <class ELFT> @@ -191,10 +191,10 @@ void ThumbV7PILongThunk<ELFT>::writeTo(uint8_t *Buf, ThunkSection &IS) const { template <class ELFT> void ThumbV7PILongThunk<ELFT>::addSymbols(ThunkSection &IS) { - this->ThunkSym = addSyntheticLocal<ELFT>( + this->ThunkSym = addSyntheticLocal( Saver.save("__ThumbV7PILongThunk_" + this->Destination.getName()), STT_FUNC, this->Offset, size(), &IS); - addSyntheticLocal<ELFT>("$t", STT_NOTYPE, this->Offset, 0, &IS); + addSyntheticLocal("$t", STT_NOTYPE, this->Offset, 0, &IS); } // Write MIPS LA25 thunk code to call PIC function from the non-PIC one. @@ -212,7 +212,7 @@ void MipsThunk<ELFT>::writeTo(uint8_t *Buf, ThunkSection &) const { } template <class ELFT> void MipsThunk<ELFT>::addSymbols(ThunkSection &IS) { - this->ThunkSym = addSyntheticLocal<ELFT>( + this->ThunkSym = addSyntheticLocal( Saver.save("__LA25Thunk_" + this->Destination.getName()), STT_FUNC, this->Offset, size(), &IS); } diff --git a/contrib/llvm/tools/lld/ELF/Writer.cpp b/contrib/llvm/tools/lld/ELF/Writer.cpp index 96e4501754cf..35778f9c16c3 100644 --- a/contrib/llvm/tools/lld/ELF/Writer.cpp +++ b/contrib/llvm/tools/lld/ELF/Writer.cpp @@ -164,11 +164,10 @@ static void combineMergableSections() { uint64_t Flags = MS->Flags & ~(uint64_t)(SHF_GROUP | SHF_COMPRESSED); uint32_t Alignment = std::max<uint32_t>(MS->Alignment, MS->Entsize); - auto I = - llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { - return Sec->Name == OutsecName && Sec->Flags == Flags && - Sec->Alignment == Alignment; - }); + auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { + return Sec->Name == OutsecName && Sec->Flags == Flags && + Sec->Alignment == Alignment; + }); if (I == MergeSections.end()) { MergeSyntheticSection *Syn = make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment); @@ -312,11 +311,11 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); }; - In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true); - In<ELFT>::Dynamic = make<DynamicSection<ELFT>>(); + InX::DynStrTab = make<StringTableSection>(".dynstr", true); + InX::Dynamic = make<DynamicSection<ELFT>>(); In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>( Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc); - In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false); + InX::ShStrTab = make<StringTableSection>(".shstrtab", false); Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC); Out::ElfHeader->Size = sizeof(Elf_Ehdr); @@ -324,41 +323,41 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { Out::ProgramHeaders->updateAlignment(Config->Wordsize); if (needsInterpSection<ELFT>()) { - In<ELFT>::Interp = createInterpSection(); - Add(In<ELFT>::Interp); + InX::Interp = createInterpSection(); + Add(InX::Interp); } else { - In<ELFT>::Interp = nullptr; + InX::Interp = nullptr; } if (!Config->Relocatable) Add(createCommentSection<ELFT>()); if (Config->Strip != StripPolicy::All) { - In<ELFT>::StrTab = make<StringTableSection>(".strtab", false); - In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab); + InX::StrTab = make<StringTableSection>(".strtab", false); + InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab); } if (Config->BuildId != BuildIdKind::None) { - In<ELFT>::BuildId = make<BuildIdSection>(); - Add(In<ELFT>::BuildId); + InX::BuildId = make<BuildIdSection>(); + Add(InX::BuildId); } - In<ELFT>::Common = createCommonSection<ELFT>(); - if (In<ELFT>::Common) + InX::Common = createCommonSection<ELFT>(); + if (InX::Common) Add(InX::Common); - In<ELFT>::Bss = make<BssSection>(".bss"); - Add(In<ELFT>::Bss); - In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro"); - Add(In<ELFT>::BssRelRo); + InX::Bss = make<BssSection>(".bss"); + Add(InX::Bss); + InX::BssRelRo = make<BssSection>(".bss.rel.ro"); + Add(InX::BssRelRo); // Add MIPS-specific sections. bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() || Config->Pic || Config->ExportDynamic; if (Config->EMachine == EM_MIPS) { if (!Config->Shared && HasDynSymTab) { - In<ELFT>::MipsRldMap = make<MipsRldMapSection>(); - Add(In<ELFT>::MipsRldMap); + InX::MipsRldMap = make<MipsRldMapSection>(); + Add(InX::MipsRldMap); } if (auto *Sec = MipsAbiFlagsSection<ELFT>::create()) Add(Sec); @@ -369,8 +368,8 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { } if (HasDynSymTab) { - In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab); - Add(In<ELFT>::DynSymTab); + InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab); + Add(InX::DynSymTab); In<ELFT>::VerSym = make<VersionTableSection<ELFT>>(); Add(In<ELFT>::VerSym); @@ -384,8 +383,8 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { Add(In<ELFT>::VerNeed); if (Config->GnuHash) { - In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>(); - Add(In<ELFT>::GnuHashTab); + InX::GnuHashTab = make<GnuHashTableSection>(); + Add(InX::GnuHashTab); } if (Config->SysvHash) { @@ -393,29 +392,29 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { Add(In<ELFT>::HashTab); } - Add(In<ELFT>::Dynamic); - Add(In<ELFT>::DynStrTab); + Add(InX::Dynamic); + Add(InX::DynStrTab); Add(In<ELFT>::RelaDyn); } // Add .got. MIPS' .got is so different from the other archs, // it has its own class. if (Config->EMachine == EM_MIPS) { - In<ELFT>::MipsGot = make<MipsGotSection>(); - Add(In<ELFT>::MipsGot); + InX::MipsGot = make<MipsGotSection>(); + Add(InX::MipsGot); } else { - In<ELFT>::Got = make<GotSection<ELFT>>(); - Add(In<ELFT>::Got); + InX::Got = make<GotSection<ELFT>>(); + Add(InX::Got); } - In<ELFT>::GotPlt = make<GotPltSection>(); - Add(In<ELFT>::GotPlt); - In<ELFT>::IgotPlt = make<IgotPltSection>(); - Add(In<ELFT>::IgotPlt); + InX::GotPlt = make<GotPltSection>(); + Add(InX::GotPlt); + InX::IgotPlt = make<IgotPltSection>(); + Add(InX::IgotPlt); if (Config->GdbIndex) { - In<ELFT>::GdbIndex = make<GdbIndexSection>(); - Add(In<ELFT>::GdbIndex); + InX::GdbIndex = make<GdbIndexSection>(); + Add(InX::GdbIndex); } // We always need to add rel[a].plt to output if it has entries. @@ -431,10 +430,10 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { false /*Sort*/); Add(In<ELFT>::RelaIplt); - In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize); - Add(In<ELFT>::Plt); - In<ELFT>::Iplt = make<PltSection>(0); - Add(In<ELFT>::Iplt); + InX::Plt = make<PltSection>(Target->PltHeaderSize); + Add(InX::Plt); + InX::Iplt = make<PltSection>(0); + Add(InX::Iplt); if (!Config->Relocatable) { if (Config->EhFrameHdr) { @@ -445,11 +444,11 @@ template <class ELFT> void Writer<ELFT>::createSyntheticSections() { Add(In<ELFT>::EhFrame); } - if (In<ELFT>::SymTab) - Add(In<ELFT>::SymTab); - Add(In<ELFT>::ShStrTab); - if (In<ELFT>::StrTab) - Add(In<ELFT>::StrTab); + if (InX::SymTab) + Add(InX::SymTab); + Add(InX::ShStrTab); + if (InX::StrTab) + Add(InX::StrTab); } static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName, @@ -504,7 +503,7 @@ static bool includeInSymtab(const SymbolBody &B) { // Local symbols are not in the linker's symbol table. This function scans // each object file's symbol table to copy local symbols to the output. template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { - if (!In<ELFT>::SymTab) + if (!InX::SymTab) return; for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) { for (SymbolBody *B : F->getLocalSymbols()) { @@ -522,7 +521,7 @@ template <class ELFT> void Writer<ELFT>::copyLocalSymbols() { SectionBase *Sec = DR->Section; if (!shouldKeepInSymtab(Sec, B->getName(), *B)) continue; - In<ELFT>::SymTab->addSymbol(B); + InX::SymTab->addSymbol(B); } } } @@ -542,43 +541,17 @@ template <class ELFT> void Writer<ELFT>::addSectionSymbols() { auto *Sym = make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION, /*Value=*/0, /*Size=*/0, IS, nullptr); - In<ELFT>::SymTab->addSymbol(Sym); + InX::SymTab->addSymbol(Sym); } } -// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that -// we would like to make sure appear is a specific order to maximize their -// coverage by a single signed 16-bit offset from the TOC base pointer. -// Conversely, the special .tocbss section should be first among all SHT_NOBITS -// sections. This will put it next to the loaded special PPC64 sections (and, -// thus, within reach of the TOC base pointer). -static int getPPC64SectionRank(StringRef SectionName) { - return StringSwitch<int>(SectionName) - .Case(".tocbss", 0) - .Case(".branch_lt", 2) - .Case(".toc", 3) - .Case(".toc1", 4) - .Case(".opd", 5) - .Default(1); -} - -// All sections with SHF_MIPS_GPREL flag should be grouped together -// because data in these sections is addressable with a gp relative address. -static int getMipsSectionRank(const OutputSection *S) { - if ((S->Flags & SHF_MIPS_GPREL) == 0) - return 0; - if (S->Name == ".got") - return 1; - return 2; -} - // Today's loaders have a feature to make segments read-only after // processing dynamic relocations to enhance security. PT_GNU_RELRO // is defined for that. // // This function returns true if a section needs to be put into a // PT_GNU_RELRO segment. -template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) { +bool elf::isRelroSection(const OutputSection *Sec) { if (!Config->ZRelro) return false; @@ -613,27 +586,27 @@ template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) { // .got contains pointers to external symbols. They are resolved by // the dynamic linker when a module is loaded into memory, and after // that they are not expected to change. So, it can be in RELRO. - if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec) + if (InX::Got && Sec == InX::Got->OutSec) return true; // .got.plt contains pointers to external function symbols. They are // by default resolved lazily, so we usually cannot put it into RELRO. // However, if "-z now" is given, the lazy symbol resolution is // disabled, which enables us to put it into RELRO. - if (Sec == In<ELFT>::GotPlt->OutSec) + if (Sec == InX::GotPlt->OutSec) return Config->ZNow; // .dynamic section contains data for the dynamic linker, and // there's no need to write to it at runtime, so it's better to put // it into RELRO. - if (Sec == In<ELFT>::Dynamic->OutSec) + if (Sec == InX::Dynamic->OutSec) return true; // .bss.rel.ro is used for copy relocations for read-only symbols. // Since the dynamic linker needs to process copy relocations, the // section cannot be read-only, but once initialized, they shouldn't // change. - if (Sec == In<ELFT>::BssRelRo->OutSec) + if (Sec == InX::BssRelRo->OutSec) return true; // Sections with some special names are put into RELRO. This is a @@ -645,105 +618,149 @@ template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) { S == ".eh_frame" || S == ".openbsd.randomdata"; } -template <class ELFT> -static bool compareSectionsNonScript(const OutputSection *A, - const OutputSection *B) { +// We compute a rank for each section. The rank indicates where the +// section should be placed in the file. Instead of using simple +// numbers (0,1,2...), we use a series of flags. One for each decision +// point when placing the section. +// Using flags has two key properties: +// * It is easy to check if a give branch was taken. +// * It is easy two see how similar two ranks are (see getRankProximity). +enum RankFlags { + RF_NOT_ADDR_SET = 1 << 16, + RF_NOT_INTERP = 1 << 15, + RF_NOT_ALLOC = 1 << 14, + RF_WRITE = 1 << 13, + RF_EXEC = 1 << 12, + RF_NON_TLS_BSS = 1 << 11, + RF_NON_TLS_BSS_RO = 1 << 10, + RF_NOT_TLS = 1 << 9, + RF_BSS = 1 << 8, + RF_PPC_NOT_TOCBSS = 1 << 7, + RF_PPC_OPD = 1 << 6, + RF_PPC_TOCL = 1 << 5, + RF_PPC_TOC = 1 << 4, + RF_PPC_BRANCH_LT = 1 << 3, + RF_MIPS_GPREL = 1 << 2, + RF_MIPS_NOT_GOT = 1 << 1 +}; + +static unsigned getSectionRank(const OutputSection *Sec) { + unsigned Rank = 0; + + // We want to put section specified by -T option first, so we + // can start assigning VA starting from them later. + if (Config->SectionStartMap.count(Sec->Name)) + return Rank; + Rank |= RF_NOT_ADDR_SET; + // Put .interp first because some loaders want to see that section // on the first page of the executable file when loaded into memory. - bool AIsInterp = A->Name == ".interp"; - bool BIsInterp = B->Name == ".interp"; - if (AIsInterp != BIsInterp) - return AIsInterp; + if (Sec->Name == ".interp") + return Rank; + Rank |= RF_NOT_INTERP; // Allocatable sections go first to reduce the total PT_LOAD size and // so debug info doesn't change addresses in actual code. - bool AIsAlloc = A->Flags & SHF_ALLOC; - bool BIsAlloc = B->Flags & SHF_ALLOC; - if (AIsAlloc != BIsAlloc) - return AIsAlloc; - - // We don't have any special requirements for the relative order of two non - // allocatable sections. - if (!AIsAlloc) - return false; - - // We want to put section specified by -T option first, so we - // can start assigning VA starting from them later. - auto AAddrSetI = Config->SectionStartMap.find(A->Name); - auto BAddrSetI = Config->SectionStartMap.find(B->Name); - bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end(); - bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end(); - if (AHasAddrSet != BHasAddrSet) - return AHasAddrSet; - if (AHasAddrSet) - return AAddrSetI->second < BAddrSetI->second; + if (!(Sec->Flags & SHF_ALLOC)) + return Rank | RF_NOT_ALLOC; // We want the read only sections first so that they go in the PT_LOAD // covering the program headers at the start of the file. - bool AIsWritable = A->Flags & SHF_WRITE; - bool BIsWritable = B->Flags & SHF_WRITE; - if (AIsWritable != BIsWritable) - return BIsWritable; + if (Sec->Flags & SHF_WRITE) + Rank |= RF_WRITE; - if (!Config->SingleRoRx) { + if (Sec->Flags & SHF_EXECINSTR) { // For a corresponding reason, put non exec sections first (the program // header PT_LOAD is not executable). // We only do that if we are not using linker scripts, since with linker // scripts ro and rx sections are in the same PT_LOAD, so their relative // order is not important. The same applies for -no-rosegment. - bool AIsExec = A->Flags & SHF_EXECINSTR; - bool BIsExec = B->Flags & SHF_EXECINSTR; - if (AIsExec != BIsExec) - return BIsExec; + if ((Rank & RF_WRITE) || !Config->SingleRoRx) + Rank |= RF_EXEC; } // If we got here we know that both A and B are in the same PT_LOAD. - bool AIsTls = A->Flags & SHF_TLS; - bool BIsTls = B->Flags & SHF_TLS; - bool AIsNoBits = A->Type == SHT_NOBITS; - bool BIsNoBits = B->Type == SHT_NOBITS; + bool IsTls = Sec->Flags & SHF_TLS; + bool IsNoBits = Sec->Type == SHT_NOBITS; // The first requirement we have is to put (non-TLS) nobits sections last. The // reason is that the only thing the dynamic linker will see about them is a // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the // PT_LOAD, so that has to correspond to the nobits sections. - bool AIsNonTlsNoBits = AIsNoBits && !AIsTls; - bool BIsNonTlsNoBits = BIsNoBits && !BIsTls; - if (AIsNonTlsNoBits != BIsNonTlsNoBits) - return BIsNonTlsNoBits; + bool IsNonTlsNoBits = IsNoBits && !IsTls; + if (IsNonTlsNoBits) + Rank |= RF_NON_TLS_BSS; // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo // sections after r/w ones, so that the RelRo sections are contiguous. - bool AIsRelRo = isRelroSection<ELFT>(A); - bool BIsRelRo = isRelroSection<ELFT>(B); - if (AIsRelRo != BIsRelRo) - return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo; + bool IsRelRo = isRelroSection(Sec); + if (IsNonTlsNoBits && !IsRelRo) + Rank |= RF_NON_TLS_BSS_RO; + if (!IsNonTlsNoBits && IsRelRo) + Rank |= RF_NON_TLS_BSS_RO; // The TLS initialization block needs to be a single contiguous block in a R/W // PT_LOAD, so stick TLS sections directly before the other RelRo R/W // sections. The TLS NOBITS sections are placed here as they don't take up // virtual address space in the PT_LOAD. - if (AIsTls != BIsTls) - return AIsTls; + if (!IsTls) + Rank |= RF_NOT_TLS; // Within the TLS initialization block, the non-nobits sections need to appear // first. - if (AIsNoBits != BIsNoBits) - return BIsNoBits; + if (IsNoBits) + Rank |= RF_BSS; + + // // Some architectures have additional ordering restrictions for sections + // // within the same PT_LOAD. + if (Config->EMachine == EM_PPC64) { + // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections + // that we would like to make sure appear is a specific order to maximize + // their coverage by a single signed 16-bit offset from the TOC base + // pointer. Conversely, the special .tocbss section should be first among + // all SHT_NOBITS sections. This will put it next to the loaded special + // PPC64 sections (and, thus, within reach of the TOC base pointer). + StringRef Name = Sec->Name; + if (Name != ".tocbss") + Rank |= RF_PPC_NOT_TOCBSS; + + if (Name == ".opd") + Rank |= RF_PPC_OPD; + + if (Name == ".toc1") + Rank |= RF_PPC_TOCL; + + if (Name == ".toc") + Rank |= RF_PPC_TOC; + + if (Name == ".branch_lt") + Rank |= RF_PPC_BRANCH_LT; + } + if (Config->EMachine == EM_MIPS) { + // All sections with SHF_MIPS_GPREL flag should be grouped together + // because data in these sections is addressable with a gp relative address. + if (Sec->Flags & SHF_MIPS_GPREL) + Rank |= RF_MIPS_GPREL; - // Some architectures have additional ordering restrictions for sections - // within the same PT_LOAD. - if (Config->EMachine == EM_PPC64) - return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name); - if (Config->EMachine == EM_MIPS) - return getMipsSectionRank(A) < getMipsSectionRank(B); + if (Sec->Name != ".got") + Rank |= RF_MIPS_NOT_GOT; + } + return Rank; +} + +static bool compareSectionsNonScript(const OutputSection *A, + const OutputSection *B) { + if (A->SortRank != B->SortRank) + return A->SortRank < B->SortRank; + if (!(A->SortRank & RF_NOT_ADDR_SET)) + return Config->SectionStartMap.lookup(A->Name) < + Config->SectionStartMap.lookup(B->Name); return false; } // Output section ordering is determined by this function. -template <class ELFT> static bool compareSections(const OutputSection *A, const OutputSection *B) { // For now, put sections mentioned in a linker script // first. Sections not on linker script will have a SectionIndex of @@ -753,7 +770,7 @@ static bool compareSections(const OutputSection *A, const OutputSection *B) { if (AIndex != BIndex) return AIndex < BIndex; - return compareSectionsNonScript<ELFT>(A, B); + return compareSectionsNonScript(A, B); } // Program header entry @@ -802,7 +819,7 @@ addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val, // need these symbols, since IRELATIVE relocs are resolved through GOT // and PLT. For details, see http://www.airs.com/blog/archives/403. template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() { - if (In<ELFT>::DynSymTab) + if (InX::DynSymTab) return; StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start"; addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK); @@ -855,16 +872,19 @@ template <class ELFT> void Writer<ELFT>::addReservedSymbols() { // static linking the linker is required to optimize away any references to // __tls_get_addr, so it's not defined anywhere. Create a hidden definition // to avoid the undefined symbol error. - if (!In<ELFT>::DynSymTab) + if (!InX::DynSymTab) Symtab<ELFT>::X->addIgnored("__tls_get_addr"); + // __ehdr_start is the location of ELF file headers. Note that we define + // this symbol unconditionally even when using a linker script, which + // differs from the behavior implemented by GNU linker which only define + // this symbol if ELF headers are in the memory mapped segment. + addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN); + // If linker script do layout we do not need to create any standart symbols. if (Script->Opt.HasSections) return; - // __ehdr_start is the location of ELF file headers. - addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN); - auto Add = [](StringRef S) { return addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT); }; @@ -960,18 +980,36 @@ template <class ELFT> void Writer<ELFT>::createSections() { Sec->assignOffsets(); } -static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) { - if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC)) - return false; - - bool S1IsWrite = S1.Flags & SHF_WRITE; - bool S2IsWrite = S2.Flags & SHF_WRITE; - if (S1IsWrite != S2IsWrite) - return false; +// We want to find how similar two ranks are. +// The more branches in getSectionRank that match, the more similar they are. +// Since each branch corresponds to a bit flag, we can just use +// countLeadingZeros. +static unsigned getRankProximity(OutputSection *A, OutputSection *B) { + return countLeadingZeros(A->SortRank ^ B->SortRank); +} - if (!S1IsWrite) - return true; // RO and RX share a PT_LOAD with linker scripts. - return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR); +// We want to place orphan sections so that they share as much +// characteristics with their neighbors as possible. For example, if +// both are rw, or both are tls. +template <typename ELFT> +static std::vector<OutputSection *>::iterator +findOrphanPos(std::vector<OutputSection *>::iterator B, + std::vector<OutputSection *>::iterator E) { + OutputSection *Sec = *E; + + // Find the first element that has as close a rank as possible. + auto I = std::max_element(B, E, [=](OutputSection *A, OutputSection *B) { + return getRankProximity(Sec, A) < getRankProximity(Sec, B); + }); + if (I == E) + return E; + + // Consider all existing sections with the same proximity. + unsigned Proximity = getRankProximity(Sec, *I); + while (I != E && getRankProximity(Sec, *I) == Proximity && + Sec->SortRank >= (*I)->SortRank) + ++I; + return I; } template <class ELFT> void Writer<ELFT>::sortSections() { @@ -979,12 +1017,18 @@ template <class ELFT> void Writer<ELFT>::sortSections() { // relative order for SHF_LINK_ORDER sections. if (Config->Relocatable) return; + + if (Script->Opt.HasSections) + Script->adjustSectionsBeforeSorting(); + + for (OutputSection *Sec : OutputSections) + Sec->SortRank = getSectionRank(Sec); + if (!Script->Opt.HasSections) { std::stable_sort(OutputSections.begin(), OutputSections.end(), - compareSectionsNonScript<ELFT>); + compareSectionsNonScript); return; } - Script->adjustSectionsBeforeSorting(); // The order of the sections in the script is arbitrary and may not agree with // compareSectionsNonScript. This means that we cannot easily define a @@ -1004,14 +1048,13 @@ template <class ELFT> void Writer<ELFT>::sortSections() { // .d (ro) # not in script // // The way we define an order then is: - // * First put script sections at the start and sort the script and - // non-script sections independently. + // * First put script sections at the start and sort the script sections. // * Move each non-script section to its preferred position. We try // to put each section in the last position where it it can share // a PT_LOAD. std::stable_sort(OutputSections.begin(), OutputSections.end(), - compareSections<ELFT>); + compareSections); auto I = OutputSections.begin(); auto E = OutputSections.end(); @@ -1019,31 +1062,16 @@ template <class ELFT> void Writer<ELFT>::sortSections() { std::find_if(OutputSections.begin(), E, [](OutputSection *S) { return S->SectionIndex == INT_MAX; }); while (NonScriptI != E) { - auto BestPos = std::max_element( - I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) { - bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A); - bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B); - if (ACanSharePtLoad != BCanSharePtLoad) - return BCanSharePtLoad; - - bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A); - bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B); - if (ACmp != BCmp) - return BCmp; // FIXME: missing test - - size_t PosA = &A - &OutputSections[0]; - size_t PosB = &B - &OutputSections[0]; - return ACmp ? PosA > PosB : PosA < PosB; - }); - - // max_element only returns NonScriptI if the range is empty. If the range - // is not empty we should consider moving the the element forward one - // position. - if (BestPos != NonScriptI && - !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos)) - ++BestPos; - std::rotate(BestPos, NonScriptI, NonScriptI + 1); - ++NonScriptI; + auto Pos = findOrphanPos<ELFT>(I, NonScriptI); + + // As an optimization, find all sections with the same sort rank + // and insert them with one rotate. + unsigned Rank = (*NonScriptI)->SortRank; + auto End = std::find_if(NonScriptI + 1, E, [=](OutputSection *Sec) { + return Sec->SortRank != Rank; + }); + std::rotate(Pos, NonScriptI, End); + NonScriptI = End; } Script->adjustSectionsAfterSorting(); @@ -1103,8 +1131,8 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { // It should be okay as no one seems to care about the type. // Even the author of gold doesn't remember why gold behaves that way. // https://sourceware.org/ml/binutils/2002-03/msg00360.html - if (In<ELFT>::DynSymTab) - addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0); + if (InX::DynSymTab) + addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0); // Define __rel[a]_iplt_{start,end} symbols if needed. addRelIpltSymbols(); @@ -1119,10 +1147,10 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { // we can correctly decide if a dynamic relocation is needed. forEachRelSec(scanRelocations<ELFT>); - if (In<ELFT>::Plt && !In<ELFT>::Plt->empty()) - In<ELFT>::Plt->addSymbols(); - if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty()) - In<ELFT>::Iplt->addSymbols(); + if (InX::Plt && !InX::Plt->empty()) + InX::Plt->addSymbols(); + if (InX::Iplt && !InX::Iplt->empty()) + InX::Iplt->addSymbols(); // Now that we have defined all possible global symbols including linker- // synthesized ones. Visit all symbols to give the finishing touches. @@ -1131,11 +1159,11 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { if (!includeInSymtab(*Body)) continue; - if (In<ELFT>::SymTab) - In<ELFT>::SymTab->addSymbol(Body); + if (InX::SymTab) + InX::SymTab->addSymbol(Body); - if (In<ELFT>::DynSymTab && S->includeInDynsym()) { - In<ELFT>::DynSymTab->addSymbol(Body); + if (InX::DynSymTab && S->includeInDynsym()) { + InX::DynSymTab->addSymbol(Body); if (auto *SS = dyn_cast<SharedSymbol>(Body)) if (cast<SharedFile<ELFT>>(SS->File)->isNeeded()) In<ELFT>::VerNeed->addSymbol(SS); @@ -1161,7 +1189,7 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { unsigned I = 1; for (OutputSection *Sec : OutputSections) { Sec->SectionIndex = I++; - Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name); + Sec->ShName = InX::ShStrTab->addString(Sec->Name); } // Binary and relocatable output does not have PHDRS. @@ -1175,15 +1203,14 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { // Dynamic section must be the last one in this list and dynamic // symbol table section (DynSymTab) must be the first one. - applySynthetic({In<ELFT>::DynSymTab, In<ELFT>::Bss, In<ELFT>::BssRelRo, - In<ELFT>::GnuHashTab, In<ELFT>::HashTab, In<ELFT>::SymTab, - In<ELFT>::ShStrTab, In<ELFT>::StrTab, In<ELFT>::VerDef, - In<ELFT>::DynStrTab, In<ELFT>::GdbIndex, In<ELFT>::Got, - In<ELFT>::MipsGot, In<ELFT>::IgotPlt, In<ELFT>::GotPlt, - In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt, - In<ELFT>::Plt, In<ELFT>::Iplt, In<ELFT>::Plt, - In<ELFT>::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed, - In<ELFT>::Dynamic}, + applySynthetic({InX::DynSymTab, InX::Bss, InX::BssRelRo, + InX::GnuHashTab, In<ELFT>::HashTab, InX::SymTab, + InX::ShStrTab, InX::StrTab, In<ELFT>::VerDef, + InX::DynStrTab, InX::GdbIndex, InX::Got, + InX::MipsGot, InX::IgotPlt, InX::GotPlt, + In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt, + InX::Plt, InX::Iplt, In<ELFT>::EhFrameHdr, + In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic}, [](SyntheticSection *SS) { SS->finalizeContents(); }); // Some architectures use small displacements for jump instructions. @@ -1198,7 +1225,7 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { // when no more Thunks are added ThunkCreator<ELFT> TC; if (TC.createThunks(OutputSections)) - applySynthetic({In<ELFT>::MipsGot}, + applySynthetic({InX::MipsGot}, [](SyntheticSection *SS) { SS->updateAllocSize(); }); } // Fill other section headers. The dynamic table is finalized @@ -1214,7 +1241,7 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() { [](OutputSection *S) { S->maybeCompress<ELFT>(); }); // createThunks may have added local symbols to the static symbol table - applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab}, + applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab}, [](SyntheticSection *SS) { SS->postThunkContents(); }); } @@ -1332,7 +1359,7 @@ template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() { // different flags or is loaded at a discontiguous address using AT linker // script command. uint64_t NewFlags = computeFlags(Sec->getPhdrFlags()); - if (Script->hasLMA(Sec->Name) || Flags != NewFlags) { + if (Script->hasLMA(Sec) || Flags != NewFlags) { Load = AddHdr(PT_LOAD, NewFlags); Flags = NewFlags; } @@ -1349,15 +1376,15 @@ template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() { Ret.push_back(std::move(TlsHdr)); // Add an entry for .dynamic. - if (In<ELFT>::DynSymTab) - AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags()) - ->add(In<ELFT>::Dynamic->OutSec); + if (InX::DynSymTab) + AddHdr(PT_DYNAMIC, InX::Dynamic->OutSec->getPhdrFlags()) + ->add(InX::Dynamic->OutSec); // PT_GNU_RELRO includes all sections that should be marked as // read-only by dynamic linker after proccessing relocations. PhdrEntry RelRo(PT_GNU_RELRO, PF_R); for (OutputSection *Sec : OutputSections) - if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec)) + if (needsPtLoad(Sec) && isRelroSection(Sec)) RelRo.add(Sec); if (RelRo.First) Ret.push_back(std::move(RelRo)); @@ -1395,7 +1422,7 @@ template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() { PhdrEntry *Note = nullptr; for (OutputSection *Sec : OutputSections) { if (Sec->Type == SHT_NOTE) { - if (!Note || Script->hasLMA(Sec->Name)) + if (!Note || Script->hasLMA(Sec)) Note = AddHdr(PT_NOTE, PF_R); Note->add(Sec); } else { @@ -1542,7 +1569,7 @@ template <class ELFT> uint64_t Writer<ELFT>::getEntryAddr() { if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry)) return B->getVA(); uint64_t Addr; - if (!Config->Entry.getAsInteger(0, Addr)) + if (to_integer(Config->Entry, Addr)) return Addr; // Case 4 @@ -1644,7 +1671,7 @@ template <class ELFT> void Writer<ELFT>::writeHeader() { EHdr->e_phnum = Phdrs.size(); EHdr->e_shentsize = sizeof(Elf_Shdr); EHdr->e_shnum = OutputSections.size() + 1; - EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex; + EHdr->e_shstrndx = InX::ShStrTab->OutSec->SectionIndex; if (Config->EMachine == EM_ARM) // We don't currently use any features incompatible with EF_ARM_EABI_VER5, @@ -1738,21 +1765,16 @@ template <class ELFT> void Writer<ELFT>::writeSections() { } template <class ELFT> void Writer<ELFT>::writeBuildId() { - if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec) + if (!InX::BuildId || !InX::BuildId->OutSec) return; // Compute a hash of all sections of the output file. uint8_t *Start = Buffer->getBufferStart(); uint8_t *End = Start + FileSize; - In<ELFT>::BuildId->writeBuildId({Start, End}); + InX::BuildId->writeBuildId({Start, End}); } template void elf::writeResult<ELF32LE>(); template void elf::writeResult<ELF32BE>(); template void elf::writeResult<ELF64LE>(); template void elf::writeResult<ELF64BE>(); - -template bool elf::isRelroSection<ELF32LE>(const OutputSection *); -template bool elf::isRelroSection<ELF32BE>(const OutputSection *); -template bool elf::isRelroSection<ELF64LE>(const OutputSection *); -template bool elf::isRelroSection<ELF64BE>(const OutputSection *); diff --git a/contrib/llvm/tools/lld/ELF/Writer.h b/contrib/llvm/tools/lld/ELF/Writer.h index 8b965f7beddb..17fbda394a20 100644 --- a/contrib/llvm/tools/lld/ELF/Writer.h +++ b/contrib/llvm/tools/lld/ELF/Writer.h @@ -24,7 +24,7 @@ template <class ELFT> class ObjectFile; template <class ELFT> class SymbolTable; template <class ELFT> void writeResult(); template <class ELFT> void markLive(); -template <class ELFT> bool isRelroSection(const OutputSection *Sec); +bool isRelroSection(const OutputSection *Sec); // This describes a program header entry. // Each contains type, access flags and range of output sections that will be diff --git a/contrib/llvm/tools/lld/include/lld/Core/Parallel.h b/contrib/llvm/tools/lld/include/lld/Core/Parallel.h deleted file mode 100644 index 58fa87e85c51..000000000000 --- a/contrib/llvm/tools/lld/include/lld/Core/Parallel.h +++ /dev/null @@ -1,166 +0,0 @@ -//===- lld/Core/Parallel.h - Parallel utilities ---------------------------===// -// -// The LLVM Linker -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef LLD_CORE_PARALLEL_H -#define LLD_CORE_PARALLEL_H - -#include "lld/Core/LLVM.h" -#include "lld/Core/TaskGroup.h" -#include "llvm/Support/MathExtras.h" -#include "llvm/Config/llvm-config.h" - -#include <algorithm> - -#if defined(_MSC_VER) && LLVM_ENABLE_THREADS -#include <concrt.h> -#include <ppl.h> -#endif - -namespace lld { - -#if !LLVM_ENABLE_THREADS -template <class RandomAccessIterator, class Comparator> -void parallel_sort( - RandomAccessIterator Start, RandomAccessIterator End, - const Comparator &Comp = std::less< - typename std::iterator_traits<RandomAccessIterator>::value_type>()) { - std::sort(Start, End, Comp); -} -#elif defined(_MSC_VER) -// Use ppl parallel_sort on Windows. -template <class RandomAccessIterator, class Comparator> -void parallel_sort( - RandomAccessIterator Start, RandomAccessIterator End, - const Comparator &Comp = std::less< - typename std::iterator_traits<RandomAccessIterator>::value_type>()) { - concurrency::parallel_sort(Start, End, Comp); -} -#else -namespace detail { -const ptrdiff_t MinParallelSize = 1024; - -/// \brief Inclusive median. -template <class RandomAccessIterator, class Comparator> -RandomAccessIterator medianOf3(RandomAccessIterator Start, - RandomAccessIterator End, - const Comparator &Comp) { - RandomAccessIterator Mid = Start + (std::distance(Start, End) / 2); - return Comp(*Start, *(End - 1)) - ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start) - : End - 1) - : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid : End - 1) - : Start); -} - -template <class RandomAccessIterator, class Comparator> -void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIterator End, - const Comparator &Comp, TaskGroup &TG, size_t Depth) { - // Do a sequential sort for small inputs. - if (std::distance(Start, End) < detail::MinParallelSize || Depth == 0) { - std::sort(Start, End, Comp); - return; - } - - // Partition. - auto Pivot = medianOf3(Start, End, Comp); - // Move Pivot to End. - std::swap(*(End - 1), *Pivot); - Pivot = std::partition(Start, End - 1, [&Comp, End](decltype(*Start) V) { - return Comp(V, *(End - 1)); - }); - // Move Pivot to middle of partition. - std::swap(*Pivot, *(End - 1)); - - // Recurse. - TG.spawn([=, &Comp, &TG] { - parallel_quick_sort(Start, Pivot, Comp, TG, Depth - 1); - }); - parallel_quick_sort(Pivot + 1, End, Comp, TG, Depth - 1); -} -} - -template <class RandomAccessIterator, class Comparator> -void parallel_sort( - RandomAccessIterator Start, RandomAccessIterator End, - const Comparator &Comp = std::less< - typename std::iterator_traits<RandomAccessIterator>::value_type>()) { - TaskGroup TG; - detail::parallel_quick_sort(Start, End, Comp, TG, - llvm::Log2_64(std::distance(Start, End)) + 1); -} -#endif - -template <class T> void parallel_sort(T *Start, T *End) { - parallel_sort(Start, End, std::less<T>()); -} - -#if !LLVM_ENABLE_THREADS -template <class IterTy, class FuncTy> -void parallel_for_each(IterTy Begin, IterTy End, FuncTy Fn) { - std::for_each(Begin, End, Fn); -} - -template <class IndexTy, class FuncTy> -void parallel_for(IndexTy Begin, IndexTy End, FuncTy Fn) { - for (IndexTy I = Begin; I != End; ++I) - Fn(I); -} -#elif defined(_MSC_VER) -// Use ppl parallel_for_each on Windows. -template <class IterTy, class FuncTy> -void parallel_for_each(IterTy Begin, IterTy End, FuncTy Fn) { - concurrency::parallel_for_each(Begin, End, Fn); -} - -template <class IndexTy, class FuncTy> -void parallel_for(IndexTy Begin, IndexTy End, FuncTy Fn) { - concurrency::parallel_for(Begin, End, Fn); -} -#else -template <class IterTy, class FuncTy> -void parallel_for_each(IterTy Begin, IterTy End, FuncTy Fn) { - // TaskGroup has a relatively high overhead, so we want to reduce - // the number of spawn() calls. We'll create up to 1024 tasks here. - // (Note that 1024 is an arbitrary number. This code probably needs - // improving to take the number of available cores into account.) - ptrdiff_t TaskSize = std::distance(Begin, End) / 1024; - if (TaskSize == 0) - TaskSize = 1; - - TaskGroup TG; - while (TaskSize <= std::distance(Begin, End)) { - TG.spawn([=, &Fn] { std::for_each(Begin, Begin + TaskSize, Fn); }); - Begin += TaskSize; - } - TG.spawn([=, &Fn] { std::for_each(Begin, End, Fn); }); -} - -template <class IndexTy, class FuncTy> -void parallel_for(IndexTy Begin, IndexTy End, FuncTy Fn) { - ptrdiff_t TaskSize = (End - Begin) / 1024; - if (TaskSize == 0) - TaskSize = 1; - - TaskGroup TG; - IndexTy I = Begin; - for (; I + TaskSize < End; I += TaskSize) { - TG.spawn([=, &Fn] { - for (IndexTy J = I, E = I + TaskSize; J != E; ++J) - Fn(J); - }); - } - TG.spawn([=, &Fn] { - for (IndexTy J = I; J < End; ++J) - Fn(J); - }); -} -#endif -} // End namespace lld - -#endif // LLD_CORE_PARALLEL_H diff --git a/contrib/llvm/tools/lld/include/lld/Core/TaskGroup.h b/contrib/llvm/tools/lld/include/lld/Core/TaskGroup.h deleted file mode 100644 index 82e9122f4ae2..000000000000 --- a/contrib/llvm/tools/lld/include/lld/Core/TaskGroup.h +++ /dev/null @@ -1,65 +0,0 @@ -//===- lld/Core/TaskGroup.h - Task Group ----------------------------------===// -// -// The LLVM Linker -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#ifndef LLD_CORE_TASKGROUP_H -#define LLD_CORE_TASKGROUP_H - -#include "lld/Core/LLVM.h" - -#include <condition_variable> -#include <functional> -#include <mutex> - -namespace lld { -/// \brief Allows one or more threads to wait on a potentially unknown number of -/// events. -/// -/// A latch starts at \p count. inc() increments this, and dec() decrements it. -/// All calls to sync() will block while the count is not 0. -/// -/// Calling dec() on a Latch with a count of 0 has undefined behaivor. -class Latch { - uint32_t _count; - mutable std::mutex _condMut; - mutable std::condition_variable _cond; - -public: - explicit Latch(uint32_t count = 0) : _count(count) {} - ~Latch() { sync(); } - - void inc() { - std::unique_lock<std::mutex> lock(_condMut); - ++_count; - } - - void dec() { - std::unique_lock<std::mutex> lock(_condMut); - if (--_count == 0) - _cond.notify_all(); - } - - void sync() const { - std::unique_lock<std::mutex> lock(_condMut); - _cond.wait(lock, [&] { return _count == 0; }); - } -}; - -/// \brief Allows launching a number of tasks and waiting for them to finish -/// either explicitly via sync() or implicitly on destruction. -class TaskGroup { - Latch _latch; - -public: - void spawn(std::function<void()> f); - - void sync() const { _latch.sync(); } -}; -} - -#endif diff --git a/contrib/llvm/tools/lld/lib/Core/CMakeLists.txt b/contrib/llvm/tools/lld/lib/Core/CMakeLists.txt index cdd4e679ffa2..f2bf90509295 100644 --- a/contrib/llvm/tools/lld/lib/Core/CMakeLists.txt +++ b/contrib/llvm/tools/lld/lib/Core/CMakeLists.txt @@ -12,7 +12,6 @@ add_lld_library(lldCore Resolver.cpp SymbolTable.cpp TargetOptionsCommandFlags.cpp - TaskGroup.cpp Writer.cpp ADDITIONAL_HEADER_DIRS diff --git a/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/LayoutPass.cpp b/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/LayoutPass.cpp index 24dbf79d3e3b..7bca07eb16d6 100644 --- a/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/LayoutPass.cpp +++ b/contrib/llvm/tools/lld/lib/ReaderWriter/MachO/LayoutPass.cpp @@ -9,12 +9,12 @@ #include "LayoutPass.h" #include "lld/Core/Instrumentation.h" -#include "lld/Core/Parallel.h" #include "lld/Core/PassManager.h" #include "lld/ReaderWriter/MachOLinkingContext.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/Parallel.h" #include <algorithm> #include <set> #include <utility> @@ -461,10 +461,10 @@ llvm::Error LayoutPass::perform(SimpleFile &mergedFile) { }); std::vector<LayoutPass::SortKey> vec = decorate(atomRange); - parallel_sort(vec.begin(), vec.end(), - [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool { - return compareAtoms(l, r, _customSorter); - }); + sort(llvm::parallel::par, vec.begin(), vec.end(), + [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool { + return compareAtoms(l, r, _customSorter); + }); DEBUG(checkTransitivity(vec, _customSorter)); undecorate(atomRange, vec); diff --git a/contrib/llvm/tools/lldb/include/lldb/API/SBError.h b/contrib/llvm/tools/lldb/include/lldb/API/SBError.h index a3b1f87053ad..a099a9be271a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/API/SBError.h +++ b/contrib/llvm/tools/lldb/include/lldb/API/SBError.h @@ -68,18 +68,18 @@ protected: friend class SBBreakpoint; friend class SBBreakpointLocation; - lldb_private::Error *get(); + lldb_private::Status *get(); - lldb_private::Error *operator->(); + lldb_private::Status *operator->(); - const lldb_private::Error &operator*() const; + const lldb_private::Status &operator*() const; - lldb_private::Error &ref(); + lldb_private::Status &ref(); - void SetError(const lldb_private::Error &lldb_error); + void SetError(const lldb_private::Status &lldb_error); private: - std::unique_ptr<lldb_private::Error> m_opaque_ap; + std::unique_ptr<lldb_private::Status> m_opaque_ap; void CreateIfNeeded(); }; diff --git a/contrib/llvm/tools/lldb/include/lldb/API/SBPlatform.h b/contrib/llvm/tools/lldb/include/lldb/API/SBPlatform.h index 3f7e1acb74b5..952e31066319 100644 --- a/contrib/llvm/tools/lldb/include/lldb/API/SBPlatform.h +++ b/contrib/llvm/tools/lldb/include/lldb/API/SBPlatform.h @@ -156,7 +156,8 @@ protected: void SetSP(const lldb::PlatformSP &platform_sp); SBError ExecuteConnected( - const std::function<lldb_private::Error(const lldb::PlatformSP &)> &func); + const std::function<lldb_private::Status(const lldb::PlatformSP &)> + &func); lldb::PlatformSP m_opaque_sp; }; diff --git a/contrib/llvm/tools/lldb/include/lldb/API/SBTarget.h b/contrib/llvm/tools/lldb/include/lldb/API/SBTarget.h index 21341fbc27fa..62398fcd4b94 100644 --- a/contrib/llvm/tools/lldb/include/lldb/API/SBTarget.h +++ b/contrib/llvm/tools/lldb/include/lldb/API/SBTarget.h @@ -544,7 +544,7 @@ public: /// into this call /// /// @param[out] error - /// Error information is written here if the memory read fails. + /// Status information is written here if the memory read fails. /// /// @return /// The amount of data read in host bytes. diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h index 4a16df047ee3..408647c3b5da 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Breakpoint.h @@ -169,7 +169,7 @@ public: virtual bool EvaluatePrecondition(StoppointCallbackContext &context); - virtual Error ConfigurePrecondition(Args &options); + virtual Status ConfigurePrecondition(Args &options); virtual void GetDescription(Stream &stream, lldb::DescriptionLevel level); }; @@ -178,7 +178,7 @@ public: // Saving & restoring breakpoints: static lldb::BreakpointSP CreateFromStructuredData( - Target &target, StructuredData::ObjectSP &data_object_sp, Error &error); + Target &target, StructuredData::ObjectSP &data_object_sp, Status &error); static bool SerializedBreakpointMatchesNames(StructuredData::ObjectSP &bkpt_object_sp, @@ -613,7 +613,7 @@ public: lldb::SearchFilterSP GetSearchFilter() { return m_filter_sp; } - bool AddName(const char *new_name, Error &error); + bool AddName(llvm::StringRef new_name, Status &error); void RemoveName(const char *name_to_remove) { if (name_to_remove) diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointID.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointID.h index aa4add4cd665..57411b316317 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointID.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointID.h @@ -84,7 +84,7 @@ public: /// \b true if the name is a breakpoint name (as opposed to an ID or /// range) false otherwise. //------------------------------------------------------------------ - static bool StringIsBreakpointName(llvm::StringRef str, Error &error); + static bool StringIsBreakpointName(llvm::StringRef str, Status &error); //------------------------------------------------------------------ /// Takes a breakpoint ID and the breakpoint location id and returns diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointLocation.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointLocation.h index d0567ccf2e04..a1086aa3fe5f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointLocation.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointLocation.h @@ -161,7 +161,7 @@ public: //------------------------------------------------------------------ const char *GetConditionText(size_t *hash = nullptr) const; - bool ConditionSaysStop(ExecutionContext &exe_ctx, Error &error); + bool ConditionSaysStop(ExecutionContext &exe_ctx, Status &error); //------------------------------------------------------------------ /// Set the valid thread to be checked when the breakpoint is hit. diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h index 024e915908c0..4ed8469eba3d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointOptions.h @@ -50,7 +50,7 @@ public: static std::unique_ptr<CommandData> CreateFromStructuredData(const StructuredData::Dictionary &options_dict, - Error &error); + Status &error); StringList user_source; std::string script_source; @@ -119,7 +119,7 @@ public: static std::unique_ptr<BreakpointOptions> CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); virtual StructuredData::ObjectSP SerializeToStructuredData(); diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolver.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolver.h index 7a57250d632b..7bcd889ce78b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolver.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolver.h @@ -140,7 +140,7 @@ public: static lldb::BreakpointResolverSP CreateFromStructuredData(const StructuredData::Dictionary &resolver_dict, - Error &error); + Status &error); virtual StructuredData::ObjectSP SerializeToStructuredData() { return StructuredData::ObjectSP(); @@ -192,7 +192,7 @@ public: static const char *ResolverTyToName(enum ResolverTy); - static ResolverTy NameToResolverTy(const char *name); + static ResolverTy NameToResolverTy(llvm::StringRef name); virtual lldb::BreakpointResolverSP CopyForBreakpoint(Breakpoint &breakpoint) = 0; diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverAddress.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverAddress.h index 6d2d505811f9..9d757c8853b9 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverAddress.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverAddress.h @@ -39,7 +39,7 @@ public: static BreakpointResolver * CreateFromStructuredData(Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileLine.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileLine.h index 50750b1fbdf5..f7bba3d4ccb4 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileLine.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileLine.h @@ -36,7 +36,7 @@ public: static BreakpointResolver * CreateFromStructuredData(Breakpoint *bkpt, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileRegex.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileRegex.h index 6f00dac3f0a7..d620e99ffc60 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileRegex.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverFileRegex.h @@ -38,7 +38,7 @@ public: static BreakpointResolver * CreateFromStructuredData(Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverName.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverName.h index 4223125d9268..c7716d5146ef 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverName.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/BreakpointResolverName.h @@ -57,7 +57,7 @@ public: static BreakpointResolver * CreateFromStructuredData(Breakpoint *bkpt, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Watchpoint.h b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Watchpoint.h index beb7bad1ee9d..69067a567621 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Watchpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Breakpoint/Watchpoint.h @@ -100,7 +100,7 @@ public: void DumpSnapshots(Stream *s, const char *prefix = nullptr) const; void DumpWithLevel(Stream *s, lldb::DescriptionLevel description_level) const; Target &GetTarget() { return m_target; } - const Error &GetError() { return m_error; } + const Status &GetError() { return m_error; } //------------------------------------------------------------------ /// Returns the WatchpointOptions structure set for this watchpoint. @@ -213,8 +213,8 @@ private: lldb::ValueObjectSP m_old_value_sp; lldb::ValueObjectSP m_new_value_sp; CompilerType m_type; - Error m_error; // An error object describing errors associated with this - // watchpoint. + Status m_error; // An error object describing errors associated with this + // watchpoint. WatchpointOptions m_options; // Settable watchpoint options, which is a delegate to handle // the callback machinery. diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Communication.h b/contrib/llvm/tools/lldb/include/lldb/Core/Communication.h index 9459573ca90e..57fa483bd3a3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Communication.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Communication.h @@ -33,7 +33,7 @@ namespace lldb_private { class ConstString; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { @@ -71,7 +71,7 @@ namespace lldb_private { /// reads data and caches any received bytes. To start the read thread /// clients call: /// -/// bool Communication::StartReadThread (Error *); +/// bool Communication::StartReadThread (Status *); /// /// If true is returned a read thread has been spawned that will /// continually execute a call to the pure virtual DoRead function: @@ -154,10 +154,10 @@ public: /// internal error object should be filled in with an /// appropriate value based on the result of this function. /// - /// @see Error& Communication::GetError (); + /// @see Status& Communication::GetError (); /// @see bool Connection::Connect (const char *url); //------------------------------------------------------------------ - lldb::ConnectionStatus Connect(const char *url, Error *error_ptr); + lldb::ConnectionStatus Connect(const char *url, Status *error_ptr); //------------------------------------------------------------------ /// Disconnect the communications connection if one is currently @@ -168,10 +168,10 @@ public: /// internal error object should be filled in with an /// appropriate value based on the result of this function. /// - /// @see Error& Communication::GetError (); + /// @see Status& Communication::GetError (); /// @see bool Connection::Disconnect (); //------------------------------------------------------------------ - lldb::ConnectionStatus Disconnect(Error *error_ptr = nullptr); + lldb::ConnectionStatus Disconnect(Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Check if the connection is valid. @@ -217,7 +217,7 @@ public: /// @see size_t Connection::Read (void *, size_t); //------------------------------------------------------------------ size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, - lldb::ConnectionStatus &status, Error *error_ptr); + lldb::ConnectionStatus &status, Status *error_ptr); //------------------------------------------------------------------ /// The actual write function that attempts to write to the @@ -237,7 +237,7 @@ public: /// The number of bytes actually Written. //------------------------------------------------------------------ size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, - Error *error_ptr); + Status *error_ptr); //------------------------------------------------------------------ /// Sets the connection that it to be used by this class. @@ -280,7 +280,7 @@ public: /// @see void Communication::AppendBytesToCache (const uint8_t * bytes, size_t /// len, bool broadcast); //------------------------------------------------------------------ - virtual bool StartReadThread(Error *error_ptr = nullptr); + virtual bool StartReadThread(Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Stops the read thread by cancelling it. @@ -289,9 +289,9 @@ public: /// \b True if the read thread was successfully canceled, \b /// false otherwise. //------------------------------------------------------------------ - virtual bool StopReadThread(Error *error_ptr = nullptr); + virtual bool StopReadThread(Status *error_ptr = nullptr); - virtual bool JoinReadThread(Error *error_ptr = nullptr); + virtual bool JoinReadThread(Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Checks if there is a currently running read thread. /// @@ -361,7 +361,7 @@ protected: size_t ReadFromConnection(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, - lldb::ConnectionStatus &status, Error *error_ptr); + lldb::ConnectionStatus &status, Status *error_ptr); //------------------------------------------------------------------ /// Append new bytes that get read from the read thread into the diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h b/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h index 8d84377e3757..27757b2f77e7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Connection.h @@ -22,7 +22,7 @@ #include <stddef.h> // for size_t namespace lldb_private { -class Error; +class Status; } namespace lldb_private { template <typename Ratio> class Timeout; @@ -75,10 +75,10 @@ public: /// internal error object should be filled in with an /// appropriate value based on the result of this function. /// - /// @see Error& Communication::GetError (); + /// @see Status& Communication::GetError (); //------------------------------------------------------------------ virtual lldb::ConnectionStatus Connect(llvm::StringRef url, - Error *error_ptr) = 0; + Status *error_ptr) = 0; //------------------------------------------------------------------ /// Disconnect the communications connection if one is currently @@ -94,9 +94,9 @@ public: /// internal error object should be filled in with an /// appropriate value based on the result of this function. /// - /// @see Error& Communication::GetError (); + /// @see Status& Communication::GetError (); //------------------------------------------------------------------ - virtual lldb::ConnectionStatus Disconnect(Error *error_ptr) = 0; + virtual lldb::ConnectionStatus Disconnect(Status *error_ptr) = 0; //------------------------------------------------------------------ /// Check if the connection is valid. @@ -137,7 +137,7 @@ public: //------------------------------------------------------------------ virtual size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, - lldb::ConnectionStatus &status, Error *error_ptr) = 0; + lldb::ConnectionStatus &status, Status *error_ptr) = 0; //------------------------------------------------------------------ /// The actual write function that attempts to write to the @@ -162,7 +162,7 @@ public: /// The number of bytes actually Written. //------------------------------------------------------------------ virtual size_t Write(const void *dst, size_t dst_len, - lldb::ConnectionStatus &status, Error *error_ptr) = 0; + lldb::ConnectionStatus &status, Status *error_ptr) = 0; //------------------------------------------------------------------ /// Returns a URI that describes this connection object diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Debugger.h b/contrib/llvm/tools/lldb/include/lldb/Core/Debugger.h index 56201273fdd2..cedf9ecdb120 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Debugger.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Debugger.h @@ -30,8 +30,8 @@ #include "lldb/Target/Platform.h" #include "lldb/Target/TargetList.h" #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/FileSpec.h" // for FileSpec +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/UserID.h" #include "lldb/lldb-defines.h" // for DISALLOW_COPY_AND_ASSIGN #include "lldb/lldb-enumerations.h" // for ScriptLanguage, Langua... @@ -239,9 +239,9 @@ public: eStopDisassemblyTypeAlways }; - Error SetPropertyValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, llvm::StringRef property_path, - llvm::StringRef value) override; + Status SetPropertyValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, llvm::StringRef property_path, + llvm::StringRef value) override; bool GetAutoConfirm() const; @@ -306,7 +306,7 @@ public: const ConstString &GetInstanceName() { return m_instance_name; } - bool LoadPlugin(const FileSpec &spec, Error &error); + bool LoadPlugin(const FileSpec &spec, Status &error); void ExecuteIOHandlers(); @@ -318,7 +318,7 @@ public: bool IsHandlingEvents() const { return m_event_handler_thread.IsJoinable(); } - Error RunREPL(lldb::LanguageType language, const char *repl_options); + Status RunREPL(lldb::LanguageType language, const char *repl_options); // This is for use in the command interpreter, when you either want the // selected target, or if no target diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/FormatEntity.h b/contrib/llvm/tools/lldb/include/lldb/Core/FormatEntity.h index 6705c155cefc..aa5ccb48e56a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/FormatEntity.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/FormatEntity.h @@ -10,8 +10,8 @@ #ifndef liblldb_FormatEntity_h_ #define liblldb_FormatEntity_h_ -#include "lldb/Utility/Error.h" -#include "lldb/Utility/FileSpec.h" // for FileSpec +#include "lldb/Utility/FileSpec.h" // for FileSpec +#include "lldb/Utility/Status.h" #include "lldb/lldb-enumerations.h" // for Format::eFormatDefault, Format #include "lldb/lldb-types.h" // for addr_t #include <algorithm> // for min @@ -205,11 +205,11 @@ public: const Address *addr, ValueObject *valobj, bool function_changed, bool initial_function); - static Error Parse(const llvm::StringRef &format, Entry &entry); + static Status Parse(const llvm::StringRef &format, Entry &entry); - static Error ExtractVariableInfo(llvm::StringRef &format_str, - llvm::StringRef &variable_name, - llvm::StringRef &variable_format); + static Status ExtractVariableInfo(llvm::StringRef &format_str, + llvm::StringRef &variable_name, + llvm::StringRef &variable_format); static size_t AutoComplete(llvm::StringRef s, int match_start_point, int max_return_elements, bool &word_complete, @@ -228,8 +228,8 @@ public: llvm::StringRef element_format); protected: - static Error ParseInternal(llvm::StringRef &format, Entry &parent_entry, - uint32_t depth); + static Status ParseInternal(llvm::StringRef &format, Entry &parent_entry, + uint32_t depth); }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/MappedHash.h b/contrib/llvm/tools/lldb/include/lldb/Core/MappedHash.h index cab98ee5b302..18d383ed581c 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/MappedHash.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/MappedHash.h @@ -326,7 +326,7 @@ public: 1u, // Bucket hash data collision, but key didn't match eResultEndOfHashData = 2u, // The chain of items for this hash data in // this bucket is terminated, search no more - eResultError = 3u // Error parsing the hash data, abort + eResultError = 3u // Status parsing the hash data, abort }; struct Pair { @@ -409,7 +409,7 @@ public: // searching return false; case eResultError: - // Error parsing the hash data, abort + // Status parsing the hash data, abort return false; } } diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Module.h b/contrib/llvm/tools/lldb/include/lldb/Core/Module.h index 33735bc99f60..2ffe57ad8a4d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Module.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Module.h @@ -17,8 +17,8 @@ #include "lldb/Symbol/TypeSystem.h" #include "lldb/Target/PathMappingList.h" #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/UUID.h" #include "lldb/lldb-defines.h" // for DISALLOW_COPY_AND_ASSIGN #include "lldb/lldb-enumerations.h" // for LanguageType, SymbolType @@ -652,7 +652,7 @@ public: //------------------------------------------------------------------ bool IsLoadedInTarget(Target *target); - bool LoadScriptingResourceInTarget(Target *target, Error &error, + bool LoadScriptingResourceInTarget(Target *target, Status &error, Stream *feedback_stream = nullptr); //------------------------------------------------------------------ @@ -728,7 +728,7 @@ public: /// failed (see the `error` for more information in that case). //------------------------------------------------------------------ ObjectFile *GetMemoryObjectFile(const lldb::ProcessSP &process_sp, - lldb::addr_t header_addr, Error &error, + lldb::addr_t header_addr, Status &error, size_t size_to_read = 512); //------------------------------------------------------------------ /// Get the symbol vendor interface for the current architecture. @@ -1033,7 +1033,7 @@ public: /// /// @return //------------------------------------------------------------------ - Error LoadInMemory(Target &target, bool set_pc); + Status LoadInMemory(Target &target, bool set_pc); //---------------------------------------------------------------------- /// @class LookupInfo Module.h "lldb/Core/Module.h" diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ModuleList.h b/contrib/llvm/tools/lldb/include/lldb/Core/ModuleList.h index d82d1c0d48d8..4b637c9b0427 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ModuleList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ModuleList.h @@ -12,9 +12,9 @@ #include "lldb/Core/Address.h" // for Address #include "lldb/Core/ModuleSpec.h" // for ModuleSpec -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/FileSpec.h" // for FileSpec #include "lldb/Utility/Iterable.h" +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-enumerations.h" #include "lldb/lldb-forward.h" #include "lldb/lldb-types.h" @@ -530,18 +530,18 @@ public: //------------------------------------------------------------------ size_t GetSize() const; - bool LoadScriptingResourcesInTarget(Target *target, std::list<Error> &errors, + bool LoadScriptingResourcesInTarget(Target *target, std::list<Status> &errors, Stream *feedback_stream = nullptr, bool continue_on_error = true); static bool ModuleIsInCache(const Module *module_ptr); - static Error GetSharedModule(const ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - lldb::ModuleSP *old_module_sp_ptr, - bool *did_create_ptr, - bool always_create = false); + static Status GetSharedModule(const ModuleSpec &module_spec, + lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + lldb::ModuleSP *old_module_sp_ptr, + bool *did_create_ptr, + bool always_create = false); static bool RemoveSharedModule(lldb::ModuleSP &module_sp); diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/PluginManager.h b/contrib/llvm/tools/lldb/include/lldb/Core/PluginManager.h index 645ab85eaa7e..d9851e5ecfc1 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/PluginManager.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/PluginManager.h @@ -10,8 +10,8 @@ #ifndef liblldb_PluginManager_h_ #define liblldb_PluginManager_h_ -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-enumerations.h" // for ScriptLanguage #include "lldb/lldb-forward.h" // for OptionValuePropertiesSP #include "lldb/lldb-private-interfaces.h" // for DebuggerInitializeCallback @@ -202,8 +202,8 @@ public: static ObjectFileCreateMemoryInstance GetObjectFileCreateMemoryCallbackForPluginName(const ConstString &name); - static Error SaveCore(const lldb::ProcessSP &process_sp, - const FileSpec &outfile); + static Status SaveCore(const lldb::ProcessSP &process_sp, + const FileSpec &outfile); //------------------------------------------------------------------ // ObjectContainer diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/RegisterValue.h b/contrib/llvm/tools/lldb/include/lldb/Core/RegisterValue.h index 66c4689d702d..a45db00fb76e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/RegisterValue.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/RegisterValue.h @@ -12,7 +12,7 @@ #include "lldb/Core/Scalar.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-enumerations.h" // for ByteOrder, Format #include "lldb/lldb-types.h" // for offset_t @@ -105,11 +105,11 @@ public: // into "dst". uint32_t GetAsMemoryData(const RegisterInfo *reg_info, void *dst, uint32_t dst_len, lldb::ByteOrder dst_byte_order, - Error &error) const; + Status &error) const; uint32_t SetFromMemoryData(const RegisterInfo *reg_info, const void *src, uint32_t src_len, lldb::ByteOrder src_byte_order, - Error &error); + Status &error); bool GetScalarValue(Scalar &scalar) const; @@ -241,13 +241,13 @@ public: bool SignExtend(uint32_t sign_bitpos); - Error SetValueFromString(const RegisterInfo *reg_info, - llvm::StringRef value_str); - Error SetValueFromString(const RegisterInfo *reg_info, - const char *value_str) = delete; + Status SetValueFromString(const RegisterInfo *reg_info, + llvm::StringRef value_str); + Status SetValueFromString(const RegisterInfo *reg_info, + const char *value_str) = delete; - Error SetValueFromData(const RegisterInfo *reg_info, DataExtractor &data, - lldb::offset_t offset, bool partial_data_ok); + Status SetValueFromData(const RegisterInfo *reg_info, DataExtractor &data, + lldb::offset_t offset, bool partial_data_ok); // The default value of 0 for reg_name_right_align_at means no alignment at // all. diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Scalar.h b/contrib/llvm/tools/lldb/include/lldb/Core/Scalar.h index c534044af753..943398b88020 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Scalar.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Scalar.h @@ -10,7 +10,7 @@ #ifndef liblldb_Scalar_h_ #define liblldb_Scalar_h_ -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-enumerations.h" // for Encoding, ByteOrder #include "lldb/lldb-private-types.h" // for type128 @@ -146,7 +146,7 @@ public: bool GetData(DataExtractor &data, size_t limit_byte_size = UINT32_MAX) const; size_t GetAsMemoryData(void *dst, size_t dst_len, - lldb::ByteOrder dst_byte_order, Error &error) const; + lldb::ByteOrder dst_byte_order, Status &error) const; bool IsZero() const; @@ -272,11 +272,11 @@ public: long double LongDouble(long double fail_value = 0.0) const; - Error SetValueFromCString(const char *s, lldb::Encoding encoding, - size_t byte_size); + Status SetValueFromCString(const char *s, lldb::Encoding encoding, + size_t byte_size); - Error SetValueFromData(DataExtractor &data, lldb::Encoding encoding, - size_t byte_size); + Status SetValueFromData(DataExtractor &data, lldb::Encoding encoding, + size_t byte_size); static bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) { if (total_byte_size > 8) diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h b/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h index 829305ff5dee..06fb94d8fbdf 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/SearchFilter.h @@ -28,7 +28,7 @@ namespace lldb_private { class CompileUnit; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class Function; @@ -250,7 +250,7 @@ public: static lldb::SearchFilterSP CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); virtual StructuredData::ObjectSP SerializeToStructuredData() { return StructuredData::ObjectSP(); @@ -285,7 +285,7 @@ public: static const char *FilterTyToName(enum FilterTy); - static FilterTy NameToFilterTy(const char *name); + static FilterTy NameToFilterTy(llvm::StringRef name); protected: // Serialization of SearchFilter options: @@ -351,7 +351,7 @@ public: static lldb::SearchFilterSP CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; @@ -405,7 +405,7 @@ public: static lldb::SearchFilterSP CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; @@ -462,7 +462,7 @@ public: static lldb::SearchFilterSP CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; @@ -515,7 +515,7 @@ public: static lldb::SearchFilterSP CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h index eecfd86f7988..6cb78dc48ab5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredData.h @@ -28,7 +28,7 @@ #include <stdint.h> // for uint64_t namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class Stream; @@ -143,15 +143,12 @@ public: : nullptr); } - std::string GetStringValue(const char *fail_value = nullptr) { + llvm::StringRef GetStringValue(const char *fail_value = nullptr) { String *s = GetAsString(); if (s) return s->GetValue(); - if (fail_value && fail_value[0]) - return std::string(fail_value); - - return std::string(); + return fail_value; } Generic *GetAsGeneric() { @@ -220,7 +217,7 @@ public: return success; } - bool GetItemAtIndexAsString(size_t idx, std::string &result) const { + bool GetItemAtIndexAsString(size_t idx, llvm::StringRef &result) const { ObjectSP value_sp = GetItemAtIndex(idx); if (value_sp.get()) { if (auto string_value = value_sp->GetAsString()) { @@ -231,8 +228,8 @@ public: return false; } - bool GetItemAtIndexAsString(size_t idx, std::string &result, - const std::string &default_val) const { + bool GetItemAtIndexAsString(size_t idx, llvm::StringRef &result, + llvm::StringRef default_val) const { bool success = GetItemAtIndexAsString(idx, result); if (!success) result = default_val; @@ -339,18 +336,13 @@ public: class String : public Object { public: - String(const char *cstr = nullptr) : Object(Type::eTypeString), m_value() { - if (cstr) - m_value = cstr; - } - - String(const std::string &s) : Object(Type::eTypeString), m_value(s) {} - - String(const std::string &&s) : Object(Type::eTypeString), m_value(s) {} + String() : Object(Type::eTypeString) {} + explicit String(llvm::StringRef S) + : Object(Type::eTypeString), m_value(S) {} - void SetValue(const std::string &string) { m_value = string; } + void SetValue(llvm::StringRef S) { m_value = S; } - const std::string &GetValue() { return m_value; } + llvm::StringRef GetValue() { return m_value; } void Dump(Stream &s, bool pretty_print = true) const override; @@ -430,7 +422,7 @@ public: } bool GetValueForKeyAsString(llvm::StringRef key, - std::string &result) const { + llvm::StringRef &result) const { ObjectSP value_sp = GetValueForKey(key); if (value_sp.get()) { if (auto string_value = value_sp->GetAsString()) { @@ -441,14 +433,14 @@ public: return false; } - bool GetValueForKeyAsString(llvm::StringRef key, std::string &result, + bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result, const char *default_val) const { bool success = GetValueForKeyAsString(key, result); if (!success) { if (default_val) result = default_val; else - result.clear(); + result = llvm::StringRef(); } return success; } @@ -513,7 +505,7 @@ public: AddItem(key, std::make_shared<Float>(value)); } - void AddStringItem(llvm::StringRef key, std::string value) { + void AddStringItem(llvm::StringRef key, llvm::StringRef value) { AddItem(key, std::make_shared<String>(std::move(value))); } @@ -558,7 +550,7 @@ public: static ObjectSP ParseJSON(std::string json_text); - static ObjectSP ParseJSONFromFile(const FileSpec &file, Error &error); + static ObjectSP ParseJSONFromFile(const FileSpec &file, Status &error); }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h index 94f9cce52548..81d59f83ac3d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/StructuredDataImpl.h @@ -12,9 +12,9 @@ #include "lldb/Core/Event.h" #include "lldb/Core/StructuredData.h" -#include "lldb/Utility/Error.h" -#include "lldb/Utility/Stream.h" #include "lldb/Target/StructuredDataPlugin.h" +#include "lldb/Utility/Status.h" +#include "lldb/Utility/Stream.h" #include "lldb/lldb-forward.h" #pragma mark-- @@ -45,8 +45,8 @@ public: m_data_sp.reset(); } - Error GetAsJSON(Stream &stream) const { - Error error; + Status GetAsJSON(Stream &stream) const { + Status error; if (!m_data_sp) { error.SetErrorString("No structured data."); @@ -57,8 +57,8 @@ public: return error; } - Error GetDescription(Stream &stream) const { - Error error; + Status GetDescription(Stream &stream) const { + Status error; if (!m_data_sp) { error.SetErrorString("Cannot pretty print structured data: " diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h b/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h index 6da00b0e27a4..55aab193032e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Timer.h @@ -37,10 +37,23 @@ namespace lldb_private { class Timer { public: + class Category { + public: + explicit Category(const char *category_name); + + private: + friend class Timer; + const char *m_name; + std::atomic<uint64_t> m_nanos; + std::atomic<Category *> m_next; + + DISALLOW_COPY_AND_ASSIGN(Category); + }; + //-------------------------------------------------------------- /// Default constructor. //-------------------------------------------------------------- - Timer(const char *category, const char *format, ...) + Timer(Category &category, const char *format, ...) __attribute__((format(printf, 3, 4))); //-------------------------------------------------------------- @@ -62,7 +75,7 @@ protected: using TimePoint = std::chrono::steady_clock::time_point; void ChildDuration(TimePoint::duration dur) { m_child_duration += dur; } - const char *m_category; + Category &m_category; TimePoint m_total_start; TimePoint::duration m_child_duration{0}; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/UserSettingsController.h b/contrib/llvm/tools/lldb/include/lldb/Core/UserSettingsController.h index 0207187f0718..67bc9b2c0713 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/UserSettingsController.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/UserSettingsController.h @@ -10,7 +10,7 @@ #ifndef liblldb_UserSettingsController_h_ #define liblldb_UserSettingsController_h_ -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-forward.h" // for OptionValuePropertiesSP #include "lldb/lldb-private-enumerations.h" // for VarSetOperationType @@ -57,15 +57,16 @@ public: virtual lldb::OptionValueSP GetPropertyValue(const ExecutionContext *exe_ctx, llvm::StringRef property_path, bool will_modify, - Error &error) const; + Status &error) const; - virtual Error SetPropertyValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, - llvm::StringRef property_path, llvm::StringRef value); + virtual Status SetPropertyValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, + llvm::StringRef property_path, + llvm::StringRef value); - virtual Error DumpPropertyValue(const ExecutionContext *exe_ctx, Stream &strm, - llvm::StringRef property_path, - uint32_t dump_mask); + virtual Status DumpPropertyValue(const ExecutionContext *exe_ctx, + Stream &strm, llvm::StringRef property_path, + uint32_t dump_mask); virtual void DumpAllPropertyValues(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask); diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/Value.h b/contrib/llvm/tools/lldb/include/lldb/Core/Value.h index 9a667cf65752..678b56fc49f5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/Value.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/Value.h @@ -13,7 +13,7 @@ #include "lldb/Core/Scalar.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-enumerations.h" // for ByteOrder, ByteOrder::eB... #include "lldb/lldb-private-enumerations.h" // for AddressType #include "lldb/lldb-private-types.h" // for type128, RegisterInfo @@ -219,11 +219,11 @@ public: lldb::Format GetValueDefaultFormat(); - uint64_t GetValueByteSize(Error *error_ptr, ExecutionContext *exe_ctx); + uint64_t GetValueByteSize(Status *error_ptr, ExecutionContext *exe_ctx); - Error GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, - uint32_t data_offset, - Module *module); // Can be nullptr + Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, + uint32_t data_offset, + Module *module); // Can be nullptr static const char *GetValueTypeAsCString(ValueType context_type); diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObject.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObject.h index 0898754b211a..fa1d14870b05 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObject.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObject.h @@ -18,8 +18,8 @@ #include "lldb/Target/Process.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/SharedCluster.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/UserID.h" #include "lldb/lldb-defines.h" // for LLDB_INVALID... #include "lldb/lldb-enumerations.h" // for DynamicValue... @@ -462,7 +462,7 @@ public: virtual int64_t GetValueAsSigned(int64_t fail_value, bool *success = nullptr); - virtual bool SetValueFromCString(const char *value_str, Error &error); + virtual bool SetValueFromCString(const char *value_str, Status &error); // Return the module associated with this value object in case the // value is from an executable file and might have its data in @@ -482,7 +482,7 @@ public: //------------------------------------------------------------------ // The functions below should NOT be modified by subclasses //------------------------------------------------------------------ - const Error &GetError(); + const Status &GetError(); const ConstString &GetName() const; @@ -520,7 +520,7 @@ public: // return 'false' whenever you set the error, otherwise // callers may assume true means everything is OK - this will // break breakpoint conditions among potentially a few others - virtual bool IsLogicalTrue(Error &error); + virtual bool IsLogicalTrue(Status &error); virtual const char *GetLocationAsCString(); @@ -620,7 +620,7 @@ public: virtual lldb::ValueObjectSP CreateConstantValue(const ConstString &name); - virtual lldb::ValueObjectSP Dereference(Error &error); + virtual lldb::ValueObjectSP Dereference(Status &error); // Creates a copy of the ValueObject with a new name and setting the current // ValueObject as its parent. It should be used when we want to change the @@ -628,7 +628,7 @@ public: // (e.g. sythetic child provider). virtual lldb::ValueObjectSP Clone(const ConstString &new_name); - virtual lldb::ValueObjectSP AddressOf(Error &error); + virtual lldb::ValueObjectSP AddressOf(Status &error); virtual lldb::addr_t GetLiveAddress() { return LLDB_INVALID_ADDRESS; } @@ -700,16 +700,16 @@ public: bool IsCStringContainer(bool check_pointer = false); std::pair<size_t, bool> - ReadPointedString(lldb::DataBufferSP &buffer_sp, Error &error, + ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error, uint32_t max_length = 0, bool honor_array = true, lldb::Format item_format = lldb::eFormatCharArray); virtual size_t GetPointeeData(DataExtractor &data, uint32_t item_idx = 0, uint32_t item_count = 1); - virtual uint64_t GetData(DataExtractor &data, Error &error); + virtual uint64_t GetData(DataExtractor &data, Status &error); - virtual bool SetData(DataExtractor &data, Error &error); + virtual bool SetData(DataExtractor &data, Status &error); virtual bool GetIsConstant() const { return m_update_point.IsConstant(); } @@ -880,8 +880,9 @@ protected: DataExtractor m_data; // A data extractor that can be used to extract the value. Value m_value; - Error m_error; // An error object that can describe any errors that occur when - // updating values. + Status + m_error; // An error object that can describe any errors that occur when + // updating values. std::string m_value_str; // Cached value string that will get cleared if/when // the value is updated. std::string m_old_value_str; // Cached old value string from the last time the diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResult.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResult.h index 403d19324c46..1f56129df24a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResult.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResult.h @@ -15,7 +15,7 @@ #include "lldb/Core/ValueObjectConstResultImpl.h" #include "lldb/Symbol/CompilerType.h" // for CompilerType #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-defines.h" // for LLDB_INVALID_ADDRESS #include "lldb/lldb-enumerations.h" // for ByteOrder, Dynamic... #include "lldb/lldb-forward.h" // for ValueObjectSP, Dat... @@ -69,7 +69,7 @@ public: // When an expression fails to evaluate, we return an error static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, - const Error &error); + const Status &error); uint64_t GetByteSize() override; @@ -85,7 +85,7 @@ public: void SetByteSize(size_t size); - lldb::ValueObjectSP Dereference(Error &error) override; + lldb::ValueObjectSP Dereference(Status &error) override; ValueObject *CreateChildAtIndex(size_t idx, bool synthetic_array_member, int32_t synthetic_index) override; @@ -94,7 +94,7 @@ public: uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str = ConstString()) override; - lldb::ValueObjectSP AddressOf(Error &error) override; + lldb::ValueObjectSP AddressOf(Status &error) override; lldb::addr_t GetAddressOf(bool scalar_is_load_address = true, AddressType *address_type = nullptr) override; @@ -153,7 +153,7 @@ private: ValueObjectConstResult(ExecutionContextScope *exe_scope, const Value &value, const ConstString &name, Module *module = nullptr); - ValueObjectConstResult(ExecutionContextScope *exe_scope, const Error &error); + ValueObjectConstResult(ExecutionContextScope *exe_scope, const Status &error); DISALLOW_COPY_AND_ASSIGN(ValueObjectConstResult); }; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultCast.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultCast.h index 3443bfb4885b..442cce420855 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultCast.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultCast.h @@ -25,7 +25,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ValueObject; @@ -41,7 +41,7 @@ public: ~ValueObjectConstResultCast() override; - lldb::ValueObjectSP Dereference(Error &error) override; + lldb::ValueObjectSP Dereference(Status &error) override; ValueObject *CreateChildAtIndex(size_t idx, bool synthetic_array_member, int32_t synthetic_index) override; @@ -54,7 +54,7 @@ public: uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str = ConstString()) override; - lldb::ValueObjectSP AddressOf(Error &error) override; + lldb::ValueObjectSP AddressOf(Status &error) override; size_t GetPointeeData(DataExtractor &data, uint32_t item_idx = 0, uint32_t item_count = 1) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultChild.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultChild.h index 3da59dc2eb56..a74da0013aba 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultChild.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultChild.h @@ -24,7 +24,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ValueObject; @@ -48,7 +48,7 @@ public: ~ValueObjectConstResultChild() override; - lldb::ValueObjectSP Dereference(Error &error) override; + lldb::ValueObjectSP Dereference(Status &error) override; ValueObject *CreateChildAtIndex(size_t idx, bool synthetic_array_member, int32_t synthetic_index) override; @@ -61,7 +61,7 @@ public: uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str = ConstString()) override; - lldb::ValueObjectSP AddressOf(Error &error) override; + lldb::ValueObjectSP AddressOf(Status &error) override; size_t GetPointeeData(DataExtractor &data, uint32_t item_idx = 0, uint32_t item_count = 1) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultImpl.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultImpl.h index 2586aab4c781..d86f25e30579 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultImpl.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectConstResultImpl.h @@ -25,7 +25,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ValueObject; @@ -45,7 +45,7 @@ public: virtual ~ValueObjectConstResultImpl() = default; - lldb::ValueObjectSP Dereference(Error &error); + lldb::ValueObjectSP Dereference(Status &error); ValueObject *CreateChildAtIndex(size_t idx, bool synthetic_array_member, int32_t synthetic_index); @@ -55,7 +55,7 @@ public: bool can_create, ConstString name_const_str = ConstString()); - lldb::ValueObjectSP AddressOf(Error &error); + lldb::ValueObjectSP AddressOf(Status &error); lldb::addr_t GetLiveAddress() { return m_live_address; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectDynamicValue.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectDynamicValue.h index 99eb1ebcf977..018ee2c764bf 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectDynamicValue.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectDynamicValue.h @@ -32,7 +32,7 @@ namespace lldb_private { class Declaration; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { @@ -86,9 +86,9 @@ public: m_owning_valobj_sp = owning_sp; } - bool SetValueFromCString(const char *value_str, Error &error) override; + bool SetValueFromCString(const char *value_str, Status &error) override; - bool SetData(DataExtractor &data, Error &error) override; + bool SetData(DataExtractor &data, Status &error) override; TypeImpl GetTypeImpl() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectRegister.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectRegister.h index 50d0e12bb3f4..2aaef9bee99e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectRegister.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectRegister.h @@ -26,7 +26,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ExecutionContextScope; @@ -148,9 +148,9 @@ public: size_t CalculateNumChildren(uint32_t max) override; - bool SetValueFromCString(const char *value_str, Error &error) override; + bool SetValueFromCString(const char *value_str, Status &error) override; - bool SetData(DataExtractor &data, Error &error) override; + bool SetData(DataExtractor &data, Status &error) override; bool ResolveValue(Scalar &scalar) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectSyntheticFilter.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectSyntheticFilter.h index d83f038744e5..e32e14030418 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectSyntheticFilter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectSyntheticFilter.h @@ -29,7 +29,7 @@ namespace lldb_private { class Declaration; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class SyntheticChildrenFrontEnd; @@ -110,7 +110,7 @@ public: bool GetIsConstant() const override { return false; } - bool SetValueFromCString(const char *value_str, Error &error) override; + bool SetValueFromCString(const char *value_str, Status &error) override; void SetFormat(lldb::Format format) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectVariable.h b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectVariable.h index dbb7c2b9483e..9dd140a84f45 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectVariable.h +++ b/contrib/llvm/tools/lldb/include/lldb/Core/ValueObjectVariable.h @@ -29,7 +29,7 @@ namespace lldb_private { class Declaration; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ExecutionContextScope; @@ -73,9 +73,9 @@ public: const char *GetLocationAsCString() override; - bool SetValueFromCString(const char *value_str, Error &error) override; + bool SetValueFromCString(const char *value_str, Status &error) override; - bool SetData(DataExtractor &data, Error &error) override; + bool SetData(DataExtractor &data, Status &error) override; virtual lldb::VariableSP GetVariable() override { return m_variable_sp; } diff --git a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h index fbfc25dd9c9f..a4d51b065480 100644 --- a/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h +++ b/contrib/llvm/tools/lldb/include/lldb/DataFormatters/TypeSummary.h @@ -25,7 +25,7 @@ #include "lldb/Core/FormatEntity.h" #include "lldb/Core/StructuredData.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" namespace lldb_private { class TypeSummaryOptions { @@ -286,7 +286,7 @@ private: struct StringSummaryFormat : public TypeSummaryImpl { std::string m_format_str; FormatEntity::Entry m_format; - Error m_error; + Status m_error; StringSummaryFormat(const TypeSummaryImpl::Flags &flags, const char *f); diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/DWARFExpression.h b/contrib/llvm/tools/lldb/include/lldb/Expression/DWARFExpression.h index ae9eb3fb2d16..1816c3b7a00f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/DWARFExpression.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/DWARFExpression.h @@ -14,7 +14,7 @@ #include "lldb/Core/Disassembler.h" #include "lldb/Core/Scalar.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include <functional> @@ -266,7 +266,7 @@ public: ClangExpressionDeclMap *decl_map, lldb::addr_t loclist_base_load_addr, const Value *initial_value_ptr, const Value *object_address_ptr, - Value &result, Error *error_ptr) const; + Value &result, Status *error_ptr) const; //------------------------------------------------------------------ /// Wrapper for the static evaluate function that uses member @@ -277,7 +277,7 @@ public: ClangExpressionDeclMap *decl_map, RegisterContext *reg_ctx, lldb::addr_t loclist_base_load_addr, const Value *initial_value_ptr, const Value *object_address_ptr, - Value &result, Error *error_ptr) const; + Value &result, Status *error_ptr) const; //------------------------------------------------------------------ /// Evaluate a DWARF location expression in a particular context @@ -345,7 +345,7 @@ public: DWARFCompileUnit *dwarf_cu, const lldb::offset_t offset, const lldb::offset_t length, const lldb::RegisterKind reg_set, const Value *initial_value_ptr, const Value *object_address_ptr, - Value &result, Error *error_ptr); + Value &result, Status *error_ptr); //------------------------------------------------------------------ /// Loads a ClangExpressionVariableList into the object diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/ExpressionParser.h b/contrib/llvm/tools/lldb/include/lldb/Expression/ExpressionParser.h index 9f33908b8f1b..19526d28b9b3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/ExpressionParser.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/ExpressionParser.h @@ -10,7 +10,7 @@ #ifndef liblldb_ExpressionParser_h_ #define liblldb_ExpressionParser_h_ -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-public.h" namespace lldb_private { @@ -108,7 +108,7 @@ public: /// An error code indicating the success or failure of the operation. /// Test with Success(). //------------------------------------------------------------------ - virtual Error + virtual Status PrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, std::shared_ptr<IRExecutionUnit> &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/IRExecutionUnit.h b/contrib/llvm/tools/lldb/include/lldb/Expression/IRExecutionUnit.h index 635e0b727d5c..b0b4d7a5c586 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/IRExecutionUnit.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/IRExecutionUnit.h @@ -39,7 +39,7 @@ class ObjectCache; namespace lldb_private { -class Error; +class Status; //---------------------------------------------------------------------- /// @class IRExecutionUnit IRExecutionUnit.h "lldb/Expression/IRExecutionUnit.h" @@ -86,7 +86,7 @@ public: : nullptr); } - void GetRunnableInfo(Error &error, lldb::addr_t &func_addr, + void GetRunnableInfo(Status &error, lldb::addr_t &func_addr, lldb::addr_t &func_end); //------------------------------------------------------------------ @@ -95,7 +95,7 @@ public: /// IRExecutionUnit unless the client explicitly chooses to free it. //------------------------------------------------------------------ - lldb::addr_t WriteNow(const uint8_t *bytes, size_t size, Error &error); + lldb::addr_t WriteNow(const uint8_t *bytes, size_t size, Status &error); void FreeNow(lldb::addr_t allocation); @@ -240,7 +240,7 @@ private: //------------------------------------------------------------------ bool WriteData(lldb::ProcessSP &process_sp); - Error DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp); + Status DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp); struct SearchSpec; @@ -391,7 +391,7 @@ private: void dump(Log *log); }; - bool CommitOneAllocation(lldb::ProcessSP &process_sp, Error &error, + bool CommitOneAllocation(lldb::ProcessSP &process_sp, Status &error, AllocationRecord &record); typedef std::vector<AllocationRecord> RecordVector; diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/IRInterpreter.h b/contrib/llvm/tools/lldb/include/lldb/Expression/IRInterpreter.h index f9392c18c25c..36e03c6fc4f6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/IRInterpreter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/IRInterpreter.h @@ -39,20 +39,20 @@ class IRMemoryMap; class IRInterpreter { public: static bool CanInterpret(llvm::Module &module, llvm::Function &function, - lldb_private::Error &error, + lldb_private::Status &error, const bool support_function_calls); static bool Interpret(llvm::Module &module, llvm::Function &function, llvm::ArrayRef<lldb::addr_t> args, lldb_private::IRExecutionUnit &execution_unit, - lldb_private::Error &error, + lldb_private::Status &error, lldb::addr_t stack_frame_bottom, lldb::addr_t stack_frame_top, lldb_private::ExecutionContext &exe_ctx); private: static bool supportsFunction(llvm::Function &llvm_function, - lldb_private::Error &err); + lldb_private::Status &err); }; #endif diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/IRMemoryMap.h b/contrib/llvm/tools/lldb/include/lldb/Expression/IRMemoryMap.h index c1a194d1afad..abb5cd745053 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/IRMemoryMap.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/IRMemoryMap.h @@ -54,25 +54,25 @@ public: }; lldb::addr_t Malloc(size_t size, uint8_t alignment, uint32_t permissions, - AllocationPolicy policy, bool zero_memory, Error &error); - void Leak(lldb::addr_t process_address, Error &error); - void Free(lldb::addr_t process_address, Error &error); + AllocationPolicy policy, bool zero_memory, Status &error); + void Leak(lldb::addr_t process_address, Status &error); + void Free(lldb::addr_t process_address, Status &error); void WriteMemory(lldb::addr_t process_address, const uint8_t *bytes, - size_t size, Error &error); + size_t size, Status &error); void WriteScalarToMemory(lldb::addr_t process_address, Scalar &scalar, - size_t size, Error &error); + size_t size, Status &error); void WritePointerToMemory(lldb::addr_t process_address, lldb::addr_t address, - Error &error); + Status &error); void ReadMemory(uint8_t *bytes, lldb::addr_t process_address, size_t size, - Error &error); + Status &error); void ReadScalarFromMemory(Scalar &scalar, lldb::addr_t process_address, - size_t size, Error &error); + size_t size, Status &error); void ReadPointerFromMemory(lldb::addr_t *address, - lldb::addr_t process_address, Error &error); + lldb::addr_t process_address, Status &error); bool GetAllocSize(lldb::addr_t address, size_t &size); void GetMemoryData(DataExtractor &extractor, lldb::addr_t process_address, - size_t size, Error &error); + size_t size, Status &error); lldb::ByteOrder GetByteOrder(); uint32_t GetAddressByteSize(); diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/LLVMUserExpression.h b/contrib/llvm/tools/lldb/include/lldb/Expression/LLVMUserExpression.h index 48d0161991d7..745d413e077b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/LLVMUserExpression.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/LLVMUserExpression.h @@ -81,7 +81,7 @@ protected: lldb::ExpressionVariableSP &result) override; virtual void ScanContext(ExecutionContext &exe_ctx, - lldb_private::Error &err) = 0; + lldb_private::Status &err) = 0; bool PrepareToExecuteJITExpression(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx, diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/Materializer.h b/contrib/llvm/tools/lldb/include/lldb/Expression/Materializer.h index ed3f91cc67ec..b86bc656d6b5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/Materializer.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/Materializer.h @@ -20,7 +20,7 @@ #include "lldb/Expression/IRMemoryMap.h" #include "lldb/Symbol/TaggedASTType.h" #include "lldb/Target/StackFrame.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-types.h" namespace lldb_private { @@ -38,7 +38,7 @@ public: ~Dematerializer() { Wipe(); } - void Dematerialize(Error &err, lldb::addr_t frame_top, + void Dematerialize(Status &err, lldb::addr_t frame_top, lldb::addr_t frame_bottom); void Wipe(); @@ -72,7 +72,7 @@ public: typedef std::weak_ptr<Dematerializer> DematerializerWP; DematerializerSP Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err); + lldb::addr_t process_address, Status &err); class PersistentVariableDelegate { public: @@ -83,13 +83,13 @@ public: uint32_t AddPersistentVariable(lldb::ExpressionVariableSP &persistent_variable_sp, - PersistentVariableDelegate *delegate, Error &err); - uint32_t AddVariable(lldb::VariableSP &variable_sp, Error &err); + PersistentVariableDelegate *delegate, Status &err); + uint32_t AddVariable(lldb::VariableSP &variable_sp, Status &err); uint32_t AddResultVariable(const CompilerType &type, bool is_lvalue, bool keep_in_memory, - PersistentVariableDelegate *delegate, Error &err); - uint32_t AddSymbol(const Symbol &symbol_sp, Error &err); - uint32_t AddRegister(const RegisterInfo ®ister_info, Error &err); + PersistentVariableDelegate *delegate, Status &err); + uint32_t AddSymbol(const Symbol &symbol_sp, Status &err); + uint32_t AddRegister(const RegisterInfo ®ister_info, Status &err); uint32_t GetStructAlignment() { return m_struct_alignment; } @@ -102,11 +102,11 @@ public: virtual ~Entity() = default; virtual void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) = 0; + lldb::addr_t process_address, Status &err) = 0; virtual void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) = 0; + lldb::addr_t frame_bottom, Status &err) = 0; virtual void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address, Log *log) = 0; virtual void Wipe(IRMemoryMap &map, lldb::addr_t process_address) = 0; diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/REPL.h b/contrib/llvm/tools/lldb/include/lldb/Expression/REPL.h index 56d31cfd3b15..0c1e97fec259 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/REPL.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/REPL.h @@ -60,7 +60,7 @@ public: /// @return /// The range of the containing object in the target process. //------------------------------------------------------------------ - static lldb::REPLSP Create(Error &Error, lldb::LanguageType language, + static lldb::REPLSP Create(Status &Status, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options); @@ -85,7 +85,7 @@ public: lldb::IOHandlerSP GetIOHandler(); - Error RunLoop(); + Status RunLoop(); //------------------------------------------------------------------ // IOHandler::Delegate functions @@ -126,7 +126,7 @@ protected: // Subclasses should override these functions to implement a functional REPL. //---------------------------------------------------------------------- - virtual Error DoInitialization() = 0; + virtual Status DoInitialization() = 0; virtual ConstString GetSourceFileBasename() = 0; diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/UserExpression.h b/contrib/llvm/tools/lldb/include/lldb/Expression/UserExpression.h index fca667e8ee96..ced5cb2bf2b7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/UserExpression.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/UserExpression.h @@ -259,13 +259,13 @@ public: static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, - lldb::ValueObjectSP &result_valobj_sp, Error &error, + lldb::ValueObjectSP &result_valobj_sp, Status &error, uint32_t line_offset = 0, std::string *fixed_expression = nullptr, lldb::ModuleSP *jit_module_sp_ptr = nullptr); - static const Error::ValueType kNoResult = + static const Status::ValueType kNoResult = 0x1001; ///< ValueObject::GetError() returns this if there is no result - ///from the expression. + /// from the expression. const char *GetFixedText() { if (m_fixed_text.empty()) @@ -281,7 +281,7 @@ protected: lldb::ExpressionVariableSP &result) = 0; static lldb::addr_t GetObjectPointer(lldb::StackFrameSP frame_sp, - ConstString &object_name, Error &err); + ConstString &object_name, Status &err); //------------------------------------------------------------------ /// Populate m_in_cplusplus_method and m_in_objectivec_method based on the diff --git a/contrib/llvm/tools/lldb/include/lldb/Expression/UtilityFunction.h b/contrib/llvm/tools/lldb/include/lldb/Expression/UtilityFunction.h index 0e2b87da20ad..9c54db35fa37 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Expression/UtilityFunction.h +++ b/contrib/llvm/tools/lldb/include/lldb/Expression/UtilityFunction.h @@ -123,7 +123,7 @@ public: FunctionCaller *MakeFunctionCaller(const CompilerType &return_type, const ValueList &arg_value_list, lldb::ThreadSP compilation_thread, - Error &error); + Status &error); // This one retrieves the function caller that is already made. If you // haven't made it yet, this returns nullptr diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/File.h b/contrib/llvm/tools/lldb/include/lldb/Host/File.h index 35317780f1ce..560a655237f3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/File.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/File.h @@ -12,7 +12,7 @@ #include "lldb/Host/IOObject.h" #include "lldb/Host/PosixApi.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include <stdarg.h> @@ -164,7 +164,7 @@ public: /// @return /// A reference to the file specification object. //------------------------------------------------------------------ - Error GetFileSpec(FileSpec &file_spec) const; + Status GetFileSpec(FileSpec &file_spec) const; //------------------------------------------------------------------ /// Open a file for read/writing with the specified options. @@ -181,10 +181,10 @@ public: /// @param[in] permissions /// Options to use when opening (see File::Permissions) //------------------------------------------------------------------ - Error Open(const char *path, uint32_t options, - uint32_t permissions = lldb::eFilePermissionsFileDefault); + Status Open(const char *path, uint32_t options, + uint32_t permissions = lldb::eFilePermissionsFileDefault); - Error Close() override; + Status Close() override; void Clear(); @@ -216,7 +216,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Read(void *buf, size_t &num_bytes) override; + Status Read(void *buf, size_t &num_bytes) override; //------------------------------------------------------------------ /// Write bytes to a file at the current file position. @@ -237,7 +237,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Write(const void *buf, size_t &num_bytes) override; + Status Write(const void *buf, size_t &num_bytes) override; //------------------------------------------------------------------ /// Seek to an offset relative to the beginning of the file. @@ -253,13 +253,13 @@ public: /// beginning of the file. /// /// @param[in] error_ptr - /// A pointer to a lldb_private::Error object that will be + /// A pointer to a lldb_private::Status object that will be /// filled in if non-nullptr. /// /// @return /// The resulting seek offset, or -1 on error. //------------------------------------------------------------------ - off_t SeekFromStart(off_t offset, Error *error_ptr = nullptr); + off_t SeekFromStart(off_t offset, Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Seek to an offset relative to the current file position. @@ -275,13 +275,13 @@ public: /// current file position. /// /// @param[in] error_ptr - /// A pointer to a lldb_private::Error object that will be + /// A pointer to a lldb_private::Status object that will be /// filled in if non-nullptr. /// /// @return /// The resulting seek offset, or -1 on error. //------------------------------------------------------------------ - off_t SeekFromCurrent(off_t offset, Error *error_ptr = nullptr); + off_t SeekFromCurrent(off_t offset, Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Seek to an offset relative to the end of the file. @@ -298,13 +298,13 @@ public: /// absolute file offset. /// /// @param[in] error_ptr - /// A pointer to a lldb_private::Error object that will be + /// A pointer to a lldb_private::Status object that will be /// filled in if non-nullptr. /// /// @return /// The resulting seek offset, or -1 on error. //------------------------------------------------------------------ - off_t SeekFromEnd(off_t offset, Error *error_ptr = nullptr); + off_t SeekFromEnd(off_t offset, Status *error_ptr = nullptr); //------------------------------------------------------------------ /// Read bytes from a file from the specified file offset. @@ -329,7 +329,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Read(void *dst, size_t &num_bytes, off_t &offset); + Status Read(void *dst, size_t &num_bytes, off_t &offset); //------------------------------------------------------------------ /// Read bytes from a file from the specified file offset. @@ -360,8 +360,8 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Read(size_t &num_bytes, off_t &offset, bool null_terminate, - lldb::DataBufferSP &data_buffer_sp); + Status Read(size_t &num_bytes, off_t &offset, bool null_terminate, + lldb::DataBufferSP &data_buffer_sp); //------------------------------------------------------------------ /// Write bytes to a file at the specified file offset. @@ -388,7 +388,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Write(const void *src, size_t &num_bytes, off_t &offset); + Status Write(const void *src, size_t &num_bytes, off_t &offset); //------------------------------------------------------------------ /// Flush the current stream @@ -397,7 +397,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Flush(); + Status Flush(); //------------------------------------------------------------------ /// Sync to disk. @@ -406,7 +406,7 @@ public: /// An error object that indicates success or the reason for /// failure. //------------------------------------------------------------------ - Error Sync(); + Status Sync(); //------------------------------------------------------------------ /// Get the permissions for a this file. @@ -415,9 +415,9 @@ public: /// Bits logical OR'ed together from the permission bits defined /// in lldb_private::File::Permissions. //------------------------------------------------------------------ - uint32_t GetPermissions(Error &error) const; + uint32_t GetPermissions(Status &error) const; - static uint32_t GetPermissions(const FileSpec &file_spec, Error &error); + static uint32_t GetPermissions(const FileSpec &file_spec, Status &error); //------------------------------------------------------------------ /// Return true if this file is interactive. diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/FileCache.h b/contrib/llvm/tools/lldb/include/lldb/Host/FileCache.h index 094ee695ce32..1c03540c1eb3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/FileCache.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/FileCache.h @@ -15,8 +15,8 @@ #include "lldb/lldb-forward.h" #include "lldb/lldb-types.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" namespace lldb_private { class FileCache { @@ -29,13 +29,13 @@ public: static FileCache &GetInstance(); lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, - uint32_t mode, Error &error); - bool CloseFile(lldb::user_id_t fd, Error &error); + uint32_t mode, Status &error); + bool CloseFile(lldb::user_id_t fd, Status &error); uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, - uint64_t src_len, Error &error); + uint64_t src_len, Status &error); uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Error &error); + uint64_t dst_len, Status &error); private: static FileCache *m_instance; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/FileSystem.h b/contrib/llvm/tools/lldb/include/lldb/Host/FileSystem.h index 794308ff4244..c13d5c84c631 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/FileSystem.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/FileSystem.h @@ -10,8 +10,8 @@ #ifndef liblldb_Host_FileSystem_h #define liblldb_Host_FileSystem_h -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/Chrono.h" #include "lldb/lldb-types.h" @@ -26,10 +26,10 @@ public: static const char *DEV_NULL; static const char *PATH_CONVERSION_ERROR; - static Error Symlink(const FileSpec &src, const FileSpec &dst); - static Error Readlink(const FileSpec &src, FileSpec &dst); + static Status Symlink(const FileSpec &src, const FileSpec &dst); + static Status Readlink(const FileSpec &src, FileSpec &dst); - static Error ResolveSymbolicLink(const FileSpec &src, FileSpec &dst); + static Status ResolveSymbolicLink(const FileSpec &src, FileSpec &dst); /// Wraps ::fopen in a platform-independent way. Once opened, FILEs can be /// manipulated and closed with the normal ::fread, ::fclose, etc. functions. diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/Host.h b/contrib/llvm/tools/lldb/include/lldb/Host/Host.h index 8415d429d5e2..c474dccab5db 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/Host.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/Host.h @@ -190,19 +190,19 @@ public: static short GetPosixspawnFlags(const ProcessLaunchInfo &launch_info); - static Error LaunchProcessPosixSpawn(const char *exe_path, - const ProcessLaunchInfo &launch_info, - lldb::pid_t &pid); + static Status LaunchProcessPosixSpawn(const char *exe_path, + const ProcessLaunchInfo &launch_info, + lldb::pid_t &pid); static bool AddPosixSpawnFileAction(void *file_actions, const FileAction *info, Log *log, - Error &error); + Status &error); #endif static const lldb::UnixSignalsSP &GetUnixSignals(); - static Error LaunchProcess(ProcessLaunchInfo &launch_info); + static Status LaunchProcess(ProcessLaunchInfo &launch_info); //------------------------------------------------------------------ /// Perform expansion of the command-line for this launch info @@ -211,10 +211,10 @@ public: // argument magic the platform defines as part of its typical // user experience //------------------------------------------------------------------ - static Error ShellExpandArguments(ProcessLaunchInfo &launch_info); + static Status ShellExpandArguments(ProcessLaunchInfo &launch_info); // TODO: Convert this function to take a StringRef. - static Error RunShellCommand( + static Status RunShellCommand( const char *command, // Shouldn't be NULL const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory @@ -226,7 +226,7 @@ public: uint32_t timeout_sec, bool run_in_default_shell = true); - static Error RunShellCommand( + static Status RunShellCommand( const Args &args, const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeProcessBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeProcessBase.h index 0befe867c296..07f98c24776c 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeProcessBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeProcessBase.h @@ -11,7 +11,7 @@ #define lldb_Host_HostNativeProcessBase_h_ #include "lldb/Host/HostProcess.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" @@ -28,8 +28,8 @@ public: : m_process(process) {} virtual ~HostNativeProcessBase() {} - virtual Error Terminate() = 0; - virtual Error GetMainModule(FileSpec &file_spec) const = 0; + virtual Status Terminate() = 0; + virtual Status GetMainModule(FileSpec &file_spec) const = 0; virtual lldb::pid_t GetProcessId() const = 0; virtual bool IsRunning() const = 0; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeThreadBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeThreadBase.h index 9bf86e0759f5..f1f89f3b75fe 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeThreadBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/HostNativeThreadBase.h @@ -10,7 +10,7 @@ #ifndef lldb_Host_HostNativeThreadBase_h_ #define lldb_Host_HostNativeThreadBase_h_ -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" @@ -31,8 +31,8 @@ public: explicit HostNativeThreadBase(lldb::thread_t thread); virtual ~HostNativeThreadBase() {} - virtual Error Join(lldb::thread_result_t *result) = 0; - virtual Error Cancel() = 0; + virtual Status Join(lldb::thread_result_t *result) = 0; + virtual Status Cancel() = 0; virtual bool IsJoinable() const; virtual void Reset(); lldb::thread_t Release(); diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/HostProcess.h b/contrib/llvm/tools/lldb/include/lldb/Host/HostProcess.h index 56c3ddd9a1c2..dfc997bd81f7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/HostProcess.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/HostProcess.h @@ -40,8 +40,8 @@ public: HostProcess(lldb::process_t process); ~HostProcess(); - Error Terminate(); - Error GetMainModule(FileSpec &file_spec) const; + Status Terminate(); + Status GetMainModule(FileSpec &file_spec) const; lldb::pid_t GetProcessId() const; bool IsRunning() const; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/HostThread.h b/contrib/llvm/tools/lldb/include/lldb/Host/HostThread.h index 96314813cf7c..0d2fbe6045af 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/HostThread.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/HostThread.h @@ -11,7 +11,7 @@ #define lldb_Host_HostThread_h_ #include "lldb/Host/HostNativeThreadForward.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-types.h" #include <memory> @@ -34,8 +34,8 @@ public: HostThread(); HostThread(lldb::thread_t thread); - Error Join(lldb::thread_result_t *result); - Error Cancel(); + Status Join(lldb::thread_result_t *result); + Status Cancel(); void Reset(); lldb::thread_t Release(); diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h b/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h index 90e0bcdcd9df..98ad5056de74 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/IOObject.h @@ -34,10 +34,10 @@ public: : m_fd_type(type), m_should_close_fd(should_close) {} virtual ~IOObject() {} - virtual Error Read(void *buf, size_t &num_bytes) = 0; - virtual Error Write(const void *buf, size_t &num_bytes) = 0; + virtual Status Read(void *buf, size_t &num_bytes) = 0; + virtual Status Write(const void *buf, size_t &num_bytes) = 0; virtual bool IsValid() const = 0; - virtual Error Close() = 0; + virtual Status Close() = 0; FDType GetFdType() const { return m_fd_type; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/LockFileBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/LockFileBase.h index 74eafb279324..4eda1916c72e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/LockFileBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/LockFileBase.h @@ -10,7 +10,7 @@ #ifndef liblldb_Host_LockFileBase_h_ #define liblldb_Host_LockFileBase_h_ -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include <functional> @@ -22,30 +22,30 @@ public: bool IsLocked() const; - Error WriteLock(const uint64_t start, const uint64_t len); - Error TryWriteLock(const uint64_t start, const uint64_t len); + Status WriteLock(const uint64_t start, const uint64_t len); + Status TryWriteLock(const uint64_t start, const uint64_t len); - Error ReadLock(const uint64_t start, const uint64_t len); - Error TryReadLock(const uint64_t start, const uint64_t len); + Status ReadLock(const uint64_t start, const uint64_t len); + Status TryReadLock(const uint64_t start, const uint64_t len); - Error Unlock(); + Status Unlock(); protected: - using Locker = std::function<Error(const uint64_t, const uint64_t)>; + using Locker = std::function<Status(const uint64_t, const uint64_t)>; LockFileBase(int fd); virtual bool IsValidFile() const; - virtual Error DoWriteLock(const uint64_t start, const uint64_t len) = 0; - virtual Error DoTryWriteLock(const uint64_t start, const uint64_t len) = 0; + virtual Status DoWriteLock(const uint64_t start, const uint64_t len) = 0; + virtual Status DoTryWriteLock(const uint64_t start, const uint64_t len) = 0; - virtual Error DoReadLock(const uint64_t start, const uint64_t len) = 0; - virtual Error DoTryReadLock(const uint64_t start, const uint64_t len) = 0; + virtual Status DoReadLock(const uint64_t start, const uint64_t len) = 0; + virtual Status DoTryReadLock(const uint64_t start, const uint64_t len) = 0; - virtual Error DoUnlock() = 0; + virtual Status DoUnlock() = 0; - Error DoLock(const Locker &locker, const uint64_t start, const uint64_t len); + Status DoLock(const Locker &locker, const uint64_t start, const uint64_t len); int m_fd; // not owned. bool m_locked; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoop.h b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoop.h index f5d906e98a7b..a722348b8843 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoop.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoop.h @@ -47,7 +47,7 @@ public: ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp, const Callback &callback, - Error &error) override; + Status &error) override; // Listening for signals from multiple MainLoop instances is perfectly safe as // long as they don't try to listen for the same signal. The callback function @@ -57,9 +57,9 @@ public: // However, since the callback is not invoked synchronously, you cannot use // this mechanism to handle SIGSEGV and the like. SignalHandleUP RegisterSignal(int signo, const Callback &callback, - Error &error); + Status &error); - Error Run() override; + Status Run() override; // This should only be performed from a callback. Do not attempt to terminate // the processing from another thread. diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h index b746a9cb208c..39ca9a0f0c9e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/MainLoopBase.h @@ -15,7 +15,7 @@ #include "llvm/Support/ErrorHandling.h" #include "lldb/Host/IOObject.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" namespace lldb_private { @@ -49,14 +49,14 @@ public: virtual ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp, const Callback &callback, - Error &error) { + Status &error) { llvm_unreachable("Not implemented"); } // Waits for registered events and invoke the proper callbacks. Returns when // all callbacks // deregister themselves or when someone requests termination. - virtual Error Run() { llvm_unreachable("Not implemented"); } + virtual Status Run() { llvm_unreachable("Not implemented"); } // Requests the exit of the Run() function. virtual void RequestTermination() { llvm_unreachable("Not implemented"); } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/MonitoringProcessLauncher.h b/contrib/llvm/tools/lldb/include/lldb/Host/MonitoringProcessLauncher.h index 7aa819a16c7c..9ad36e90a779 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/MonitoringProcessLauncher.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/MonitoringProcessLauncher.h @@ -25,7 +25,7 @@ public: std::unique_ptr<ProcessLauncher> delegate_launcher); HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) override; + Status &error) override; private: std::unique_ptr<ProcessLauncher> m_delegate_launcher; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/PipeBase.h b/contrib/llvm/tools/lldb/include/lldb/Host/PipeBase.h index f141b5d413a0..ad62072c7ba5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/PipeBase.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/PipeBase.h @@ -14,7 +14,7 @@ #include <chrono> #include <string> -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" @@ -23,17 +23,18 @@ class PipeBase { public: virtual ~PipeBase(); - virtual Error CreateNew(bool child_process_inherit) = 0; - virtual Error CreateNew(llvm::StringRef name, bool child_process_inherit) = 0; - virtual Error CreateWithUniqueName(llvm::StringRef prefix, - bool child_process_inherit, - llvm::SmallVectorImpl<char> &name) = 0; + virtual Status CreateNew(bool child_process_inherit) = 0; + virtual Status CreateNew(llvm::StringRef name, + bool child_process_inherit) = 0; + virtual Status CreateWithUniqueName(llvm::StringRef prefix, + bool child_process_inherit, + llvm::SmallVectorImpl<char> &name) = 0; - virtual Error OpenAsReader(llvm::StringRef name, - bool child_process_inherit) = 0; + virtual Status OpenAsReader(llvm::StringRef name, + bool child_process_inherit) = 0; - Error OpenAsWriter(llvm::StringRef name, bool child_process_inherit); - virtual Error + Status OpenAsWriter(llvm::StringRef name, bool child_process_inherit); + virtual Status OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) = 0; @@ -51,13 +52,13 @@ public: virtual void Close() = 0; // Delete named pipe. - virtual Error Delete(llvm::StringRef name) = 0; + virtual Status Delete(llvm::StringRef name) = 0; - virtual Error Write(const void *buf, size_t size, size_t &bytes_written) = 0; - virtual Error ReadWithTimeout(void *buf, size_t size, - const std::chrono::microseconds &timeout, - size_t &bytes_read) = 0; - Error Read(void *buf, size_t size, size_t &bytes_read); + virtual Status Write(const void *buf, size_t size, size_t &bytes_written) = 0; + virtual Status ReadWithTimeout(void *buf, size_t size, + const std::chrono::microseconds &timeout, + size_t &bytes_read) = 0; + Status Read(void *buf, size_t size, size_t &bytes_read); }; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/ProcessLauncher.h b/contrib/llvm/tools/lldb/include/lldb/Host/ProcessLauncher.h index 12049a69b3da..49fa84113f6c 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/ProcessLauncher.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/ProcessLauncher.h @@ -13,14 +13,14 @@ namespace lldb_private { class ProcessLaunchInfo; -class Error; +class Status; class HostProcess; class ProcessLauncher { public: virtual ~ProcessLauncher() {} virtual HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) = 0; + Status &error) = 0; }; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h b/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h index 36d506281cf8..c4233a233a89 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/Socket.h @@ -18,7 +18,7 @@ #include "lldb/Host/IOObject.h" #include "lldb/Host/Predicate.h" #include "lldb/Host/SocketAddress.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #ifdef _WIN32 #include "lldb/Host/windows/windows.h" @@ -53,34 +53,35 @@ public: static std::unique_ptr<Socket> Create(const SocketProtocol protocol, bool child_processes_inherit, - Error &error); + Status &error); - virtual Error Connect(llvm::StringRef name) = 0; - virtual Error Listen(llvm::StringRef name, int backlog) = 0; - virtual Error Accept(Socket *&socket) = 0; + virtual Status Connect(llvm::StringRef name) = 0; + virtual Status Listen(llvm::StringRef name, int backlog) = 0; + virtual Status Accept(Socket *&socket) = 0; // Initialize a Tcp Socket object in listening mode. listen and accept are // implemented // separately because the caller may wish to manipulate or query the socket // after it is // initialized, but before entering a blocking accept. - static Error TcpListen(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket, - Predicate<uint16_t> *predicate, int backlog = 5); - static Error TcpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket); - static Error UdpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket); - static Error UnixDomainConnect(llvm::StringRef host_and_port, + static Status TcpListen(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket, + Predicate<uint16_t> *predicate, int backlog = 5); + static Status TcpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket); + static Status UdpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket); + static Status UnixDomainConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, + Socket *&socket); + static Status UnixDomainAccept(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket); - static Error UnixDomainAccept(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket); - static Error UnixAbstractConnect(llvm::StringRef host_and_port, + static Status UnixAbstractConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, + Socket *&socket); + static Status UnixAbstractAccept(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket); - static Error UnixAbstractAccept(llvm::StringRef host_and_port, - bool child_processes_inherit, - Socket *&socket); int GetOption(int level, int option_name, int &option_value); int SetOption(int level, int option_name, int option_value); @@ -88,18 +89,18 @@ public: NativeSocket GetNativeSocket() const { return m_socket; } SocketProtocol GetSocketProtocol() const { return m_protocol; } - Error Read(void *buf, size_t &num_bytes) override; - Error Write(const void *buf, size_t &num_bytes) override; + Status Read(void *buf, size_t &num_bytes) override; + Status Write(const void *buf, size_t &num_bytes) override; - virtual Error PreDisconnect(); - Error Close() override; + virtual Status PreDisconnect(); + Status Close() override; bool IsValid() const override { return m_socket != kInvalidSocketValue; } WaitableHandle GetWaitableHandle() override; static bool DecodeHostAndPort(llvm::StringRef host_and_port, std::string &host_str, std::string &port_str, - int32_t &port, Error *error_ptr); + int32_t &port, Status *error_ptr); protected: Socket(SocketProtocol protocol, bool should_close, @@ -107,13 +108,13 @@ protected: virtual size_t Send(const void *buf, const size_t num_bytes); - static void SetLastError(Error &error); + static void SetLastError(Status &error); static NativeSocket CreateSocket(const int domain, const int type, const int protocol, - bool child_processes_inherit, Error &error); + bool child_processes_inherit, Status &error); static NativeSocket AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, - bool child_processes_inherit, Error &error); + bool child_processes_inherit, Status &error); SocketProtocol m_protocol; NativeSocket m_socket; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/ThreadLauncher.h b/contrib/llvm/tools/lldb/include/lldb/Host/ThreadLauncher.h index 4e388ca6bb9c..b50f0e2c2c43 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/ThreadLauncher.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/ThreadLauncher.h @@ -12,7 +12,7 @@ #define lldb_Host_ThreadLauncher_h_ #include "lldb/Host/HostThread.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-types.h" #include "llvm/ADT/StringRef.h" @@ -23,7 +23,7 @@ class ThreadLauncher { public: static HostThread LaunchThread(llvm::StringRef name, lldb::thread_func_t thread_function, - lldb::thread_arg_t thread_arg, Error *error_ptr, + lldb::thread_arg_t thread_arg, Status *error_ptr, size_t min_stack_byte_size = 0); // Minimum stack size in bytes, // set stack size to zero for // default platform thread stack diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpoint.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpoint.h index 2f872e1d5a52..73639d64c9e8 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpoint.h @@ -24,9 +24,9 @@ public: virtual ~NativeBreakpoint(); - Error Enable(); + Status Enable(); - Error Disable(); + Status Disable(); lldb::addr_t GetAddress() const { return m_addr; } @@ -38,9 +38,9 @@ protected: const lldb::addr_t m_addr; int32_t m_ref_count; - virtual Error DoEnable() = 0; + virtual Status DoEnable() = 0; - virtual Error DoDisable() = 0; + virtual Status DoDisable() = 0; private: bool m_enabled; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpointList.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpointList.h index 1d314e02b1d5..ffa659fdd869 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpointList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeBreakpointList.h @@ -10,7 +10,7 @@ #ifndef liblldb_NativeBreakpointList_h_ #define liblldb_NativeBreakpointList_h_ -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-forward.h" // #include "lldb/Host/NativeBreakpoint.h" @@ -29,24 +29,25 @@ using HardwareBreakpointMap = std::map<lldb::addr_t, HardwareBreakpoint>; class NativeBreakpointList { public: - typedef std::function<Error(lldb::addr_t addr, size_t size_hint, - bool hardware, NativeBreakpointSP &breakpoint_sp)> + typedef std::function<Status(lldb::addr_t addr, size_t size_hint, + bool hardware, + NativeBreakpointSP &breakpoint_sp)> CreateBreakpointFunc; NativeBreakpointList(); - Error AddRef(lldb::addr_t addr, size_t size_hint, bool hardware, - CreateBreakpointFunc create_func); + Status AddRef(lldb::addr_t addr, size_t size_hint, bool hardware, + CreateBreakpointFunc create_func); - Error DecRef(lldb::addr_t addr); + Status DecRef(lldb::addr_t addr); - Error EnableBreakpoint(lldb::addr_t addr); + Status EnableBreakpoint(lldb::addr_t addr); - Error DisableBreakpoint(lldb::addr_t addr); + Status DisableBreakpoint(lldb::addr_t addr); - Error GetBreakpoint(lldb::addr_t addr, NativeBreakpointSP &breakpoint_sp); + Status GetBreakpoint(lldb::addr_t addr, NativeBreakpointSP &breakpoint_sp); - Error RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, size_t size) const; + Status RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, size_t size) const; private: typedef std::map<lldb::addr_t, NativeBreakpointSP> BreakpointMap; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h index 7ad09d41eacf..388edef0578d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeProcessProtocol.h @@ -11,7 +11,7 @@ #define liblldb_NativeProcessProtocol_h_ #include "lldb/Host/MainLoop.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-forward.h" #include "lldb/lldb-types.h" #include "llvm/ADT/ArrayRef.h" @@ -37,11 +37,11 @@ class NativeProcessProtocol public: virtual ~NativeProcessProtocol() {} - virtual Error Resume(const ResumeActionList &resume_actions) = 0; + virtual Status Resume(const ResumeActionList &resume_actions) = 0; - virtual Error Halt() = 0; + virtual Status Halt() = 0; - virtual Error Detach() = 0; + virtual Status Detach() = 0; //------------------------------------------------------------------ /// Sends a process a UNIX signal \a signal. @@ -49,7 +49,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error Signal(int signo) = 0; + virtual Status Signal(int signo) = 0; //------------------------------------------------------------------ /// Tells a process to interrupt all operations as if by a Ctrl-C. @@ -61,36 +61,36 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error Interrupt(); + virtual Status Interrupt(); - virtual Error Kill() = 0; + virtual Status Kill() = 0; //------------------------------------------------------------------ // Tells a process not to stop the inferior on given signals // and just reinject them back. //------------------------------------------------------------------ - virtual Error IgnoreSignals(llvm::ArrayRef<int> signals); + virtual Status IgnoreSignals(llvm::ArrayRef<int> signals); //---------------------------------------------------------------------- // Memory and memory region functions //---------------------------------------------------------------------- - virtual Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info); + virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info); - virtual Error ReadMemory(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) = 0; + virtual Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read) = 0; - virtual Error ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) = 0; + virtual Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, + size_t size, size_t &bytes_read) = 0; - virtual Error WriteMemory(lldb::addr_t addr, const void *buf, size_t size, - size_t &bytes_written) = 0; + virtual Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, + size_t &bytes_written) = 0; - virtual Error AllocateMemory(size_t size, uint32_t permissions, - lldb::addr_t &addr) = 0; + virtual Status AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) = 0; - virtual Error DeallocateMemory(lldb::addr_t addr) = 0; + virtual Status DeallocateMemory(lldb::addr_t addr) = 0; virtual lldb::addr_t GetSharedLibraryInfoAddress() = 0; @@ -103,23 +103,23 @@ public: //---------------------------------------------------------------------- // Breakpoint functions //---------------------------------------------------------------------- - virtual Error SetBreakpoint(lldb::addr_t addr, uint32_t size, - bool hardware) = 0; + virtual Status SetBreakpoint(lldb::addr_t addr, uint32_t size, + bool hardware) = 0; - virtual Error RemoveBreakpoint(lldb::addr_t addr, bool hardware = false); + virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware = false); - virtual Error EnableBreakpoint(lldb::addr_t addr); + virtual Status EnableBreakpoint(lldb::addr_t addr); - virtual Error DisableBreakpoint(lldb::addr_t addr); + virtual Status DisableBreakpoint(lldb::addr_t addr); //---------------------------------------------------------------------- // Hardware Breakpoint functions //---------------------------------------------------------------------- virtual const HardwareBreakpointMap &GetHardwareBreakpointMap() const; - virtual Error SetHardwareBreakpoint(lldb::addr_t addr, size_t size); + virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size); - virtual Error RemoveHardwareBreakpoint(lldb::addr_t addr); + virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr); //---------------------------------------------------------------------- // Watchpoint functions @@ -129,10 +129,10 @@ public: virtual llvm::Optional<std::pair<uint32_t, uint32_t>> GetHardwareDebugSupportInfo() const; - virtual Error SetWatchpoint(lldb::addr_t addr, size_t size, - uint32_t watch_flags, bool hardware); + virtual Status SetWatchpoint(lldb::addr_t addr, size_t size, + uint32_t watch_flags, bool hardware); - virtual Error RemoveWatchpoint(lldb::addr_t addr); + virtual Status RemoveWatchpoint(lldb::addr_t addr); //---------------------------------------------------------------------- // Accessors @@ -239,11 +239,11 @@ public: //------------------------------------------------------------------ bool UnregisterNativeDelegate(NativeDelegate &native_delegate); - virtual Error GetLoadedModuleFileSpec(const char *module_path, - FileSpec &file_spec) = 0; + virtual Status GetLoadedModuleFileSpec(const char *module_path, + FileSpec &file_spec) = 0; - virtual Error GetFileLoadAddress(const llvm::StringRef &file_name, - lldb::addr_t &load_addr) = 0; + virtual Status GetFileLoadAddress(const llvm::StringRef &file_name, + lldb::addr_t &load_addr) = 0; //------------------------------------------------------------------ /// Launch a process for debugging. This method will create an concrete @@ -273,9 +273,9 @@ public: /// An error object indicating if the operation succeeded, /// and if not, what error occurred. //------------------------------------------------------------------ - static Error Launch(ProcessLaunchInfo &launch_info, - NativeDelegate &native_delegate, MainLoop &mainloop, - NativeProcessProtocolSP &process_sp); + static Status Launch(ProcessLaunchInfo &launch_info, + NativeDelegate &native_delegate, MainLoop &mainloop, + NativeProcessProtocolSP &process_sp); //------------------------------------------------------------------ /// Attach to an existing process. This method will create an concrete @@ -305,8 +305,8 @@ public: /// An error object indicating if the operation succeeded, /// and if not, what error occurred. //------------------------------------------------------------------ - static Error Attach(lldb::pid_t pid, NativeDelegate &native_delegate, - MainLoop &mainloop, NativeProcessProtocolSP &process_sp); + static Status Attach(lldb::pid_t pid, NativeDelegate &native_delegate, + MainLoop &mainloop, NativeProcessProtocolSP &process_sp); protected: lldb::pid_t m_pid; @@ -356,9 +356,9 @@ protected: // ----------------------------------------------------------- // Internal interface for software breakpoints // ----------------------------------------------------------- - Error SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint); + Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint); - virtual Error + virtual Status GetSoftwareBreakpointTrapOpcode(size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) = 0; @@ -376,7 +376,7 @@ protected: // ----------------------------------------------------------- // Static helper methods for derived classes. // ----------------------------------------------------------- - static Error ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch); + static Status ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch); private: void SynchronouslyNotifyProcessStateChanged(lldb::StateType state); diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeRegisterContext.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeRegisterContext.h index 1d8b51c60cc4..982d81b9ac4c 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeRegisterContext.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeRegisterContext.h @@ -53,15 +53,15 @@ public: virtual const RegisterSet *GetRegisterSet(uint32_t set_index) const = 0; - virtual Error ReadRegister(const RegisterInfo *reg_info, - RegisterValue ®_value) = 0; + virtual Status ReadRegister(const RegisterInfo *reg_info, + RegisterValue ®_value) = 0; - virtual Error WriteRegister(const RegisterInfo *reg_info, - const RegisterValue ®_value) = 0; + virtual Status WriteRegister(const RegisterInfo *reg_info, + const RegisterValue ®_value) = 0; - virtual Error ReadAllRegisterValues(lldb::DataBufferSP &data_sp) = 0; + virtual Status ReadAllRegisterValues(lldb::DataBufferSP &data_sp) = 0; - virtual Error WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) = 0; + virtual Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) = 0; uint32_t ConvertRegisterKindToRegisterNumber(uint32_t kind, uint32_t num) const; @@ -75,10 +75,10 @@ public: virtual bool ClearHardwareBreakpoint(uint32_t hw_idx); - virtual Error ClearAllHardwareBreakpoints(); + virtual Status ClearAllHardwareBreakpoints(); - virtual Error GetHardwareBreakHitIndex(uint32_t &bp_index, - lldb::addr_t trap_addr); + virtual Status GetHardwareBreakHitIndex(uint32_t &bp_index, + lldb::addr_t trap_addr); virtual uint32_t NumSupportedHardwareWatchpoints(); @@ -87,14 +87,14 @@ public: virtual bool ClearHardwareWatchpoint(uint32_t hw_index); - virtual Error ClearAllHardwareWatchpoints(); + virtual Status ClearAllHardwareWatchpoints(); - virtual Error IsWatchpointHit(uint32_t wp_index, bool &is_hit); + virtual Status IsWatchpointHit(uint32_t wp_index, bool &is_hit); - virtual Error GetWatchpointHitIndex(uint32_t &wp_index, - lldb::addr_t trap_addr); + virtual Status GetWatchpointHitIndex(uint32_t &wp_index, + lldb::addr_t trap_addr); - virtual Error IsWatchpointVacant(uint32_t wp_index, bool &is_vacant); + virtual Status IsWatchpointVacant(uint32_t wp_index, bool &is_vacant); virtual lldb::addr_t GetWatchpointAddress(uint32_t wp_index); @@ -114,12 +114,12 @@ public: virtual bool HardwareSingleStep(bool enable); - virtual Error + virtual Status ReadRegisterValueFromMemory(const lldb_private::RegisterInfo *reg_info, lldb::addr_t src_addr, size_t src_len, RegisterValue ®_value); - virtual Error + virtual Status WriteRegisterValueToMemory(const lldb_private::RegisterInfo *reg_info, lldb::addr_t dst_addr, size_t dst_len, const RegisterValue ®_value); @@ -141,15 +141,15 @@ public: virtual lldb::addr_t GetPCfromBreakpointLocation(lldb::addr_t fail_value = LLDB_INVALID_ADDRESS); - Error SetPC(lldb::addr_t pc); + Status SetPC(lldb::addr_t pc); lldb::addr_t GetSP(lldb::addr_t fail_value = LLDB_INVALID_ADDRESS); - Error SetSP(lldb::addr_t sp); + Status SetSP(lldb::addr_t sp); lldb::addr_t GetFP(lldb::addr_t fail_value = LLDB_INVALID_ADDRESS); - Error SetFP(lldb::addr_t fp); + Status SetFP(lldb::addr_t fp); const char *GetRegisterName(uint32_t reg); @@ -162,9 +162,9 @@ public: lldb::addr_t ReadRegisterAsUnsigned(const RegisterInfo *reg_info, lldb::addr_t fail_value); - Error WriteRegisterFromUnsigned(uint32_t reg, uint64_t uval); + Status WriteRegisterFromUnsigned(uint32_t reg, uint64_t uval); - Error WriteRegisterFromUnsigned(const RegisterInfo *reg_info, uint64_t uval); + Status WriteRegisterFromUnsigned(const RegisterInfo *reg_info, uint64_t uval); // uint32_t // GetStopID () const diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeThreadProtocol.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeThreadProtocol.h index 8f26616a2b4a..2e6c96a34cf5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeThreadProtocol.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeThreadProtocol.h @@ -33,13 +33,13 @@ public: virtual NativeRegisterContextSP GetRegisterContext() = 0; - virtual Error ReadRegister(uint32_t reg, RegisterValue ®_value); + virtual Status ReadRegister(uint32_t reg, RegisterValue ®_value); - virtual Error WriteRegister(uint32_t reg, const RegisterValue ®_value); + virtual Status WriteRegister(uint32_t reg, const RegisterValue ®_value); - virtual Error SaveAllRegisters(lldb::DataBufferSP &data_sp); + virtual Status SaveAllRegisters(lldb::DataBufferSP &data_sp); - virtual Error RestoreAllRegisters(lldb::DataBufferSP &data_sp); + virtual Status RestoreAllRegisters(lldb::DataBufferSP &data_sp); virtual bool GetStopReason(ThreadStopInfo &stop_info, std::string &description) = 0; @@ -51,17 +51,17 @@ public: // --------------------------------------------------------------------- // Thread-specific watchpoints // --------------------------------------------------------------------- - virtual Error SetWatchpoint(lldb::addr_t addr, size_t size, - uint32_t watch_flags, bool hardware) = 0; + virtual Status SetWatchpoint(lldb::addr_t addr, size_t size, + uint32_t watch_flags, bool hardware) = 0; - virtual Error RemoveWatchpoint(lldb::addr_t addr) = 0; + virtual Status RemoveWatchpoint(lldb::addr_t addr) = 0; // --------------------------------------------------------------------- // Thread-specific Hardware Breakpoint routines // --------------------------------------------------------------------- - virtual Error SetHardwareBreakpoint(lldb::addr_t addr, size_t size) = 0; + virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size) = 0; - virtual Error RemoveHardwareBreakpoint(lldb::addr_t addr) = 0; + virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr) = 0; protected: NativeProcessProtocolWP m_process_wp; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeWatchpointList.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeWatchpointList.h index ae3476f5f07e..02920e6faacb 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeWatchpointList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/NativeWatchpointList.h @@ -10,7 +10,7 @@ #ifndef liblldb_NativeWatchpointList_h_ #define liblldb_NativeWatchpointList_h_ -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-forward.h" #include <map> @@ -25,10 +25,10 @@ struct NativeWatchpoint { class NativeWatchpointList { public: - Error Add(lldb::addr_t addr, size_t size, uint32_t watch_flags, - bool hardware); + Status Add(lldb::addr_t addr, size_t size, uint32_t watch_flags, + bool hardware); - Error Remove(lldb::addr_t addr); + Status Remove(lldb::addr_t addr); using WatchpointMap = std::map<lldb::addr_t, NativeWatchpoint>; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/SoftwareBreakpoint.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/SoftwareBreakpoint.h index 703f6bb95d48..e0f235fecd93 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/SoftwareBreakpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/SoftwareBreakpoint.h @@ -18,18 +18,18 @@ class SoftwareBreakpoint : public NativeBreakpoint { friend class NativeBreakpointList; public: - static Error CreateSoftwareBreakpoint(NativeProcessProtocol &process, - lldb::addr_t addr, size_t size_hint, - NativeBreakpointSP &breakpoint_spn); + static Status CreateSoftwareBreakpoint(NativeProcessProtocol &process, + lldb::addr_t addr, size_t size_hint, + NativeBreakpointSP &breakpoint_spn); SoftwareBreakpoint(NativeProcessProtocol &process, lldb::addr_t addr, const uint8_t *saved_opcodes, const uint8_t *trap_opcodes, size_t opcode_size); protected: - Error DoEnable() override; + Status DoEnable() override; - Error DoDisable() override; + Status DoDisable() override; bool IsSoftwareBreakpoint() const override; @@ -42,11 +42,11 @@ private: uint8_t m_trap_opcodes[MAX_TRAP_OPCODE_SIZE]; const size_t m_opcode_size; - static Error EnableSoftwareBreakpoint(NativeProcessProtocol &process, - lldb::addr_t addr, - size_t bp_opcode_size, - const uint8_t *bp_opcode_bytes, - uint8_t *saved_opcode_bytes); + static Status EnableSoftwareBreakpoint(NativeProcessProtocol &process, + lldb::addr_t addr, + size_t bp_opcode_size, + const uint8_t *bp_opcode_bytes, + uint8_t *saved_opcode_bytes); }; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/TCPSocket.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/TCPSocket.h index 5b72f344019f..0d32a70fd381 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/TCPSocket.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/TCPSocket.h @@ -39,11 +39,11 @@ public: int SetOptionNoDelay(); int SetOptionReuseAddress(); - Error Connect(llvm::StringRef name) override; - Error Listen(llvm::StringRef name, int backlog) override; - Error Accept(Socket *&conn_socket) override; + Status Connect(llvm::StringRef name) override; + Status Listen(llvm::StringRef name, int backlog) override; + Status Accept(Socket *&conn_socket) override; - Error CreateSocket(int domain); + Status CreateSocket(int domain); bool IsValid() const override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/common/UDPSocket.h b/contrib/llvm/tools/lldb/include/lldb/Host/common/UDPSocket.h index 977ce151e4ff..27b2d1dc9834 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/common/UDPSocket.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/common/UDPSocket.h @@ -17,16 +17,16 @@ class UDPSocket : public Socket { public: UDPSocket(bool should_close, bool child_processes_inherit); - static Error Connect(llvm::StringRef name, bool child_processes_inherit, - Socket *&socket); + static Status Connect(llvm::StringRef name, bool child_processes_inherit, + Socket *&socket); private: UDPSocket(NativeSocket socket); size_t Send(const void *buf, const size_t num_bytes) override; - Error Connect(llvm::StringRef name) override; - Error Listen(llvm::StringRef name, int backlog) override; - Error Accept(Socket *&socket) override; + Status Connect(llvm::StringRef name) override; + Status Listen(llvm::StringRef name, int backlog) override; + Status Accept(Socket *&socket) override; SocketAddress m_sockaddr; }; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h index f002dd167ce2..f57c93684002 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ConnectionFileDescriptorPosix.h @@ -26,7 +26,7 @@ namespace lldb_private { -class Error; +class Status; class Socket; class SocketAddress; @@ -53,20 +53,20 @@ public: bool IsConnected() const override; - lldb::ConnectionStatus Connect(llvm::StringRef s, Error *error_ptr) override; + lldb::ConnectionStatus Connect(llvm::StringRef s, Status *error_ptr) override; - lldb::ConnectionStatus Disconnect(Error *error_ptr) override; + lldb::ConnectionStatus Disconnect(Status *error_ptr) override; size_t Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, - lldb::ConnectionStatus &status, Error *error_ptr) override; + lldb::ConnectionStatus &status, Status *error_ptr) override; size_t Write(const void *src, size_t src_len, lldb::ConnectionStatus &status, - Error *error_ptr) override; + Status *error_ptr) override; std::string GetURI() override; lldb::ConnectionStatus BytesAvailable(const Timeout<std::micro> &timeout, - Error *error_ptr); + Status *error_ptr); bool InterruptRead() override; @@ -83,21 +83,21 @@ protected: void CloseCommandPipe(); lldb::ConnectionStatus SocketListenAndAccept(llvm::StringRef host_and_port, - Error *error_ptr); + Status *error_ptr); lldb::ConnectionStatus ConnectTCP(llvm::StringRef host_and_port, - Error *error_ptr); + Status *error_ptr); - lldb::ConnectionStatus ConnectUDP(llvm::StringRef args, Error *error_ptr); + lldb::ConnectionStatus ConnectUDP(llvm::StringRef args, Status *error_ptr); lldb::ConnectionStatus NamedSocketConnect(llvm::StringRef socket_name, - Error *error_ptr); + Status *error_ptr); lldb::ConnectionStatus NamedSocketAccept(llvm::StringRef socket_name, - Error *error_ptr); + Status *error_ptr); lldb::ConnectionStatus UnixAbstractSocketConnect(llvm::StringRef socket_name, - Error *error_ptr); + Status *error_ptr); lldb::IOObjectSP m_read_sp; lldb::IOObjectSP m_write_sp; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/DomainSocket.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/DomainSocket.h index 78a3dc89828a..e66b3f971faf 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/DomainSocket.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/DomainSocket.h @@ -17,9 +17,9 @@ class DomainSocket : public Socket { public: DomainSocket(bool should_close, bool child_processes_inherit); - Error Connect(llvm::StringRef name) override; - Error Listen(llvm::StringRef name, int backlog) override; - Error Accept(Socket *&socket) override; + Status Connect(llvm::StringRef name) override; + Status Listen(llvm::StringRef name, int backlog) override; + Status Accept(Socket *&socket) override; protected: DomainSocket(SocketProtocol protocol, bool child_processes_inherit); diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostProcessPosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostProcessPosix.h index aed3cccef2e2..0a6d8822d44f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostProcessPosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostProcessPosix.h @@ -15,7 +15,7 @@ // Other libraries and framework includes // Project includes #include "lldb/Host/HostNativeProcessBase.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-types.h" namespace lldb_private { @@ -28,11 +28,11 @@ public: HostProcessPosix(lldb::process_t process); ~HostProcessPosix() override; - virtual Error Signal(int signo) const; - static Error Signal(lldb::process_t process, int signo); + virtual Status Signal(int signo) const; + static Status Signal(lldb::process_t process, int signo); - Error Terminate() override; - Error GetMainModule(FileSpec &file_spec) const override; + Status Terminate() override; + Status GetMainModule(FileSpec &file_spec) const override; lldb::pid_t GetProcessId() const override; bool IsRunning() const override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostThreadPosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostThreadPosix.h index 99b99d767b18..c230a61bc575 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostThreadPosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/HostThreadPosix.h @@ -22,10 +22,10 @@ public: HostThreadPosix(lldb::thread_t thread); ~HostThreadPosix() override; - Error Join(lldb::thread_result_t *result) override; - Error Cancel() override; + Status Join(lldb::thread_result_t *result) override; + Status Cancel() override; - Error Detach(); + Status Detach(); }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/LockFilePosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/LockFilePosix.h index dde9bd0eefe6..a59a7fe3e729 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/LockFilePosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/LockFilePosix.h @@ -20,15 +20,15 @@ public: ~LockFilePosix() override; protected: - Error DoWriteLock(const uint64_t start, const uint64_t len) override; + Status DoWriteLock(const uint64_t start, const uint64_t len) override; - Error DoTryWriteLock(const uint64_t start, const uint64_t len) override; + Status DoTryWriteLock(const uint64_t start, const uint64_t len) override; - Error DoReadLock(const uint64_t start, const uint64_t len) override; + Status DoReadLock(const uint64_t start, const uint64_t len) override; - Error DoTryReadLock(const uint64_t start, const uint64_t len) override; + Status DoTryReadLock(const uint64_t start, const uint64_t len) override; - Error DoUnlock() override; + Status DoUnlock() override; }; } // namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/PipePosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/PipePosix.h index 738f95ed0db8..8208b1b8bd6b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/PipePosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/PipePosix.h @@ -35,12 +35,14 @@ public: ~PipePosix() override; - Error CreateNew(bool child_process_inherit) override; - Error CreateNew(llvm::StringRef name, bool child_process_inherit) override; - Error CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, - llvm::SmallVectorImpl<char> &name) override; - Error OpenAsReader(llvm::StringRef name, bool child_process_inherit) override; - Error + Status CreateNew(bool child_process_inherit) override; + Status CreateNew(llvm::StringRef name, bool child_process_inherit) override; + Status CreateWithUniqueName(llvm::StringRef prefix, + bool child_process_inherit, + llvm::SmallVectorImpl<char> &name) override; + Status OpenAsReader(llvm::StringRef name, + bool child_process_inherit) override; + Status OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) override; @@ -57,12 +59,12 @@ public: // Close both descriptors void Close() override; - Error Delete(llvm::StringRef name) override; + Status Delete(llvm::StringRef name) override; - Error Write(const void *buf, size_t size, size_t &bytes_written) override; - Error ReadWithTimeout(void *buf, size_t size, - const std::chrono::microseconds &timeout, - size_t &bytes_read) override; + Status Write(const void *buf, size_t size, size_t &bytes_written) override; + Status ReadWithTimeout(void *buf, size_t size, + const std::chrono::microseconds &timeout, + size_t &bytes_read) override; private: int m_fds[2]; diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosix.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosix.h index e481e3dc7ea9..4800c4066049 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosix.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosix.h @@ -17,7 +17,7 @@ namespace lldb_private { class ProcessLauncherPosix : public ProcessLauncher { public: HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) override; + Status &error) override; }; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosixFork.h b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosixFork.h index 77bdab535c1b..1193a20b4d36 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosixFork.h +++ b/contrib/llvm/tools/lldb/include/lldb/Host/posix/ProcessLauncherPosixFork.h @@ -17,7 +17,7 @@ namespace lldb_private { class ProcessLauncherPosixFork : public ProcessLauncher { public: HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) override; + Status &error) override; }; } // end of namespace lldb_private diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/Args.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/Args.h index bdbf81e02d9d..98046cd59545 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/Args.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/Args.h @@ -21,7 +21,7 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" // Project includes -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-types.h" #include "lldb/lldb-types.h" @@ -322,8 +322,8 @@ public: /// /// @see class Options //------------------------------------------------------------------ - Error ParseOptions(Options &options, ExecutionContext *execution_context, - lldb::PlatformSP platform_sp, bool require_validation); + Status ParseOptions(Options &options, ExecutionContext *execution_context, + lldb::PlatformSP platform_sp, bool require_validation); bool IsPositionalArgument(const char *arg); @@ -377,7 +377,7 @@ public: static lldb::addr_t StringToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, - lldb::addr_t fail_value, Error *error); + lldb::addr_t fail_value, Status *error); static bool StringToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr); @@ -387,17 +387,17 @@ public: static int64_t StringToOptionEnum(llvm::StringRef s, OptionEnumValueElement *enum_values, - int32_t fail_value, Error &error); + int32_t fail_value, Status &error); static lldb::ScriptLanguage StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value, bool *success_ptr); // TODO: Use StringRef - static Error StringToFormat(const char *s, lldb::Format &format, - size_t *byte_size_ptr); // If non-NULL, then a - // byte size can precede - // the format character + static Status StringToFormat(const char *s, lldb::Format &format, + size_t *byte_size_ptr); // If non-NULL, then a + // byte size can precede + // the format character static lldb::Encoding StringToEncoding(llvm::StringRef s, diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h index 031ea10d6ad4..f47411079a3a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandInterpreter.h @@ -510,7 +510,7 @@ protected: StringList *matches = nullptr) const; private: - Error PreprocessCommand(std::string &command); + Status PreprocessCommand(std::string &command); // Completely resolves aliases and abbreviations, returning a pointer to the // final command object and updating command_line to the fully substituted diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandReturnObject.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandReturnObject.h index 8e467e118477..7b04c391bc76 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandReturnObject.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/CommandReturnObject.h @@ -129,7 +129,7 @@ public: AppendError(llvm::formatv(format, std::forward<Args>(args)...).str()); } - void SetError(const Error &error, const char *fallback_error_cstr = nullptr); + void SetError(const Status &error, const char *fallback_error_cstr = nullptr); void SetError(llvm::StringRef error_cstr); diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupArchitecture.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupArchitecture.h index 742cd6d1321d..e73a53421f28 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupArchitecture.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupArchitecture.h @@ -31,8 +31,8 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupBoolean.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupBoolean.h index 931a6d73e728..53d08d79d67a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupBoolean.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupBoolean.h @@ -38,9 +38,9 @@ public: return llvm::ArrayRef<OptionDefinition>(&m_option_definition, 1); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFile.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFile.h index 93e3ed75d342..d0c25b8bf8e6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFile.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFile.h @@ -37,9 +37,9 @@ public: return llvm::ArrayRef<OptionDefinition>(&m_option_definition, 1); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; @@ -70,9 +70,9 @@ public: return llvm::ArrayRef<OptionDefinition>(&m_option_definition, 1); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFormat.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFormat.h index f3a42037afc5..ddf2ccece3bd 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFormat.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupFormat.h @@ -43,9 +43,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupOutputFile.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupOutputFile.h index cb891f0f7ecb..19453c6215ef 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupOutputFile.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupOutputFile.h @@ -31,9 +31,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupPlatform.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupPlatform.h index 8cee9a671869..e79662400279 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupPlatform.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupPlatform.h @@ -36,15 +36,15 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; lldb::PlatformSP CreatePlatformWithOptions(CommandInterpreter &interpreter, const ArchSpec &arch, - bool make_selected, Error &error, + bool make_selected, Status &error, ArchSpec &platform_arch) const; bool PlatformWasSpecified() const { return !m_platform_name.empty(); } diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupString.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupString.h index 21bfc08d130f..01e8aa9dc3b6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupString.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupString.h @@ -35,9 +35,9 @@ public: return llvm::ArrayRef<OptionDefinition>(&m_option_definition, 1); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUInt64.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUInt64.h index 3f04eac72888..82eb0e26af9b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUInt64.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUInt64.h @@ -36,9 +36,9 @@ public: return llvm::ArrayRef<OptionDefinition>(&m_option_definition, 1); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUUID.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUUID.h index 9a7c6cf9cffe..def97d5f2551 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUUID.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupUUID.h @@ -31,9 +31,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupValueObjectDisplay.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupValueObjectDisplay.h index 694464b8b917..0e075773b3f7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupValueObjectDisplay.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupValueObjectDisplay.h @@ -31,9 +31,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupVariable.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupVariable.h index 0735de45d1a6..c9e90320e141 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupVariable.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupVariable.h @@ -31,9 +31,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupWatchpoint.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupWatchpoint.h index c67c8f071b54..f2665638ba85 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupWatchpoint.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionGroupWatchpoint.h @@ -32,9 +32,9 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; - Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValue.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValue.h index 648ad33e2fc8..6008e1ea4411 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValue.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValue.h @@ -16,7 +16,7 @@ // Project includes #include "lldb/Core/FormatEntity.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-private-enumerations.h" #include "lldb/lldb-private-interfaces.h" @@ -91,7 +91,7 @@ public: virtual void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) = 0; - virtual Error + virtual Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign); @@ -108,15 +108,16 @@ public: // Subclasses can override these functions //----------------------------------------------------------------- virtual lldb::OptionValueSP GetSubValue(const ExecutionContext *exe_ctx, - llvm::StringRef name, bool will_modify, - Error &error) const { + llvm::StringRef name, + bool will_modify, + Status &error) const { error.SetErrorStringWithFormat("'%s' is not a value subvalue", name.str().c_str()); return lldb::OptionValueSP(); } - virtual Error SetSubValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, llvm::StringRef name, - llvm::StringRef value); + virtual Status SetSubValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, llvm::StringRef name, + llvm::StringRef value); virtual bool IsAggregateValue() const { return false; } @@ -180,7 +181,7 @@ public: static lldb::OptionValueSP CreateValueFromCStringForTypeMask(const char *value_cstr, uint32_t type_mask, - Error &error); + Status &error); // Get this value as a uint64_t value if it is encoded as a boolean, // uint64_t or int64_t. Other types will cause "fail_value" to be diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArch.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArch.h index aa548124e2d6..e1a354d4ae21 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArch.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArch.h @@ -46,10 +46,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArray.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArray.h index 1e568cac402d..bbf4e371a893 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArray.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueArray.h @@ -36,10 +36,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; @@ -55,7 +55,7 @@ public: lldb::OptionValueSP GetSubValue(const ExecutionContext *exe_ctx, llvm::StringRef name, bool will_modify, - Error &error) const override; + Status &error) const override; //--------------------------------------------------------------------- // Subclass specific functions @@ -122,7 +122,7 @@ public: size_t GetArgs(Args &args) const; - Error SetArgs(const Args &args, VarSetOperationType op); + Status SetArgs(const Args &args, VarSetOperationType op); protected: typedef std::vector<lldb::OptionValueSP> collection; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueBoolean.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueBoolean.h index d429c0577ecb..1ff84dd3367d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueBoolean.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueBoolean.h @@ -37,10 +37,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueChar.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueChar.h index d18644700573..0c5f602efe9b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueChar.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueChar.h @@ -38,10 +38,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueDictionary.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueDictionary.h index 5d015a55a8f9..4e8c86008ea4 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueDictionary.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueDictionary.h @@ -38,7 +38,7 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; @@ -66,10 +66,10 @@ public: lldb::OptionValueSP GetSubValue(const ExecutionContext *exe_ctx, llvm::StringRef name, bool will_modify, - Error &error) const override; + Status &error) const override; - Error SetSubValue(const ExecutionContext *exe_ctx, VarSetOperationType op, - llvm::StringRef name, llvm::StringRef value) override; + Status SetSubValue(const ExecutionContext *exe_ctx, VarSetOperationType op, + llvm::StringRef name, llvm::StringRef value) override; bool SetValueForKey(const ConstString &key, const lldb::OptionValueSP &value_sp, @@ -79,7 +79,7 @@ public: size_t GetArgs(Args &args) const; - Error SetArgs(const Args &args, VarSetOperationType op); + Status SetArgs(const Args &args, VarSetOperationType op); protected: typedef std::map<ConstString, lldb::OptionValueSP> collection; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueEnumeration.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueEnumeration.h index d47248b72c67..4aa8823e620f 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueEnumeration.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueEnumeration.h @@ -13,7 +13,7 @@ #include "lldb/Core/UniqueCStringMap.h" #include "lldb/Interpreter/OptionValue.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/lldb-private-types.h" @@ -44,10 +44,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpec.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpec.h index 654c04d4d274..b53c03471e2b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpec.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpec.h @@ -37,10 +37,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpecList.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpecList.h index 1e42362c9163..9529fbcf38bc 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpecList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFileSpecList.h @@ -37,10 +37,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormat.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormat.h index 5351aeca0627..ce7997024b09 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormat.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormat.h @@ -38,10 +38,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormatEntity.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormatEntity.h index 472cd9ee4f92..e5a65b7e7eb6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormatEntity.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueFormatEntity.h @@ -34,10 +34,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueLanguage.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueLanguage.h index a388a6a92eaf..8f81c5df0739 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueLanguage.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueLanguage.h @@ -41,10 +41,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValuePathMappings.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValuePathMappings.h index d5336aafc993..0e2e98d74b74 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValuePathMappings.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValuePathMappings.h @@ -35,10 +35,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueProperties.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueProperties.h index 0b49e0b00672..16d31aa4ea90 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueProperties.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueProperties.h @@ -43,7 +43,7 @@ public: lldb::OptionValueSP DeepCopy() const override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; @@ -52,9 +52,9 @@ public: ConstString GetName() const override { return m_name; } - virtual Error DumpPropertyValue(const ExecutionContext *exe_ctx, Stream &strm, - llvm::StringRef property_path, - uint32_t dump_mask); + virtual Status DumpPropertyValue(const ExecutionContext *exe_ctx, + Stream &strm, llvm::StringRef property_path, + uint32_t dump_mask); virtual void DumpAllDescriptions(CommandInterpreter &interpreter, Stream &strm) const; @@ -110,11 +110,12 @@ public: bool value_will_be_modified) const; lldb::OptionValueSP GetSubValue(const ExecutionContext *exe_ctx, - llvm::StringRef name, bool value_will_be_modified, - Error &error) const override; + llvm::StringRef name, + bool value_will_be_modified, + Status &error) const override; - Error SetSubValue(const ExecutionContext *exe_ctx, VarSetOperationType op, - llvm::StringRef path, llvm::StringRef value) override; + Status SetSubValue(const ExecutionContext *exe_ctx, VarSetOperationType op, + llvm::StringRef path, llvm::StringRef value) override; virtual bool PredicateMatches(const ExecutionContext *exe_ctx, llvm::StringRef predicate) const { diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueRegex.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueRegex.h index 7bb8d419bde0..afe9318ae014 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueRegex.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueRegex.h @@ -35,10 +35,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueSInt64.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueSInt64.h index 1e1647866873..a6893d23e692 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueSInt64.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueSInt64.h @@ -50,10 +50,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueString.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueString.h index 18b8215fe3c7..4a9f2227680e 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueString.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueString.h @@ -24,7 +24,7 @@ namespace lldb_private { class OptionValueString : public OptionValue { public: - typedef Error (*ValidatorCallback)(const char *string, void *baton); + typedef Status (*ValidatorCallback)(const char *string, void *baton); enum Options { eOptionEncodeCharacterEscapeSequences = (1u << 0) }; @@ -85,10 +85,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; @@ -119,10 +119,10 @@ public: const char *GetDefaultValue() const { return m_default_value.c_str(); } llvm::StringRef GetDefaultValueAsRef() const { return m_default_value; } - Error SetCurrentValue(const char *) = delete; - Error SetCurrentValue(llvm::StringRef value); + Status SetCurrentValue(const char *) = delete; + Status SetCurrentValue(llvm::StringRef value); - Error AppendToCurrentValue(const char *value); + Status AppendToCurrentValue(const char *value); void SetDefaultValue(const char *value) { if (value && value[0]) diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUInt64.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUInt64.h index cbf932b1bda4..be13ff073721 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUInt64.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUInt64.h @@ -38,8 +38,8 @@ public: // string isn't a uint64_t value or any other error occurs, return an // empty lldb::OptionValueSP and fill error in with the correct stuff. //--------------------------------------------------------------------- - static lldb::OptionValueSP Create(const char *, Error &) = delete; - static lldb::OptionValueSP Create(llvm::StringRef value_str, Error &error); + static lldb::OptionValueSP Create(const char *, Status &) = delete; + static lldb::OptionValueSP Create(llvm::StringRef value_str, Status &error); //--------------------------------------------------------------------- // Virtual subclass pure virtual overrides //--------------------------------------------------------------------- @@ -49,10 +49,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUUID.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUUID.h index 62c25859580c..6e0aeebb0e99 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUUID.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/OptionValueUUID.h @@ -36,10 +36,10 @@ public: void DumpValue(const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask) override; - Error + Status SetValueFromString(llvm::StringRef value, VarSetOperationType op = eVarSetOperationAssign) override; - Error + Status SetValueFromString(const char *, VarSetOperationType = eVarSetOperationAssign) = delete; diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/Options.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/Options.h index fc5ff972da46..87121005575a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/Options.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/Options.h @@ -38,7 +38,7 @@ static inline bool isprint8(int ch) { /// Options is designed to be subclassed to contain all needed /// options for a given command. The options can be parsed by calling: /// \code -/// Error Args::ParseOptions (Options &); +/// Status Args::ParseOptions (Options &); /// \endcode /// /// The options are specified using the format defined for the libc @@ -62,11 +62,11 @@ static inline bool isprint8(int ch) { /// return g_options; /// } /// -/// virtual Error +/// virtual Status /// SetOptionValue (uint32_t option_idx, int option_val, const char /// *option_arg) /// { -/// Error error; +/// Status error; /// switch (option_val) /// { /// case 'g': debug = true; break; @@ -171,7 +171,7 @@ public: // prone and subclasses shouldn't have to do it. void NotifyOptionParsingStarting(ExecutionContext *execution_context); - Error NotifyOptionParsingFinished(ExecutionContext *execution_context); + Status NotifyOptionParsingFinished(ExecutionContext *execution_context); //------------------------------------------------------------------ /// Set the value of an option. @@ -192,8 +192,8 @@ public: /// @see Args::ParseOptions (Options&) /// @see man getopt_long_only //------------------------------------------------------------------ - virtual Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) = 0; + virtual Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) = 0; //------------------------------------------------------------------ /// Handles the generic bits of figuring out whether we are in an @@ -324,10 +324,10 @@ protected: // all option settings to default values. virtual void OptionParsingStarting(ExecutionContext *execution_context) = 0; - virtual Error OptionParsingFinished(ExecutionContext *execution_context) { + virtual Status OptionParsingFinished(ExecutionContext *execution_context) { // If subclasses need to know when the options are done being parsed // they can implement this function to do extra checking - Error error; + Status error; return error; } }; @@ -340,16 +340,16 @@ public: virtual llvm::ArrayRef<OptionDefinition> GetDefinitions() = 0; - virtual Error SetOptionValue(uint32_t option_idx, - llvm::StringRef option_value, - ExecutionContext *execution_context) = 0; + virtual Status SetOptionValue(uint32_t option_idx, + llvm::StringRef option_value, + ExecutionContext *execution_context) = 0; virtual void OptionParsingStarting(ExecutionContext *execution_context) = 0; - virtual Error OptionParsingFinished(ExecutionContext *execution_context) { + virtual Status OptionParsingFinished(ExecutionContext *execution_context) { // If subclasses need to know when the options are done being parsed // they can implement this function to do extra checking - Error error; + Status error; return error; } }; @@ -401,12 +401,12 @@ public: bool DidFinalize() { return m_did_finalize; } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; - Error OptionParsingFinished(ExecutionContext *execution_context) override; + Status OptionParsingFinished(ExecutionContext *execution_context) override; llvm::ArrayRef<OptionDefinition> GetDefinitions() override { assert(m_did_finalize); diff --git a/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h b/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h index 271a5bba761e..01b342ae41ca 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h +++ b/contrib/llvm/tools/lldb/include/lldb/Interpreter/ScriptInterpreter.h @@ -20,7 +20,7 @@ #include "lldb/Core/Broadcaster.h" #include "lldb/Core/PluginInterface.h" #include "lldb/Core/StructuredData.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Host/PseudoTerminal.h" @@ -107,24 +107,24 @@ public: return true; } - virtual Error ExecuteMultipleLines( + virtual Status ExecuteMultipleLines( const char *in_string, const ExecuteScriptOptions &options = ExecuteScriptOptions()) { - Error error; + Status error; error.SetErrorString("not implemented"); return error; } - virtual Error + virtual Status ExportFunctionDefinitionToInterpreter(StringList &function_def) { - Error error; + Status error; error.SetErrorString("not implemented"); return error; } - virtual Error GenerateBreakpointCommandCallbackData(StringList &input, - std::string &output) { - Error error; + virtual Status GenerateBreakpointCommandCallbackData(StringList &input, + std::string &output) { + Status error; error.SetErrorString("not implemented"); return error; } @@ -235,19 +235,19 @@ public: } virtual StructuredData::ObjectSP - LoadPluginModule(const FileSpec &file_spec, lldb_private::Error &error) { + LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) { return StructuredData::ObjectSP(); } virtual StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, - const char *setting_name, lldb_private::Error &error) { + const char *setting_name, lldb_private::Status &error) { return StructuredData::DictionarySP(); } - virtual Error GenerateFunction(const char *signature, - const StringList &input) { - Error error; + virtual Status GenerateFunction(const char *signature, + const StringList &input) { + Status error; error.SetErrorString("unimplemented"); return error; } @@ -260,22 +260,22 @@ public: CommandReturnObject &result); /// Set the specified text as the callback for the breakpoint. - Error + Status SetBreakpointCommandCallback(std::vector<BreakpointOptions *> &bp_options_vec, const char *callback_text); - virtual Error SetBreakpointCommandCallback(BreakpointOptions *bp_options, - const char *callback_text) { - Error error; + virtual Status SetBreakpointCommandCallback(BreakpointOptions *bp_options, + const char *callback_text) { + Status error; error.SetErrorString("unimplemented"); return error; } /// This one is for deserialization: - virtual Error SetBreakpointCommandCallback( + virtual Status SetBreakpointCommandCallback( BreakpointOptions *bp_options, std::unique_ptr<BreakpointOptions::CommandData> &data_up) { - Error error; + Status error; error.SetErrorString("unimplemented"); return error; } @@ -346,7 +346,7 @@ public: RunScriptBasedCommand(const char *impl_function, const char *args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, - Error &error, + Status &error, const lldb_private::ExecutionContext &exe_ctx) { return false; } @@ -355,40 +355,40 @@ public: RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp, const char *args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, - Error &error, + Status &error, const lldb_private::ExecutionContext &exe_ctx) { return false; } virtual bool RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, - Error &error) { + Status &error) { error.SetErrorString("unimplemented"); return false; } virtual bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, - std::string &output, Error &error) { + std::string &output, Status &error) { error.SetErrorString("unimplemented"); return false; } virtual bool RunScriptFormatKeyword(const char *impl_function, Target *target, - std::string &output, Error &error) { + std::string &output, Status &error) { error.SetErrorString("unimplemented"); return false; } virtual bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, std::string &output, - Error &error) { + Status &error) { error.SetErrorString("unimplemented"); return false; } virtual bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, std::string &output, - Error &error) { + Status &error) { error.SetErrorString("unimplemented"); return false; } @@ -420,7 +420,7 @@ public: virtual bool LoadScriptingModule(const char *filename, bool can_reload, bool init_session, - lldb_private::Error &error, + lldb_private::Status &error, StructuredData::ObjectSP *module_sp = nullptr) { error.SetErrorString("loading unimplemented"); return false; diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/ClangASTContext.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/ClangASTContext.h index a083810cfe9f..08f5175f2cba 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/ClangASTContext.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/ClangASTContext.h @@ -275,17 +275,16 @@ public: bool IsValid() const { if (args.empty()) return false; - return args.size() == names.size(); - } - - size_t GetSize() const { - if (IsValid()) - return args.size(); - return 0; + return args.size() == names.size() && + ((bool)pack_name == (bool)packed_args) && + (!packed_args || !packed_args->packed_args); } llvm::SmallVector<const char *, 2> names; llvm::SmallVector<clang::TemplateArgument, 2> args; + + const char * pack_name = nullptr; + std::unique_ptr<TemplateParameterInfos> packed_args; }; clang::FunctionTemplateDecl * diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/ObjectFile.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/ObjectFile.h index 296c9ff2129f..a4c7b01ece17 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/ObjectFile.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/ObjectFile.h @@ -826,7 +826,7 @@ public: /// /// @return //------------------------------------------------------------------ - virtual Error LoadInMemory(Target &target, bool set_pc); + virtual Status LoadInMemory(Target &target, bool set_pc); protected: //------------------------------------------------------------------ diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/SymbolContext.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/SymbolContext.h index 2ca3fdb71286..e4dcc73bb52b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/SymbolContext.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/SymbolContext.h @@ -234,7 +234,7 @@ public: bool use_inline_block_range, AddressRange &range) const; bool GetAddressRangeFromHereToEndLine(uint32_t end_line, AddressRange &range, - Error &error); + Status &error); void GetDescription(Stream *s, lldb::DescriptionLevel level, Target *target) const; diff --git a/contrib/llvm/tools/lldb/include/lldb/Symbol/Variable.h b/contrib/llvm/tools/lldb/include/lldb/Symbol/Variable.h index f076a04434e1..507b41309042 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Symbol/Variable.h +++ b/contrib/llvm/tools/lldb/include/lldb/Symbol/Variable.h @@ -97,7 +97,7 @@ public: typedef size_t (*GetVariableCallback)(void *baton, const char *name, VariableList &var_list); - static Error GetValuesForVariableExpressionPath( + static Status GetValuesForVariableExpressionPath( llvm::StringRef variable_expr_path, ExecutionContextScope *scope, GetVariableCallback callback, void *baton, VariableList &variable_list, ValueObjectList &valobj_list); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h b/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h index 4b611d244e21..a8e08e1a800a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ABI.h @@ -16,7 +16,7 @@ // Project includes #include "lldb/Core/PluginInterface.h" #include "lldb/Symbol/UnwindPlan.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include "llvm/ADT/ArrayRef.h" @@ -77,8 +77,8 @@ public: bool persistent = true) const; // Set the Return value object in the current frame as though a function with - virtual Error SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value) = 0; + virtual Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value) = 0; protected: // This is the method the ABI will call to actually calculate the return diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/DynamicLoader.h b/contrib/llvm/tools/lldb/include/lldb/Target/DynamicLoader.h index ced6ef44000a..b5890662d4e5 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/DynamicLoader.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/DynamicLoader.h @@ -12,8 +12,8 @@ // Project includes #include "lldb/Core/PluginInterface.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" // for FileSpec +#include "lldb/Utility/Status.h" #include "lldb/Utility/UUID.h" #include "lldb/lldb-defines.h" // for LLDB_INVALID_ADDRESS #include "lldb/lldb-forward.h" // for ModuleSP, ThreadPlanSP @@ -213,7 +213,7 @@ public: /// \b true if it is currently ok to try and load a shared /// library into the process, \b false otherwise. //------------------------------------------------------------------ - virtual Error CanLoadImage() = 0; + virtual Status CanLoadImage() = 0; //------------------------------------------------------------------ /// Ask if the eh_frame information for the given SymbolContext should diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Language.h b/contrib/llvm/tools/lldb/include/lldb/Target/Language.h index bcf840f93edd..f81679f78129 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Language.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Language.h @@ -199,7 +199,7 @@ public: // it should return an appropriate closure here virtual DumpValueObjectOptions::DeclPrintingHelper GetDeclPrintingHelper(); - virtual LazyBool IsLogicalTrue(ValueObject &valobj, Error &error); + virtual LazyBool IsLogicalTrue(ValueObject &valobj, Status &error); // for a ValueObject of some "reference type", if the value points to the // nil/null object, this method returns true diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/LanguageRuntime.h b/contrib/llvm/tools/lldb/include/lldb/Target/LanguageRuntime.h index a57216e84794..98db941669c7 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/LanguageRuntime.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/LanguageRuntime.h @@ -48,7 +48,7 @@ public: static SearchFilter * CreateFromStructuredData(Target &target, const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData() override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Memory.h b/contrib/llvm/tools/lldb/include/lldb/Target/Memory.h index f0a4bc5881f0..af6be15df9fb 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Memory.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Memory.h @@ -40,7 +40,7 @@ public: void Flush(lldb::addr_t addr, size_t size); - size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Error &error); + size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Status &error); uint32_t GetMemoryCacheLineSize() const { return m_L2_cache_line_byte_size; } @@ -135,7 +135,7 @@ public: void Clear(); lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, - Error &error); + Status &error); bool DeallocateMemory(lldb::addr_t ptr); @@ -143,7 +143,7 @@ protected: typedef std::shared_ptr<AllocatedBlock> AllocatedBlockSP; AllocatedBlockSP AllocatePage(uint32_t byte_size, uint32_t permissions, - uint32_t chunk_size, Error &error); + uint32_t chunk_size, Status &error); //------------------------------------------------------------------ // Classes that inherit from MemoryCache can see and modify these diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ModuleCache.h b/contrib/llvm/tools/lldb/include/lldb/Target/ModuleCache.h index 49a7c97c60c3..4959ee8ea0a3 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ModuleCache.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ModuleCache.h @@ -14,8 +14,8 @@ #include "lldb/lldb-types.h" #include "lldb/Host/File.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" #include <functional> #include <string> @@ -49,24 +49,24 @@ class UUID; class ModuleCache { public: using ModuleDownloader = - std::function<Error(const ModuleSpec &, const FileSpec &)>; + std::function<Status(const ModuleSpec &, const FileSpec &)>; using SymfileDownloader = - std::function<Error(const lldb::ModuleSP &, const FileSpec &)>; + std::function<Status(const lldb::ModuleSP &, const FileSpec &)>; - Error GetAndPut(const FileSpec &root_dir_spec, const char *hostname, - const ModuleSpec &module_spec, - const ModuleDownloader &module_downloader, - const SymfileDownloader &symfile_downloader, - lldb::ModuleSP &cached_module_sp, bool *did_create_ptr); + Status GetAndPut(const FileSpec &root_dir_spec, const char *hostname, + const ModuleSpec &module_spec, + const ModuleDownloader &module_downloader, + const SymfileDownloader &symfile_downloader, + lldb::ModuleSP &cached_module_sp, bool *did_create_ptr); private: - Error Put(const FileSpec &root_dir_spec, const char *hostname, - const ModuleSpec &module_spec, const FileSpec &tmp_file, - const FileSpec &target_file); + Status Put(const FileSpec &root_dir_spec, const char *hostname, + const ModuleSpec &module_spec, const FileSpec &tmp_file, + const FileSpec &target_file); - Error Get(const FileSpec &root_dir_spec, const char *hostname, - const ModuleSpec &module_spec, lldb::ModuleSP &cached_module_sp, - bool *did_create_ptr); + Status Get(const FileSpec &root_dir_spec, const char *hostname, + const ModuleSpec &module_spec, lldb::ModuleSP &cached_module_sp, + bool *did_create_ptr); std::unordered_map<std::string, lldb::ModuleWP> m_loaded_modules; }; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ObjCLanguageRuntime.h b/contrib/llvm/tools/lldb/include/lldb/Target/ObjCLanguageRuntime.h index 0a9ffa933bd1..97a2a731581a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ObjCLanguageRuntime.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ObjCLanguageRuntime.h @@ -168,7 +168,7 @@ public: bool EvaluatePrecondition(StoppointCallbackContext &context) override; void GetDescription(Stream &stream, lldb::DescriptionLevel level) override; - Error ConfigurePrecondition(Args &args) override; + Status ConfigurePrecondition(Args &args) override; protected: void AddClassName(const char *class_name); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/PathMappingList.h b/contrib/llvm/tools/lldb/include/lldb/Target/PathMappingList.h index 2b844882e4ad..b1b551f2d24d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/PathMappingList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/PathMappingList.h @@ -16,7 +16,7 @@ #include <vector> // Other libraries and framework includes #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" // Project includes namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h b/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h index fb05d3e06dd5..cc007d959c65 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h @@ -111,10 +111,10 @@ public: // Find an existing platform plug-in by name static lldb::PlatformSP Find(const ConstString &name); - static lldb::PlatformSP Create(const ConstString &name, Error &error); + static lldb::PlatformSP Create(const ConstString &name, Status &error); static lldb::PlatformSP Create(const ArchSpec &arch, - ArchSpec *platform_arch_ptr, Error &error); + ArchSpec *platform_arch_ptr, Status &error); static uint32_t GetNumConnectedRemotePlatforms(); @@ -156,9 +156,9 @@ public: /// Returns \b true if this Platform plug-in was able to find /// a suitable executable, \b false otherwise. //------------------------------------------------------------------ - virtual Error ResolveExecutable(const ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr); + virtual Status ResolveExecutable(const ModuleSpec &module_spec, + lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr); //------------------------------------------------------------------ /// Find a symbol file given a symbol file module specification. @@ -207,8 +207,8 @@ public: /// @return /// Returns an error that describes success or failure. //------------------------------------------------------------------ - virtual Error ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, - FileSpec &sym_file); + virtual Status ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, + FileSpec &sym_file); //------------------------------------------------------------------ /// Resolves the FileSpec to a (possibly) remote path. Remote @@ -316,8 +316,8 @@ public: /// @return /// An error object. //------------------------------------------------------------------ - virtual Error GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, FileSpec &local_file); + virtual Status GetFileWithUUID(const FileSpec &platform_file, + const UUID *uuid_ptr, FileSpec &local_file); //---------------------------------------------------------------------- // Locate the scripting resource given a module specification. @@ -329,18 +329,18 @@ public: LocateExecutableScriptingResources(Target *target, Module &module, Stream *feedback_stream); - virtual Error GetSharedModule(const ModuleSpec &module_spec, Process *process, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - lldb::ModuleSP *old_module_sp_ptr, - bool *did_create_ptr); + virtual Status GetSharedModule(const ModuleSpec &module_spec, + Process *process, lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + lldb::ModuleSP *old_module_sp_ptr, + bool *did_create_ptr); virtual bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec); - virtual Error ConnectRemote(Args &args); + virtual Status ConnectRemote(Args &args); - virtual Error DisconnectRemote(); + virtual Status DisconnectRemote(); //------------------------------------------------------------------ /// Get the platform's supported architectures in the order in which @@ -367,7 +367,7 @@ public: /// Launch a new process on a platform, not necessarily for /// debugging, it could be just for running the process. //------------------------------------------------------------------ - virtual Error LaunchProcess(ProcessLaunchInfo &launch_info); + virtual Status LaunchProcess(ProcessLaunchInfo &launch_info); //------------------------------------------------------------------ /// Perform expansion of the command-line for this launch info @@ -376,12 +376,12 @@ public: // argument magic the platform defines as part of its typical // user experience //------------------------------------------------------------------ - virtual Error ShellExpandArguments(ProcessLaunchInfo &launch_info); + virtual Status ShellExpandArguments(ProcessLaunchInfo &launch_info); //------------------------------------------------------------------ /// Kill process on a platform. //------------------------------------------------------------------ - virtual Error KillProcess(const lldb::pid_t pid); + virtual Status KillProcess(const lldb::pid_t pid); //------------------------------------------------------------------ /// Lets a platform answer if it is compatible with a given @@ -411,13 +411,13 @@ public: DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be nullptr, if nullptr create a new // target, else use existing one - Error &error); + Status &error); virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error); + lldb_private::Status &error); //------------------------------------------------------------------ /// Attach to an existing process using a process ID. @@ -442,7 +442,7 @@ public: Target *target, // Can be nullptr, if nullptr // create a new target, else // use existing one - Error &error) = 0; + Status &error) = 0; //------------------------------------------------------------------ /// Attach to an existing process by process name. @@ -464,7 +464,7 @@ public: // virtual lldb::ProcessSP // Attach (const char *process_name, // bool wait_for_launch, - // Error &error) = 0; + // Status &error) = 0; //------------------------------------------------------------------ // The base class Platform will take care of the host platform. @@ -552,27 +552,27 @@ public: return false; } - virtual Error MakeDirectory(const FileSpec &file_spec, uint32_t permissions); + virtual Status MakeDirectory(const FileSpec &file_spec, uint32_t permissions); - virtual Error GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions); + virtual Status GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions); - virtual Error SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions); + virtual Status SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions); virtual lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, - uint32_t mode, Error &error) { + uint32_t mode, Status &error) { return UINT64_MAX; } - virtual bool CloseFile(lldb::user_id_t fd, Error &error) { return false; } + virtual bool CloseFile(lldb::user_id_t fd, Status &error) { return false; } virtual lldb::user_id_t GetFileSize(const FileSpec &file_spec) { return UINT64_MAX; } virtual uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Error &error) { + uint64_t dst_len, Status &error) { error.SetErrorStringWithFormat( "Platform::ReadFile() is not supported in the %s platform", GetName().GetCString()); @@ -580,19 +580,19 @@ public: } virtual uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, - const void *src, uint64_t src_len, Error &error) { + const void *src, uint64_t src_len, Status &error) { error.SetErrorStringWithFormat( "Platform::ReadFile() is not supported in the %s platform", GetName().GetCString()); return -1; } - virtual Error GetFile(const FileSpec &source, const FileSpec &destination); + virtual Status GetFile(const FileSpec &source, const FileSpec &destination); - virtual Error PutFile(const FileSpec &source, const FileSpec &destination, - uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX); + virtual Status PutFile(const FileSpec &source, const FileSpec &destination, + uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX); - virtual Error + virtual Status CreateSymlink(const FileSpec &src, // The name of the link is in src const FileSpec &dst); // The symlink points to dst @@ -620,13 +620,13 @@ public: /// @return /// An error object that describes anything that went wrong. //---------------------------------------------------------------------- - virtual Error Install(const FileSpec &src, const FileSpec &dst); + virtual Status Install(const FileSpec &src, const FileSpec &dst); virtual size_t GetEnvironment(StringList &environment); virtual bool GetFileExists(const lldb_private::FileSpec &file_spec); - virtual Error Unlink(const FileSpec &file_spec); + virtual Status Unlink(const FileSpec &file_spec); virtual uint64_t ConvertMmapFlagsToPlatform(const ArchSpec &arch, unsigned flags); @@ -664,7 +664,7 @@ public: return nullptr; } - virtual lldb_private::Error RunShellCommand( + virtual lldb_private::Status RunShellCommand( const char *command, // Shouldn't be nullptr const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory @@ -830,14 +830,14 @@ public: uint32_t LoadImage(lldb_private::Process *process, const lldb_private::FileSpec &local_file, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error); + lldb_private::Status &error); virtual uint32_t DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error); + lldb_private::Status &error); - virtual Error UnloadImage(lldb_private::Process *process, - uint32_t image_token); + virtual Status UnloadImage(lldb_private::Process *process, + uint32_t image_token); //------------------------------------------------------------------ /// Connect to all processes waiting for a debugger to attach @@ -856,7 +856,7 @@ public: /// The number of processes we are successfully connected to. //------------------------------------------------------------------ virtual size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, - lldb_private::Error &error); + lldb_private::Status &error); protected: bool m_is_host; @@ -977,35 +977,35 @@ protected: m_gid_map.clear(); } - Error GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - Platform &remote_platform); + Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + Platform &remote_platform); - virtual Error DownloadModuleSlice(const FileSpec &src_file_spec, - const uint64_t src_offset, - const uint64_t src_size, - const FileSpec &dst_file_spec); + virtual Status DownloadModuleSlice(const FileSpec &src_file_spec, + const uint64_t src_offset, + const uint64_t src_size, + const FileSpec &dst_file_spec); - virtual Error DownloadSymbolFile(const lldb::ModuleSP &module_sp, - const FileSpec &dst_file_spec); + virtual Status DownloadSymbolFile(const lldb::ModuleSP &module_sp, + const FileSpec &dst_file_spec); virtual const char *GetCacheHostname(); private: - typedef std::function<Error(const ModuleSpec &)> ModuleResolver; + typedef std::function<Status(const ModuleSpec &)> ModuleResolver; - Error GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process, - lldb::ModuleSP &module_sp, - const ModuleResolver &module_resolver, - bool *did_create_ptr); + Status GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process, + lldb::ModuleSP &module_sp, + const ModuleResolver &module_resolver, + bool *did_create_ptr); bool GetCachedSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, bool *did_create_ptr); - Error LoadCachedExecutable(const ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - Platform &remote_platform); + Status LoadCachedExecutable(const ModuleSpec &module_spec, + lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + Platform &remote_platform); FileSpec GetModuleCacheRoot(); @@ -1088,7 +1088,7 @@ public: ~OptionGroupPlatformRSync() override = default; - lldb_private::Error + lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; @@ -1117,7 +1117,7 @@ public: ~OptionGroupPlatformSSH() override = default; - lldb_private::Error + lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; @@ -1144,7 +1144,7 @@ public: ~OptionGroupPlatformCaching() override = default; - lldb_private::Error + lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Process.h b/contrib/llvm/tools/lldb/include/lldb/Target/Process.h index 9a749efa7ae1..d2ab85d1652a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Process.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Process.h @@ -48,8 +48,8 @@ #include "lldb/Target/ProcessLaunchInfo.h" #include "lldb/Target/QueueList.h" #include "lldb/Target/ThreadList.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/NameMatches.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include "llvm/ADT/ArrayRef.h" @@ -282,8 +282,8 @@ public: ~ProcessLaunchCommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override { launch_info.Clear(); @@ -792,12 +792,12 @@ public: /// An error object. Call GetID() to get the process ID if /// the error object is success. //------------------------------------------------------------------ - virtual Error Launch(ProcessLaunchInfo &launch_info); + virtual Status Launch(ProcessLaunchInfo &launch_info); - virtual Error LoadCore(); + virtual Status LoadCore(); - virtual Error DoLoadCore() { - Error error; + virtual Status DoLoadCore() { + Status error; error.SetErrorStringWithFormat( "error: %s does not support loading core files.", GetPluginName().GetCString()); @@ -869,7 +869,7 @@ public: /// Returns \a pid if attaching was successful, or /// LLDB_INVALID_PROCESS_ID if attaching fails. //------------------------------------------------------------------ - virtual Error Attach(ProcessAttachInfo &attach_info); + virtual Status Attach(ProcessAttachInfo &attach_info); //------------------------------------------------------------------ /// Attach to a remote system via a URL @@ -885,7 +885,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error ConnectRemote(Stream *strm, llvm::StringRef remote_url); + virtual Status ConnectRemote(Stream *strm, llvm::StringRef remote_url); bool GetShouldDetach() const { return m_should_detach; } @@ -992,9 +992,9 @@ public: /// @see Thread:Step() /// @see Thread:Suspend() //------------------------------------------------------------------ - Error Resume(); + Status Resume(); - Error ResumeSynchronous(Stream *stream); + Status ResumeSynchronous(Stream *stream); //------------------------------------------------------------------ /// Halts a running process. @@ -1016,7 +1016,7 @@ public: /// halted. /// otherwise the halt has failed. //------------------------------------------------------------------ - Error Halt(bool clear_thread_plans = false, bool use_run_lock = true); + Status Halt(bool clear_thread_plans = false, bool use_run_lock = true); //------------------------------------------------------------------ /// Detaches from a running or stopped process. @@ -1030,7 +1030,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - Error Detach(bool keep_stopped); + Status Detach(bool keep_stopped); //------------------------------------------------------------------ /// Kills the process and shuts down all threads that were spawned @@ -1050,7 +1050,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - Error Destroy(bool force_kill); + Status Destroy(bool force_kill); //------------------------------------------------------------------ /// Sends a process a UNIX signal \a signal. @@ -1061,7 +1061,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - Error Signal(int signal); + Status Signal(int signal); void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp); @@ -1080,7 +1080,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillAttachToProcessWithID(lldb::pid_t pid) { return Error(); } + virtual Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); } //------------------------------------------------------------------ /// Called before attaching to a process. @@ -1091,9 +1091,9 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillAttachToProcessWithName(const char *process_name, - bool wait_for_launch) { - return Error(); + virtual Status WillAttachToProcessWithName(const char *process_name, + bool wait_for_launch) { + return Status(); } //------------------------------------------------------------------ @@ -1110,8 +1110,8 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error DoConnectRemote(Stream *strm, llvm::StringRef remote_url) { - Error error; + virtual Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) { + Status error; error.SetErrorString("remote connections are not supported"); return error; } @@ -1127,14 +1127,14 @@ public: /// will return the uid to attach as. /// /// @return - /// Returns a successful Error attaching was successful, or + /// Returns a successful Status attaching was successful, or /// an appropriate (possibly platform-specific) error code if /// attaching fails. /// hanming : need flag //------------------------------------------------------------------ - virtual Error DoAttachToProcessWithID(lldb::pid_t pid, - const ProcessAttachInfo &attach_info) { - Error error; + virtual Status DoAttachToProcessWithID(lldb::pid_t pid, + const ProcessAttachInfo &attach_info) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support attaching to a process by pid", GetPluginName().GetCString()); @@ -1152,14 +1152,14 @@ public: /// will return the uid to attach as. /// /// @return - /// Returns a successful Error attaching was successful, or + /// Returns a successful Status attaching was successful, or /// an appropriate (possibly platform-specific) error code if /// attaching fails. //------------------------------------------------------------------ - virtual Error + virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info) { - Error error; + Status error; error.SetErrorString("attach by name is not supported"); return error; } @@ -1202,7 +1202,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillLaunch(Module *module) { return Error(); } + virtual Status WillLaunch(Module *module) { return Status(); } //------------------------------------------------------------------ /// Launch a new process. @@ -1220,11 +1220,11 @@ public: /// requested launch. /// /// @return - /// An Error instance indicating success or failure of the + /// An Status instance indicating success or failure of the /// operation. //------------------------------------------------------------------ - virtual Error DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) { - Error error; + virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support launching processes", GetPluginName().GetCString()); @@ -1248,7 +1248,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillResume() { return Error(); } + virtual Status WillResume() { return Status(); } //------------------------------------------------------------------ /// Resumes all of a process's threads as configured using the @@ -1267,8 +1267,8 @@ public: /// @see Thread:Step() /// @see Thread:Suspend() //------------------------------------------------------------------ - virtual Error DoResume() { - Error error; + virtual Status DoResume() { + Status error; error.SetErrorStringWithFormat( "error: %s does not support resuming processes", GetPluginName().GetCString()); @@ -1292,7 +1292,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillHalt() { return Error(); } + virtual Status WillHalt() { return Status(); } //------------------------------------------------------------------ /// Halts a running process. @@ -1314,8 +1314,8 @@ public: /// Returns \b true if the process successfully halts, \b false /// otherwise. //------------------------------------------------------------------ - virtual Error DoHalt(bool &caused_stop) { - Error error; + virtual Status DoHalt(bool &caused_stop) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support halting processes", GetPluginName().GetCString()); @@ -1339,7 +1339,7 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error WillDetach() { return Error(); } + virtual Status WillDetach() { return Status(); } //------------------------------------------------------------------ /// Detaches from a running or stopped process. @@ -1348,8 +1348,8 @@ public: /// Returns \b true if the process successfully detaches, \b /// false otherwise. //------------------------------------------------------------------ - virtual Error DoDetach(bool keep_stopped) { - Error error; + virtual Status DoDetach(bool keep_stopped) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support detaching from processes", GetPluginName().GetCString()); @@ -1377,7 +1377,7 @@ public: /// Process::DoSignal(int), otherwise an error describing what /// prevents the signal from being sent. //------------------------------------------------------------------ - virtual Error WillSignal() { return Error(); } + virtual Status WillSignal() { return Status(); } //------------------------------------------------------------------ /// Sends a process a UNIX signal \a signal. @@ -1385,17 +1385,17 @@ public: /// @return /// Returns an error object. //------------------------------------------------------------------ - virtual Error DoSignal(int signal) { - Error error; + virtual Status DoSignal(int signal) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support sending signals to processes", GetPluginName().GetCString()); return error; } - virtual Error WillDestroy() { return Error(); } + virtual Status WillDestroy() { return Status(); } - virtual Error DoDestroy() = 0; + virtual Status DoDestroy() = 0; virtual void DidDestroy() {} @@ -1706,7 +1706,7 @@ public: /// The number of bytes that were actually read into \a buf. //------------------------------------------------------------------ virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, - Error &error) = 0; + Status &error) = 0; //------------------------------------------------------------------ /// Read of memory from a process. @@ -1738,7 +1738,7 @@ public: /// returned to indicate an error. //------------------------------------------------------------------ virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, - Error &error); + Status &error); //------------------------------------------------------------------ /// Read a NULL terminated string from memory @@ -1770,7 +1770,7 @@ public: /// The error status or the number of bytes prior to the null terminator. //------------------------------------------------------------------ size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes, - Error &error, size_t type_width = 1); + Status &error, size_t type_width = 1); //------------------------------------------------------------------ /// Read a NULL terminated C string from memory @@ -1782,13 +1782,13 @@ public: /// terminated (at most cstr_max_len - 1 bytes will be read). //------------------------------------------------------------------ size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, - size_t cstr_max_len, Error &error); + size_t cstr_max_len, Status &error); size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str, - Error &error); + Status &error); size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, - Error &error); + Status &error); //------------------------------------------------------------------ /// Reads an unsigned integer of the specified byte size from @@ -1819,15 +1819,15 @@ public: //------------------------------------------------------------------ uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, - Error &error); + Status &error); int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, - int64_t fail_value, Error &error); + int64_t fail_value, Status &error); - lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error); + lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error); bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, - Error &error); + Status &error); //------------------------------------------------------------------ /// Actually do the writing of memory to a process. @@ -1850,7 +1850,7 @@ public: /// The number of bytes that were actually written. //------------------------------------------------------------------ virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, - size_t size, Error &error) { + size_t size, Status &error) { error.SetErrorStringWithFormat( "error: %s does not support writing to processes", GetPluginName().GetCString()); @@ -1890,11 +1890,11 @@ public: /// The number of bytes that were actually written. //------------------------------------------------------------------ size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, - size_t size, Error &error); + size_t size, Status &error); size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, - Error &error); + Status &error); //------------------------------------------------------------------ /// Write memory to a process. @@ -1923,7 +1923,7 @@ public: //------------------------------------------------------------------ // TODO: change this to take an ArrayRef<uint8_t> size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, - Error &error); + Status &error); //------------------------------------------------------------------ /// Actually allocate memory in the process. @@ -1941,7 +1941,7 @@ public: //------------------------------------------------------------------ virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, - Error &error) { + Status &error) { error.SetErrorStringWithFormat( "error: %s does not support allocating in the debug process", GetPluginName().GetCString()); @@ -1971,7 +1971,7 @@ public: /// The address of the allocated buffer in the process, or /// LLDB_INVALID_ADDRESS if the allocation failed. //------------------------------------------------------------------ - lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Error &error); + lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error); //------------------------------------------------------------------ /// The public interface to allocating memory in the process, this also @@ -1998,7 +1998,8 @@ public: /// LLDB_INVALID_ADDRESS if the allocation failed. //------------------------------------------------------------------ - lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Error &error); + lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, + Status &error); //------------------------------------------------------------------ /// Resolve dynamically loaded indirect functions. @@ -2014,7 +2015,7 @@ public: /// LLDB_INVALID_ADDRESS if the resolution failed. //------------------------------------------------------------------ virtual lldb::addr_t ResolveIndirectFunction(const Address *address, - Error &error); + Status &error); //------------------------------------------------------------------ /// Locate the memory region that contains load_addr. @@ -2042,9 +2043,9 @@ public: /// @return /// An error value. //------------------------------------------------------------------ - virtual Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) { - Error error; + virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) { + Status error; error.SetErrorString("Process::GetMemoryRegionInfo() not supported"); return error; } @@ -2059,18 +2060,18 @@ public: /// @return /// An error value. //------------------------------------------------------------------ - virtual Error + virtual Status GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list); - virtual Error GetWatchpointSupportInfo(uint32_t &num) { - Error error; + virtual Status GetWatchpointSupportInfo(uint32_t &num) { + Status error; num = 0; error.SetErrorString("Process::GetWatchpointSupportInfo() not supported"); return error; } - virtual Error GetWatchpointSupportInfo(uint32_t &num, bool &after) { - Error error; + virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) { + Status error; num = 0; after = true; error.SetErrorString("Process::GetWatchpointSupportInfo() not supported"); @@ -2165,8 +2166,8 @@ public: /// @return /// \btrue if the memory was deallocated, \bfalse otherwise. //------------------------------------------------------------------ - virtual Error DoDeallocateMemory(lldb::addr_t ptr) { - Error error; + virtual Status DoDeallocateMemory(lldb::addr_t ptr) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support deallocating in the debug process", GetPluginName().GetCString()); @@ -2186,7 +2187,7 @@ public: /// @return /// \btrue if the memory was deallocated, \bfalse otherwise. //------------------------------------------------------------------ - Error DeallocateMemory(lldb::addr_t ptr); + Status DeallocateMemory(lldb::addr_t ptr); //------------------------------------------------------------------ /// Get any available STDOUT. @@ -2218,7 +2219,7 @@ public: /// equal to \a buf_size, another call to this function should /// be made to retrieve more STDOUT data. //------------------------------------------------------------------ - virtual size_t GetSTDOUT(char *buf, size_t buf_size, Error &error); + virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error); //------------------------------------------------------------------ /// Get any available STDERR. @@ -2250,7 +2251,7 @@ public: /// equal to \a buf_size, another call to this function should /// be made to retrieve more STDERR data. //------------------------------------------------------------------ - virtual size_t GetSTDERR(char *buf, size_t buf_size, Error &error); + virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error); //------------------------------------------------------------------ /// Puts data into this process's STDIN. @@ -2273,7 +2274,7 @@ public: /// less than \a buf_size, another call to this function should /// be made to write the rest of the data. //------------------------------------------------------------------ - virtual size_t PutSTDIN(const char *buf, size_t buf_size, Error &error) { + virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) { error.SetErrorString("stdin unsupported"); return 0; } @@ -2293,23 +2294,23 @@ public: /// equal to \a buf_size, another call to this function should /// be made to retrieve more profile data. //------------------------------------------------------------------ - virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Error &error); + virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error); //---------------------------------------------------------------------- // Process Breakpoints //---------------------------------------------------------------------- size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site); - virtual Error EnableBreakpointSite(BreakpointSite *bp_site) { - Error error; + virtual Status EnableBreakpointSite(BreakpointSite *bp_site) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support enabling breakpoints", GetPluginName().GetCString()); return error; } - virtual Error DisableBreakpointSite(BreakpointSite *bp_site) { - Error error; + virtual Status DisableBreakpointSite(BreakpointSite *bp_site) { + Status error; error.SetErrorStringWithFormat( "error: %s does not support disabling breakpoints", GetPluginName().GetCString()); @@ -2320,13 +2321,13 @@ public: // don't need to implement this function unless the standard flow of // read existing opcode, write breakpoint opcode, verify breakpoint opcode // doesn't work for a specific process plug-in. - virtual Error EnableSoftwareBreakpoint(BreakpointSite *bp_site); + virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site); // This is implemented completely using the lldb::Process API. Subclasses // don't need to implement this function unless the standard flow of // restoring original opcode in memory and verifying the restored opcode // doesn't work for a specific process plug-in. - virtual Error DisableSoftwareBreakpoint(BreakpointSite *bp_site); + virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site); BreakpointSiteList &GetBreakpointSiteList(); @@ -2334,14 +2335,14 @@ public: void DisableAllBreakpointSites(); - Error ClearBreakpointSiteByID(lldb::user_id_t break_id); + Status ClearBreakpointSiteByID(lldb::user_id_t break_id); lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner, bool use_hardware); - Error DisableBreakpointSiteByID(lldb::user_id_t break_id); + Status DisableBreakpointSiteByID(lldb::user_id_t break_id); - Error EnableBreakpointSiteByID(lldb::user_id_t break_id); + Status EnableBreakpointSiteByID(lldb::user_id_t break_id); // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove // themselves from the owner's list of this breakpoint sites. @@ -2352,9 +2353,9 @@ public: //---------------------------------------------------------------------- // Process Watchpoints (optional) //---------------------------------------------------------------------- - virtual Error EnableWatchpoint(Watchpoint *wp, bool notify = true); + virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true); - virtual Error DisableWatchpoint(Watchpoint *wp, bool notify = true); + virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true); //------------------------------------------------------------------ // Thread Queries @@ -2613,8 +2614,8 @@ public: ProcessRunLock &GetRunLock(); - virtual Error SendEventData(const char *data) { - Error return_error("Sending an event is not supported for this process."); + virtual Status SendEventData(const char *data) { + Status return_error("Sending an event is not supported for this process."); return return_error; } @@ -2665,9 +2666,9 @@ public: /// The load address of the file if it is loaded into the /// processes address space, LLDB_INVALID_ADDRESS otherwise. //------------------------------------------------------------------ - virtual Error GetFileLoadAddress(const FileSpec &file, bool &is_loaded, - lldb::addr_t &load_addr) { - return Error("Not supported"); + virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, + lldb::addr_t &load_addr) { + return Status("Not supported"); } size_t AddImageToken(lldb::addr_t image_ptr); @@ -2729,7 +2730,7 @@ public: /// @return /// Returns the result of attempting to configure the feature. //------------------------------------------------------------------ - virtual Error + virtual Status ConfigureStructuredData(const ConstString &type_name, const StructuredData::ObjectSP &config_sp); @@ -2781,7 +2782,7 @@ public: /// configuration. //------------------------------------------------------------------ virtual lldb::user_id_t StartTrace(lldb::TraceOptionsSP &options, - Error &error) { + Status &error) { error.SetErrorString("Not implemented"); return LLDB_INVALID_UID; } @@ -2796,7 +2797,7 @@ public: /// to be stopped a thread_id can be supplied. //------------------------------------------------------------------ virtual void StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id, - Error &error) { + Status &error) { error.SetErrorString("Not implemented"); } @@ -2809,7 +2810,7 @@ public: /// thread for trace extraction. //------------------------------------------------------------------ virtual size_t GetData(lldb::user_id_t uid, lldb::tid_t thread_id, - Error &error, void *buf, size_t size, + Status &error, void *buf, size_t size, size_t offset = 0) { error.SetErrorString("Not implemented"); return 0; @@ -2819,7 +2820,7 @@ public: /// Similar API as above except for obtaining meta data //------------------------------------------------------------------ virtual size_t GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id, - Error &error, void *buf, size_t size, + Status &error, void *buf, size_t size, size_t offset = 0) { error.SetErrorString("Not implemented"); return 0; @@ -2834,7 +2835,7 @@ public: /// configuration used by a specific thread. The thread_id specified /// should also match the uid otherwise an error will be returned. //------------------------------------------------------------------ - virtual void GetTraceConfig(lldb::user_id_t uid, Error &error, + virtual void GetTraceConfig(lldb::user_id_t uid, Status &error, lldb::TraceOptionsSP &options) { error.SetErrorString("Not implemented"); return; @@ -2850,9 +2851,9 @@ protected: /// state of m_run_lock, but just causes the process to resume. /// /// @return - /// An Error object describing the success or failure of the resume. + /// An Status object describing the success or failure of the resume. //------------------------------------------------------------------ - Error PrivateResume(); + Status PrivateResume(); //------------------------------------------------------------------ // Called internally @@ -3179,7 +3180,7 @@ private: protected: void HandlePrivateEvent(lldb::EventSP &event_sp); - Error HaltPrivate(); + Status HaltPrivate(); lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout<std::micro> &timeout); @@ -3196,7 +3197,7 @@ protected: const Timeout<std::micro> &timeout); size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, - Error &error); + Status &error); void AppendSTDOUT(const char *s, size_t len); @@ -3217,9 +3218,9 @@ protected: return static_cast<bool>(m_process_input_reader); } - Error StopForDestroyOrDetach(lldb::EventSP &exit_event_sp); + Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp); - virtual Error UpdateAutomaticSignalFiltering(); + virtual Status UpdateAutomaticSignalFiltering(); bool StateChangedIsExternallyHijacked(); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ProcessLaunchInfo.h b/contrib/llvm/tools/lldb/include/lldb/Target/ProcessLaunchInfo.h index 083e0bbed8bd..93a1a9ebd239 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ProcessLaunchInfo.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ProcessLaunchInfo.h @@ -94,7 +94,7 @@ public: void Clear(); - bool ConvertArgumentsForLaunchingInShell(Error &error, bool localhost, + bool ConvertArgumentsForLaunchingInShell(Status &error, bool localhost, bool will_debug, bool first_arg_is_full_shell_command, int32_t num_resumes); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ProcessStructReader.h b/contrib/llvm/tools/lldb/include/lldb/Target/ProcessStructReader.h index acc5c1f32686..cfc8fe11a39a 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ProcessStructReader.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ProcessStructReader.h @@ -17,7 +17,7 @@ #include "lldb/Target/Process.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include <initializer_list> #include <map> @@ -68,7 +68,7 @@ public: } size_t total_size = struct_type.GetByteSize(nullptr); lldb::DataBufferSP buffer_sp(new DataBufferHeap(total_size, 0)); - Error error; + Status error; process->ReadMemoryFromInferior(base_addr, buffer_sp->GetBytes(), total_size, error); if (error.Fail()) diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/RegisterContext.h b/contrib/llvm/tools/lldb/include/lldb/Target/RegisterContext.h index 485645b2dc14..c438a0cd12cf 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/RegisterContext.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/RegisterContext.h @@ -138,12 +138,12 @@ public: virtual bool HardwareSingleStep(bool enable); - virtual Error + virtual Status ReadRegisterValueFromMemory(const lldb_private::RegisterInfo *reg_info, lldb::addr_t src_addr, uint32_t src_len, RegisterValue ®_value); - virtual Error + virtual Status WriteRegisterValueToMemory(const lldb_private::RegisterInfo *reg_info, lldb::addr_t dst_addr, uint32_t dst_len, const RegisterValue ®_value); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/StackFrame.h b/contrib/llvm/tools/lldb/include/lldb/Target/StackFrame.h index 1f25575e236a..cb503875a5c0 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/StackFrame.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/StackFrame.h @@ -24,7 +24,7 @@ #include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/ExecutionContextScope.h" #include "lldb/Target/StackID.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/UserID.h" @@ -201,7 +201,7 @@ public: /// Returns true if the CFA value was successfully set in value. Some /// frames may be unable to provide this value; they will return false. //------------------------------------------------------------------ - bool GetFrameBaseValue(Scalar &value, Error *error_ptr); + bool GetFrameBaseValue(Scalar &value, Status *error_ptr); //------------------------------------------------------------------ /// Get the DWARFExpression corresponding to the Canonical Frame Address. @@ -215,7 +215,7 @@ public: /// @return /// Returns the corresponding DWARF expression, or NULL. //------------------------------------------------------------------ - DWARFExpression *GetFrameBaseExpression(Error *error_ptr); + DWARFExpression *GetFrameBaseExpression(Status *error_ptr); //------------------------------------------------------------------ /// Get the current lexical scope block for this StackFrame, if possible. @@ -315,7 +315,7 @@ public: //------------------------------------------------------------------ lldb::ValueObjectSP GetValueForVariableExpressionPath( llvm::StringRef var_expr, lldb::DynamicValueType use_dynamic, - uint32_t options, lldb::VariableSP &var_sp, Error &error); + uint32_t options, lldb::VariableSP &var_sp, Status &error); //------------------------------------------------------------------ /// Determine whether this StackFrame has debug information available or not @@ -535,7 +535,7 @@ private: SymbolContext m_sc; Flags m_flags; Scalar m_frame_base; - Error m_frame_base_error; + Status m_frame_base_error; bool m_cfa_is_valid; // Does this frame have a CFA? Different from CFA == // LLDB_INVALID_ADDRESS uint32_t m_stop_id; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h b/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h index aa4452a9c3f2..a4d2c0382628 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/StructuredDataPlugin.h @@ -123,8 +123,8 @@ public: /// The error if formatting the object contents failed; otherwise, /// success. // ------------------------------------------------------------------------- - virtual Error GetDescription(const StructuredData::ObjectSP &object_sp, - lldb_private::Stream &stream) = 0; + virtual Status GetDescription(const StructuredData::ObjectSP &object_sp, + lldb_private::Stream &stream) = 0; // ------------------------------------------------------------------------- /// Returns whether the plugin's features are enabled. diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Target.h b/contrib/llvm/tools/lldb/include/lldb/Target/Target.h index 8aa263f59254..ff9451939909 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Target.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Target.h @@ -490,7 +490,7 @@ public: // UpdateInstanceName (); lldb::ModuleSP GetSharedModule(const ModuleSpec &module_spec, - Error *error_ptr = nullptr); + Status *error_ptr = nullptr); //---------------------------------------------------------------------- // Settings accessors @@ -528,11 +528,11 @@ public: void Destroy(); - Error Launch(ProcessLaunchInfo &launch_info, - Stream *stream); // Optional stream to receive first stop info + Status Launch(ProcessLaunchInfo &launch_info, + Stream *stream); // Optional stream to receive first stop info - Error Attach(ProcessAttachInfo &attach_info, - Stream *stream); // Optional stream to receive first stop info + Status Attach(ProcessAttachInfo &attach_info, + Stream *stream); // Optional stream to receive first stop info //------------------------------------------------------------------ // This part handles the breakpoints. @@ -611,7 +611,7 @@ public: CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal, Args *additional_args = nullptr, - Error *additional_args_error = nullptr); + Status *additional_args_error = nullptr); // This is the same as the func_name breakpoint except that you can specify a // vector of names. This is cheaper @@ -644,7 +644,7 @@ public: // Use this to create a watchpoint: lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, - Error &error); + Status &error); lldb::WatchpointSP GetLastCreatedWatchpoint() { return m_last_created_watchpoint; @@ -687,15 +687,16 @@ public: bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count); - Error SerializeBreakpointsToFile(const FileSpec &file, - const BreakpointIDList &bp_ids, bool append); + Status SerializeBreakpointsToFile(const FileSpec &file, + const BreakpointIDList &bp_ids, + bool append); - Error CreateBreakpointsFromFile(const FileSpec &file, - BreakpointIDList &new_bps); + Status CreateBreakpointsFromFile(const FileSpec &file, + BreakpointIDList &new_bps); - Error CreateBreakpointsFromFile(const FileSpec &file, - std::vector<std::string> &names, - BreakpointIDList &new_bps); + Status CreateBreakpointsFromFile(const FileSpec &file, + std::vector<std::string> &names, + BreakpointIDList &new_bps); //------------------------------------------------------------------ /// Get \a load_addr as a callable code load address for this target @@ -808,7 +809,7 @@ public: //------------------------------------------------------------------ void SetExecutableModule(lldb::ModuleSP &module_sp, bool get_dependent_files); - bool LoadScriptingResources(std::list<Error> &errors, + bool LoadScriptingResources(std::list<Status> &errors, Stream *feedback_stream = nullptr, bool continue_on_error = true) { return m_images.LoadScriptingResourcesInTarget( @@ -914,7 +915,7 @@ public: Debugger &GetDebugger() { return m_debugger; } size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, - Error &error); + Status &error); // Reading memory through the target allows us to skip going to the process // for reading memory if possible and it allows us to try and read from @@ -927,27 +928,27 @@ public: // 2 - if there is a valid process, try and read from its memory // 3 - if (prefer_file_cache == false) then read from object file cache size_t ReadMemory(const Address &addr, bool prefer_file_cache, void *dst, - size_t dst_len, Error &error, + size_t dst_len, Status &error, lldb::addr_t *load_addr_ptr = nullptr); size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, - Error &error); + Status &error); size_t ReadCStringFromMemory(const Address &addr, char *dst, - size_t dst_max_len, Error &result_error); + size_t dst_max_len, Status &result_error); size_t ReadScalarIntegerFromMemory(const Address &addr, bool prefer_file_cache, uint32_t byte_size, bool is_signed, Scalar &scalar, - Error &error); + Status &error); uint64_t ReadUnsignedIntegerFromMemory(const Address &addr, bool prefer_file_cache, size_t integer_byte_size, - uint64_t fail_value, Error &error); + uint64_t fail_value, Status &error); bool ReadPointerFromMemory(const Address &addr, bool prefer_file_cache, - Error &error, Address &pointer_addr); + Status &error, Address &pointer_addr); SectionLoadList &GetSectionLoadList() { return m_section_load_history.GetCurrentSectionLoadList(); @@ -978,7 +979,7 @@ public: PathMappingList &GetImageSearchPathList(); - TypeSystem *GetScratchTypeSystemForLanguage(Error *error, + TypeSystem *GetScratchTypeSystemForLanguage(Status *error, lldb::LanguageType language, bool create_on_demand = true); @@ -993,7 +994,7 @@ public: UserExpression *GetUserExpressionForLanguage( llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, - const EvaluateExpressionOptions &options, Error &error); + const EvaluateExpressionOptions &options, Status &error); // Creates a FunctionCaller for the given language, the rest of the parameters // have the @@ -1008,7 +1009,7 @@ public: const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, - const char *name, Error &error); + const char *name, Status &error); // Creates a UtilityFunction for the given language, the rest of the // parameters have the @@ -1018,7 +1019,7 @@ public: UtilityFunction *GetUtilityFunctionForLanguage(const char *expr, lldb::LanguageType language, const char *name, - Error &error); + Status &error); ClangASTContext *GetScratchClangASTContext(bool create_on_demand = true); @@ -1028,7 +1029,7 @@ public: // Install any files through the platform that need be to installed // prior to launching or attaching. //---------------------------------------------------------------------- - Error Install(ProcessLaunchInfo *launch_info); + Status Install(ProcessLaunchInfo *launch_info); bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr); @@ -1183,7 +1184,7 @@ public: GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules, const FileSpecList *containingSourceFiles); - lldb::REPLSP GetREPL(Error &err, lldb::LanguageType language, + lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create); void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp); diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/TargetList.h b/contrib/llvm/tools/lldb/include/lldb/Target/TargetList.h index 81b81dba7757..43f4520369b6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/TargetList.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/TargetList.h @@ -91,10 +91,10 @@ public: /// @return /// An error object that indicates success or failure //------------------------------------------------------------------ - Error CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, - llvm::StringRef triple_str, bool get_dependent_modules, - const OptionGroupPlatform *platform_options, - lldb::TargetSP &target_sp); + Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, + llvm::StringRef triple_str, bool get_dependent_modules, + const OptionGroupPlatform *platform_options, + lldb::TargetSP &target_sp); //------------------------------------------------------------------ /// Create a new Target. @@ -102,9 +102,9 @@ public: /// Same as the function above, but used when you already know the /// platform you will be using //------------------------------------------------------------------ - Error CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, - const ArchSpec &arch, bool get_dependent_modules, - lldb::PlatformSP &platform_sp, lldb::TargetSP &target_sp); + Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, + const ArchSpec &arch, bool get_dependent_modules, + lldb::PlatformSP &platform_sp, lldb::TargetSP &target_sp); //------------------------------------------------------------------ /// Delete a Target object from the list. @@ -211,20 +211,20 @@ protected: private: lldb::TargetSP GetDummyTarget(lldb_private::Debugger &debugger); - Error CreateDummyTarget(Debugger &debugger, - llvm::StringRef specified_arch_name, - lldb::TargetSP &target_sp); + Status CreateDummyTarget(Debugger &debugger, + llvm::StringRef specified_arch_name, + lldb::TargetSP &target_sp); - Error CreateTargetInternal(Debugger &debugger, llvm::StringRef user_exe_path, - llvm::StringRef triple_str, - bool get_dependent_files, - const OptionGroupPlatform *platform_options, - lldb::TargetSP &target_sp, bool is_dummy_target); + Status CreateTargetInternal(Debugger &debugger, llvm::StringRef user_exe_path, + llvm::StringRef triple_str, + bool get_dependent_files, + const OptionGroupPlatform *platform_options, + lldb::TargetSP &target_sp, bool is_dummy_target); - Error CreateTargetInternal(Debugger &debugger, llvm::StringRef user_exe_path, - const ArchSpec &arch, bool get_dependent_modules, - lldb::PlatformSP &platform_sp, - lldb::TargetSP &target_sp, bool is_dummy_target); + Status CreateTargetInternal(Debugger &debugger, llvm::StringRef user_exe_path, + const ArchSpec &arch, bool get_dependent_modules, + lldb::PlatformSP &platform_sp, + lldb::TargetSP &target_sp, bool is_dummy_target); DISALLOW_COPY_AND_ASSIGN(TargetList); }; diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h b/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h index 47d0b7d767d6..cfab13069278 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/Thread.h @@ -441,16 +441,16 @@ public: return GetStackFrameList()->GetCurrentInlinedDepth(); } - Error ReturnFromFrameWithIndex(uint32_t frame_idx, - lldb::ValueObjectSP return_value_sp, - bool broadcast = false); + Status ReturnFromFrameWithIndex(uint32_t frame_idx, + lldb::ValueObjectSP return_value_sp, + bool broadcast = false); - Error ReturnFromFrame(lldb::StackFrameSP frame_sp, - lldb::ValueObjectSP return_value_sp, - bool broadcast = false); + Status ReturnFromFrame(lldb::StackFrameSP frame_sp, + lldb::ValueObjectSP return_value_sp, + bool broadcast = false); - Error JumpToLine(const FileSpec &file, uint32_t line, bool can_leave_function, - std::string *warnings = nullptr); + Status JumpToLine(const FileSpec &file, uint32_t line, + bool can_leave_function, std::string *warnings = nullptr); virtual lldb::StackFrameSP GetFrameWithStackID(const StackID &stack_id) { if (stack_id.IsValid()) @@ -530,7 +530,7 @@ public: /// @return /// An error that describes anything that went wrong //------------------------------------------------------------------ - virtual Error + virtual Status StepIn(bool source_step, LazyBool step_in_avoids_code_without_debug_info = eLazyBoolCalculate, LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate); @@ -548,7 +548,7 @@ public: /// @return /// An error that describes anything that went wrong //------------------------------------------------------------------ - virtual Error StepOver( + virtual Status StepOver( bool source_step, LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate); @@ -561,7 +561,7 @@ public: /// @return /// An error that describes anything that went wrong //------------------------------------------------------------------ - virtual Error StepOut(); + virtual Status StepOut(); //------------------------------------------------------------------ /// Retrieves the per-thread data area. @@ -973,7 +973,7 @@ public: /// An error if the thread plan could not be unwound. //------------------------------------------------------------------ - Error UnwindInnermostExpression(); + Status UnwindInnermostExpression(); //------------------------------------------------------------------ /// Gets the outer-most plan that was popped off the plan stack in the diff --git a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h index 204f1f9fbd70..d00172d1763b 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h +++ b/contrib/llvm/tools/lldb/include/lldb/Target/ThreadSpec.h @@ -45,7 +45,7 @@ public: static std::unique_ptr<ThreadSpec> CreateFromStructuredData(const StructuredData::Dictionary &data_dict, - Error &error); + Status &error); StructuredData::ObjectSP SerializeToStructuredData(); @@ -55,9 +55,9 @@ public: void SetTID(lldb::tid_t tid) { m_tid = tid; } - void SetName(const char *name) { m_name = name; } + void SetName(llvm::StringRef name) { m_name = name; } - void SetQueueName(const char *queue_name) { m_queue_name = queue_name; } + void SetQueueName(llvm::StringRef queue_name) { m_queue_name = queue_name; } uint32_t GetIndex() const { return m_index; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h b/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h index 5c5d382048c1..bf8ed9afc008 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/JSON.h @@ -253,7 +253,7 @@ class JSONParser : public StringExtractor { public: enum Token { Invalid, - Error, + Status, ObjectStart, ObjectEnd, ArrayStart, diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/RegularExpression.h b/contrib/llvm/tools/lldb/include/lldb/Utility/RegularExpression.h index d97e35647583..dba7001ce0fa 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/RegularExpression.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/RegularExpression.h @@ -210,7 +210,7 @@ private: // Member variables //------------------------------------------------------------------ std::string m_re; ///< A copy of the original regular expression text - int m_comp_err; ///< Error code for the regular expression compilation + int m_comp_err; ///< Status code for the regular expression compilation regex_t m_preg; ///< The compiled regular expression }; diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/SelectHelper.h b/contrib/llvm/tools/lldb/include/lldb/Utility/SelectHelper.h index 5fa856b15d9f..12950d032fb6 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/SelectHelper.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/SelectHelper.h @@ -10,7 +10,7 @@ #ifndef liblldb_SelectHelper_h_ #define liblldb_SelectHelper_h_ -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-types.h" // for socket_t #include "llvm/ADT/DenseMap.h" @@ -49,7 +49,7 @@ public: // Call the system's select() to wait for descriptors using // timeout provided in a call the SelectHelper::SetTimeout(), // or infinite wait if no timeout was set. - lldb_private::Error Select(); + lldb_private::Status Select(); protected: struct FDInfo { diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/Error.h b/contrib/llvm/tools/lldb/include/lldb/Utility/Status.h index a236ab45a0bb..4ac191b1f613 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/Error.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/Status.h @@ -1,4 +1,5 @@ -//===-- Error.h -------------------------------------------------*- C++ -*-===// +//===-- Status.h -------------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -30,12 +31,12 @@ class raw_ostream; namespace lldb_private { //---------------------------------------------------------------------- -/// @class Error Error.h "lldb/Utility/Error.h" +/// @class Status Status.h "lldb/Utility/Status.h" /// @brief An error handling class. /// /// This class is designed to be able to hold any error code that can be /// encountered on a given platform. The errors are stored as a value -/// of type Error::ValueType. This value should be large enough to hold +/// of type Status::ValueType. This value should be large enough to hold /// any and all errors that the class supports. Each error has an /// associated type that is of type lldb::ErrorType. New types /// can be added to support new error types, and architecture specific @@ -49,7 +50,7 @@ namespace lldb_private { /// be cached until the error is cleared of the value of the error /// changes. //---------------------------------------------------------------------- -class Error { +class Status { public: //------------------------------------------------------------------ /// Every error value that this object can contain needs to be able @@ -68,15 +69,17 @@ public: /// @param[in] type /// The type for \a err. //------------------------------------------------------------------ - Error(); + Status(); - explicit Error(ValueType err, lldb::ErrorType type = lldb::eErrorTypeGeneric); + explicit Status(ValueType err, + lldb::ErrorType type = lldb::eErrorTypeGeneric); - /* implicit */ Error(std::error_code EC); + /* implicit */ Status(std::error_code EC); - explicit Error(const char *format, ...) __attribute__((format(printf, 2, 3))); + explicit Status(const char *format, ...) + __attribute__((format(printf, 2, 3))); - Error(const Error &rhs); + Status(const Status &rhs); //------------------------------------------------------------------ /// Assignment operator. /// @@ -86,7 +89,7 @@ public: /// @return /// A const reference to this object. //------------------------------------------------------------------ - const Error &operator=(const Error &rhs); + const Status &operator=(const Status &rhs); //------------------------------------------------------------------ /// Assignment operator from a kern_return_t. @@ -99,9 +102,9 @@ public: /// @return /// A const reference to this object. //------------------------------------------------------------------ - const Error &operator=(uint32_t err); + const Status &operator=(uint32_t err); - ~Error(); + ~Status(); //------------------------------------------------------------------ /// Get the error string associated with the current error. @@ -186,7 +189,7 @@ public: /// Set the current error to errno. /// /// Update the error value to be \c errno and update the type to - /// be \c Error::POSIX. + /// be \c Status::POSIX. //------------------------------------------------------------------ void SetErrorToErrno(); @@ -194,7 +197,7 @@ public: /// Set the current error to a generic error. /// /// Update the error value to be \c LLDB_GENERIC_ERROR and update the - /// type to be \c Error::Generic. + /// type to be \c Status::Generic. //------------------------------------------------------------------ void SetErrorToGenericError(); @@ -257,7 +260,7 @@ protected: //------------------------------------------------------------------ /// Member variables //------------------------------------------------------------------ - ValueType m_code; ///< Error code as an integer value. + ValueType m_code; ///< Status code as an integer value. lldb::ErrorType m_type; ///< The type of the above error code. mutable std::string m_string; ///< A string representation of the error code. }; @@ -265,8 +268,8 @@ protected: } // namespace lldb_private namespace llvm { -template <> struct format_provider<lldb_private::Error> { - static void format(const lldb_private::Error &error, llvm::raw_ostream &OS, +template <> struct format_provider<lldb_private::Status> { + static void format(const lldb_private::Status &error, llvm::raw_ostream &OS, llvm::StringRef Options); }; } diff --git a/contrib/llvm/tools/lldb/include/lldb/Utility/UUID.h b/contrib/llvm/tools/lldb/include/lldb/Utility/UUID.h index 28069bbe4c73..6313025dec15 100644 --- a/contrib/llvm/tools/lldb/include/lldb/Utility/UUID.h +++ b/contrib/llvm/tools/lldb/include/lldb/Utility/UUID.h @@ -54,6 +54,7 @@ public: std::string GetAsString(const char *separator = nullptr) const; + size_t SetFromStringRef(llvm::StringRef str, uint32_t num_uuid_bytes = 16); size_t SetFromCString(const char *c_str, uint32_t num_uuid_bytes = 16); // Decode as many UUID bytes (up to 16) as possible from the C string "cstr" diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-forward.h b/contrib/llvm/tools/lldb/include/lldb/lldb-forward.h index 2180b31527e0..392dc641558d 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-forward.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-forward.h @@ -87,7 +87,7 @@ class DynamicCheckerFunctions; class DynamicLoader; class Editline; class EmulateInstruction; -class Error; +class Status; class EvaluateExpressionOptions; class Event; class EventData; diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-private-enumerations.h b/contrib/llvm/tools/lldb/include/lldb/lldb-private-enumerations.h index 9572bee81177..332265665237 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-private-enumerations.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-private-enumerations.h @@ -205,9 +205,10 @@ typedef enum MemoryModuleLoadLevel { enum class LineStatus { Success, // The line that was just edited if good and should be added to the // lines - Error, // There is an error with the current line and it needs to be re-edited - // before it can be accepted - Done // Lines are complete + Status, // There is an error with the current line and it needs to be + // re-edited + // before it can be accepted + Done // Lines are complete }; //---------------------------------------------------------------------- diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h b/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h index d3e80075625e..9f25eb1f9a29 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-private-interfaces.h @@ -46,7 +46,7 @@ typedef ObjectFile *(*ObjectFileCreateMemoryInstance)( const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp, const lldb::ProcessSP &process_sp, lldb::addr_t offset); typedef bool (*ObjectFileSaveCore)(const lldb::ProcessSP &process_sp, - const FileSpec &outfile, Error &error); + const FileSpec &outfile, Status &error); typedef EmulateInstruction *(*EmulateInstructionCreateInstance)( const ArchSpec &arch, InstructionType inst_type); typedef OperatingSystem *(*OperatingSystemCreateInstance)(Process *process, @@ -58,8 +58,8 @@ typedef lldb::CommandObjectSP (*LanguageRuntimeGetCommandObject)( CommandInterpreter &interpreter); typedef lldb::StructuredDataPluginSP (*StructuredDataPluginCreateInstance)( Process &process); -typedef Error (*StructuredDataFilterLaunchInfo)(ProcessLaunchInfo &launch_info, - Target *target); +typedef Status (*StructuredDataFilterLaunchInfo)(ProcessLaunchInfo &launch_info, + Target *target); typedef SystemRuntime *(*SystemRuntimeCreateInstance)(Process *process); typedef lldb::PlatformSP (*PlatformCreateInstance)(bool force, const ArchSpec *arch); @@ -96,7 +96,7 @@ typedef lldb::InstrumentationRuntimeSP (*InstrumentationRuntimeCreateInstance)( const lldb::ProcessSP &process_sp); typedef lldb::TypeSystemSP (*TypeSystemCreateInstance)( lldb::LanguageType language, Module *module, Target *target); -typedef lldb::REPLSP (*REPLCreateInstance)(Error &error, +typedef lldb::REPLSP (*REPLCreateInstance)(Status &error, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options); diff --git a/contrib/llvm/tools/lldb/include/lldb/lldb-private-types.h b/contrib/llvm/tools/lldb/include/lldb/lldb-private-types.h index 4f192b66369f..fd21641218fb 100644 --- a/contrib/llvm/tools/lldb/include/lldb/lldb-private-types.h +++ b/contrib/llvm/tools/lldb/include/lldb/lldb-private-types.h @@ -27,7 +27,7 @@ class Platform; class ExecutionContext; typedef llvm::sys::DynamicLibrary (*LoadPluginCallbackType)( - const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Error &error); + const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Status &error); //---------------------------------------------------------------------- // Every register is described in detail including its name, alternate diff --git a/contrib/llvm/tools/lldb/source/API/SBBreakpoint.cpp b/contrib/llvm/tools/lldb/source/API/SBBreakpoint.cpp index 0b661a646f31..bf9603248d71 100644 --- a/contrib/llvm/tools/lldb/source/API/SBBreakpoint.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBBreakpoint.cpp @@ -557,7 +557,7 @@ SBError SBBreakpoint::SetScriptCallbackBody(const char *callback_body_text) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); BreakpointOptions *bp_options = bkpt_sp->GetOptions(); - Error error = + Status error = bkpt_sp->GetTarget() .GetDebugger() .GetCommandInterpreter() @@ -578,8 +578,8 @@ bool SBBreakpoint::AddName(const char *new_name) { if (bkpt_sp) { std::lock_guard<std::recursive_mutex> guard( bkpt_sp->GetTarget().GetAPIMutex()); - Error error; // Think I'm just going to swallow the error here, it's - // probably more annoying to have to provide it. + Status error; // Think I'm just going to swallow the error here, it's + // probably more annoying to have to provide it. return bkpt_sp->AddName(new_name, error); } diff --git a/contrib/llvm/tools/lldb/source/API/SBBreakpointLocation.cpp b/contrib/llvm/tools/lldb/source/API/SBBreakpointLocation.cpp index d8779ffe2ba8..dc9c00d8dd57 100644 --- a/contrib/llvm/tools/lldb/source/API/SBBreakpointLocation.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBBreakpointLocation.cpp @@ -171,7 +171,7 @@ SBBreakpointLocation::SetScriptCallbackBody(const char *callback_body_text) { std::lock_guard<std::recursive_mutex> guard( loc_sp->GetTarget().GetAPIMutex()); BreakpointOptions *bp_options = loc_sp->GetLocationOptions(); - Error error = + Status error = loc_sp->GetBreakpoint() .GetTarget() .GetDebugger() diff --git a/contrib/llvm/tools/lldb/source/API/SBCommandReturnObject.cpp b/contrib/llvm/tools/lldb/source/API/SBCommandReturnObject.cpp index 7eed94e05b10..5a8909b98e53 100644 --- a/contrib/llvm/tools/lldb/source/API/SBCommandReturnObject.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBCommandReturnObject.cpp @@ -17,8 +17,8 @@ #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -182,7 +182,7 @@ bool SBCommandReturnObject::GetDescription(SBStream &description) { Stream &strm = description.ref(); if (m_opaque_ap) { - description.Printf("Status: "); + description.Printf("Error: "); lldb::ReturnStatus status = m_opaque_ap->GetStatus(); if (status == lldb::eReturnStatusStarted) strm.PutCString("Started"); @@ -271,7 +271,7 @@ void SBCommandReturnObject::SetError(lldb::SBError &error, if (error.IsValid()) m_opaque_ap->SetError(error.ref(), fallback_error_cstr); else if (fallback_error_cstr) - m_opaque_ap->SetError(Error(), fallback_error_cstr); + m_opaque_ap->SetError(Status(), fallback_error_cstr); } } diff --git a/contrib/llvm/tools/lldb/source/API/SBDebugger.cpp b/contrib/llvm/tools/lldb/source/API/SBDebugger.cpp index 8d23d3eb8505..3cdb6bbfd5f9 100644 --- a/contrib/llvm/tools/lldb/source/API/SBDebugger.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBDebugger.cpp @@ -57,7 +57,7 @@ using namespace lldb_private; static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, - Error &error) { + Status &error) { llvm::sys::DynamicLibrary dynlib = llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str()); if (dynlib.isValid()) { @@ -551,7 +551,7 @@ SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename, TargetSP target_sp; if (m_opaque_sp) { const bool add_dependent_modules = true; - Error error(m_opaque_sp->GetTargetList().CreateTarget( + Status error(m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, target_triple, add_dependent_modules, nullptr, target_sp)); sb_target.SetSP(target_sp); @@ -574,7 +574,7 @@ SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename, SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { - Error error; + Status error; const bool add_dependent_modules = true; error = m_opaque_sp->GetTargetList().CreateTarget( @@ -600,7 +600,7 @@ SBTarget SBDebugger::CreateTarget(const char *filename) { SBTarget sb_target; TargetSP target_sp; if (m_opaque_sp) { - Error error; + Status error; const bool add_dependent_modules = true; error = m_opaque_sp->GetTargetList().CreateTarget( *m_opaque_sp, filename, "", add_dependent_modules, nullptr, target_sp); @@ -873,7 +873,7 @@ SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value, SBError sb_error; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); - Error error; + Status error; if (debugger_sp) { ExecutionContext exe_ctx( debugger_sp->GetCommandInterpreter().GetExecutionContext()); @@ -894,7 +894,7 @@ SBDebugger::GetInternalVariableValue(const char *var_name, SBStringList ret_value; DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName( ConstString(debugger_instance_name))); - Error error; + Status error; if (debugger_sp) { ExecutionContext exe_ctx( debugger_sp->GetCommandInterpreter().GetExecutionContext()); diff --git a/contrib/llvm/tools/lldb/source/API/SBError.cpp b/contrib/llvm/tools/lldb/source/API/SBError.cpp index a692a9678cde..b2811d0ac381 100644 --- a/contrib/llvm/tools/lldb/source/API/SBError.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBError.cpp @@ -9,8 +9,8 @@ #include "lldb/API/SBError.h" #include "lldb/API/SBStream.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include <stdarg.h> @@ -21,7 +21,7 @@ SBError::SBError() : m_opaque_ap() {} SBError::SBError(const SBError &rhs) : m_opaque_ap() { if (rhs.IsValid()) - m_opaque_ap.reset(new Error(*rhs)); + m_opaque_ap.reset(new Status(*rhs)); } SBError::~SBError() {} @@ -31,7 +31,7 @@ const SBError &SBError::operator=(const SBError &rhs) { if (m_opaque_ap.get()) *m_opaque_ap = *rhs; else - m_opaque_ap.reset(new Error(*rhs)); + m_opaque_ap.reset(new Status(*rhs)); } else m_opaque_ap.reset(); @@ -108,7 +108,7 @@ void SBError::SetError(uint32_t err, ErrorType type) { m_opaque_ap->SetError(err, type); } -void SBError::SetError(const Error &lldb_error) { +void SBError::SetError(const Status &lldb_error) { CreateIfNeeded(); *m_opaque_ap = lldb_error; } @@ -141,19 +141,19 @@ bool SBError::IsValid() const { return m_opaque_ap.get() != NULL; } void SBError::CreateIfNeeded() { if (m_opaque_ap.get() == NULL) - m_opaque_ap.reset(new Error()); + m_opaque_ap.reset(new Status()); } -lldb_private::Error *SBError::operator->() { return m_opaque_ap.get(); } +lldb_private::Status *SBError::operator->() { return m_opaque_ap.get(); } -lldb_private::Error *SBError::get() { return m_opaque_ap.get(); } +lldb_private::Status *SBError::get() { return m_opaque_ap.get(); } -lldb_private::Error &SBError::ref() { +lldb_private::Status &SBError::ref() { CreateIfNeeded(); return *m_opaque_ap; } -const lldb_private::Error &SBError::operator*() const { +const lldb_private::Status &SBError::operator*() const { // Be sure to call "IsValid()" before calling this function or it will crash return *m_opaque_ap; } diff --git a/contrib/llvm/tools/lldb/source/API/SBFrame.cpp b/contrib/llvm/tools/lldb/source/API/SBFrame.cpp index d52bbe8069f8..684a707dda94 100644 --- a/contrib/llvm/tools/lldb/source/API/SBFrame.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBFrame.cpp @@ -606,7 +606,7 @@ lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path, frame = exe_ctx.GetFramePtr(); if (frame) { VariableSP var_sp; - Error error; + Status error; ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath( var_path, eNoDynamicValues, StackFrame::eExpressionPathOptionCheckPtrVsMember | diff --git a/contrib/llvm/tools/lldb/source/API/SBHostOS.cpp b/contrib/llvm/tools/lldb/source/API/SBHostOS.cpp index c25499db89cd..90b75a6ecd7b 100644 --- a/contrib/llvm/tools/lldb/source/API/SBHostOS.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBHostOS.cpp @@ -80,7 +80,7 @@ lldb::thread_t SBHostOS::ThreadCreate(const char *name, void SBHostOS::ThreadCreated(const char *name) {} bool SBHostOS::ThreadCancel(lldb::thread_t thread, SBError *error_ptr) { - Error error; + Status error; HostThread host_thread(thread); error = host_thread.Cancel(); if (error_ptr) @@ -90,7 +90,7 @@ bool SBHostOS::ThreadCancel(lldb::thread_t thread, SBError *error_ptr) { } bool SBHostOS::ThreadDetach(lldb::thread_t thread, SBError *error_ptr) { - Error error; + Status error; #if defined(_WIN32) if (error_ptr) error_ptr->SetErrorString("ThreadDetach is not supported on this platform"); @@ -106,7 +106,7 @@ bool SBHostOS::ThreadDetach(lldb::thread_t thread, SBError *error_ptr) { bool SBHostOS::ThreadJoin(lldb::thread_t thread, lldb::thread_result_t *result, SBError *error_ptr) { - Error error; + Status error; HostThread host_thread(thread); error = host_thread.Join(result); if (error_ptr) diff --git a/contrib/llvm/tools/lldb/source/API/SBModule.cpp b/contrib/llvm/tools/lldb/source/API/SBModule.cpp index 3865ba927977..17f3dcc5656d 100644 --- a/contrib/llvm/tools/lldb/source/API/SBModule.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBModule.cpp @@ -37,8 +37,8 @@ SBModule::SBModule(const lldb::ModuleSP &module_sp) : m_opaque_sp(module_sp) {} SBModule::SBModule(const SBModuleSpec &module_spec) : m_opaque_sp() { ModuleSP module_sp; - Error error = ModuleList::GetSharedModule(*module_spec.m_opaque_ap, module_sp, - NULL, NULL, NULL); + Status error = ModuleList::GetSharedModule(*module_spec.m_opaque_ap, + module_sp, NULL, NULL, NULL); if (module_sp) SetSP(module_sp); } diff --git a/contrib/llvm/tools/lldb/source/API/SBPlatform.cpp b/contrib/llvm/tools/lldb/source/API/SBPlatform.cpp index 0f1b99236a71..87cbc4537a3c 100644 --- a/contrib/llvm/tools/lldb/source/API/SBPlatform.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBPlatform.cpp @@ -17,7 +17,7 @@ #include "lldb/Interpreter/Args.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/FileSystem.h" @@ -205,7 +205,7 @@ const char *SBPlatformShellCommand::GetOutput() { SBPlatform::SBPlatform() : m_opaque_sp() {} SBPlatform::SBPlatform(const char *platform_name) : m_opaque_sp() { - Error error; + Status error; if (platform_name && platform_name[0]) m_opaque_sp = Platform::Create(ConstString(platform_name), error); } @@ -374,7 +374,7 @@ SBError SBPlatform::Put(SBFileSpec &src, SBFileSpec &dst) { return platform_sp->PutFile(src.ref(), dst.ref(), permissions); } - Error error; + Status error; error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", src.ref().GetPath().c_str()); return error; @@ -386,7 +386,7 @@ SBError SBPlatform::Install(SBFileSpec &src, SBFileSpec &dst) { if (src.Exists()) return platform_sp->Install(src.ref(), dst.ref()); - Error error; + Status error; error.SetErrorStringWithFormat("'src' argument doesn't exist: '%s'", src.ref().GetPath().c_str()); return error; @@ -397,7 +397,7 @@ SBError SBPlatform::Run(SBPlatformShellCommand &shell_command) { return ExecuteConnected([&](const lldb::PlatformSP &platform_sp) { const char *command = shell_command.GetCommand(); if (!command) - return Error("invalid shell command (empty)"); + return Status("invalid shell command (empty)"); const char *working_dir = shell_command.GetWorkingDirectory(); if (working_dir == NULL) { @@ -427,7 +427,7 @@ SBError SBPlatform::Kill(const lldb::pid_t pid) { } SBError SBPlatform::ExecuteConnected( - const std::function<Error(const lldb::PlatformSP &)> &func) { + const std::function<Status(const lldb::PlatformSP &)> &func) { SBError sb_error; const auto platform_sp(GetSP()); if (platform_sp) { diff --git a/contrib/llvm/tools/lldb/source/API/SBProcess.cpp b/contrib/llvm/tools/lldb/source/API/SBProcess.cpp index 0348113a9873..8b79e521a371 100644 --- a/contrib/llvm/tools/lldb/source/API/SBProcess.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBProcess.cpp @@ -281,7 +281,7 @@ size_t SBProcess::PutSTDIN(const char *src, size_t src_len) { size_t ret_val = 0; ProcessSP process_sp(GetSP()); if (process_sp) { - Error error; + Status error; ret_val = process_sp->PutSTDIN(src, src_len, error); } @@ -298,7 +298,7 @@ size_t SBProcess::GetSTDOUT(char *dst, size_t dst_len) const { size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { - Error error; + Status error; bytes_read = process_sp->GetSTDOUT(dst, dst_len, error); } @@ -317,7 +317,7 @@ size_t SBProcess::GetSTDERR(char *dst, size_t dst_len) const { size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { - Error error; + Status error; bytes_read = process_sp->GetSTDERR(dst, dst_len, error); } @@ -336,7 +336,7 @@ size_t SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const { size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { - Error error; + Status error; bytes_read = process_sp->GetAsyncProfileData(dst, dst_len, error); } diff --git a/contrib/llvm/tools/lldb/source/API/SBStream.cpp b/contrib/llvm/tools/lldb/source/API/SBStream.cpp index 5ae5a01589de..159ec07e4e02 100644 --- a/contrib/llvm/tools/lldb/source/API/SBStream.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBStream.cpp @@ -10,7 +10,7 @@ #include "lldb/API/SBStream.h" #include "lldb/Core/StreamFile.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" diff --git a/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp b/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp index 2fca56f2f223..971c4ab2295d 100644 --- a/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBStructuredData.cpp @@ -14,7 +14,7 @@ #include "lldb/Core/StructuredData.h" #include "lldb/Core/StructuredDataImpl.h" #include "lldb/Target/StructuredDataPlugin.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -62,7 +62,7 @@ SBError SBStructuredData::GetAsJSON(lldb::SBStream &stream) const { } lldb::SBError SBStructuredData::GetDescription(lldb::SBStream &stream) const { - Error error = m_impl_up->GetDescription(stream.ref()); + Status error = m_impl_up->GetDescription(stream.ref()); SBError sb_error; sb_error.SetError(error); return sb_error; diff --git a/contrib/llvm/tools/lldb/source/API/SBTarget.cpp b/contrib/llvm/tools/lldb/source/API/SBTarget.cpp index 4032383eb56c..0ab7375ccc30 100644 --- a/contrib/llvm/tools/lldb/source/API/SBTarget.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBTarget.cpp @@ -74,7 +74,7 @@ using namespace lldb_private; namespace { -Error AttachToProcess(ProcessAttachInfo &attach_info, Target &target) { +Status AttachToProcess(ProcessAttachInfo &attach_info, Target &target) { std::lock_guard<std::recursive_mutex> guard(target.GetAPIMutex()); auto process_sp = target.GetProcessSP(); @@ -85,8 +85,8 @@ Error AttachToProcess(ProcessAttachInfo &attach_info, Target &target) { // listener, so if a valid listener is supplied, we need to error out // to let the client know. if (attach_info.GetListener()) - return Error("process is connected and already has a listener, pass " - "empty listener"); + return Status("process is connected and already has a listener, pass " + "empty listener"); } } @@ -1279,7 +1279,7 @@ lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size, } // Target::CreateWatchpoint() is thread safe. - Error cw_error; + Status cw_error; // This API doesn't take in a type, so we can't figure out what it is. CompilerType *type = NULL; watchpoint_sp = @@ -1863,7 +1863,7 @@ lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr, DataBufferHeap data( target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0); bool prefer_file_cache = false; - lldb_private::Error error; + lldb_private::Status error; lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; const size_t bytes_read = target_sp->ReadMemory(*addr_ptr, prefer_file_cache, data.GetBytes(), diff --git a/contrib/llvm/tools/lldb/source/API/SBThread.cpp b/contrib/llvm/tools/lldb/source/API/SBThread.cpp index 3961a7f925a0..2c82bc3bcdcf 100644 --- a/contrib/llvm/tools/lldb/source/API/SBThread.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBThread.cpp @@ -562,7 +562,7 @@ bool SBThread::GetInfoItemByPathAsString(const char *path, SBStream &strm) { info_root_sp->GetObjectForDotSeparatedPath(path); if (node) { if (node->GetType() == StructuredData::Type::eTypeString) { - strm.Printf("%s", node->GetAsString()->GetValue().c_str()); + strm.Printf("%s", node->GetAsString()->GetValue().str().c_str()); success = true; } if (node->GetType() == StructuredData::Type::eTypeInteger) { @@ -1037,7 +1037,7 @@ SBError SBThread::JumpToLine(lldb::SBFileSpec &file_spec, uint32_t line) { Thread *thread = exe_ctx.GetThreadPtr(); - Error err = thread->JumpToLine(file_spec.get(), line, true); + Status err = thread->JumpToLine(file_spec.get(), line, true); sb_error.SetError(err); return sb_error; } diff --git a/contrib/llvm/tools/lldb/source/API/SBValue.cpp b/contrib/llvm/tools/lldb/source/API/SBValue.cpp index ea0f9f591ab9..b6f044c61a78 100644 --- a/contrib/llvm/tools/lldb/source/API/SBValue.cpp +++ b/contrib/llvm/tools/lldb/source/API/SBValue.cpp @@ -112,7 +112,7 @@ public: lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, std::unique_lock<std::recursive_mutex> &lock, - Error &error) { + Status &error) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); if (!m_valobj_sp) { error.SetErrorString("invalid value object"); @@ -218,12 +218,12 @@ public: return in_value.GetSP(m_stop_locker, m_lock, m_lock_error); } - Error &GetError() { return m_lock_error; } + Status &GetError() { return m_lock_error; } private: Process::StopLocker m_stop_locker; std::unique_lock<std::recursive_mutex> m_lock; - Error m_lock_error; + Status m_lock_error; }; SBValue::SBValue() : m_opaque_sp() {} @@ -1112,7 +1112,7 @@ SBValue SBValue::Dereference() { ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { - Error error; + Status error; sb_value = value_sp->Dereference(error); } Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API)); @@ -1336,7 +1336,7 @@ lldb::SBValue SBValue::AddressOf() { ValueLocker locker; lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { - Error error; + Status error; sb_value.SetSP(value_sp->AddressOf(error), GetPreferDynamicValue(), GetPreferSyntheticValue()); } @@ -1445,7 +1445,7 @@ lldb::SBData SBValue::GetData() { lldb::ValueObjectSP value_sp(GetSP(locker)); if (value_sp) { DataExtractorSP data_sp(new DataExtractor()); - Error error; + Status error; value_sp->GetData(*data_sp, error); if (error.Success()) *sb_data = data_sp; @@ -1475,7 +1475,7 @@ bool SBValue::SetData(lldb::SBData &data, SBError &error) { error.SetErrorString("No data to set"); ret = false; } else { - Error set_error; + Status set_error; value_sp->SetData(*data_extractor, set_error); @@ -1541,7 +1541,7 @@ lldb::SBWatchpoint SBValue::Watch(bool resolve_location, bool read, bool write, if (write) watch_type |= LLDB_WATCH_TYPE_WRITE; - Error rc; + Status rc; CompilerType type(value_sp->GetCompilerType()); WatchpointSP watchpoint_sp = target_sp->CreateWatchpoint(addr, byte_size, &type, watch_type, rc); diff --git a/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp b/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp index 4a20691a2219..64ea3575e5f4 100644 --- a/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp +++ b/contrib/llvm/tools/lldb/source/API/SystemInitializerFull.cpp @@ -400,7 +400,8 @@ void SystemInitializerFull::InitializeSWIG() { } void SystemInitializerFull::Terminate() { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); Debugger::SettingsTerminate(); diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/Breakpoint.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/Breakpoint.cpp index 2b44691186c0..4c58f8231344 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/Breakpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/Breakpoint.cpp @@ -127,7 +127,7 @@ StructuredData::ObjectSP Breakpoint::SerializeToStructuredData() { } lldb::BreakpointSP Breakpoint::CreateFromStructuredData( - Target &target, StructuredData::ObjectSP &object_data, Error &error) { + Target &target, StructuredData::ObjectSP &object_data, Status &error) { BreakpointSP result_sp; StructuredData::Dictionary *breakpoint_dict = object_data->GetAsDictionary(); @@ -146,7 +146,7 @@ lldb::BreakpointSP Breakpoint::CreateFromStructuredData( return result_sp; } - Error create_error; + Status create_error; BreakpointResolverSP resolver_sp = BreakpointResolver::CreateFromStructuredData(*resolver_dict, create_error); @@ -207,10 +207,10 @@ lldb::BreakpointSP Breakpoint::CreateFromStructuredData( if (success && names_array) { size_t num_names = names_array->GetSize(); for (size_t i = 0; i < num_names; i++) { - std::string name; - Error error; + llvm::StringRef name; + Status error; success = names_array->GetItemAtIndexAsString(i, name); - result_sp->AddName(name.c_str(), error); + result_sp->AddName(name, error); } } @@ -242,7 +242,7 @@ bool Breakpoint::SerializedBreakpointMatchesNames( std::vector<std::string>::iterator end = names.end(); for (size_t i = 0; i < num_names; i++) { - std::string name; + llvm::StringRef name; if (names_array->GetItemAtIndexAsString(i, name)) { if (std::find(begin, end, name) != end) { return true; @@ -833,10 +833,10 @@ size_t Breakpoint::GetNumResolvedLocations() const { size_t Breakpoint::GetNumLocations() const { return m_locations.GetSize(); } -bool Breakpoint::AddName(const char *new_name, Error &error) { - if (!new_name) +bool Breakpoint::AddName(llvm::StringRef new_name, Status &error) { + if (new_name.empty()) return false; - if (!BreakpointID::StringIsBreakpointName(llvm::StringRef(new_name), error)) { + if (!BreakpointID::StringIsBreakpointName(new_name, error)) { error.SetErrorStringWithFormat("input name \"%s\" not a breakpoint name.", new_name); return false; @@ -997,8 +997,9 @@ bool Breakpoint::BreakpointPrecondition::EvaluatePrecondition( void Breakpoint::BreakpointPrecondition::GetDescription( Stream &stream, lldb::DescriptionLevel level) {} -Error Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) { - Error error; +Status +Breakpoint::BreakpointPrecondition::ConfigurePrecondition(Args &options) { + Status error; error.SetErrorString("Base breakpoint precondition has no options."); return error; } diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointID.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointID.cpp index 07742d9d7cf8..112f7c0b5195 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointID.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointID.cpp @@ -15,7 +15,7 @@ // Project includes #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Breakpoint/BreakpointID.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -98,7 +98,7 @@ BreakpointID::ParseCanonicalReference(llvm::StringRef input) { return BreakpointID(bp_id, loc_id); } -bool BreakpointID::StringIsBreakpointName(llvm::StringRef str, Error &error) { +bool BreakpointID::StringIsBreakpointName(llvm::StringRef str, Status &error) { error.Clear(); if (str.empty()) return false; diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointIDList.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointIDList.cpp index 037b03e1e46a..7b461147a4e9 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointIDList.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointIDList.cpp @@ -137,7 +137,7 @@ void BreakpointIDList::FindAndReplaceIDRanges(Args &old_args, Target *target, } llvm::StringRef range_expr; - Error error; + Status error; std::tie(range_from, range_to) = BreakpointIDList::SplitIDRangeExpression(current_arg); diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointList.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointList.cpp index 7f35588ea877..15bcb34a3d85 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointList.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointList.cpp @@ -139,7 +139,7 @@ BreakpointList::FindBreakpointByID(break_id_t break_id) const { bool BreakpointList::FindBreakpointsByName(const char *name, BreakpointList &matching_bps) { - Error error; + Status error; if (!name) return false; diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointLocation.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointLocation.cpp index 52bdefc4077f..ec8f141e8d38 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointLocation.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointLocation.cpp @@ -197,7 +197,7 @@ const char *BreakpointLocation::GetConditionText(size_t *hash) const { } bool BreakpointLocation::ConditionSaysStop(ExecutionContext &exe_ctx, - Error &error) { + Status &error) { Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS); std::lock_guard<std::mutex> guard(m_condition_mutex); @@ -260,7 +260,7 @@ bool BreakpointLocation::ConditionSaysStop(ExecutionContext &exe_ctx, options.SetResultIsInternal( true); // Don't generate a user variable for condition expressions. - Error expr_error; + Status expr_error; diagnostics.Clear(); diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointOptions.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointOptions.cpp index 9851990a838e..bef63cc0f222 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointOptions.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointOptions.cpp @@ -63,7 +63,7 @@ BreakpointOptions::CommandData::SerializeToStructuredData() { std::unique_ptr<BreakpointOptions::CommandData> BreakpointOptions::CommandData::CreateFromStructuredData( - const StructuredData::Dictionary &options_dict, Error &error) { + const StructuredData::Dictionary &options_dict, Status &error) { std::unique_ptr<CommandData> data_up(new CommandData()); bool found_something = false; @@ -73,7 +73,7 @@ BreakpointOptions::CommandData::CreateFromStructuredData( if (success) found_something = true; - std::string interpreter_str; + llvm::StringRef interpreter_str; ScriptLanguage interp_language; success = options_dict.GetValueForKeyAsString( GetKey(OptionNames::Interpreter), interpreter_str); @@ -99,7 +99,7 @@ BreakpointOptions::CommandData::CreateFromStructuredData( found_something = true; size_t num_elems = user_source->GetSize(); for (size_t i = 0; i < num_elems; i++) { - std::string elem_string; + llvm::StringRef elem_string; success = user_source->GetItemAtIndexAsString(i, elem_string); if (success) data_up->user_source.AppendString(elem_string); @@ -196,7 +196,7 @@ BreakpointOptions::~BreakpointOptions() = default; std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData( Target &target, const StructuredData::Dictionary &options_dict, - Error &error) { + Status &error) { bool enabled = true; bool one_shot = false; int32_t ignore_count = 0; @@ -230,7 +230,7 @@ std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData( success = options_dict.GetValueForKeyAsDictionary( CommandData::GetSerializationKey(), cmds_dict); if (success && cmds_dict) { - Error cmds_error; + Status cmds_error; cmd_data_up = CommandData::CreateFromStructuredData(*cmds_dict, cmds_error); if (cmds_error.Fail()) { error.SetErrorStringWithFormat( @@ -260,7 +260,7 @@ std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData( .c_str()); return nullptr; } - Error script_error; + Status script_error; script_error = interp->SetBreakpointCommandCallback(bp_options.get(), cmd_data_up); if (script_error.Fail()) { @@ -275,7 +275,7 @@ std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData( success = options_dict.GetValueForKeyAsDictionary( ThreadSpec::GetSerializationKey(), thread_spec_dict); if (success) { - Error thread_spec_error; + Status thread_spec_error; std::unique_ptr<ThreadSpec> thread_spec_up = ThreadSpec::CreateFromStructuredData(*thread_spec_dict, thread_spec_error); diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolver.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolver.cpp index f2579a0877e2..31aefb08f976 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolver.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolver.cpp @@ -56,9 +56,9 @@ const char *BreakpointResolver::ResolverTyToName(enum ResolverTy type) { } BreakpointResolver::ResolverTy -BreakpointResolver::NameToResolverTy(const char *name) { +BreakpointResolver::NameToResolverTy(llvm::StringRef name) { for (size_t i = 0; i < LastKnownResolverType; i++) { - if (strcmp(name, g_ty_to_name[i]) == 0) + if (name == g_ty_to_name[i]) return (ResolverTy)i; } return UnknownResolver; @@ -72,14 +72,14 @@ BreakpointResolver::BreakpointResolver(Breakpoint *bkpt, BreakpointResolver::~BreakpointResolver() {} BreakpointResolverSP BreakpointResolver::CreateFromStructuredData( - const StructuredData::Dictionary &resolver_dict, Error &error) { + const StructuredData::Dictionary &resolver_dict, Status &error) { BreakpointResolverSP result_sp; if (!resolver_dict.IsValid()) { error.SetErrorString("Can't deserialize from an invalid data object."); return result_sp; } - std::string subclass_name; + llvm::StringRef subclass_name; bool success = resolver_dict.GetValueForKeyAsString( GetSerializationSubclassKey(), subclass_name); @@ -90,10 +90,10 @@ BreakpointResolverSP BreakpointResolver::CreateFromStructuredData( return result_sp; } - ResolverTy resolver_type = NameToResolverTy(subclass_name.c_str()); + ResolverTy resolver_type = NameToResolverTy(subclass_name); if (resolver_type == UnknownResolver) { - error.SetErrorStringWithFormat("Unknown resolver type: %s.", - subclass_name.c_str()); + error.SetErrorStringWithFormatv("Unknown resolver type: {0}.", + subclass_name); return result_sp; } diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverAddress.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverAddress.cpp index 4674ef08eae1..32f2045ed59a 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverAddress.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverAddress.cpp @@ -44,8 +44,8 @@ BreakpointResolverAddress::~BreakpointResolverAddress() {} BreakpointResolver *BreakpointResolverAddress::CreateFromStructuredData( Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error) { - std::string module_name; + Status &error) { + llvm::StringRef module_name; lldb::addr_t addr_offset; FileSpec module_filespec; bool success; diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp index 610c8c956cf5..780d25db9ccb 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileLine.cpp @@ -38,8 +38,8 @@ BreakpointResolverFileLine::~BreakpointResolverFileLine() {} BreakpointResolver *BreakpointResolverFileLine::CreateFromStructuredData( Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error) { - std::string filename; + Status &error) { + llvm::StringRef filename; uint32_t line_no; bool check_inlines; bool skip_prologue; diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp index df6f5c2e4bf2..54c05a042468 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp @@ -37,10 +37,10 @@ BreakpointResolverFileRegex::~BreakpointResolverFileRegex() {} BreakpointResolver *BreakpointResolverFileRegex::CreateFromStructuredData( Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error) { + Status &error) { bool success; - std::string regex_string; + llvm::StringRef regex_string; success = options_dict.GetValueForKeyAsString( GetKey(OptionNames::RegexString), regex_string); if (!success) { @@ -65,7 +65,7 @@ BreakpointResolver *BreakpointResolverFileRegex::CreateFromStructuredData( if (success && names_array) { size_t num_names = names_array->GetSize(); for (size_t i = 0; i < num_names; i++) { - std::string name; + llvm::StringRef name; success = names_array->GetItemAtIndexAsString(i, name); if (!success) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverName.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverName.cpp index f8ce775096ce..468de35db0ee 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverName.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/BreakpointResolverName.cpp @@ -92,16 +92,16 @@ BreakpointResolverName::BreakpointResolverName( BreakpointResolver *BreakpointResolverName::CreateFromStructuredData( Breakpoint *bkpt, const StructuredData::Dictionary &options_dict, - Error &error) { + Status &error) { LanguageType language = eLanguageTypeUnknown; - std::string language_name; + llvm::StringRef language_name; bool success = options_dict.GetValueForKeyAsString( GetKey(OptionNames::LanguageName), language_name); if (success) { language = Language::GetLanguageTypeFromString(language_name); if (language == eLanguageTypeUnknown) { - error.SetErrorStringWithFormat("BRN::CFSD: Unknown language: %s.", - language_name.c_str()); + error.SetErrorStringWithFormatv("BRN::CFSD: Unknown language: {0}.", + language_name); return nullptr; } } @@ -122,7 +122,7 @@ BreakpointResolver *BreakpointResolverName::CreateFromStructuredData( return nullptr; } - std::string regex_text; + llvm::StringRef regex_text; success = options_dict.GetValueForKeyAsString( GetKey(OptionNames::RegexString), regex_text); if (success) { @@ -162,7 +162,7 @@ BreakpointResolver *BreakpointResolverName::CreateFromStructuredData( std::vector<uint32_t> name_masks; for (size_t i = 0; i < num_elem; i++) { uint32_t name_mask; - std::string name; + llvm::StringRef name; success = names_array->GetItemAtIndexAsString(i, name); if (!success) { diff --git a/contrib/llvm/tools/lldb/source/Breakpoint/Watchpoint.cpp b/contrib/llvm/tools/lldb/source/Breakpoint/Watchpoint.cpp index 3dbd6d23821c..a141a6b5c2f9 100644 --- a/contrib/llvm/tools/lldb/source/Breakpoint/Watchpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Breakpoint/Watchpoint.cpp @@ -286,7 +286,7 @@ void Watchpoint::SetCondition(const char *condition) { m_condition_ap.reset(); } else { // Pass nullptr for expr_prefix (no translation-unit level definitions). - Error error; + Status error; m_condition_ap.reset(m_target.GetUserExpressionForLanguage( condition, llvm::StringRef(), lldb::eLanguageTypeUnknown, UserExpression::eResultTypeAny, EvaluateExpressionOptions(), error)); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.cpp index 8042aa9d81db..92c2107dc33c 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.cpp @@ -55,10 +55,10 @@ CommandObjectArgs::CommandOptions::CommandOptions( CommandObjectArgs::CommandOptions::~CommandOptions() = default; -Error CommandObjectArgs::CommandOptions::SetOptionValue( +Status CommandObjectArgs::CommandOptions::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = m_getopt_table[option_idx].val; error.SetErrorStringWithFormat("invalid short option character '%c'", diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.h b/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.h index a4b3f9fed0ee..aa7d2411adc8 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.h +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectArgs.h @@ -27,8 +27,8 @@ public: ~CommandOptions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpoint.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpoint.cpp index d77cf55b60e9..266864d1a1f0 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpoint.cpp @@ -178,9 +178,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -662,7 +662,7 @@ protected: .get(); } break; case eSetTypeException: { - Error precond_error; + Status precond_error; bp = target ->CreateExceptionBreakpoint( m_options.m_exception_language, m_options.m_catch_bp, @@ -705,7 +705,7 @@ protected: bp->GetOptions()->SetCondition(m_options.m_condition.c_str()); if (!m_options.m_breakpoint_names.empty()) { - Error name_error; + Status name_error; for (auto name : m_options.m_breakpoint_names) { bp->AddName(name.c_str(), name_error); if (name_error.Fail()) { @@ -844,9 +844,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1305,9 +1305,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1452,9 +1452,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1611,9 +1611,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1751,9 +1751,9 @@ public: return llvm::makeArrayRef(g_breakpoint_name_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_breakpoint_name_options[option_idx].short_option; switch (short_option) { @@ -1864,8 +1864,8 @@ protected: lldb::break_id_t bp_id = valid_bp_ids.GetBreakpointIDAtIndex(index).GetBreakpointID(); BreakpointSP bp_sp = breakpoints.FindBreakpointByID(bp_id); - Error error; // We don't need to check the error here, since the option - // parser checked it... + Status error; // We don't need to check the error here, since the option + // parser checked it... bp_sp->AddName(m_name_options.m_name.GetCurrentValue(), error); } } @@ -2093,9 +2093,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -2103,7 +2103,7 @@ public: m_filename.assign(option_arg); break; case 'N': { - Error name_error; + Status name_error; if (!BreakpointID::StringIsBreakpointName(llvm::StringRef(option_arg), name_error)) { error.SetErrorStringWithFormat("Invalid breakpoint name: %s", @@ -2150,8 +2150,8 @@ protected: FileSpec input_spec(m_options.m_filename, true); BreakpointIDList new_bps; - Error error = target->CreateBreakpointsFromFile(input_spec, - m_options.m_names, new_bps); + Status error = target->CreateBreakpointsFromFile( + input_spec, m_options.m_names, new_bps); if (!error.Success()) { result.AppendError(error.AsCString()); @@ -2223,9 +2223,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -2281,7 +2281,7 @@ protected: return false; } } - Error error = target->SerializeBreakpointsToFile( + Status error = target->SerializeBreakpointsToFile( FileSpec(m_options.m_filename, true), valid_bp_ids, m_options.m_append); if (!error.Success()) { result.AppendErrorWithFormat("error serializing breakpoints: %s.", diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpointCommand.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpointCommand.cpp index 73c0c314533c..de4911953107 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpointCommand.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBreakpointCommand.cpp @@ -281,9 +281,9 @@ are no syntax errors may indicate that a function was declared but never called. ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -511,9 +511,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBugreport.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBugreport.cpp index 04050e3a6692..7ba8ab945eae 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectBugreport.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectBugreport.cpp @@ -84,7 +84,7 @@ protected: open_options |= File::eOpenOptionTruncate; StreamFileSP outfile_stream = std::make_shared<StreamFile>(); - Error error = outfile_stream->GetFile().Open(path, open_options); + Status error = outfile_stream->GetFile().Open(path, open_options); if (error.Fail()) { result.AppendErrorWithFormat("Failed to open file '%s' for %s: %s\n", path, append ? "append" : "write", diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectCommands.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectCommands.cpp index e39c0330b653..c9d71a65754b 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectCommands.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectCommands.cpp @@ -71,9 +71,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -261,9 +261,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -371,9 +371,9 @@ protected: return llvm::makeArrayRef(g_alias_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = GetDefinitions()[option_idx].short_option; std::string option_str(option_value); @@ -579,7 +579,7 @@ protected: if (!ParseOptions(args, result)) return false; - Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + Status error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); if (error.Fail()) { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -1030,7 +1030,7 @@ protected: bool check_only = false; for (size_t i = 0; i < num_lines; ++i) { llvm::StringRef bytes_strref(lines[i]); - Error error = AppendRegexSubstitution(bytes_strref, check_only); + Status error = AppendRegexSubstitution(bytes_strref, check_only); if (error.Fail()) { if (!m_interpreter.GetDebugger() .GetCommandInterpreter() @@ -1058,7 +1058,7 @@ protected: return false; } - Error error; + Status error; auto name = command[0].ref; m_regex_cmd_ap = llvm::make_unique<CommandObjectRegexCommand>( m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0, @@ -1101,9 +1101,9 @@ protected: return result.Succeeded(); } - Error AppendRegexSubstitution(const llvm::StringRef ®ex_sed, - bool check_only) { - Error error; + Status AppendRegexSubstitution(const llvm::StringRef ®ex_sed, + bool check_only) { + Status error; if (!m_regex_cmd_ap) { error.SetErrorStringWithFormat( @@ -1215,9 +1215,9 @@ private: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1311,7 +1311,7 @@ protected: CommandReturnObject &result) override { ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); - Error error; + Status error; result.SetStatus(eReturnStatusInvalid); @@ -1400,7 +1400,7 @@ protected: CommandReturnObject &result) override { ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter(); - Error error; + Status error; result.SetStatus(eReturnStatusInvalid); @@ -1487,9 +1487,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1534,7 +1534,7 @@ protected: } for (auto &entry : command.entries()) { - Error error; + Status error; const bool init_session = true; // FIXME: this is necessary because CommandObject::CheckRequirements() @@ -1619,9 +1619,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.cpp index 4496462476b4..5d0f2417f992 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.cpp @@ -71,10 +71,10 @@ CommandObjectDisassemble::CommandOptions::CommandOptions() CommandObjectDisassemble::CommandOptions::~CommandOptions() = default; -Error CommandObjectDisassemble::CommandOptions::SetOptionValue( +Status CommandObjectDisassemble::CommandOptions::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = m_getopt_table[option_idx].val; @@ -224,11 +224,11 @@ void CommandObjectDisassemble::CommandOptions::OptionParsingStarting( some_location_specified = false; } -Error CommandObjectDisassemble::CommandOptions::OptionParsingFinished( +Status CommandObjectDisassemble::CommandOptions::OptionParsingFinished( ExecutionContext *execution_context) { if (!some_location_specified) current_function = true; - return Error(); + return Status(); } llvm::ArrayRef<OptionDefinition> diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.h b/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.h index db89aa24d6a0..8ca390056dd8 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.h +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectDisassemble.h @@ -32,8 +32,8 @@ public: ~CommandOptions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; @@ -49,7 +49,7 @@ public: return flavor_string.c_str(); } - Error OptionParsingFinished(ExecutionContext *execution_context) override; + Status OptionParsingFinished(ExecutionContext *execution_context) override; bool show_mixed; // Show mixed source/assembly bool show_bytes; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.cpp index 8a0afce741e9..b6e0016c88e4 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.cpp @@ -69,10 +69,10 @@ static OptionDefinition g_expression_options[] = { // clang-format on }; -Error CommandObjectExpression::CommandOptions::SetOptionValue( +Status CommandObjectExpression::CommandOptions::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = GetDefinitions()[option_idx].short_option; @@ -295,15 +295,15 @@ CommandObjectExpression::~CommandObjectExpression() = default; Options *CommandObjectExpression::GetOptions() { return &m_option_group; } -static lldb_private::Error +static lldb_private::Status CanBeUsedForElementCountPrinting(ValueObject &valobj) { CompilerType type(valobj.GetCompilerType()); CompilerType pointee; if (!type.IsPointerType(&pointee)) - return Error("as it does not refer to a pointer"); + return Status("as it does not refer to a pointer"); if (pointee.IsVoidType()) - return Error("as it refers to a pointer to void"); - return Error(); + return Status("as it refers to a pointer to void"); + return Status(); } bool CommandObjectExpression::EvaluateExpression(const char *expr, @@ -384,7 +384,7 @@ bool CommandObjectExpression::EvaluateExpression(const char *expr, result_valobj_sp->SetFormat(format); if (m_varobj_options.elem_count > 0) { - Error error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); + Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp)); if (error.Fail()) { result->AppendErrorWithFormat( "expression cannot be used with --element-count %s\n", @@ -533,7 +533,7 @@ bool CommandObjectExpression::DoExecute(const char *command, if (!ParseOptions(args, result)) return false; - Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + Status error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); if (error.Fail()) { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -564,7 +564,7 @@ bool CommandObjectExpression::DoExecute(const char *command, // interpreter, // so just push one bool initialize = false; - Error repl_error; + Status repl_error; REPLSP repl_sp(target->GetREPL( repl_error, m_command_options.language, nullptr, false)); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.h b/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.h index 7c21adcc26fe..0cf2a7263d52 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.h +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectExpression.h @@ -34,8 +34,8 @@ public: llvm::ArrayRef<OptionDefinition> GetDefinitions() override; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp index 7e81f5f94140..8b981a93ad7f 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectFrame.cpp @@ -77,9 +77,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'r': @@ -263,9 +263,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'r': @@ -604,7 +604,7 @@ protected: } else // No regex, either exact variable names or variable // expressions. { - Error error; + Status error; uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess | diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectHelp.h b/contrib/llvm/tools/lldb/source/Commands/CommandObjectHelp.h index cd9006619bc8..f1f87f8e63cc 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectHelp.h +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectHelp.h @@ -46,9 +46,9 @@ public: ~CommandOptions() override {} - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp index 2099310d32c3..e545d5679725 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectLog.cpp @@ -93,9 +93,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectMemory.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectMemory.cpp index 1679614fe3f7..8f4c186a8d69 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectMemory.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectMemory.cpp @@ -74,9 +74,9 @@ public: return llvm::makeArrayRef(g_read_memory_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_read_memory_options[option_idx].short_option; switch (short_option) { @@ -120,8 +120,8 @@ public: m_offset.Clear(); } - Error FinalizeSettings(Target *target, OptionGroupFormat &format_options) { - Error error; + Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) { + Status error; OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue(); OptionValueUInt64 &count_value = format_options.GetCountValue(); const bool byte_size_option_set = byte_size_value.OptionWasSet(); @@ -378,7 +378,7 @@ protected: } CompilerType clang_ast_type; - Error error; + Status error; const char *view_as_type_cstr = m_memory_options.m_view_as_type.GetCurrentValue(); @@ -716,7 +716,7 @@ protected: while (item_count < count) { std::string buffer; buffer.resize(item_byte_size + 1, 0); - Error error; + Status error; size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0], item_byte_size + 1, error); if (error.Fail()) { @@ -909,9 +909,9 @@ public: return llvm::makeArrayRef(g_memory_find_option_table); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_memory_find_option_table[option_idx].short_option; @@ -1008,7 +1008,7 @@ protected: return 0; uint8_t retval = 0; - Error error; + Status error; if (0 == m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) { m_is_valid = false; @@ -1035,7 +1035,7 @@ protected: return false; } - Error error; + Status error; lldb::addr_t low_addr = Args::StringToAddress(&m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error); if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) { @@ -1202,9 +1202,9 @@ public: return llvm::makeArrayRef(g_memory_write_option_table); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_memory_write_option_table[option_idx].short_option; @@ -1344,7 +1344,7 @@ protected: OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); size_t item_byte_size = byte_size_value.GetCurrentValue(); - Error error; + Status error; lldb::addr_t addr = Args::StringToAddress(&m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error); @@ -1365,7 +1365,7 @@ protected: if (data_sp) { length = data_sp->GetByteSize(); if (length > 0) { - Error error; + Status error; size_t bytes_written = process->WriteMemory(addr, data_sp->GetBytes(), length, error); @@ -1506,7 +1506,7 @@ protected: // Include the NULL for C strings... if (m_format_options.GetFormat() == eFormatCString) ++len; - Error error; + Status error; if (process->WriteMemory(addr, entry.c_str(), len, error) == len) { addr += len; } else { @@ -1574,7 +1574,7 @@ protected: } if (!buffer.GetString().empty()) { - Error error; + Status error; if (process->WriteMemory(addr, buffer.GetString().data(), buffer.GetString().size(), error) == buffer.GetString().size()) @@ -1641,7 +1641,7 @@ protected: return false; } - Error error; + Status error; lldb::addr_t addr = Args::StringToAddress(&m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error); @@ -1699,7 +1699,7 @@ protected: bool DoExecute(Args &command, CommandReturnObject &result) override { ProcessSP process_sp = m_exe_ctx.GetProcessSP(); if (process_sp) { - Error error; + Status error; lldb::addr_t load_addr = m_prev_end_addr; m_prev_end_addr = LLDB_INVALID_ADDRESS; diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlatform.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlatform.cpp index 62ea683e6e0d..5fa851f584a7 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlatform.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlatform.cpp @@ -85,10 +85,10 @@ public: ~OptionPermissions() override = default; - lldb_private::Error + lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override { - Error error; + Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 'v': { @@ -200,7 +200,7 @@ protected: if (platform_name && platform_name[0]) { const bool select = true; m_platform_options.SetPlatformName(platform_name); - Error error; + Status error; ArchSpec platform_arch; PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions( m_interpreter, ArchSpec(), select, error, platform_arch)); @@ -329,7 +329,7 @@ protected: PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { - Error error(platform_sp->ConnectRemote(args)); + Status error(platform_sp->ConnectRemote(args)); if (error.Success()) { platform_sp->GetStatus(ostrm); result.SetStatus(eReturnStatusSuccessFinishResult); @@ -382,7 +382,7 @@ protected: m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { if (args.GetArgumentCount() == 0) { - Error error; + Status error; if (platform_sp->IsConnected()) { // Cache the instance name if there is one since we are @@ -498,7 +498,8 @@ public: else mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX | lldb::eFilePermissionsWorldRX; - Error error = platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode); + Status error = + platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -539,7 +540,7 @@ public: PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { - Error error; + Status error; std::string cmd_line; args.GetCommandString(cmd_line); mode_t perms; @@ -599,7 +600,7 @@ public: args.GetCommandString(cmd_line); const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); - Error error; + Status error; bool success = platform_sp->CloseFile(fd, error); if (success) { result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd); @@ -646,7 +647,7 @@ public: const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); std::string buffer(m_options.m_count, 0); - Error error; + Status error; uint32_t retcode = platform_sp->ReadFile( fd, m_options.m_offset, &buffer[0], m_options.m_count, error); result.AppendMessageWithFormat("Return = %d\n", retcode); @@ -668,9 +669,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; char short_option = (char)m_getopt_table[option_idx].val; switch (short_option) { @@ -738,7 +739,7 @@ public: if (platform_sp) { std::string cmd_line; args.GetCommandString(cmd_line); - Error error; + Status error; const lldb::user_id_t fd = StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX); uint32_t retcode = @@ -762,9 +763,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; char short_option = (char)m_getopt_table[option_idx].val; switch (short_option) { @@ -889,8 +890,8 @@ public: if (platform_sp) { const char *remote_file_path = args.GetArgumentAtIndex(0); const char *local_file_path = args.GetArgumentAtIndex(1); - Error error = platform_sp->GetFile(FileSpec(remote_file_path, false), - FileSpec(local_file_path, false)); + Status error = platform_sp->GetFile(FileSpec(remote_file_path, false), + FileSpec(local_file_path, false)); if (error.Success()) { result.AppendMessageWithFormat( "successfully get-file from %s (remote) to %s (host)\n", @@ -999,7 +1000,7 @@ public: PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { - Error error(platform_sp->PutFile(src_fs, dst_fs)); + Status error(platform_sp->PutFile(src_fs, dst_fs)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { @@ -1043,7 +1044,7 @@ protected: } if (platform_sp) { - Error error; + Status error; const size_t argc = args.GetArgumentCount(); Target *target = m_exe_ctx.GetTargetPtr(); Module *exe_module = target->GetExecutableModulePointer(); @@ -1153,7 +1154,7 @@ protected: } if (platform_sp) { - Error error; + Status error; if (args.GetArgumentCount() == 0) { if (platform_sp) { Stream &ostrm = result.GetOutputStream(); @@ -1271,9 +1272,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; bool success = false; @@ -1449,7 +1450,7 @@ protected: if (platform_sp) { const size_t argc = args.GetArgumentCount(); if (argc > 0) { - Error error; + Status error; if (platform_sp->IsConnected()) { Stream &ostrm = result.GetOutputStream(); @@ -1515,9 +1516,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; char short_option = (char)m_getopt_table[option_idx].val; switch (short_option) { case 'p': { @@ -1624,7 +1625,7 @@ public: PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { - Error err; + Status err; ProcessSP remote_process_sp = platform_sp->Attach( m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err); if (err.Fail()) { @@ -1700,9 +1701,9 @@ public: return llvm::makeArrayRef(g_platform_shell_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const char short_option = (char)GetDefinitions()[option_idx].short_option; @@ -1782,7 +1783,7 @@ public: PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); - Error error; + Status error; if (platform_sp) { FileSpec working_dir{}; std::string output; @@ -1861,7 +1862,7 @@ public: return false; } - Error error = platform_sp->Install(src, dst); + Status error = platform_sp->Install(src, dst); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlugin.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlugin.cpp index 7ae968b95fc8..7e1b7f61f766 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlugin.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectPlugin.cpp @@ -68,7 +68,7 @@ protected: return false; } - Error error; + Status error; FileSpec dylib_fspec(command[0].ref, true); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectProcess.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectProcess.cpp index 557bdeecc22c..9fbdd7630548 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectProcess.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectProcess.cpp @@ -74,7 +74,7 @@ protected: } else { if (process->GetShouldDetach()) { bool keep_stopped = false; - Error detach_error(process->Detach(keep_stopped)); + Status detach_error(process->Detach(keep_stopped)); if (detach_error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); process = nullptr; @@ -85,7 +85,7 @@ protected: result.SetStatus(eReturnStatusFailed); } } else { - Error destroy_error(process->Destroy(false)); + Status destroy_error(process->Destroy(false)); if (destroy_error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); process = nullptr; @@ -231,7 +231,7 @@ protected: } StreamString stream; - Error error = target->Launch(m_options.launch_info, &stream); + Status error = target->Launch(m_options.launch_info, &stream); if (error.Success()) { ProcessSP process_sp(target->GetProcessSP()); @@ -338,9 +338,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'c': @@ -470,7 +470,7 @@ protected: if (target == nullptr) { // If there isn't a current target create one. TargetSP new_target_sp; - Error error; + Status error; error = m_interpreter.GetDebugger().GetTargetList().CreateTarget( m_interpreter.GetDebugger(), "", "", false, @@ -603,9 +603,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'i': @@ -687,7 +687,7 @@ protected: const uint32_t iohandler_id = process->GetIOHandlerID(); StreamString stream; - Error error; + Status error; if (synchronous_execution) error = process->ResumeSynchronous(&stream); else @@ -751,9 +751,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -816,7 +816,7 @@ protected: else keep_stopped = false; - Error error(process->Detach(keep_stopped)); + Status error(process->Detach(keep_stopped)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -854,9 +854,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -919,7 +919,7 @@ protected: if (!m_options.plugin_name.empty()) plugin_name = m_options.plugin_name.c_str(); - Error error; + Status error; Debugger &debugger = m_interpreter.GetDebugger(); PlatformSP platform_sp = m_interpreter.GetPlatform(true); ProcessSP process_sp = platform_sp->ConnectProcess( @@ -983,9 +983,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'i': @@ -1033,7 +1033,7 @@ protected: Process *process = m_exe_ctx.GetProcessPtr(); for (auto &entry : command.entries()) { - Error error; + Status error; PlatformSP platform = process->GetTarget().GetPlatform(); llvm::StringRef image_path = entry.ref; uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; @@ -1103,7 +1103,7 @@ protected: result.SetStatus(eReturnStatusFailed); break; } else { - Error error(process->GetTarget().GetPlatform()->UnloadImage( + Status error(process->GetTarget().GetPlatform()->UnloadImage( process, image_token)); if (error.Success()) { result.AppendMessageWithFormat( @@ -1169,7 +1169,7 @@ protected: command.GetArgumentAtIndex(0)); result.SetStatus(eReturnStatusFailed); } else { - Error error(process->Signal(signo)); + Status error(process->Signal(signo)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -1215,7 +1215,7 @@ protected: if (command.GetArgumentCount() == 0) { bool clear_thread_plans = true; - Error error(process->Halt(clear_thread_plans)); + Status error(process->Halt(clear_thread_plans)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -1258,7 +1258,7 @@ protected: } if (command.GetArgumentCount() == 0) { - Error error(process->Destroy(true)); + Status error(process->Destroy(true)); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -1298,7 +1298,7 @@ protected: if (process_sp) { if (command.GetArgumentCount() == 1) { FileSpec output_file(command.GetArgumentAtIndex(0), false); - Error error = PluginManager::SaveCore(process_sp, output_file); + Status error = PluginManager::SaveCore(process_sp, output_file); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); } else { @@ -1377,9 +1377,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectRegister.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectRegister.cpp index 4d856d6bd1e0..6de8c667e7a7 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectRegister.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectRegister.cpp @@ -257,9 +257,9 @@ protected: alternate_name.Clear(); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = GetDefinitions()[option_idx].short_option; switch (short_option) { case 's': { @@ -367,7 +367,7 @@ protected: if (reg_info) { RegisterValue reg_value; - Error error(reg_value.SetValueFromString(reg_info, value_str)); + Status error(reg_value.SetValueFromString(reg_info, value_str)); if (error.Success()) { if (reg_ctx->WriteRegister(reg_info, reg_value)) { // Toss all frames and anything else in the thread diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectSettings.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectSettings.cpp index 4a9f69f9c192..d42466cd13b1 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectSettings.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectSettings.cpp @@ -102,9 +102,9 @@ insert-before or insert-after."); ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -167,7 +167,7 @@ insert-before or insert-after."); // Complete setting value const char *setting_var_name = input.GetArgumentAtIndex(setting_var_idx); - Error error; + Status error; lldb::OptionValueSP value_sp( m_interpreter.GetDebugger().GetPropertyValue( &m_exe_ctx, setting_var_name, false, error)); @@ -211,7 +211,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, false, false); - Error error; + Status error; if (m_options.m_global) { error = m_interpreter.GetDebugger().SetPropertyValue( nullptr, eVarSetOperationAssign, var_name, var_value_cstr); @@ -296,7 +296,7 @@ protected: if (!args.empty()) { for (const auto &arg : args) { - Error error(m_interpreter.GetDebugger().DumpPropertyValue( + Status error(m_interpreter.GetDebugger().DumpPropertyValue( &m_exe_ctx, result.GetOutputStream(), arg.ref, OptionValue::eDumpGroupValue)); if (error.Success()) { @@ -494,7 +494,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationRemove, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -602,7 +602,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationReplace, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -716,7 +716,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationInsertBefore, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -827,7 +827,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationInsertAfter, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -929,7 +929,7 @@ protected: const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationAppend, var_name, var_value_cstr)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -1006,7 +1006,7 @@ protected: return false; } - Error error(m_interpreter.GetDebugger().SetPropertyValue( + Status error(m_interpreter.GetDebugger().SetPropertyValue( &m_exe_ctx, eVarSetOperationClear, var_name, llvm::StringRef())); if (error.Fail()) { result.AppendError(error.AsCString()); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectSource.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectSource.cpp index 1b9ee1bf8c73..f3c92b9a28c0 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectSource.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectSource.cpp @@ -59,9 +59,9 @@ class CommandObjectSourceInfo : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = GetDefinitions()[option_idx].short_option; switch (short_option) { case 'l': @@ -683,9 +683,9 @@ class CommandObjectSourceList : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = GetDefinitions()[option_idx].short_option; switch (short_option) { case 'l': diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp index a2df4909dc02..343530ea4f35 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectTarget.cpp @@ -269,8 +269,8 @@ protected: } const char *file_path = command.GetArgumentAtIndex(0); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "(lldb) target create '%s'", - file_path); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "(lldb) target create '%s'", file_path); FileSpec file_spec; if (file_path) @@ -284,7 +284,7 @@ protected: llvm::StringRef arch_cstr = m_arch_option.GetArchitectureName(); const bool get_dependent_files = m_add_dependents.GetOptionValue().GetCurrentValue(); - Error error(debugger.GetTargetList().CreateTarget( + Status error(debugger.GetTargetList().CreateTarget( debugger, file_path, arch_cstr, get_dependent_files, nullptr, target_sp)); @@ -303,7 +303,7 @@ protected: if (file_spec && file_spec.Exists()) { // if the remote file does not exist, push it there if (!platform_sp->GetFileExists(remote_file)) { - Error err = platform_sp->PutFile(file_spec, remote_file); + Status err = platform_sp->PutFile(file_spec, remote_file); if (err.Fail()) { result.AppendError(err.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -324,7 +324,7 @@ protected: } if (file_path) { // copy the remote file to the local file - Error err = platform_sp->GetFile(remote_file, file_spec); + Status err = platform_sp->GetFile(remote_file, file_spec); if (err.Fail()) { result.AppendError(err.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -839,7 +839,7 @@ protected: matches = target->GetImages().FindGlobalVariables( regex, true, UINT32_MAX, variable_list); } else { - Error error(Variable::GetValuesForVariableExpressionPath( + Status error(Variable::GetValuesForVariableExpressionPath( arg, m_exe_ctx.GetBestExecutionContextScope(), GetVariableCallback, target, variable_list, valobj_list)); matches = variable_list.GetSize(); @@ -1993,9 +1993,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -2515,7 +2515,7 @@ protected: m_symbol_file.GetOptionValue().GetCurrentValue(); if (!module_spec.GetArchitecture().IsValid()) module_spec.GetArchitecture() = target->GetArchitecture(); - Error error; + Status error; ModuleSP module_sp(target->GetSharedModule(module_spec, &error)); if (!module_sp) { const char *error_cstr = error.AsCString(); @@ -2750,7 +2750,7 @@ protected: process->Flush(); } if (load) { - Error error = module->LoadInMemory(*target, set_pc); + Status error = module->LoadInMemory(*target, set_pc); if (error.Fail()) { result.AppendError(error.AsCString()); return false; @@ -2857,9 +2857,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; if (short_option == 'g') { @@ -3220,9 +3220,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; @@ -3520,9 +3520,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; @@ -4114,7 +4114,7 @@ protected: // Make sure we load any scripting resources that may be embedded // in the debug info files in case the platform supports that. - Error error; + Status error; StreamString feedback_stream; module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream); @@ -4398,9 +4398,9 @@ public: return llvm::makeArrayRef(g_target_stop_hook_add_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp index 7ba6f2c19a8d..6b0f1b455bc1 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectThread.cpp @@ -162,9 +162,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -330,9 +330,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -556,7 +556,7 @@ protected: AddressRange range; SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything); if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER) { - Error error; + Status error; if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range, error)) { result.AppendErrorWithFormat("invalid end-line option: %s.", @@ -565,7 +565,7 @@ protected: return false; } } else if (m_options.m_end_line_is_block_end) { - Error error; + Status error; Block *block = frame->GetSymbolContext(eSymbolContextBlock).block; if (!block) { result.AppendErrorWithFormat("Could not find the current block."); @@ -660,7 +660,7 @@ protected: const uint32_t iohandler_id = process->GetIOHandlerID(); StreamString stream; - Error error; + Status error; if (synchronous_execution) error = process->ResumeSynchronous(&stream); else @@ -841,7 +841,7 @@ public: } StreamString stream; - Error error; + Status error; if (synchronous_execution) error = process->ResumeSynchronous(&stream); else @@ -908,9 +908,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1174,7 +1174,7 @@ protected: process->GetThreadList().SetSelectedThreadByID(m_options.m_thread_idx); StreamString stream; - Error error; + Status error; if (synchronous_execution) error = process->ResumeSynchronous(&stream); else @@ -1325,10 +1325,10 @@ public: m_json_stopinfo = false; } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { const int short_option = m_getopt_table[option_idx].val; - Error error; + Status error; switch (short_option) { case 'j': @@ -1340,7 +1340,7 @@ public: break; default: - return Error("invalid short option character '%c'", short_option); + return Status("invalid short option character '%c'", short_option); } return error; } @@ -1418,9 +1418,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1498,7 +1498,7 @@ protected: "called expressions"); Thread *thread = m_exe_ctx.GetThreadPtr(); - Error error; + Status error; error = thread->UnwindInnermostExpression(); if (!error.Success()) { result.AppendErrorWithFormat("Unwinding expression failed - %s.", @@ -1553,7 +1553,7 @@ protected: } } - Error error; + Status error; ThreadSP thread_sp = m_exe_ctx.GetThreadSP(); const bool broadcast = true; error = thread_sp->ReturnFromFrame(frame_sp, return_valobj_sp, broadcast); @@ -1602,24 +1602,24 @@ public: m_force = false; } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { const int short_option = m_getopt_table[option_idx].val; - Error error; + Status error; switch (short_option) { case 'f': m_filenames.AppendIfUnique(FileSpec(option_arg, false)); if (m_filenames.GetSize() > 1) - return Error("only one source file expected."); + return Status("only one source file expected."); break; case 'l': if (option_arg.getAsInteger(0, m_line_num)) - return Error("invalid line number: '%s'.", option_arg.str().c_str()); + return Status("invalid line number: '%s'.", option_arg.str().c_str()); break; case 'b': if (option_arg.getAsInteger(0, m_line_offset)) - return Error("invalid line offset: '%s'.", option_arg.str().c_str()); + return Status("invalid line offset: '%s'.", option_arg.str().c_str()); break; case 'a': m_load_addr = Args::StringToAddress(execution_context, option_arg, @@ -1629,7 +1629,7 @@ public: m_force = true; break; default: - return Error("invalid short option character '%c'", short_option); + return Status("invalid short option character '%c'", short_option); } return error; } @@ -1702,7 +1702,7 @@ protected: } std::string warnings; - Error err = thread->JumpToLine(file, line, m_options.m_force, &warnings); + Status err = thread->JumpToLine(file, line, m_options.m_force, &warnings); if (err.Fail()) { result.SetError(err); @@ -1747,9 +1747,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectType.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectType.cpp index b34a42738d4f..2d4271cab362 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectType.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectType.cpp @@ -127,8 +127,8 @@ private: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; @@ -213,7 +213,7 @@ public: options->m_flags, funct_name_str.c_str(), lines.CopyList(" ").c_str())); - Error error; + Status error; for (size_t i = 0; i < options->m_target_types.GetSize(); i++) { const char *type_name = @@ -283,7 +283,7 @@ public: static bool AddSummary(ConstString type_name, lldb::TypeSummaryImplSP entry, SummaryFormatType type, std::string category, - Error *error = nullptr); + Status *error = nullptr); protected: bool DoExecute(Args &command, CommandReturnObject &result) override; @@ -321,9 +321,9 @@ private: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; bool success; @@ -464,7 +464,7 @@ protected: DataVisualization::Categories::GetCategory( ConstString(options->m_category.c_str()), category); - Error error; + Status error; for (size_t i = 0; i < options->m_target_types.GetSize(); i++) { const char *type_name = @@ -523,7 +523,7 @@ public: static bool AddSynth(ConstString type_name, lldb::SyntheticChildrenSP entry, SynthFormatType type, std::string category_name, - Error *error); + Status *error); }; //------------------------------------------------------------------------- @@ -562,9 +562,9 @@ private: m_custom_type_name.clear(); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_type_format_add_options[option_idx].short_option; bool success; @@ -769,9 +769,9 @@ protected: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -909,9 +909,9 @@ private: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1025,9 +1025,9 @@ class CommandObjectTypeFormatterList : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'w': @@ -1243,10 +1243,10 @@ public: #endif // LLDB_DISABLE_PYTHON -Error CommandObjectTypeSummaryAdd::CommandOptions::SetOptionValue( +Status CommandObjectTypeSummaryAdd::CommandOptions::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = m_getopt_table[option_idx].val; bool success; @@ -1423,7 +1423,7 @@ bool CommandObjectTypeSummaryAdd::Execute_ScriptSummary( // if I am here, script_format must point to something good, so I can add that // as a script summary to all interested parties - Error error; + Status error; for (auto &entry : command.entries()) { CommandObjectTypeSummaryAdd::AddSummary( @@ -1498,7 +1498,7 @@ bool CommandObjectTypeSummaryAdd::Execute_StringSummary( lldb::TypeSummaryImplSP entry(string_format.release()); // now I have a valid format, let's add it to every type - Error error; + Status error; for (auto &arg_entry : command.entries()) { if (arg_entry.ref.empty()) { result.AppendError("empty typenames not allowed"); @@ -1681,7 +1681,7 @@ bool CommandObjectTypeSummaryAdd::AddSummary(ConstString type_name, TypeSummaryImplSP entry, SummaryFormatType type, std::string category_name, - Error *error) { + Status *error) { lldb::TypeCategoryImplSP category; DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), category); @@ -1799,9 +1799,9 @@ class CommandObjectTypeCategoryDefine : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1903,9 +1903,9 @@ class CommandObjectTypeCategoryEnable : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -2080,9 +2080,9 @@ class CommandObjectTypeCategoryDisable : public CommandObjectParsed { ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -2407,7 +2407,7 @@ bool CommandObjectTypeSynthAdd::Execute_PythonClass( DataVisualization::Categories::GetCategory( ConstString(m_options.m_category.c_str()), category); - Error error; + Status error; for (auto &arg_entry : command.entries()) { if (arg_entry.ref.empty()) { @@ -2450,7 +2450,7 @@ bool CommandObjectTypeSynthAdd::AddSynth(ConstString type_name, SyntheticChildrenSP entry, SynthFormatType type, std::string category_name, - Error *error) { + Status *error) { lldb::TypeCategoryImplSP category; DataVisualization::Categories::GetCategory(ConstString(category_name.c_str()), category); @@ -2512,9 +2512,9 @@ private: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; bool success; @@ -2586,7 +2586,7 @@ private: bool AddFilter(ConstString type_name, TypeFilterImplSP entry, FilterFormatType type, std::string category_name, - Error *error) { + Status *error) { lldb::TypeCategoryImplSP category; DataVisualization::Categories::GetCategory( ConstString(category_name.c_str()), category); @@ -2717,7 +2717,7 @@ protected: DataVisualization::Categories::GetCategory( ConstString(m_options.m_category.c_str()), category); - Error error; + Status error; WarnOnPotentialUnquotedUnsignedType(command, result); @@ -2787,9 +2787,9 @@ protected: return llvm::makeArrayRef(g_type_lookup_options); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, + ExecutionContext *execution_context) override { + Status error; const int short_option = g_type_lookup_options[option_idx].short_option; @@ -2899,7 +2899,7 @@ public: if (!ParseOptions(args, result)) return false; - Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + Status error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); if (error.Fail()) { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpoint.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpoint.cpp index 1ad53cdb88ad..9c84c992e715 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpoint.cpp @@ -197,9 +197,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -245,7 +245,7 @@ protected: if (target->GetProcessSP() && target->GetProcessSP()->IsAlive()) { uint32_t num_supported_hardware_watchpoints; - Error error = target->GetProcessSP()->GetWatchpointSupportInfo( + Status error = target->GetProcessSP()->GetWatchpointSupportInfo( num_supported_hardware_watchpoints); if (error.Success()) result.AppendMessageWithFormat( @@ -561,9 +561,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -689,9 +689,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -881,7 +881,7 @@ protected: } // Things have checked out ok... - Error error; + Status error; uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess; @@ -895,7 +895,7 @@ protected: VariableList variable_list; ValueObjectList valobj_list; - Error error(Variable::GetValuesForVariableExpressionPath( + Status error(Variable::GetValuesForVariableExpressionPath( command.GetArgumentAtIndex(0), m_exe_ctx.GetBestExecutionContextScope(), GetVariableCallback, target, variable_list, valobj_list)); @@ -1060,7 +1060,7 @@ protected: if (!ParseOptions(args, result)) return false; - Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); + Status error(m_option_group.NotifyOptionParsingFinished(&exe_ctx)); if (error.Fail()) { result.AppendError(error.AsCString()); result.SetStatus(eReturnStatusFailed); @@ -1135,7 +1135,7 @@ protected: /// of the expression, so convert to that if we found a valid type. CompilerType compiler_type(valobj_sp->GetCompilerType()); - Error error; + Status error; Watchpoint *wp = target->CreateWatchpoint(addr, size, &compiler_type, watch_type, error) .get(); diff --git a/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpointCommand.cpp b/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpointCommand.cpp index 1509c487a8a7..ec7e4a1f9cde 100644 --- a/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpointCommand.cpp +++ b/contrib/llvm/tools/lldb/source/Commands/CommandObjectWatchpointCommand.cpp @@ -319,9 +319,9 @@ are no syntax errors may indicate that a function was declared but never called. ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Core/Address.cpp b/contrib/llvm/tools/lldb/source/Core/Address.cpp index 91229a9b18eb..6328e433852a 100644 --- a/contrib/llvm/tools/lldb/source/Core/Address.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Address.cpp @@ -33,8 +33,8 @@ #include "lldb/Utility/ConstString.h" // for ConstString #include "lldb/Utility/DataExtractor.h" // for DataExtractor #include "lldb/Utility/Endian.h" // for InlHostByteOrder -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/FileSpec.h" // for FileSpec +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" // for StreamString @@ -67,7 +67,7 @@ static size_t ReadBytes(ExecutionContextScope *exe_scope, TargetSP target_sp(exe_scope->CalculateTarget()); if (target_sp) { - Error error; + Status error; bool prefer_file_cache = false; return target_sp->ReadMemory(address, prefer_file_cache, dst, dst_len, error); @@ -322,7 +322,7 @@ addr_t Address::GetCallableLoadAddress(Target *target, bool is_indirect) const { if (is_indirect && target) { ProcessSP processSP = target->GetProcessSP(); - Error error; + Status error; if (processSP) { code_addr = processSP->ResolveIndirectFunction(this, error); if (!error.Success()) @@ -734,7 +734,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style, if (process) { addr_t load_addr = GetLoadAddress(target); if (load_addr != LLDB_INVALID_ADDRESS) { - Error memory_error; + Status memory_error; addr_t dereferenced_load_addr = process->ReadPointerFromMemory(load_addr, memory_error); if (dereferenced_load_addr != LLDB_INVALID_ADDRESS) { diff --git a/contrib/llvm/tools/lldb/source/Core/ArchSpec.cpp b/contrib/llvm/tools/lldb/source/Core/ArchSpec.cpp index 7c1b399177fd..91b73847ac1f 100644 --- a/contrib/llvm/tools/lldb/source/Core/ArchSpec.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ArchSpec.cpp @@ -1555,7 +1555,7 @@ static void StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread) { #if 0 // ARM mode: check for condition on intsruction const addr_t pc = reg_ctx_sp->GetPC(); - Error error; + Status error; // If we fail to read the opcode we will get UINT64_MAX as the // result in "opcode" which we can use to detect if we read a // valid opcode. @@ -1635,7 +1635,7 @@ void ArchSpec::PiecewiseTripleCompare( } bool ArchSpec::IsAlwaysThumbInstructions() const { - std::string Error; + std::string Status; if (GetTriple().getArch() == llvm::Triple::arm || GetTriple().getArch() == llvm::Triple::thumb) { // v. https://en.wikipedia.org/wiki/ARM_Cortex-M diff --git a/contrib/llvm/tools/lldb/source/Core/Communication.cpp b/contrib/llvm/tools/lldb/source/Core/Communication.cpp index a543858582ef..72873a9510b5 100644 --- a/contrib/llvm/tools/lldb/source/Core/Communication.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Communication.cpp @@ -15,9 +15,9 @@ #include "lldb/Host/HostThread.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" // for LogIfAnyCategoriesSet, LIBLLDB... +#include "lldb/Utility/Status.h" // for Status #include "llvm/ADT/None.h" // for None #include "llvm/ADT/Optional.h" // for Optional @@ -75,7 +75,7 @@ void Communication::Clear() { StopReadThread(nullptr); } -ConnectionStatus Communication::Connect(const char *url, Error *error_ptr) { +ConnectionStatus Communication::Connect(const char *url, Status *error_ptr) { Clear(); lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION, @@ -90,7 +90,7 @@ ConnectionStatus Communication::Connect(const char *url, Error *error_ptr) { return eConnectionStatusNoConnection; } -ConnectionStatus Communication::Disconnect(Error *error_ptr) { +ConnectionStatus Communication::Disconnect(Status *error_ptr) { lldb_private::LogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); @@ -123,7 +123,7 @@ bool Communication::HasConnection() const { size_t Communication::Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, - ConnectionStatus &status, Error *error_ptr) { + ConnectionStatus &status, Status *error_ptr) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMUNICATION); LLDB_LOG( log, @@ -170,7 +170,7 @@ size_t Communication::Read(void *dst, size_t dst_len, } size_t Communication::Write(const void *src, size_t src_len, - ConnectionStatus &status, Error *error_ptr) { + ConnectionStatus &status, Status *error_ptr) { lldb::ConnectionSP connection_sp(m_connection_sp); std::lock_guard<std::mutex> guard(m_write_mutex); @@ -189,7 +189,7 @@ size_t Communication::Write(const void *src, size_t src_len, return 0; } -bool Communication::StartReadThread(Error *error_ptr) { +bool Communication::StartReadThread(Status *error_ptr) { if (error_ptr) error_ptr->Clear(); @@ -212,7 +212,7 @@ bool Communication::StartReadThread(Error *error_ptr) { return m_read_thread_enabled; } -bool Communication::StopReadThread(Error *error_ptr) { +bool Communication::StopReadThread(Status *error_ptr) { if (!m_read_thread.IsJoinable()) return true; @@ -225,15 +225,15 @@ bool Communication::StopReadThread(Error *error_ptr) { // error = m_read_thread.Cancel(); - Error error = m_read_thread.Join(nullptr); + Status error = m_read_thread.Join(nullptr); return error.Success(); } -bool Communication::JoinReadThread(Error *error_ptr) { +bool Communication::JoinReadThread(Status *error_ptr) { if (!m_read_thread.IsJoinable()) return true; - Error error = m_read_thread.Join(nullptr); + Status error = m_read_thread.Join(nullptr); return error.Success(); } @@ -280,7 +280,7 @@ void Communication::AppendBytesToCache(const uint8_t *bytes, size_t len, size_t Communication::ReadFromConnection(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, ConnectionStatus &status, - Error *error_ptr) { + Status *error_ptr) { lldb::ConnectionSP connection_sp(m_connection_sp); if (connection_sp) return connection_sp->Read(dst, dst_len, timeout, status, error_ptr); @@ -303,7 +303,7 @@ lldb::thread_result_t Communication::ReadThread(lldb::thread_arg_t p) { uint8_t buf[1024]; - Error error; + Status error; ConnectionStatus status = eConnectionStatusSuccess; bool done = false; while (!done && comm->m_read_thread_enabled) { diff --git a/contrib/llvm/tools/lldb/source/Core/Debugger.cpp b/contrib/llvm/tools/lldb/source/Core/Debugger.cpp index 751ceed13149..75fcedb10156 100644 --- a/contrib/llvm/tools/lldb/source/Core/Debugger.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Debugger.cpp @@ -287,9 +287,10 @@ enum { LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; -Error Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, - llvm::StringRef property_path, llvm::StringRef value) { +Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, + llvm::StringRef property_path, + llvm::StringRef value) { bool is_load_script = (property_path == "target.load-script-from-symbol-file"); bool is_escape_non_printables = (property_path == "escape-non-printables"); TargetSP target_sp; @@ -299,7 +300,7 @@ Error Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); } - Error error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); + Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); if (error.Success()) { // FIXME it would be nice to have "on-change" callbacks for properties if (property_path == g_properties[ePropertyPrompt].name) { @@ -321,7 +322,7 @@ Error Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, load_script_old_value == eLoadScriptFromSymFileWarn) { if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue) { - std::list<Error> errors; + std::list<Status> errors; StreamString feedback_stream; if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) { StreamFileSP stream_sp(GetErrorFile()); @@ -550,7 +551,7 @@ void Debugger::SettingsInitialize() { Target::SettingsInitialize(); } void Debugger::SettingsTerminate() { Target::SettingsTerminate(); } -bool Debugger::LoadPlugin(const FileSpec &spec, Error &error) { +bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) { if (g_load_plugin_callback) { llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback(shared_from_this(), spec, error); @@ -570,7 +571,7 @@ bool Debugger::LoadPlugin(const FileSpec &spec, Error &error) { static FileSpec::EnumerateDirectoryResult LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, const FileSpec &file_spec) { - Error error; + Status error; static ConstString g_dylibext("dylib"); static ConstString g_solibext("so"); @@ -595,7 +596,7 @@ LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, return FileSpec::eEnumerateDirectoryResultNext; } - Error plugin_load_error; + Status plugin_load_error; debugger->LoadPlugin(plugin_file_spec, plugin_load_error); return FileSpec::eEnumerateDirectoryResultNext; @@ -1365,7 +1366,7 @@ size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) { process = target_sp->GetProcessSP().get(); } if (process) { - Error error; + Status error; size_t len; char stdio_buffer[1024]; while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer), @@ -1393,7 +1394,7 @@ size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) { process = target_sp->GetProcessSP().get(); } if (process) { - Error error; + Status error; size_t len; char stdio_buffer[1024]; while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer), @@ -1463,7 +1464,7 @@ void Debugger::HandleProcessEvent(const EventSP &event_sp) { EventDataStructuredData::GetObjectFromEvent(event_sp.get()); if (output_stream_sp) { StreamString content_stream; - Error error = + Status error = plugin_sp->GetDescription(structured_data_sp, content_stream); if (error.Success()) { if (!content_stream.GetString().empty()) { @@ -1702,8 +1703,8 @@ Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { return GetDummyTarget(); } -Error Debugger::RunREPL(LanguageType language, const char *repl_options) { - Error err; +Status Debugger::RunREPL(LanguageType language, const char *repl_options) { + Status err; FileSpec repl_executable; if (language == eLanguageTypeUnknown) { diff --git a/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp b/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp index 51d93d9acdbb..0a5d763b6d3f 100644 --- a/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Disassembler.cpp @@ -35,8 +35,8 @@ #include "lldb/Target/Thread.h" // for Thread #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" // for StreamString #include "lldb/lldb-private-enumerations.h" // for InstructionType:... @@ -59,7 +59,8 @@ using namespace lldb_private; DisassemblerSP Disassembler::FindPlugin(const ArchSpec &arch, const char *flavor, const char *plugin_name) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Disassembler::FindPlugin (arch = %s, plugin_name = %s)", arch.GetArchitectureName(), plugin_name); @@ -340,7 +341,7 @@ bool Disassembler::ElideMixedSourceAndDisassemblyLine( } else { TargetSP target_sp = exe_ctx.GetTargetSP(); if (target_sp) { - Error error; + Status error; OptionValueSP value_sp = target_sp->GetDebugger().GetPropertyValue( &exe_ctx, "target.process.thread.step-avoid-regexp", false, error); if (value_sp && value_sp->GetType() == OptionValue::eTypeRegex) { @@ -1118,7 +1119,7 @@ InstructionList::GetIndexOfNextBranchInstruction(uint32_t start, while (i > start) { --i; - Error error; + Status error; uint32_t inst_bytes; bool prefer_file_cache = false; // Read from process if process is running lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; @@ -1179,7 +1180,7 @@ size_t Disassembler::ParseInstructions(const ExecutionContext *exe_ctx, auto data_sp = std::make_shared<DataBufferHeap>(byte_size, '\0'); - Error error; + Status error; lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; const size_t bytes_read = target->ReadMemory( range.GetBaseAddress(), prefer_file_cache, data_sp->GetBytes(), @@ -1224,7 +1225,7 @@ size_t Disassembler::ParseInstructions(const ExecutionContext *exe_ctx, DataBufferHeap *heap_buffer = new DataBufferHeap(byte_size, '\0'); DataBufferSP data_sp(heap_buffer); - Error error; + Status error; lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; const size_t bytes_read = target->ReadMemory(start, prefer_file_cache, heap_buffer->GetBytes(), @@ -1460,4 +1461,3 @@ std::function<bool(const Instruction::Operand &)> lldb_private::OperandMatchers::MatchOpType(Instruction::Operand::Type type) { return [type](const Instruction::Operand &op) { return op.m_type == type; }; } - diff --git a/contrib/llvm/tools/lldb/source/Core/DynamicLoader.cpp b/contrib/llvm/tools/lldb/source/Core/DynamicLoader.cpp index 03fad244acfc..5477498dadc8 100644 --- a/contrib/llvm/tools/lldb/source/Core/DynamicLoader.cpp +++ b/contrib/llvm/tools/lldb/source/Core/DynamicLoader.cpp @@ -181,7 +181,7 @@ ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file, // address to read the file out of the memory instead of a load bias. bool is_loaded = false; lldb::addr_t load_addr; - Error error = m_process->GetFileLoadAddress(file, is_loaded, load_addr); + Status error = m_process->GetFileLoadAddress(file, is_loaded, load_addr); if (error.Success() && is_loaded) { check_alternative_file_name = false; base_addr = load_addr; @@ -193,7 +193,7 @@ ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file, // different name based on the memory region info. if (check_alternative_file_name) { MemoryRegionInfo memory_info; - Error error = m_process->GetMemoryRegionInfo(base_addr, memory_info); + Status error = m_process->GetMemoryRegionInfo(base_addr, memory_info); if (error.Success() && memory_info.GetMapped() && memory_info.GetRange().GetRangeBase() == base_addr && !(memory_info.GetName().IsEmpty())) { @@ -223,7 +223,7 @@ ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file, int64_t DynamicLoader::ReadUnsignedIntWithSizeInBytes(addr_t addr, int size_in_bytes) { - Error error; + Status error; uint64_t value = m_process->ReadUnsignedIntegerFromMemory(addr, size_in_bytes, 0, error); if (error.Fail()) @@ -233,7 +233,7 @@ int64_t DynamicLoader::ReadUnsignedIntWithSizeInBytes(addr_t addr, } addr_t DynamicLoader::ReadPointer(addr_t addr) { - Error error; + Status error; addr_t value = m_process->ReadPointerFromMemory(addr, error); if (error.Fail()) return LLDB_INVALID_ADDRESS; diff --git a/contrib/llvm/tools/lldb/source/Core/EmulateInstruction.cpp b/contrib/llvm/tools/lldb/source/Core/EmulateInstruction.cpp index f18a4af67ef9..2ee2c79de270 100644 --- a/contrib/llvm/tools/lldb/source/Core/EmulateInstruction.cpp +++ b/contrib/llvm/tools/lldb/source/Core/EmulateInstruction.cpp @@ -19,7 +19,7 @@ #include "lldb/Target/StackFrame.h" // for StackFrame #include "lldb/Utility/ConstString.h" // for ConstString #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream, Stream::::eBinary #include "lldb/Utility/StreamString.h" #include "lldb/lldb-forward.h" // for ProcessSP @@ -263,7 +263,7 @@ size_t EmulateInstruction::ReadMemoryFrame(EmulateInstruction *instruction, ProcessSP process_sp(frame->CalculateProcess()); if (process_sp) { - Error error; + Status error; return process_sp->ReadMemory(addr, dst, dst_len, error); } return 0; @@ -280,7 +280,7 @@ size_t EmulateInstruction::WriteMemoryFrame(EmulateInstruction *instruction, ProcessSP process_sp(frame->CalculateProcess()); if (process_sp) { - Error error; + Status error; return process_sp->WriteMemory(addr, src, src_len, error); } diff --git a/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp b/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp index 835a1c54a0e0..9fb294aad2fb 100644 --- a/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp +++ b/contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp @@ -303,7 +303,7 @@ void FormatEntity::Entry::AppendText(const char *cstr) { return AppendText(llvm::StringRef(cstr)); } -Error FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) { +Status FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) { entry.Clear(); entry.type = Entry::Type::Root; llvm::StringRef modifiable_format(format_str); @@ -408,7 +408,7 @@ static bool RunScriptFormatKeyword(Stream &s, const SymbolContext *sc, ScriptInterpreter *script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); if (script_interpreter) { - Error error; + Status error; std::string script_output; if (script_interpreter->RunScriptFormatKeyword(script_function_name, t, @@ -778,7 +778,7 @@ static bool DumpValue(Stream &s, const SymbolContext *sc, var_name_final_if_array_range, index_lower, index_higher); - Error error; + Status error; const std::string &expr_path = entry.string; @@ -824,7 +824,7 @@ static bool DumpValue(Stream &s, const SymbolContext *sc, // this happens when we are not going through // GetValueForVariableExpressionPath // to get to the target ValueObject - Error error; + Status error; target = target->Dereference(error).get(); if (error.Fail()) { if (log) @@ -1050,7 +1050,7 @@ static bool FormatThreadExtendedInfoRecurse( s.Printf("%f", value->GetAsFloat()->GetValue()); return true; } else if (value->GetType() == StructuredData::Type::eTypeString) { - s.Printf("%s", value->GetAsString()->GetValue().c_str()); + s.Format("{0}", value->GetAsString()->GetValue()); return true; } else if (value->GetType() == StructuredData::Type::eTypeArray) { if (value->GetAsArray()->GetSize() > 0) { @@ -1079,7 +1079,7 @@ bool FormatEntity::FormatStringRef(const llvm::StringRef &format_str, Stream &s, bool initial_function) { if (!format_str.empty()) { FormatEntity::Entry root; - Error error = FormatEntity::Parse(format_str, root); + Status error = FormatEntity::Parse(format_str, root); if (error.Success()) { return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj, function_changed, initial_function); @@ -1096,7 +1096,7 @@ bool FormatEntity::FormatCString(const char *format, Stream &s, if (format && format[0]) { FormatEntity::Entry root; llvm::StringRef format_str(format); - Error error = FormatEntity::Parse(format_str, root); + Status error = FormatEntity::Parse(format_str, root); if (error.Success()) { return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj, function_changed, initial_function); @@ -1866,10 +1866,10 @@ static bool DumpCommaSeparatedChildEntryNames( return false; } -static Error ParseEntry(const llvm::StringRef &format_str, - const FormatEntity::Entry::Definition *parent, - FormatEntity::Entry &entry) { - Error error; +static Status ParseEntry(const llvm::StringRef &format_str, + const FormatEntity::Entry::Definition *parent, + FormatEntity::Entry &entry) { + Status error; const size_t sep_pos = format_str.find_first_of(".[:"); const char sep_char = @@ -1956,7 +1956,7 @@ static const FormatEntity::Entry::Definition * FindEntry(const llvm::StringRef &format_str, const FormatEntity::Entry::Definition *parent, llvm::StringRef &remainder) { - Error error; + Status error; std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.'); const size_t n = parent->num_children; @@ -1983,9 +1983,9 @@ FindEntry(const llvm::StringRef &format_str, return parent; } -Error FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry, - uint32_t depth) { - Error error; +Status FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry, + uint32_t depth) { + Status error; while (!format.empty() && error.Success()) { const size_t non_special_chars = format.find_first_of("${}\\"); @@ -2279,10 +2279,10 @@ Error FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry, return error; } -Error FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str, - llvm::StringRef &variable_name, - llvm::StringRef &variable_format) { - Error error; +Status FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str, + llvm::StringRef &variable_name, + llvm::StringRef &variable_format) { + Status error; variable_name = llvm::StringRef(); variable_format = llvm::StringRef(); diff --git a/contrib/llvm/tools/lldb/source/Core/IOHandler.cpp b/contrib/llvm/tools/lldb/source/Core/IOHandler.cpp index b5dd0bd8a25f..e5fe490991f9 100644 --- a/contrib/llvm/tools/lldb/source/Core/IOHandler.cpp +++ b/contrib/llvm/tools/lldb/source/Core/IOHandler.cpp @@ -27,7 +27,7 @@ #include "lldb/Core/StreamFile.h" #include "lldb/Host/File.h" // for File #include "lldb/Host/Predicate.h" // for Predicate, ::eBroad... -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/StreamString.h" // for StreamString #include "lldb/Utility/StringList.h" // for StringList #include "lldb/lldb-forward.h" // for StreamFileSP @@ -515,7 +515,7 @@ bool IOHandlerEditline::GetLines(StringList &lines, bool &interrupted) { } else { #endif bool done = false; - Error error; + Status error; while (!done) { // Show line numbers if we are asked to @@ -4640,7 +4640,7 @@ void IOHandlerCursesGUI::Activate() { WindowSP threads_window_sp( main_window_sp->CreateSubWindow("Threads", threads_bounds, false)); WindowSP status_window_sp( - main_window_sp->CreateSubWindow("Status", status_bounds, false)); + main_window_sp->CreateSubWindow("Error", status_bounds, false)); status_window_sp->SetCanBeActive( false); // Don't let the status bar become the active window main_window_sp->SetDelegate( diff --git a/contrib/llvm/tools/lldb/source/Core/Mangled.cpp b/contrib/llvm/tools/lldb/source/Core/Mangled.cpp index 3d96340b911c..c2e9b8904a0a 100644 --- a/contrib/llvm/tools/lldb/source/Core/Mangled.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Mangled.cpp @@ -258,8 +258,8 @@ Mangled::GetDemangledName(lldb::LanguageType language) const { // haven't already decoded our mangled name. if (m_mangled && !m_demangled) { // We need to generate and cache the demangled name. - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "Mangled::GetDemangledName (m_mangled = %s)", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Mangled::GetDemangledName (m_mangled = %s)", m_mangled.GetCString()); Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DEMANGLE); diff --git a/contrib/llvm/tools/lldb/source/Core/Module.cpp b/contrib/llvm/tools/lldb/source/Core/Module.cpp index d168474c3479..1b510d2ff7b2 100644 --- a/contrib/llvm/tools/lldb/source/Core/Module.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Module.cpp @@ -39,10 +39,10 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" // for GetLogIfAn... #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" @@ -322,7 +322,7 @@ Module::~Module() { } ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp, - lldb::addr_t header_addr, Error &error, + lldb::addr_t header_addr, Status &error, size_t size_to_read) { if (m_objfile_sp) { error.SetErrorString("object file already exists"); @@ -331,7 +331,7 @@ ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp, if (process_sp) { m_did_load_objfile = true; auto data_ap = llvm::make_unique<DataBufferHeap>(size_to_read, 0); - Error readmem_error; + Status readmem_error; const size_t bytes_read = process_sp->ReadMemory(header_addr, data_ap->GetBytes(), data_ap->GetByteSize(), readmem_error); @@ -429,8 +429,8 @@ void Module::DumpSymbolContext(Stream *s) { size_t Module::GetNumCompileUnits() { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "Module::GetNumCompileUnits (module = %p)", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Module::GetNumCompileUnits (module = %p)", static_cast<void *>(this)); SymbolVendor *symbols = GetSymbolVendor(); if (symbols) @@ -453,7 +453,8 @@ CompUnitSP Module::GetCompileUnitAtIndex(size_t index) { bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", vm_addr); SectionList *section_list = GetSectionList(); @@ -616,7 +617,8 @@ uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec, uint32_t resolve_scope, SymbolContextList &sc_list) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Module::ResolveSymbolContextForFilePath (%s:%u, " "check_inlines = %s, resolve_scope = 0x%8.8x)", file_spec.GetPath().c_str(), line, @@ -987,7 +989,8 @@ size_t Module::FindTypes_Impl( const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches, llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, TypeMap &types) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); if (!sc.module_sp || sc.module_sp.get() == this) { SymbolVendor *symbols = GetSymbolVendor(); if (symbols) @@ -1078,7 +1081,8 @@ SymbolVendor *Module::GetSymbolVendor(bool can_create, if (!m_did_load_symbol_vendor.load() && can_create) { ObjectFile *obj_file = GetObjectFile(); if (obj_file != nullptr) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); m_symfile_ap.reset( SymbolVendor::FindPlugin(shared_from_this(), feedback_strm)); m_did_load_symbol_vendor = true; @@ -1278,8 +1282,8 @@ ObjectFile *Module::GetObjectFile() { if (!m_did_load_objfile.load()) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (!m_did_load_objfile.load()) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "Module::GetObjectFile () module = %s", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s", GetFileSpec().GetFilename().AsCString("")); DataBufferSP data_sp; lldb::offset_t data_offset = 0; @@ -1338,9 +1342,9 @@ SectionList *Module::GetUnifiedSectionList() { const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name, SymbolType symbol_type) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, - "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)", + func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)", name.AsCString(), symbol_type); SymbolVendor *sym_vendor = GetSymbolVendor(); if (sym_vendor) { @@ -1372,7 +1376,8 @@ void Module::SymbolIndicesToSymbolContextList( size_t Module::FindFunctionSymbols(const ConstString &name, uint32_t name_type_mask, SymbolContextList &sc_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)", name.AsCString(), name_type_mask); SymbolVendor *sym_vendor = GetSymbolVendor(); @@ -1390,9 +1395,9 @@ size_t Module::FindSymbolsWithNameAndType(const ConstString &name, // No need to protect this call using m_mutex all other method calls are // already thread safe. + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, - "Module::FindSymbolsWithNameAndType (name = %s, type = %i)", + func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)", name.AsCString(), symbol_type); const size_t initial_size = sc_list.GetSize(); SymbolVendor *sym_vendor = GetSymbolVendor(); @@ -1413,8 +1418,9 @@ size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex, // No need to protect this call using m_mutex all other method calls are // already thread safe. + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)", regex.GetText().str().c_str(), symbol_type); const size_t initial_size = sc_list.GetSize(); @@ -1537,7 +1543,7 @@ bool Module::IsLoadedInTarget(Target *target) { return false; } -bool Module::LoadScriptingResourceInTarget(Target *target, Error &error, +bool Module::LoadScriptingResourceInTarget(Target *target, Status &error, Stream *feedback_stream) { if (!target) { error.SetErrorString("invalid destination Target"); @@ -1717,6 +1723,6 @@ bool Module::GetIsDynamicLinkEditor() { return false; } -Error Module::LoadInMemory(Target &target, bool set_pc) { +Status Module::LoadInMemory(Target &target, bool set_pc) { return m_objfile_sp->LoadInMemory(target, set_pc); } diff --git a/contrib/llvm/tools/lldb/source/Core/ModuleList.cpp b/contrib/llvm/tools/lldb/source/Core/ModuleList.cpp index da23329cc3b6..b04299ead804 100644 --- a/contrib/llvm/tools/lldb/source/Core/ModuleList.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ModuleList.cpp @@ -704,17 +704,17 @@ size_t ModuleList::RemoveOrphanSharedModules(bool mandatory) { return GetSharedModuleList().RemoveOrphans(mandatory); } -Error ModuleList::GetSharedModule(const ModuleSpec &module_spec, - ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - ModuleSP *old_module_sp_ptr, - bool *did_create_ptr, bool always_create) { +Status ModuleList::GetSharedModule(const ModuleSpec &module_spec, + ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + ModuleSP *old_module_sp_ptr, + bool *did_create_ptr, bool always_create) { ModuleList &shared_module_list = GetSharedModuleList(); std::lock_guard<std::recursive_mutex> guard( shared_module_list.m_modules_mutex); char path[PATH_MAX]; - Error error; + Status error; module_sp.reset(); @@ -821,7 +821,7 @@ Error ModuleList::GetSharedModule(const ModuleSpec &module_spec, *did_create_ptr = true; shared_module_list.ReplaceEquivalent(module_sp); - return Error(); + return Status(); } } } else { @@ -955,14 +955,14 @@ bool ModuleList::RemoveSharedModuleIfOrphaned(const Module *module_ptr) { } bool ModuleList::LoadScriptingResourcesInTarget(Target *target, - std::list<Error> &errors, + std::list<Status> &errors, Stream *feedback_stream, bool continue_on_error) { if (!target) return false; std::lock_guard<std::recursive_mutex> guard(m_modules_mutex); for (auto module : m_modules) { - Error error; + Status error; if (module) { if (!module->LoadScriptingResourceInTarget(target, error, feedback_stream)) { diff --git a/contrib/llvm/tools/lldb/source/Core/PluginManager.cpp b/contrib/llvm/tools/lldb/source/Core/PluginManager.cpp index bd4ba5995204..9bb615b6a55e 100644 --- a/contrib/llvm/tools/lldb/source/Core/PluginManager.cpp +++ b/contrib/llvm/tools/lldb/source/Core/PluginManager.cpp @@ -13,8 +13,8 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StringList.h" // for StringList #if defined(LLVM_ON_WIN32) @@ -93,7 +93,7 @@ static FileSpec::EnumerateDirectoryResult LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, const FileSpec &file_spec) { // PluginManager *plugin_manager = (PluginManager *)baton; - Error error; + Status error; namespace fs = llvm::sys::fs; // If we have a regular file, a symbolic link or unknown file type, try @@ -1066,9 +1066,9 @@ PluginManager::GetObjectFileCreateMemoryCallbackForPluginName( return nullptr; } -Error PluginManager::SaveCore(const lldb::ProcessSP &process_sp, - const FileSpec &outfile) { - Error error; +Status PluginManager::SaveCore(const lldb::ProcessSP &process_sp, + const FileSpec &outfile) { + Status error; std::lock_guard<std::recursive_mutex> guard(GetObjectFileMutex()); ObjectFileInstances &instances = GetObjectFileInstances(); diff --git a/contrib/llvm/tools/lldb/source/Core/RegisterValue.cpp b/contrib/llvm/tools/lldb/source/Core/RegisterValue.cpp index 26a7515febc3..28ce67e63dc2 100644 --- a/contrib/llvm/tools/lldb/source/Core/RegisterValue.cpp +++ b/contrib/llvm/tools/lldb/source/Core/RegisterValue.cpp @@ -13,7 +13,7 @@ #include "lldb/Core/Scalar.h" #include "lldb/Interpreter/Args.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/lldb-defines.h" // for LLDB_INVALID_ADDRESS @@ -102,7 +102,7 @@ bool RegisterValue::GetData(DataExtractor &data) const { uint32_t RegisterValue::GetAsMemoryData(const RegisterInfo *reg_info, void *dst, uint32_t dst_len, lldb::ByteOrder dst_byte_order, - Error &error) const { + Status &error) const { if (reg_info == nullptr) { error.SetErrorString("invalid register info argument."); return 0; @@ -148,7 +148,7 @@ uint32_t RegisterValue::GetAsMemoryData(const RegisterInfo *reg_info, void *dst, uint32_t RegisterValue::SetFromMemoryData(const RegisterInfo *reg_info, const void *src, uint32_t src_len, lldb::ByteOrder src_byte_order, - Error &error) { + Status &error) { if (reg_info == nullptr) { error.SetErrorString("invalid register info argument."); return 0; @@ -163,7 +163,7 @@ uint32_t RegisterValue::SetFromMemoryData(const RegisterInfo *reg_info, // // Case 2: src_len > dst_len // - // Error! (The register should always be big enough to hold the data) + // Status! (The register should always be big enough to hold the data) // // Case 3: src_len < dst_len // @@ -257,11 +257,11 @@ RegisterValue::Type RegisterValue::SetType(const RegisterInfo *reg_info) { return m_type; } -Error RegisterValue::SetValueFromData(const RegisterInfo *reg_info, - DataExtractor &src, - lldb::offset_t src_offset, - bool partial_data_ok) { - Error error; +Status RegisterValue::SetValueFromData(const RegisterInfo *reg_info, + DataExtractor &src, + lldb::offset_t src_offset, + bool partial_data_ok) { + Status error; if (src.GetByteSize() == 0) { error.SetErrorString("empty data."); @@ -391,9 +391,9 @@ static bool ParseVectorEncoding(const RegisterInfo *reg_info, return true; } -Error RegisterValue::SetValueFromString(const RegisterInfo *reg_info, - llvm::StringRef value_str) { - Error error; +Status RegisterValue::SetValueFromString(const RegisterInfo *reg_info, + llvm::StringRef value_str) { + Status error; if (reg_info == nullptr) { error.SetErrorString("Invalid register info argument."); return error; diff --git a/contrib/llvm/tools/lldb/source/Core/Scalar.cpp b/contrib/llvm/tools/lldb/source/Core/Scalar.cpp index 3adf85098648..630083bae930 100644 --- a/contrib/llvm/tools/lldb/source/Core/Scalar.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Scalar.cpp @@ -12,7 +12,7 @@ #include "lldb/Host/StringConvert.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-types.h" // for offset_t @@ -2460,9 +2460,9 @@ const Scalar lldb_private::operator>>(const Scalar &lhs, const Scalar &rhs) { return result; } -Error Scalar::SetValueFromCString(const char *value_str, Encoding encoding, - size_t byte_size) { - Error error; +Status Scalar::SetValueFromCString(const char *value_str, Encoding encoding, + size_t byte_size) { + Status error; if (value_str == nullptr || value_str[0] == '\0') { error.SetErrorString("Invalid c-string value string."); return error; @@ -2596,9 +2596,9 @@ Error Scalar::SetValueFromCString(const char *value_str, Encoding encoding, return error; } -Error Scalar::SetValueFromData(DataExtractor &data, lldb::Encoding encoding, - size_t byte_size) { - Error error; +Status Scalar::SetValueFromData(DataExtractor &data, lldb::Encoding encoding, + size_t byte_size) { + Status error; type128 int128; type256 int256; @@ -2762,7 +2762,7 @@ bool Scalar::SignExtend(uint32_t sign_bit_pos) { size_t Scalar::GetAsMemoryData(void *dst, size_t dst_len, lldb::ByteOrder dst_byte_order, - Error &error) const { + Status &error) const { // Get a data extractor that points to the native scalar data DataExtractor data; if (!GetData(data)) { diff --git a/contrib/llvm/tools/lldb/source/Core/SearchFilter.cpp b/contrib/llvm/tools/lldb/source/Core/SearchFilter.cpp index 6d29e21c310e..0701955233a1 100644 --- a/contrib/llvm/tools/lldb/source/Core/SearchFilter.cpp +++ b/contrib/llvm/tools/lldb/source/Core/SearchFilter.cpp @@ -16,7 +16,7 @@ #include "lldb/Symbol/SymbolContext.h" // for SymbolContext #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" // for ConstString -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/Stream.h" // for Stream #include "lldb/lldb-enumerations.h" // for SymbolContextItem::eSymbolCo... @@ -55,9 +55,9 @@ const char *SearchFilter::FilterTyToName(enum FilterTy type) { return g_ty_to_name[type]; } -SearchFilter::FilterTy SearchFilter::NameToFilterTy(const char *name) { +SearchFilter::FilterTy SearchFilter::NameToFilterTy(llvm::StringRef name) { for (size_t i = 0; i <= LastKnownFilterType; i++) { - if (strcmp(name, g_ty_to_name[i]) == 0) + if (name == g_ty_to_name[i]) return (FilterTy)i; } return UnknownFilter; @@ -80,14 +80,14 @@ SearchFilter::~SearchFilter() = default; SearchFilterSP SearchFilter::CreateFromStructuredData( Target &target, const StructuredData::Dictionary &filter_dict, - Error &error) { + Status &error) { SearchFilterSP result_sp; if (!filter_dict.IsValid()) { error.SetErrorString("Can't deserialize from an invalid data object."); return result_sp; } - std::string subclass_name; + llvm::StringRef subclass_name; bool success = filter_dict.GetValueForKeyAsString( GetSerializationSubclassKey(), subclass_name); @@ -96,10 +96,9 @@ SearchFilterSP SearchFilter::CreateFromStructuredData( return result_sp; } - FilterTy filter_type = NameToFilterTy(subclass_name.c_str()); + FilterTy filter_type = NameToFilterTy(subclass_name); if (filter_type == UnknownFilter) { - error.SetErrorStringWithFormat("Unknown filter type: %s.", - subclass_name.c_str()); + error.SetErrorStringWithFormatv("Unknown filter type: {0}.", subclass_name); return result_sp; } @@ -338,7 +337,8 @@ Searcher::CallbackReturn SearchFilter::DoFunctionIteration( // "black list". //---------------------------------------------------------------------- SearchFilterSP SearchFilterForUnconstrainedSearches::CreateFromStructuredData( - Target &target, const StructuredData::Dictionary &data_dict, Error &error) { + Target &target, const StructuredData::Dictionary &data_dict, + Status &error) { // No options for an unconstrained search. return std::make_shared<SearchFilterForUnconstrainedSearches>( target.shared_from_this()); @@ -466,7 +466,8 @@ SearchFilterByModule::DoCopyForBreakpoint(Breakpoint &breakpoint) { } SearchFilterSP SearchFilterByModule::CreateFromStructuredData( - Target &target, const StructuredData::Dictionary &data_dict, Error &error) { + Target &target, const StructuredData::Dictionary &data_dict, + Status &error) { StructuredData::Array *modules_array; bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), modules_array); @@ -482,7 +483,7 @@ SearchFilterSP SearchFilterByModule::CreateFromStructuredData( return nullptr; } - std::string module; + llvm::StringRef module; success = modules_array->GetItemAtIndexAsString(0, module); if (!success) { error.SetErrorString("SFBM::CFSD: filter module item not a string."); @@ -628,7 +629,8 @@ SearchFilterByModuleList::DoCopyForBreakpoint(Breakpoint &breakpoint) { } SearchFilterSP SearchFilterByModuleList::CreateFromStructuredData( - Target &target, const StructuredData::Dictionary &data_dict, Error &error) { + Target &target, const StructuredData::Dictionary &data_dict, + Status &error) { StructuredData::Array *modules_array; bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), modules_array); @@ -636,7 +638,7 @@ SearchFilterSP SearchFilterByModuleList::CreateFromStructuredData( if (success) { size_t num_modules = modules_array->GetSize(); for (size_t i = 0; i < num_modules; i++) { - std::string module; + llvm::StringRef module; success = modules_array->GetItemAtIndexAsString(i, module); if (!success) { error.SetErrorStringWithFormat( @@ -691,7 +693,8 @@ operator=(const SearchFilterByModuleListAndCU &rhs) { SearchFilterByModuleListAndCU::~SearchFilterByModuleListAndCU() = default; lldb::SearchFilterSP SearchFilterByModuleListAndCU::CreateFromStructuredData( - Target &target, const StructuredData::Dictionary &data_dict, Error &error) { + Target &target, const StructuredData::Dictionary &data_dict, + Status &error) { StructuredData::Array *modules_array = nullptr; SearchFilterSP result_sp; bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), @@ -700,7 +703,7 @@ lldb::SearchFilterSP SearchFilterByModuleListAndCU::CreateFromStructuredData( if (success) { size_t num_modules = modules_array->GetSize(); for (size_t i = 0; i < num_modules; i++) { - std::string module; + llvm::StringRef module; success = modules_array->GetItemAtIndexAsString(i, module); if (!success) { error.SetErrorStringWithFormat( @@ -722,7 +725,7 @@ lldb::SearchFilterSP SearchFilterByModuleListAndCU::CreateFromStructuredData( size_t num_cus = cus_array->GetSize(); FileSpecList cus; for (size_t i = 0; i < num_cus; i++) { - std::string cu; + llvm::StringRef cu; success = cus_array->GetItemAtIndexAsString(i, cu); if (!success) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp b/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp index 649c4615ad4f..d52b7730cc65 100644 --- a/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp +++ b/contrib/llvm/tools/lldb/source/Core/StructuredData.cpp @@ -12,9 +12,9 @@ #include "lldb/Host/File.h" #include "lldb/Host/StringConvert.h" #include "lldb/Utility/DataBuffer.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/JSON.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" // for Stream #include "lldb/Utility/StreamString.h" #include "lldb/lldb-enumerations.h" // for FilePermissions::eFilePermiss... @@ -40,7 +40,7 @@ static StructuredData::ObjectSP ParseJSONObject(JSONParser &json_parser); static StructuredData::ObjectSP ParseJSONArray(JSONParser &json_parser); StructuredData::ObjectSP -StructuredData::ParseJSONFromFile(const FileSpec &input_spec, Error &error) { +StructuredData::ParseJSONFromFile(const FileSpec &input_spec, Status &error) { StructuredData::ObjectSP return_sp; if (!input_spec.Exists()) { error.SetErrorStringWithFormat("input file %s does not exist.", diff --git a/contrib/llvm/tools/lldb/source/Core/Timer.cpp b/contrib/llvm/tools/lldb/source/Core/Timer.cpp index 60da39b7f199..6de4516f721d 100644 --- a/contrib/llvm/tools/lldb/source/Core/Timer.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Timer.cpp @@ -27,8 +27,8 @@ using namespace lldb_private; #define TIMER_INDENT_AMOUNT 2 namespace { -typedef std::map<const char *, std::chrono::nanoseconds> TimerCategoryMap; typedef std::vector<Timer *> TimerStack; +static std::atomic<Timer::Category *> g_categories; } // end of anonymous namespace std::atomic<bool> Timer::g_quiet(true); @@ -38,16 +38,6 @@ static std::mutex &GetFileMutex() { return *g_file_mutex_ptr; } -static std::mutex &GetCategoryMutex() { - static std::mutex g_category_mutex; - return g_category_mutex; -} - -static TimerCategoryMap &GetCategoryMap() { - static TimerCategoryMap g_category_map; - return g_category_map; -} - static void ThreadSpecificCleanup(void *p) { delete static_cast<TimerStack *>(p); } @@ -64,9 +54,17 @@ static TimerStack *GetTimerStackForCurrentThread() { return (TimerStack *)timer_stack; } +Timer::Category::Category(const char *cat) : m_name(cat) { + m_nanos.store(0, std::memory_order_release); + Category *expected = g_categories; + do { + m_next = expected; + } while (!g_categories.compare_exchange_weak(expected, this)); +} + void Timer::SetQuiet(bool value) { g_quiet = value; } -Timer::Timer(const char *category, const char *format, ...) +Timer::Timer(Timer::Category &category, const char *format, ...) : m_category(category), m_total_start(std::chrono::steady_clock::now()) { TimerStack *stack = GetTimerStackForCurrentThread(); if (!stack) @@ -114,11 +112,7 @@ Timer::~Timer() { stack->back()->ChildDuration(total_dur); // Keep total results for each category so we can dump results. - { - std::lock_guard<std::mutex> guard(GetCategoryMutex()); - TimerCategoryMap &category_map = GetCategoryMap(); - category_map[m_category] += timer_dur; - } + m_category.m_nanos += std::chrono::nanoseconds(timer_dur).count(); } void Timer::SetDisplayDepth(uint32_t depth) { g_display_depth = depth; } @@ -126,33 +120,32 @@ void Timer::SetDisplayDepth(uint32_t depth) { g_display_depth = depth; } /* binary function predicate: * - returns whether a person is less than another person */ -static bool -CategoryMapIteratorSortCriterion(const TimerCategoryMap::const_iterator &lhs, - const TimerCategoryMap::const_iterator &rhs) { - return lhs->second > rhs->second; + +typedef std::pair<const char *, uint64_t> TimerEntry; + +static bool CategoryMapIteratorSortCriterion(const TimerEntry &lhs, + const TimerEntry &rhs) { + return lhs.second > rhs.second; } void Timer::ResetCategoryTimes() { - std::lock_guard<std::mutex> guard(GetCategoryMutex()); - TimerCategoryMap &category_map = GetCategoryMap(); - category_map.clear(); + for (Category *i = g_categories; i; i = i->m_next) + i->m_nanos.store(0, std::memory_order_release); } void Timer::DumpCategoryTimes(Stream *s) { - std::lock_guard<std::mutex> guard(GetCategoryMutex()); - TimerCategoryMap &category_map = GetCategoryMap(); - std::vector<TimerCategoryMap::const_iterator> sorted_iterators; - TimerCategoryMap::const_iterator pos, end = category_map.end(); - for (pos = category_map.begin(); pos != end; ++pos) { - sorted_iterators.push_back(pos); - } - std::sort(sorted_iterators.begin(), sorted_iterators.end(), - CategoryMapIteratorSortCriterion); - - const size_t count = sorted_iterators.size(); - for (size_t i = 0; i < count; ++i) { - const auto timer = sorted_iterators[i]->second; - s->Printf("%.9f sec for %s\n", std::chrono::duration<double>(timer).count(), - sorted_iterators[i]->first); + std::vector<TimerEntry> sorted; + for (Category *i = g_categories; i; i = i->m_next) { + uint64_t nanos = i->m_nanos.load(std::memory_order_acquire); + if (nanos) + sorted.push_back(std::make_pair(i->m_name, nanos)); } + if (sorted.empty()) + return; // Later code will break without any elements. + + // Sort by time + std::sort(sorted.begin(), sorted.end(), CategoryMapIteratorSortCriterion); + + for (const auto &timer : sorted) + s->Printf("%.9f sec for %s\n", timer.second / 1000000000., timer.first); } diff --git a/contrib/llvm/tools/lldb/source/Core/UserSettingsController.cpp b/contrib/llvm/tools/lldb/source/Core/UserSettingsController.cpp index 59a88ccdb931..a4661a6c9e8c 100644 --- a/contrib/llvm/tools/lldb/source/Core/UserSettingsController.cpp +++ b/contrib/llvm/tools/lldb/source/Core/UserSettingsController.cpp @@ -10,7 +10,7 @@ #include "lldb/Core/UserSettingsController.h" #include "lldb/Interpreter/OptionValueProperties.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include <memory> // for shared_ptr @@ -32,21 +32,23 @@ using namespace lldb; using namespace lldb_private; lldb::OptionValueSP -Properties::GetPropertyValue(const ExecutionContext *exe_ctx, llvm::StringRef path, - bool will_modify, Error &error) const { +Properties::GetPropertyValue(const ExecutionContext *exe_ctx, + llvm::StringRef path, bool will_modify, + Status &error) const { OptionValuePropertiesSP properties_sp(GetValueProperties()); if (properties_sp) return properties_sp->GetSubValue(exe_ctx, path, will_modify, error); return lldb::OptionValueSP(); } -Error Properties::SetPropertyValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, llvm::StringRef path, - llvm::StringRef value) { +Status Properties::SetPropertyValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, + llvm::StringRef path, + llvm::StringRef value) { OptionValuePropertiesSP properties_sp(GetValueProperties()); if (properties_sp) return properties_sp->SetSubValue(exe_ctx, op, path, value); - Error error; + Status error; error.SetErrorString("no properties"); return error; } @@ -67,15 +69,16 @@ void Properties::DumpAllDescriptions(CommandInterpreter &interpreter, return properties_sp->DumpAllDescriptions(interpreter, strm); } -Error Properties::DumpPropertyValue(const ExecutionContext *exe_ctx, - Stream &strm, llvm::StringRef property_path, - uint32_t dump_mask) { +Status Properties::DumpPropertyValue(const ExecutionContext *exe_ctx, + Stream &strm, + llvm::StringRef property_path, + uint32_t dump_mask) { OptionValuePropertiesSP properties_sp(GetValueProperties()); if (properties_sp) { return properties_sp->DumpPropertyValue(exe_ctx, strm, property_path, dump_mask); } - Error error; + Status error; error.SetErrorString("empty property list"); return error; } diff --git a/contrib/llvm/tools/lldb/source/Core/Value.cpp b/contrib/llvm/tools/lldb/source/Core/Value.cpp index 9aaddf77021c..63385511edb6 100644 --- a/contrib/llvm/tools/lldb/source/Core/Value.cpp +++ b/contrib/llvm/tools/lldb/source/Core/Value.cpp @@ -144,7 +144,7 @@ Type *Value::GetType() { size_t Value::AppendDataToHostBuffer(const Value &rhs) { size_t curr_size = m_data_buffer.GetByteSize(); - Error error; + Status error; switch (rhs.GetValueType()) { case eValueTypeScalar: { const size_t scalar_size = rhs.m_value.GetByteSize(); @@ -207,7 +207,7 @@ bool Value::ValueOf(ExecutionContext *exe_ctx) { return false; } -uint64_t Value::GetValueByteSize(Error *error_ptr, ExecutionContext *exe_ctx) { +uint64_t Value::GetValueByteSize(Status *error_ptr, ExecutionContext *exe_ctx) { uint64_t byte_size = 0; switch (m_context_type) { @@ -315,11 +315,11 @@ bool Value::GetData(DataExtractor &data) { return false; } -Error Value::GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, - uint32_t data_offset, Module *module) { +Status Value::GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, + uint32_t data_offset, Module *module) { data.Clear(); - Error error; + Status error; lldb::addr_t address = LLDB_INVALID_ADDRESS; AddressType address_type = eAddressTypeFile; Address file_so_addr; @@ -623,7 +623,7 @@ Scalar &Value::ResolveValue(ExecutionContext *exe_ctx) { { DataExtractor data; lldb::addr_t addr = m_value.ULongLong(LLDB_INVALID_ADDRESS); - Error error(GetValueAsData(exe_ctx, data, 0, NULL)); + Status error(GetValueAsData(exe_ctx, data, 0, NULL)); if (error.Success()) { Scalar scalar; if (compiler_type.GetValueAsScalar(data, 0, data.GetByteSize(), diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObject.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObject.cpp index 9e6b9da78b99..c09139fe2b09 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObject.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObject.cpp @@ -347,7 +347,7 @@ DataExtractor &ValueObject::GetDataExtractor() { return m_data; } -const Error &ValueObject::GetError() { +const Status &ValueObject::GetError() { UpdateValueIfNeeded(false); return m_error; } @@ -423,7 +423,7 @@ bool ValueObject::ResolveValue(Scalar &scalar) { return false; } -bool ValueObject::IsLogicalTrue(Error &error) { +bool ValueObject::IsLogicalTrue(Status &error) { if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) { LazyBool is_logical_true = language->IsLogicalTrue(*this, error); switch (is_logical_true) { @@ -771,7 +771,7 @@ size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx, if (item_idx == 0 && item_count == 1) // simply a deref { if (is_pointer_type) { - Error error; + Status error; ValueObjectSP pointee_sp = Dereference(error); if (error.Fail() || pointee_sp.get() == NULL) return 0; @@ -780,13 +780,13 @@ size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx, ValueObjectSP child_sp = GetChildAtIndex(0, true); if (child_sp.get() == NULL) return 0; - Error error; + Status error; return child_sp->GetData(data, error); } return true; } else /* (items > 1) */ { - Error error; + Status error; lldb_private::DataBufferHeap *heap_buf_ptr = NULL; lldb::DataBufferSP data_sp(heap_buf_ptr = new lldb_private::DataBufferHeap()); @@ -848,7 +848,7 @@ size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx, return 0; } -uint64_t ValueObject::GetData(DataExtractor &data, Error &error) { +uint64_t ValueObject::GetData(DataExtractor &data, Status &error) { UpdateValueIfNeeded(false); ExecutionContext exe_ctx(GetExecutionContextRef()); error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get()); @@ -866,7 +866,7 @@ uint64_t ValueObject::GetData(DataExtractor &data, Error &error) { return data.GetByteSize(); } -bool ValueObject::SetData(DataExtractor &data, Error &error) { +bool ValueObject::SetData(DataExtractor &data, Status &error) { error.Clear(); // Make sure our value is up to date first so that our location and location // type is valid. @@ -884,7 +884,7 @@ bool ValueObject::SetData(DataExtractor &data, Error &error) { switch (value_type) { case Value::eValueTypeScalar: { - Error set_error = + Status set_error = m_value.GetScalar().SetValueFromData(data, encoding, byte_size); if (!set_error.Success()) { @@ -938,7 +938,7 @@ static bool CopyStringDataToBufferSP(const StreamString &source, } std::pair<size_t, bool> -ValueObject::ReadPointedString(lldb::DataBufferSP &buffer_sp, Error &error, +ValueObject::ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error, uint32_t max_length, bool honor_array, Format item_format) { bool was_capped = false; @@ -1285,7 +1285,7 @@ bool ValueObject::DumpPrintableRepresentation( custom_format == eFormatVectorOfChar)) // print char[] & char* directly { - Error error; + Status error; lldb::DataBufferSP buffer_sp; std::pair<size_t, bool> read_string = ReadPointedString( buffer_sp, error, 0, (custom_format == eFormatVectorOfChar) || @@ -1561,7 +1561,7 @@ addr_t ValueObject::GetPointerValue(AddressType *address_type) { return address; } -bool ValueObject::SetValueFromCString(const char *value_str, Error &error) { +bool ValueObject::SetValueFromCString(const char *value_str, Status &error) { error.Clear(); // Make sure our value is up to date first so that our location and location // type is valid. @@ -2185,7 +2185,7 @@ ValueObjectSP ValueObject::GetValueForExpressionPath( if ((final_task_on_target ? *final_task_on_target : dummy_final_task_on_target) == ValueObject::eExpressionPathAftermathDereference) { - Error error; + Status error; ValueObjectSP final_value = ret_val->Dereference(error); if (error.Fail() || !final_value.get()) { if (reason_to_stop) @@ -2202,7 +2202,7 @@ ValueObjectSP ValueObject::GetValueForExpressionPath( } if (*final_task_on_target == ValueObject::eExpressionPathAftermathTakeAddress) { - Error error; + Status error; ValueObjectSP final_value = ret_val->AddressOf(error); if (error.Fail() || !final_value.get()) { if (reason_to_stop) @@ -2552,7 +2552,7 @@ ValueObjectSP ValueObject::GetValueForExpressionPath_Impl( // and use this as // a bitfield pointee_compiler_type_info.Test(eTypeIsScalar)) { - Error error; + Status error; root = root->Dereference(error); if (error.Fail() || !root) { *reason_to_stop = @@ -2697,7 +2697,7 @@ ValueObjectSP ValueObject::GetValueForExpressionPath_Impl( *what_next == ValueObject::eExpressionPathAftermathDereference && pointee_compiler_type_info.Test(eTypeIsScalar)) { - Error error; + Status error; root = root->Dereference(error); if (error.Fail() || !root) { *reason_to_stop = @@ -2839,7 +2839,7 @@ lldb::addr_t ValueObject::GetCPPVTableAddress(AddressType &address_type) { return LLDB_INVALID_ADDRESS; } -ValueObjectSP ValueObject::Dereference(Error &error) { +ValueObjectSP ValueObject::Dereference(Status &error) { if (m_deref_valobj) return m_deref_valobj->GetSP(); @@ -2904,7 +2904,7 @@ ValueObjectSP ValueObject::Dereference(Error &error) { } } -ValueObjectSP ValueObject::AddressOf(Error &error) { +ValueObjectSP ValueObject::AddressOf(Status &error) { if (m_addr_of_valobj_sp) return m_addr_of_valobj_sp; @@ -3191,7 +3191,7 @@ lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress( if (ptr_result_valobj_sp) { ptr_result_valobj_sp->GetValue().SetValueType( Value::eValueTypeLoadAddress); - Error err; + Status err; ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err); if (ptr_result_valobj_sp && !name.empty()) ptr_result_valobj_sp->SetName(ConstString(name)); diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectCast.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectCast.cpp index aa4cf60c1f9e..a489bdc74f5f 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectCast.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectCast.cpp @@ -14,7 +14,7 @@ #include "lldb/Core/ValueObject.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Target/ExecutionContext.h" -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status namespace lldb_private { class ConstString; diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectChild.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectChild.cpp index eeb28c960a3a..591bc21711ae 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectChild.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectChild.cpp @@ -14,9 +14,9 @@ #include "lldb/Symbol/CompilerType.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" -#include "lldb/Utility/Error.h" // for Error -#include "lldb/Utility/Flags.h" // for Flags -#include "lldb/lldb-forward.h" // for ProcessSP, ModuleSP +#include "lldb/Utility/Flags.h" // for Flags +#include "lldb/Utility/Status.h" // for Status +#include "lldb/lldb-forward.h" // for ProcessSP, ModuleSP #include <functional> // for _Func_impl<>::_Mybase #include <memory> // for shared_ptr diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResult.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResult.cpp index cf437ce6f7d5..1023696c35a7 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResult.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResult.cpp @@ -163,12 +163,12 @@ ValueObjectConstResult::ValueObjectConstResult( } ValueObjectSP ValueObjectConstResult::Create(ExecutionContextScope *exe_scope, - const Error &error) { + const Status &error) { return (new ValueObjectConstResult(exe_scope, error))->GetSP(); } ValueObjectConstResult::ValueObjectConstResult(ExecutionContextScope *exe_scope, - const Error &error) + const Status &error) : ValueObject(exe_scope), m_type_name(), m_byte_size(0), m_impl(this) { m_error = error; SetIsConstant(); @@ -234,7 +234,7 @@ bool ValueObjectConstResult::IsInScope() { return true; } -lldb::ValueObjectSP ValueObjectConstResult::Dereference(Error &error) { +lldb::ValueObjectSP ValueObjectConstResult::Dereference(Status &error) { return m_impl.Dereference(error); } @@ -245,7 +245,7 @@ lldb::ValueObjectSP ValueObjectConstResult::GetSyntheticChildAtOffset( name_const_str); } -lldb::ValueObjectSP ValueObjectConstResult::AddressOf(Error &error) { +lldb::ValueObjectSP ValueObjectConstResult::AddressOf(Status &error) { return m_impl.AddressOf(error); } diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultCast.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultCast.cpp index f575bebd7110..c04043264af1 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultCast.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultCast.cpp @@ -13,7 +13,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ValueObject; @@ -30,7 +30,7 @@ ValueObjectConstResultCast::ValueObjectConstResultCast( ValueObjectConstResultCast::~ValueObjectConstResultCast() {} -lldb::ValueObjectSP ValueObjectConstResultCast::Dereference(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultCast::Dereference(Status &error) { return m_impl.Dereference(error); } @@ -41,7 +41,7 @@ lldb::ValueObjectSP ValueObjectConstResultCast::GetSyntheticChildAtOffset( name_const_str); } -lldb::ValueObjectSP ValueObjectConstResultCast::AddressOf(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultCast::AddressOf(Status &error) { return m_impl.AddressOf(error); } diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultChild.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultChild.cpp index 9c6ad8becf3b..3e9f87684162 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultChild.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultChild.cpp @@ -14,7 +14,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } namespace lldb_private { class ValueObject; @@ -37,7 +37,7 @@ ValueObjectConstResultChild::ValueObjectConstResultChild( ValueObjectConstResultChild::~ValueObjectConstResultChild() {} -lldb::ValueObjectSP ValueObjectConstResultChild::Dereference(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultChild::Dereference(Status &error) { return m_impl.Dereference(error); } @@ -48,7 +48,7 @@ lldb::ValueObjectSP ValueObjectConstResultChild::GetSyntheticChildAtOffset( name_const_str); } -lldb::ValueObjectSP ValueObjectConstResultChild::AddressOf(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultChild::AddressOf(Status &error) { return m_impl.AddressOf(error); } diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultImpl.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultImpl.cpp index ed25ea8071a2..714634ed56e3 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultImpl.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectConstResultImpl.cpp @@ -27,7 +27,7 @@ namespace lldb_private { class DataExtractor; } namespace lldb_private { -class Error; +class Status; } using namespace lldb; @@ -39,7 +39,7 @@ ValueObjectConstResultImpl::ValueObjectConstResultImpl( m_live_address_type(eAddressTypeLoad), m_load_addr_backend(), m_address_of_backend() {} -lldb::ValueObjectSP ValueObjectConstResultImpl::Dereference(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultImpl::Dereference(Status &error) { if (m_impl_backend == NULL) return lldb::ValueObjectSP(); @@ -108,7 +108,7 @@ lldb::ValueObjectSP ValueObjectConstResultImpl::GetSyntheticChildAtOffset( offset, type, can_create, name_const_str); } -lldb::ValueObjectSP ValueObjectConstResultImpl::AddressOf(Error &error) { +lldb::ValueObjectSP ValueObjectConstResultImpl::AddressOf(Status &error) { if (m_address_of_backend.get() != NULL) return m_address_of_backend; diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectDynamicValue.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectDynamicValue.cpp index 59bbc025f994..bb39caa767eb 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectDynamicValue.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectDynamicValue.cpp @@ -20,9 +20,9 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" // for DataExtractor -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" // for GetLogIfAllCategoriesSet +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-types.h" // for addr_t, offset_t #include <string.h> // for strcmp, size_t @@ -275,7 +275,7 @@ bool ValueObjectDynamicValue::UpdateValue() { bool ValueObjectDynamicValue::IsInScope() { return m_parent->IsInScope(); } bool ValueObjectDynamicValue::SetValueFromCString(const char *value_str, - Error &error) { + Status &error) { if (!UpdateValueIfNeeded(false)) { error.SetErrorString("unable to read value"); return false; @@ -310,7 +310,7 @@ bool ValueObjectDynamicValue::SetValueFromCString(const char *value_str, return ret_val; } -bool ValueObjectDynamicValue::SetData(DataExtractor &data, Error &error) { +bool ValueObjectDynamicValue::SetData(DataExtractor &data, Status &error) { if (!UpdateValueIfNeeded(false)) { error.SetErrorString("unable to read value"); return false; diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectMemory.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectMemory.cpp index 0fb8f0d2de03..713751110dce 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectMemory.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectMemory.cpp @@ -17,7 +17,7 @@ #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" // for DataExtractor -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-types.h" // for addr_t #include "llvm/Support/ErrorHandling.h" // for llvm_unreachable diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectRegister.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectRegister.cpp index 6469340201e5..05022d3ed10a 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectRegister.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectRegister.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/StackFrame.h" // for StackFrame #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" // for DataExtractor -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/Utility/Stream.h" // for Stream #include "llvm/ADT/StringRef.h" // for StringRef @@ -318,7 +318,7 @@ bool ValueObjectRegister::UpdateValue() { } bool ValueObjectRegister::SetValueFromCString(const char *value_str, - Error &error) { + Status &error) { // The new value will be in the m_data. Copy that into our register value. error = m_reg_value.SetValueFromString(&m_reg_info, llvm::StringRef(value_str)); @@ -332,7 +332,7 @@ bool ValueObjectRegister::SetValueFromCString(const char *value_str, return false; } -bool ValueObjectRegister::SetData(DataExtractor &data, Error &error) { +bool ValueObjectRegister::SetData(DataExtractor &data, Status &error) { error = m_reg_value.SetValueFromData(&m_reg_info, data, 0, false); if (error.Success()) { if (m_reg_ctx_sp->WriteRegister(&m_reg_info, m_reg_value)) { diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectSyntheticFilter.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectSyntheticFilter.cpp index f0fd76ed09fc..87310c423cb8 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectSyntheticFilter.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectSyntheticFilter.cpp @@ -13,10 +13,10 @@ #include "lldb/Core/ValueObject.h" #include "lldb/DataFormatters/TypeSynthetic.h" #include "lldb/Target/ExecutionContext.h" // for ExecutionContext -#include "lldb/Utility/Error.h" // for Error #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" // for GetLogIfAllCategoriesSet #include "lldb/Utility/SharingPtr.h" // for SharingPtr +#include "lldb/Utility/Status.h" // for Status #include "llvm/ADT/STLExtras.h" @@ -324,7 +324,7 @@ bool ValueObjectSynthetic::CanProvideValue() { } bool ValueObjectSynthetic::SetValueFromCString(const char *value_str, - Error &error) { + Status &error) { return m_parent->SetValueFromCString(value_str, error); } diff --git a/contrib/llvm/tools/lldb/source/Core/ValueObjectVariable.cpp b/contrib/llvm/tools/lldb/source/Core/ValueObjectVariable.cpp index 169f8f0f6c28..9b9e51a0abb8 100644 --- a/contrib/llvm/tools/lldb/source/Core/ValueObjectVariable.cpp +++ b/contrib/llvm/tools/lldb/source/Core/ValueObjectVariable.cpp @@ -29,7 +29,7 @@ #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" // for DataExtractor -#include "lldb/Utility/Error.h" // for Error +#include "lldb/Utility/Status.h" // for Status #include "lldb/lldb-private-enumerations.h" // for AddressType::eAddressTy... #include "lldb/lldb-types.h" // for addr_t @@ -344,7 +344,7 @@ const char *ValueObjectVariable::GetLocationAsCString() { } bool ValueObjectVariable::SetValueFromCString(const char *value_str, - Error &error) { + Status &error) { if (!UpdateValueIfNeeded()) { error.SetErrorString("unable to update value before writing"); return false; @@ -373,7 +373,7 @@ bool ValueObjectVariable::SetValueFromCString(const char *value_str, return ValueObject::SetValueFromCString(value_str, error); } -bool ValueObjectVariable::SetData(DataExtractor &data, Error &error) { +bool ValueObjectVariable::SetData(DataExtractor &data, Status &error) { if (!UpdateValueIfNeeded()) { error.SetErrorString("unable to update value before writing"); return false; diff --git a/contrib/llvm/tools/lldb/source/DataFormatters/StringPrinter.cpp b/contrib/llvm/tools/lldb/source/DataFormatters/StringPrinter.cpp index 7ca3744a247a..84143a541087 100644 --- a/contrib/llvm/tools/lldb/source/DataFormatters/StringPrinter.cpp +++ b/contrib/llvm/tools/lldb/source/DataFormatters/StringPrinter.cpp @@ -15,7 +15,7 @@ #include "lldb/Target/Language.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/ConvertUTF.h" @@ -417,7 +417,7 @@ bool StringPrinter::ReadStringAndDumpToStream< StringPrinter::StringElementType::ASCII>( const ReadStringAndDumpToStreamOptions &options) { assert(options.GetStream() && "need a Stream to print the string to"); - Error my_error; + Status my_error; ProcessSP process_sp(options.GetProcessSP()); @@ -561,7 +561,7 @@ static bool ReadUTFBufferAndDumpToStream( if (!buffer_sp->GetBytes()) return false; - Error error; + Status error; char *buffer = reinterpret_cast<char *>(buffer_sp->GetBytes()); if (needs_zero_terminator) diff --git a/contrib/llvm/tools/lldb/source/DataFormatters/TypeFormat.cpp b/contrib/llvm/tools/lldb/source/DataFormatters/TypeFormat.cpp index 4d1a0096bb68..333fe91b76db 100644 --- a/contrib/llvm/tools/lldb/source/DataFormatters/TypeFormat.cpp +++ b/contrib/llvm/tools/lldb/source/DataFormatters/TypeFormat.cpp @@ -56,7 +56,7 @@ bool TypeFormatImpl_Format::FormatObject(ValueObject *valobj, if (context_type == Value::eContextTypeRegisterInfo) { const RegisterInfo *reg_info = value.GetRegisterInfo(); if (reg_info) { - Error error; + Status error; valobj->GetData(data, error); if (error.Fail()) return false; @@ -82,7 +82,7 @@ bool TypeFormatImpl_Format::FormatObject(ValueObject *valobj, TargetSP target_sp(valobj->GetTargetSP()); if (target_sp) { size_t max_len = target_sp->GetMaximumSizeOfStringSummary(); - Error error; + Status error; DataBufferSP buffer_sp(new DataBufferHeap(max_len + 1, 0)); Address address(valobj->GetPointerValue()); if (target_sp->ReadCStringFromMemory( @@ -92,7 +92,7 @@ bool TypeFormatImpl_Format::FormatObject(ValueObject *valobj, } } } else { - Error error; + Status error; valobj->GetData(data, error); if (error.Fail()) return false; @@ -185,7 +185,7 @@ bool TypeFormatImpl_EnumType::FormatObject(ValueObject *valobj, if (valobj_enum_type.IsValid() == false) return false; DataExtractor data; - Error error; + Status error; valobj->GetData(data, error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Expression/DWARFExpression.cpp b/contrib/llvm/tools/lldb/source/Expression/DWARFExpression.cpp index 928577cd7ee4..592a30cdd780 100644 --- a/contrib/llvm/tools/lldb/source/Expression/DWARFExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/DWARFExpression.cpp @@ -655,7 +655,7 @@ void DWARFExpression::GetDescription(Stream *s, lldb::DescriptionLevel level, static bool ReadRegisterValueAsScalar(RegisterContext *reg_ctx, lldb::RegisterKind reg_kind, - uint32_t reg_num, Error *error_ptr, + uint32_t reg_num, Status *error_ptr, Value &value) { if (reg_ctx == NULL) { if (error_ptr) @@ -1250,7 +1250,7 @@ bool DWARFExpression::Evaluate(ExecutionContextScope *exe_scope, lldb::addr_t loclist_base_load_addr, const Value *initial_value_ptr, const Value *object_address_ptr, Value &result, - Error *error_ptr) const { + Status *error_ptr) const { ExecutionContext exe_ctx(exe_scope); return Evaluate(&exe_ctx, expr_locals, decl_map, nullptr, loclist_base_load_addr, initial_value_ptr, object_address_ptr, @@ -1261,7 +1261,7 @@ bool DWARFExpression::Evaluate( ExecutionContext *exe_ctx, ClangExpressionVariableList *expr_locals, ClangExpressionDeclMap *decl_map, RegisterContext *reg_ctx, lldb::addr_t loclist_base_load_addr, const Value *initial_value_ptr, - const Value *object_address_ptr, Value &result, Error *error_ptr) const { + const Value *object_address_ptr, Value &result, Status *error_ptr) const { ModuleSP module_sp = m_module_wp.lock(); if (IsLocationList()) { @@ -1333,7 +1333,7 @@ bool DWARFExpression::Evaluate( DWARFCompileUnit *dwarf_cu, const lldb::offset_t opcodes_offset, const lldb::offset_t opcodes_length, const lldb::RegisterKind reg_kind, const Value *initial_value_ptr, const Value *object_address_ptr, - Value &result, Error *error_ptr) { + Value &result, Status *error_ptr) { if (opcodes_length == 0) { if (error_ptr) @@ -1467,7 +1467,7 @@ bool DWARFExpression::Evaluate( if (process) { lldb::addr_t pointer_addr = stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS); - Error error; + Status error; lldb::addr_t pointer_value = process->ReadPointerFromMemory(pointer_addr, error); if (pointer_value != LLDB_INVALID_ADDRESS) { @@ -1572,7 +1572,7 @@ bool DWARFExpression::Evaluate( lldb::addr_t pointer_addr = stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS); uint8_t addr_bytes[sizeof(lldb::addr_t)]; - Error error; + Status error; if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) == size) { DataExtractor addr_data(addr_bytes, sizeof(addr_bytes), @@ -2568,7 +2568,7 @@ bool DWARFExpression::Evaluate( ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size); pieces.AppendDataToHostBuffer(curr_piece); } else { - Error error; + Status error; // Extract the current piece into "curr_piece" Value curr_piece_source_value(stack.back()); stack.pop_back(); diff --git a/contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp b/contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp index e2f38a9f50bb..6f60f8bf9c13 100644 --- a/contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/FunctionCaller.cpp @@ -86,7 +86,7 @@ bool FunctionCaller::WriteFunctionWrapper( bool can_interpret = false; // should stay that way - Error jit_error(m_parser->PrepareForExecution( + Status jit_error(m_parser->PrepareForExecution( m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx, can_interpret, eExecutionPolicyAlways)); @@ -135,7 +135,7 @@ bool FunctionCaller::WriteFunctionArguments( return false; } - Error error; + Status error; lldb::ExpressionResults return_value = lldb::eExpressionSetupError; Process *process = exe_ctx.GetProcessPtr(); @@ -172,7 +172,7 @@ bool FunctionCaller::WriteFunctionArguments( // FIXME: We will need to extend this for Variadic functions. - Error value_error; + Status value_error; size_t num_args = arg_values.GetSize(); if (num_args != m_arg_values.GetSize()) { @@ -289,7 +289,7 @@ bool FunctionCaller::FetchFunctionResults(ExecutionContext &exe_ctx, if (process != jit_process_sp.get()) return false; - Error error; + Status error; ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory( args_addr + m_return_offset, m_return_size, 0, error); diff --git a/contrib/llvm/tools/lldb/source/Expression/IRDynamicChecks.cpp b/contrib/llvm/tools/lldb/source/Expression/IRDynamicChecks.cpp index 44ff6295ca18..0c8cba2050c0 100644 --- a/contrib/llvm/tools/lldb/source/Expression/IRDynamicChecks.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/IRDynamicChecks.cpp @@ -51,7 +51,7 @@ DynamicCheckerFunctions::~DynamicCheckerFunctions() = default; bool DynamicCheckerFunctions::Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) { - Error error; + Status error; m_valid_pointer_check.reset( exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( g_valid_pointer_check_text, lldb::eLanguageTypeC, diff --git a/contrib/llvm/tools/lldb/source/Expression/IRExecutionUnit.cpp b/contrib/llvm/tools/lldb/source/Expression/IRExecutionUnit.cpp index 4309caefbd44..e31483f1728d 100644 --- a/contrib/llvm/tools/lldb/source/Expression/IRExecutionUnit.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/IRExecutionUnit.cpp @@ -50,7 +50,7 @@ IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_ap, m_reported_allocations(false) {} lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size, - Error &error) { + Status &error) { const bool zero_memory = false; lldb::addr_t allocation_process_addr = Malloc(size, 8, lldb::ePermissionsWritable | lldb::ePermissionsReadable, @@ -62,7 +62,7 @@ lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size, WriteMemory(allocation_process_addr, bytes, size, error); if (!error.Success()) { - Error err; + Status err; Free(allocation_process_addr, err); return LLDB_INVALID_ADDRESS; @@ -71,7 +71,7 @@ lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size, if (Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) { DataBufferHeap my_buffer(size, 0); - Error err; + Status err; ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err); if (err.Success()) { @@ -90,18 +90,18 @@ void IRExecutionUnit::FreeNow(lldb::addr_t allocation) { if (allocation == LLDB_INVALID_ADDRESS) return; - Error err; + Status err; Free(allocation, err); } -Error IRExecutionUnit::DisassembleFunction(Stream &stream, - lldb::ProcessSP &process_wp) { +Status IRExecutionUnit::DisassembleFunction(Stream &stream, + lldb::ProcessSP &process_wp) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); ExecutionContext exe_ctx(process_wp); - Error ret; + Status ret; ret.Clear(); @@ -152,7 +152,7 @@ Error IRExecutionUnit::DisassembleFunction(Stream &stream, lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0)); Process *process = exe_ctx.GetProcessPtr(); - Error err; + Status err; process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err); @@ -203,7 +203,7 @@ Error IRExecutionUnit::DisassembleFunction(Stream &stream, static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie) { - Error *err = static_cast<Error *>(Context); + Status *err = static_cast<Status *>(Context); if (err && err->Success()) { err->SetErrorToGenericError(); @@ -216,7 +216,7 @@ void IRExecutionUnit::ReportSymbolLookupError(const ConstString &name) { m_failed_lookups.push_back(name); } -void IRExecutionUnit::GetRunnableInfo(Error &error, lldb::addr_t &func_addr, +void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr, lldb::addr_t &func_end) { lldb::ProcessSP process_sp(GetProcessWP().lock()); @@ -452,7 +452,7 @@ void IRExecutionUnit::GetRunnableInfo(Error &error, lldb::addr_t &func_addr, StreamString disassembly_stream; - Error err = DisassembleFunction(disassembly_stream, process_sp); + Status err = DisassembleFunction(disassembly_stream, process_sp); if (!err.Success()) { log->Printf("Couldn't disassemble function : %s", @@ -467,7 +467,7 @@ void IRExecutionUnit::GetRunnableInfo(Error &error, lldb::addr_t &func_addr, record.dump(log); DataBufferHeap my_buffer(record.m_size, 0); - Error err; + Status err; ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err); @@ -643,7 +643,7 @@ uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection( } if (m_parent.m_reported_allocations) { - Error err; + Status err; lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess(); @@ -675,7 +675,7 @@ uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection( } if (m_parent.m_reported_allocations) { - Error err; + Status err; lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess(); @@ -1104,7 +1104,7 @@ IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) { } bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp, - Error &error, + Status &error, AllocationRecord &record) { if (record.m_process_address != LLDB_INVALID_ADDRESS) { return true; @@ -1145,7 +1145,7 @@ bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp, bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) { bool ret = true; - lldb_private::Error err; + lldb_private::Status err; for (AllocationRecord &record : m_records) { ret = CommitOneAllocation(process_sp, err, record); @@ -1189,7 +1189,7 @@ bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) { bool wrote_something = false; for (AllocationRecord &record : m_records) { if (record.m_process_address != LLDB_INVALID_ADDRESS) { - lldb_private::Error err; + lldb_private::Status err; WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address, record.m_size, err); if (err.Success()) diff --git a/contrib/llvm/tools/lldb/source/Expression/IRInterpreter.cpp b/contrib/llvm/tools/lldb/source/Expression/IRInterpreter.cpp index 6867443cdf5e..6b5e22329af8 100644 --- a/contrib/llvm/tools/lldb/source/Expression/IRInterpreter.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/IRInterpreter.cpp @@ -18,8 +18,8 @@ #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Target/ABI.h" @@ -189,7 +189,7 @@ public: size_t value_size = m_target_data.getTypeStoreSize(value->getType()); lldb_private::DataExtractor value_extractor; - lldb_private::Error extract_error; + lldb_private::Status extract_error; m_execution_unit.GetMemoryData(value_extractor, process_address, value_size, extract_error); @@ -224,13 +224,13 @@ public: lldb_private::DataBufferHeap buf(value_byte_size, 0); - lldb_private::Error get_data_error; + lldb_private::Status get_data_error; if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(), m_byte_order, get_data_error)) return false; - lldb_private::Error write_error; + lldb_private::Status write_error; m_execution_unit.WriteMemory(process_address, buf.GetBytes(), buf.GetByteSize(), write_error); @@ -322,12 +322,12 @@ public: if (data_address == LLDB_INVALID_ADDRESS) return false; - lldb_private::Error write_error; + lldb_private::Status write_error; m_execution_unit.WritePointerToMemory(data_address, address, write_error); if (!write_error.Success()) { - lldb_private::Error free_error; + lldb_private::Status free_error; m_execution_unit.Free(data_address, free_error); return false; } @@ -356,7 +356,7 @@ public: size_t constant_size = m_target_data.getTypeStoreSize(constant->getType()); lldb_private::DataBufferHeap buf(constant_size, 0); - lldb_private::Error get_data_error; + lldb_private::Status get_data_error; lldb_private::Scalar resolved_scalar( resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8)); @@ -364,7 +364,7 @@ public: m_byte_order, get_data_error)) return false; - lldb_private::Error write_error; + lldb_private::Status write_error; m_execution_unit.WriteMemory(process_address, buf.GetBytes(), buf.GetByteSize(), write_error); @@ -391,7 +391,7 @@ public: } lldb::addr_t Malloc(llvm::Type *type) { - lldb_private::Error alloc_error; + lldb_private::Status alloc_error; return Malloc(m_target_data.getTypeAllocSize(type), m_target_data.getPrefTypeAlignment(type)); @@ -402,7 +402,7 @@ public: lldb_private::DataBufferHeap buf(length, 0); - lldb_private::Error read_error; + lldb_private::Status read_error; m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error); @@ -433,7 +433,7 @@ public: if (const Constant *constant = dyn_cast<Constant>(value)) { if (!ResolveConstant(data_address, constant)) { - lldb_private::Error free_error; + lldb_private::Status free_error; m_execution_unit.Free(data_address, free_error); return LLDB_INVALID_ADDRESS; } @@ -499,7 +499,7 @@ static bool CanResolveConstant(llvm::Constant *constant) { } bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function, - lldb_private::Error &error, + lldb_private::Status &error, const bool support_function_calls) { lldb_private::Log *log( lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); @@ -648,7 +648,7 @@ bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function, bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, llvm::ArrayRef<lldb::addr_t> args, lldb_private::IRExecutionUnit &execution_unit, - lldb_private::Error &error, + lldb_private::Status &error, lldb::addr_t stack_frame_bottom, lldb::addr_t stack_frame_top, lldb_private::ExecutionContext &exe_ctx) { @@ -867,7 +867,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, return false; } - lldb_private::Error write_error; + lldb_private::Status write_error; execution_unit.WritePointerToMemory(P, R, write_error); @@ -876,7 +876,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, log->Printf("Couldn't write the result pointer for an AllocaInst"); error.SetErrorToGenericError(); error.SetErrorString(memory_write_error); - lldb_private::Error free_error; + lldb_private::Status free_error; execution_unit.Free(P, free_error); execution_unit.Free(R, free_error); return false; @@ -1349,7 +1349,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, } lldb::addr_t R; - lldb_private::Error read_error; + lldb_private::Status read_error; execution_unit.ReadPointerFromMemory(&R, P, read_error); if (!read_error.Success()) { @@ -1374,7 +1374,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, return false; } - lldb_private::Error write_error; + lldb_private::Status write_error; execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(), write_error); if (!write_error.Success()) { @@ -1442,7 +1442,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, } lldb::addr_t R; - lldb_private::Error read_error; + lldb_private::Status read_error; execution_unit.ReadPointerFromMemory(&R, P, read_error); if (!read_error.Success()) { @@ -1467,7 +1467,7 @@ bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function, return false; } - lldb_private::Error write_error; + lldb_private::Status write_error; execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(), write_error); if (!write_error.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Expression/IRMemoryMap.cpp b/contrib/llvm/tools/lldb/source/Expression/IRMemoryMap.cpp index 66510ac978ae..817c75e66a3b 100644 --- a/contrib/llvm/tools/lldb/source/Expression/IRMemoryMap.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/IRMemoryMap.cpp @@ -14,9 +14,9 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb_private; @@ -31,7 +31,7 @@ IRMemoryMap::~IRMemoryMap() { if (process_sp) { AllocationMap::iterator iter; - Error err; + Status err; while ((iter = m_allocations.begin()) != m_allocations.end()) { err.Clear(); @@ -66,7 +66,7 @@ lldb::addr_t IRMemoryMap::FindSpace(size_t size) { return ret; if (process_is_alive && process_sp->CanJIT()) { - Error alloc_error; + Status alloc_error; ret = process_sp->AllocateMemory(size, lldb::ePermissionsReadable | lldb::ePermissionsWritable, @@ -104,7 +104,7 @@ lldb::addr_t IRMemoryMap::FindSpace(size_t size) { end_of_memory != 0xffffffffull); MemoryRegionInfo region_info; - Error err = process_sp->GetMemoryRegionInfo(ret, region_info); + Status err = process_sp->GetMemoryRegionInfo(ret, region_info); if (err.Success()) { while (true) { if (region_info.GetReadable() != MemoryRegionInfo::OptionalBool::eNo || @@ -297,7 +297,7 @@ IRMemoryMap::Allocation::Allocation(lldb::addr_t process_alloc, lldb::addr_t IRMemoryMap::Malloc(size_t size, uint8_t alignment, uint32_t permissions, AllocationPolicy policy, - bool zero_memory, Error &error) { + bool zero_memory, Status &error) { lldb_private::Log *log( lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); error.Clear(); @@ -397,7 +397,7 @@ lldb::addr_t IRMemoryMap::Malloc(size_t size, uint8_t alignment, permissions, alignment, policy); if (zero_memory) { - Error write_error; + Status write_error; std::vector<uint8_t> zero_buf(size, 0); WriteMemory(aligned_address, zero_buf.data(), size, write_error); } @@ -429,7 +429,7 @@ lldb::addr_t IRMemoryMap::Malloc(size_t size, uint8_t alignment, return aligned_address; } -void IRMemoryMap::Leak(lldb::addr_t process_address, Error &error) { +void IRMemoryMap::Leak(lldb::addr_t process_address, Status &error) { error.Clear(); AllocationMap::iterator iter = m_allocations.find(process_address); @@ -445,7 +445,7 @@ void IRMemoryMap::Leak(lldb::addr_t process_address, Error &error) { allocation.m_leak = true; } -void IRMemoryMap::Free(lldb::addr_t process_address, Error &error) { +void IRMemoryMap::Free(lldb::addr_t process_address, Status &error) { error.Clear(); AllocationMap::iterator iter = m_allocations.find(process_address); @@ -512,7 +512,8 @@ bool IRMemoryMap::GetAllocSize(lldb::addr_t address, size_t &size) { } void IRMemoryMap::WriteMemory(lldb::addr_t process_address, - const uint8_t *bytes, size_t size, Error &error) { + const uint8_t *bytes, size_t size, + Status &error) { error.Clear(); AllocationMap::iterator iter = FindAllocation(process_address, size); @@ -587,7 +588,7 @@ void IRMemoryMap::WriteMemory(lldb::addr_t process_address, void IRMemoryMap::WriteScalarToMemory(lldb::addr_t process_address, Scalar &scalar, size_t size, - Error &error) { + Status &error) { error.Clear(); if (size == UINT32_MAX) @@ -612,7 +613,7 @@ void IRMemoryMap::WriteScalarToMemory(lldb::addr_t process_address, } void IRMemoryMap::WritePointerToMemory(lldb::addr_t process_address, - lldb::addr_t address, Error &error) { + lldb::addr_t address, Status &error) { error.Clear(); Scalar scalar(address); @@ -621,7 +622,7 @@ void IRMemoryMap::WritePointerToMemory(lldb::addr_t process_address, } void IRMemoryMap::ReadMemory(uint8_t *bytes, lldb::addr_t process_address, - size_t size, Error &error) { + size_t size, Status &error) { error.Clear(); AllocationMap::iterator iter = FindAllocation(process_address, size); @@ -717,7 +718,7 @@ void IRMemoryMap::ReadMemory(uint8_t *bytes, lldb::addr_t process_address, void IRMemoryMap::ReadScalarFromMemory(Scalar &scalar, lldb::addr_t process_address, - size_t size, Error &error) { + size_t size, Status &error) { error.Clear(); if (size > 0) { @@ -760,7 +761,7 @@ void IRMemoryMap::ReadScalarFromMemory(Scalar &scalar, void IRMemoryMap::ReadPointerFromMemory(lldb::addr_t *address, lldb::addr_t process_address, - Error &error) { + Status &error) { error.Clear(); Scalar pointer_scalar; @@ -777,7 +778,7 @@ void IRMemoryMap::ReadPointerFromMemory(lldb::addr_t *address, void IRMemoryMap::GetMemoryData(DataExtractor &extractor, lldb::addr_t process_address, size_t size, - Error &error) { + Status &error) { error.Clear(); if (size > 0) { diff --git a/contrib/llvm/tools/lldb/source/Expression/LLVMUserExpression.cpp b/contrib/llvm/tools/lldb/source/Expression/LLVMUserExpression.cpp index 396a7e295033..83acb8249ba6 100644 --- a/contrib/llvm/tools/lldb/source/Expression/LLVMUserExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/LLVMUserExpression.cpp @@ -106,7 +106,7 @@ LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager, return lldb::eExpressionSetupError; } - Error interpreter_error; + Status interpreter_error; std::vector<lldb::addr_t> args; @@ -270,7 +270,7 @@ bool LLVMUserExpression::FinalizeJITExecution( return false; } - Error dematerialize_error; + Status dematerialize_error; m_dematerializer_sp->Dematerialize(dematerialize_error, function_stack_bottom, function_stack_top); @@ -309,7 +309,7 @@ bool LLVMUserExpression::PrepareToExecuteJITExpression( if (m_jit_start_addr != LLDB_INVALID_ADDRESS || m_can_interpret) { if (m_materialized_address == LLDB_INVALID_ADDRESS) { - Error alloc_error; + Status alloc_error; IRMemoryMap::AllocationPolicy policy = m_can_interpret ? IRMemoryMap::eAllocationPolicyHostOnly @@ -335,7 +335,7 @@ bool LLVMUserExpression::PrepareToExecuteJITExpression( struct_address = m_materialized_address; if (m_can_interpret && m_stack_frame_bottom == LLDB_INVALID_ADDRESS) { - Error alloc_error; + Status alloc_error; const size_t stack_frame_size = 512 * 1024; @@ -357,7 +357,7 @@ bool LLVMUserExpression::PrepareToExecuteJITExpression( } } - Error materialize_error; + Status materialize_error; m_dematerializer_sp = m_materializer_ap->Materialize( frame, *m_execution_unit_sp, struct_address, materialize_error); diff --git a/contrib/llvm/tools/lldb/source/Expression/Materializer.cpp b/contrib/llvm/tools/lldb/source/Expression/Materializer.cpp index 8a22daa5acdd..39fc5c8c2539 100644 --- a/contrib/llvm/tools/lldb/source/Expression/Materializer.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/Materializer.cpp @@ -74,12 +74,12 @@ public: m_alignment = 8; } - void MakeAllocation(IRMemoryMap &map, Error &err) { + void MakeAllocation(IRMemoryMap &map, Status &err) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); // Allocate a spare memory area to store the persistent variable's contents. - Error allocate_error; + Status allocate_error; const bool zero_memory = false; lldb::addr_t mem = map.Malloc( @@ -112,7 +112,7 @@ public: if (m_persistent_variable_sp->m_flags & ExpressionVariable::EVKeepInTarget) { - Error leak_error; + Status leak_error; map.Leak(mem, leak_error); m_persistent_variable_sp->m_flags &= ~ExpressionVariable::EVNeedsAllocation; @@ -120,7 +120,7 @@ public: // Write the contents of the variable to the area. - Error write_error; + Status write_error; map.WriteMemory(mem, m_persistent_variable_sp->GetValueBytes(), m_persistent_variable_sp->GetByteSize(), write_error); @@ -134,8 +134,8 @@ public: } } - void DestroyAllocation(IRMemoryMap &map, Error &err) { - Error deallocate_error; + void DestroyAllocation(IRMemoryMap &map, Status &err) { + Status deallocate_error; map.Free((lldb::addr_t)m_persistent_variable_sp->m_live_sp->GetValue() .GetScalar() @@ -153,7 +153,7 @@ public: } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) override { + lldb::addr_t process_address, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -181,7 +181,7 @@ public: m_persistent_variable_sp->m_live_sp) || m_persistent_variable_sp->m_flags & ExpressionVariable::EVIsLLDBAllocated) { - Error write_error; + Status write_error; map.WriteScalarToMemory( load_addr, @@ -204,7 +204,7 @@ public: void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) override { + lldb::addr_t frame_bottom, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -234,7 +234,7 @@ public: // live variable data hasn't been set up yet. Do this now. lldb::addr_t location; - Error read_error; + Status read_error; map.ReadPointerFromMemory(&location, load_addr, read_error); @@ -304,7 +304,7 @@ public: m_persistent_variable_sp->ValueUpdated(); - Error read_error; + Status read_error; map.ReadMemory(m_persistent_variable_sp->GetValueBytes(), mem, m_persistent_variable_sp->GetByteSize(), read_error); @@ -353,7 +353,7 @@ public: Log *log) override { StreamString dump_stream; - Error err; + Status err; const lldb::addr_t load_addr = process_address + m_offset; @@ -416,7 +416,7 @@ private: uint32_t Materializer::AddPersistentVariable( lldb::ExpressionVariableSP &persistent_variable_sp, - PersistentVariableDelegate *delegate, Error &err) { + PersistentVariableDelegate *delegate, Status &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityPersistentVariable(persistent_variable_sp, delegate)); uint32_t ret = AddStructMember(**iter); @@ -439,7 +439,7 @@ public: } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) override { + lldb::addr_t process_address, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -464,7 +464,7 @@ public: return; } - Error valobj_error = valobj_sp->GetError(); + Status valobj_error = valobj_sp->GetError(); if (valobj_error.Fail()) { err.SetErrorStringWithFormat("couldn't get the value of variable %s: %s", @@ -475,7 +475,7 @@ public: if (m_is_reference) { DataExtractor valobj_extractor; - Error extract_error; + Status extract_error; valobj_sp->GetData(valobj_extractor, extract_error); if (!extract_error.Success()) { @@ -488,7 +488,7 @@ public: lldb::offset_t offset = 0; lldb::addr_t reference_addr = valobj_extractor.GetAddress(&offset); - Error write_error; + Status write_error; map.WritePointerToMemory(load_addr, reference_addr, write_error); if (!write_error.Success()) { @@ -504,7 +504,7 @@ public: lldb::addr_t addr_of_valobj = valobj_sp->GetAddressOf(scalar_is_load_address, &address_type); if (addr_of_valobj != LLDB_INVALID_ADDRESS) { - Error write_error; + Status write_error; map.WritePointerToMemory(load_addr, addr_of_valobj, write_error); if (!write_error.Success()) { @@ -515,7 +515,7 @@ public: } } else { DataExtractor data; - Error extract_error; + Status extract_error; valobj_sp->GetData(data, extract_error); if (!extract_error.Success()) { err.SetErrorStringWithFormat("couldn't get the value of %s: %s", @@ -554,7 +554,7 @@ public: if (!byte_align) byte_align = 1; - Error alloc_error; + Status alloc_error; const bool zero_memory = false; m_temporary_allocation = map.Malloc( @@ -574,7 +574,7 @@ public: return; } - Error write_error; + Status write_error; map.WriteMemory(m_temporary_allocation, data.GetDataStart(), data.GetByteSize(), write_error); @@ -586,7 +586,7 @@ public: return; } - Error pointer_write_error; + Status pointer_write_error; map.WritePointerToMemory(load_addr, m_temporary_allocation, pointer_write_error); @@ -603,7 +603,7 @@ public: void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) override { + lldb::addr_t frame_bottom, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -631,7 +631,7 @@ public: lldb_private::DataExtractor data; - Error extract_error; + Status extract_error; map.GetMemoryData(data, m_temporary_allocation, valobj_sp->GetByteSize(), extract_error); @@ -652,7 +652,7 @@ public: } } - Error set_error; + Status set_error; if (actually_write) { valobj_sp->SetData(data, set_error); @@ -665,7 +665,7 @@ public: } } - Error free_error; + Status free_error; map.Free(m_temporary_allocation, free_error); @@ -689,7 +689,7 @@ public: const lldb::addr_t load_addr = process_address + m_offset; dump_stream.Printf("0x%" PRIx64 ": EntityVariable\n", load_addr); - Error err; + Status err; lldb::addr_t ptr = LLDB_INVALID_ADDRESS; @@ -746,7 +746,7 @@ public: void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override { if (m_temporary_allocation != LLDB_INVALID_ADDRESS) { - Error free_error; + Status free_error; map.Free(m_temporary_allocation, free_error); @@ -763,7 +763,7 @@ private: lldb::DataBufferSP m_original_data; }; -uint32_t Materializer::AddVariable(lldb::VariableSP &variable_sp, Error &err) { +uint32_t Materializer::AddVariable(lldb::VariableSP &variable_sp, Status &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityVariable(variable_sp)); uint32_t ret = AddStructMember(**iter); @@ -787,7 +787,7 @@ public: } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) override { + lldb::addr_t process_address, Status &err) override { if (!m_is_program_reference) { if (m_temporary_allocation != LLDB_INVALID_ADDRESS) { err.SetErrorString("Trying to create a temporary region for the result " @@ -806,7 +806,7 @@ public: if (!byte_align) byte_align = 1; - Error alloc_error; + Status alloc_error; const bool zero_memory = true; m_temporary_allocation = map.Malloc( @@ -822,7 +822,7 @@ public: return; } - Error pointer_write_error; + Status pointer_write_error; map.WritePointerToMemory(load_addr, m_temporary_allocation, pointer_write_error); @@ -837,7 +837,7 @@ public: void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) override { + lldb::addr_t frame_bottom, Status &err) override { err.Clear(); ExecutionContextScope *exe_scope = map.GetBestExecutionContextScope(); @@ -849,7 +849,7 @@ public: } lldb::addr_t address; - Error read_error; + Status read_error; const lldb::addr_t load_addr = process_address + m_offset; map.ReadPointerFromMemory(&address, load_addr, read_error); @@ -867,7 +867,7 @@ public: return; } - Error type_system_error; + Status type_system_error; TypeSystem *type_system = target_sp->GetScratchTypeSystemForLanguage( &type_system_error, m_type.GetMinimumLanguage()); @@ -937,7 +937,7 @@ public: ret->m_flags |= ExpressionVariable::EVNeedsAllocation; if (m_temporary_allocation != LLDB_INVALID_ADDRESS) { - Error free_error; + Status free_error; map.Free(m_temporary_allocation, free_error); } } else { @@ -956,7 +956,7 @@ public: dump_stream.Printf("0x%" PRIx64 ": EntityResultVariable\n", load_addr); - Error err; + Status err; lldb::addr_t ptr = LLDB_INVALID_ADDRESS; @@ -1013,7 +1013,7 @@ public: void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override { if (!m_keep_in_memory && m_temporary_allocation != LLDB_INVALID_ADDRESS) { - Error free_error; + Status free_error; map.Free(m_temporary_allocation, free_error); } @@ -1036,7 +1036,7 @@ uint32_t Materializer::AddResultVariable(const CompilerType &type, bool is_program_reference, bool keep_in_memory, PersistentVariableDelegate *delegate, - Error &err) { + Status &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityResultVariable(type, is_program_reference, keep_in_memory, delegate)); @@ -1054,7 +1054,7 @@ public: } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) override { + lldb::addr_t process_address, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -1086,7 +1086,7 @@ public: if (resolved_address == LLDB_INVALID_ADDRESS) resolved_address = sym_address.GetFileAddress(); - Error pointer_write_error; + Status pointer_write_error; map.WritePointerToMemory(load_addr, resolved_address, pointer_write_error); @@ -1100,7 +1100,7 @@ public: void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) override { + lldb::addr_t frame_bottom, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -1118,7 +1118,7 @@ public: Log *log) override { StreamString dump_stream; - Error err; + Status err; const lldb::addr_t load_addr = process_address + m_offset; @@ -1151,7 +1151,7 @@ private: Symbol m_symbol; }; -uint32_t Materializer::AddSymbol(const Symbol &symbol_sp, Error &err) { +uint32_t Materializer::AddSymbol(const Symbol &symbol_sp, Status &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntitySymbol(symbol_sp)); uint32_t ret = AddStructMember(**iter); @@ -1169,7 +1169,7 @@ public: } void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &err) override { + lldb::addr_t process_address, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -1216,7 +1216,7 @@ public: m_register_contents.reset(new DataBufferHeap(register_data.GetDataStart(), register_data.GetByteSize())); - Error write_error; + Status write_error; map.WriteMemory(load_addr, register_data.GetDataStart(), register_data.GetByteSize(), write_error); @@ -1231,7 +1231,7 @@ public: void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, lldb::addr_t process_address, lldb::addr_t frame_top, - lldb::addr_t frame_bottom, Error &err) override { + lldb::addr_t frame_bottom, Status &err) override { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const lldb::addr_t load_addr = process_address + m_offset; @@ -1242,7 +1242,7 @@ public: (uint64_t)load_addr, m_register_info.name); } - Error extract_error; + Status extract_error; DataExtractor register_data; @@ -1291,7 +1291,7 @@ public: Log *log) override { StreamString dump_stream; - Error err; + Status err; const lldb::addr_t load_addr = process_address + m_offset; @@ -1326,7 +1326,7 @@ private: }; uint32_t Materializer::AddRegister(const RegisterInfo ®ister_info, - Error &err) { + Status &err) { EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP()); iter->reset(new EntityRegister(register_info)); uint32_t ret = AddStructMember(**iter); @@ -1346,7 +1346,7 @@ Materializer::~Materializer() { Materializer::DematerializerSP Materializer::Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, - lldb::addr_t process_address, Error &error) { + lldb::addr_t process_address, Status &error) { ExecutionContextScope *exe_scope = frame_sp.get(); if (!exe_scope) @@ -1389,7 +1389,7 @@ Materializer::Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map, return ret; } -void Materializer::Dematerializer::Dematerialize(Error &error, +void Materializer::Dematerializer::Dematerialize(Status &error, lldb::addr_t frame_bottom, lldb::addr_t frame_top) { lldb::StackFrameSP frame_sp; diff --git a/contrib/llvm/tools/lldb/source/Expression/REPL.cpp b/contrib/llvm/tools/lldb/source/Expression/REPL.cpp index e404537562b7..84a6405f3268 100644 --- a/contrib/llvm/tools/lldb/source/Expression/REPL.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/REPL.cpp @@ -42,7 +42,7 @@ REPL::REPL(LLVMCastKind kind, Target &target) : m_target(target), m_kind(kind) { REPL::~REPL() = default; -lldb::REPLSP REPL::Create(Error &err, lldb::LanguageType language, +lldb::REPLSP REPL::Create(Status &err, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options) { uint32_t idx = 0; @@ -309,7 +309,7 @@ void REPL::IOHandlerInputComplete(IOHandler &io_handler, std::string &code) { const char *expr_prefix = nullptr; lldb::ValueObjectSP result_valobj_sp; - Error error; + Status error; lldb::ModuleSP jit_module_sp; lldb::ExpressionResults execution_results = UserExpression::Evaluate(exe_ctx, expr_options, code.c_str(), @@ -518,8 +518,8 @@ bool QuitCommandOverrideCallback(void *baton, const char **argv) { return false; } -Error REPL::RunLoop() { - Error error; +Status REPL::RunLoop() { + Status error; error = DoInitialization(); m_repl_source_path = GetSourcePath(); diff --git a/contrib/llvm/tools/lldb/source/Expression/UserExpression.cpp b/contrib/llvm/tools/lldb/source/Expression/UserExpression.cpp index c7cf106e19df..3386bc4577ae 100644 --- a/contrib/llvm/tools/lldb/source/Expression/UserExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/UserExpression.cpp @@ -101,7 +101,7 @@ bool UserExpression::MatchesContext(ExecutionContext &exe_ctx) { lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp, ConstString &object_name, - Error &err) { + Status &err) { err.Clear(); if (!frame_sp) { @@ -140,7 +140,7 @@ lldb::addr_t UserExpression::GetObjectPointer(lldb::StackFrameSP frame_sp, lldb::ExpressionResults UserExpression::Evaluate( ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr, llvm::StringRef prefix, - lldb::ValueObjectSP &result_valobj_sp, Error &error, uint32_t line_offset, + lldb::ValueObjectSP &result_valobj_sp, Status &error, uint32_t line_offset, std::string *fixed_expression, lldb::ModuleSP *jit_module_sp_ptr) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP)); diff --git a/contrib/llvm/tools/lldb/source/Expression/UtilityFunction.cpp b/contrib/llvm/tools/lldb/source/Expression/UtilityFunction.cpp index 6772fd18ac5b..52f3bfc4d128 100644 --- a/contrib/llvm/tools/lldb/source/Expression/UtilityFunction.cpp +++ b/contrib/llvm/tools/lldb/source/Expression/UtilityFunction.cpp @@ -65,7 +65,7 @@ UtilityFunction::~UtilityFunction() { FunctionCaller *UtilityFunction::MakeFunctionCaller( const CompilerType &return_type, const ValueList &arg_value_list, - lldb::ThreadSP thread_to_use_sp, Error &error) { + lldb::ThreadSP thread_to_use_sp, Status &error) { if (m_caller_up) return m_caller_up.get(); diff --git a/contrib/llvm/tools/lldb/source/Host/common/Editline.cpp b/contrib/llvm/tools/lldb/source/Host/common/Editline.cpp index 851287e76331..7d4b398a171d 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Editline.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Editline.cpp @@ -14,10 +14,10 @@ #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/Editline.h" #include "lldb/Host/Host.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/SelectHelper.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringList.h" #include "lldb/Utility/Timeout.h" diff --git a/contrib/llvm/tools/lldb/source/Host/common/File.cpp b/contrib/llvm/tools/lldb/source/Host/common/File.cpp index 1869a6db49c9..3de93ebc220b 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/File.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/File.cpp @@ -157,8 +157,8 @@ void File::SetStream(FILE *fh, bool transfer_ownership) { m_own_stream = transfer_ownership; } -Error File::Open(const char *path, uint32_t options, uint32_t permissions) { - Error error; +Status File::Open(const char *path, uint32_t options, uint32_t permissions) { + Status error; if (IsValid()) Close(); @@ -246,20 +246,20 @@ Error File::Open(const char *path, uint32_t options, uint32_t permissions) { return error; } -uint32_t File::GetPermissions(const FileSpec &file_spec, Error &error) { +uint32_t File::GetPermissions(const FileSpec &file_spec, Status &error) { if (file_spec) { error.Clear(); auto Perms = llvm::sys::fs::getPermissions(file_spec.GetPath()); if (Perms) return *Perms; - error = Error(Perms.getError()); + error = Status(Perms.getError()); return 0; } else error.SetErrorString("empty file spec"); return 0; } -uint32_t File::GetPermissions(Error &error) const { +uint32_t File::GetPermissions(Status &error) const { int fd = GetDescriptor(); if (fd != kInvalidDescriptor) { struct stat file_stats; @@ -275,8 +275,8 @@ uint32_t File::GetPermissions(Error &error) const { return 0; } -Error File::Close() { - Error error; +Status File::Close() { + Status error; if (StreamIsValid() && m_own_stream) { if (::fclose(m_stream) == EOF) error.SetErrorToErrno(); @@ -305,8 +305,8 @@ void File::Clear() { eLazyBoolCalculate; } -Error File::GetFileSpec(FileSpec &file_spec) const { - Error error; +Status File::GetFileSpec(FileSpec &file_spec) const { + Status error; #ifdef F_GETPATH if (IsValid()) { char path[PATH_MAX]; @@ -340,7 +340,7 @@ Error File::GetFileSpec(FileSpec &file_spec) const { return error; } -off_t File::SeekFromStart(off_t offset, Error *error_ptr) { +off_t File::SeekFromStart(off_t offset, Status *error_ptr) { off_t result = 0; if (DescriptorIsValid()) { result = ::lseek(m_descriptor, offset, SEEK_SET); @@ -366,7 +366,7 @@ off_t File::SeekFromStart(off_t offset, Error *error_ptr) { return result; } -off_t File::SeekFromCurrent(off_t offset, Error *error_ptr) { +off_t File::SeekFromCurrent(off_t offset, Status *error_ptr) { off_t result = -1; if (DescriptorIsValid()) { result = ::lseek(m_descriptor, offset, SEEK_CUR); @@ -392,7 +392,7 @@ off_t File::SeekFromCurrent(off_t offset, Error *error_ptr) { return result; } -off_t File::SeekFromEnd(off_t offset, Error *error_ptr) { +off_t File::SeekFromEnd(off_t offset, Status *error_ptr) { off_t result = -1; if (DescriptorIsValid()) { result = ::lseek(m_descriptor, offset, SEEK_END); @@ -418,8 +418,8 @@ off_t File::SeekFromEnd(off_t offset, Error *error_ptr) { return result; } -Error File::Flush() { - Error error; +Status File::Flush() { + Status error; if (StreamIsValid()) { int err = 0; do { @@ -434,8 +434,8 @@ Error File::Flush() { return error; } -Error File::Sync() { - Error error; +Status File::Sync() { + Status error; if (DescriptorIsValid()) { #ifdef _WIN32 int err = FlushFileBuffers((HANDLE)_get_osfhandle(m_descriptor)); @@ -462,8 +462,8 @@ Error File::Sync() { #define MAX_WRITE_SIZE INT_MAX #endif -Error File::Read(void *buf, size_t &num_bytes) { - Error error; +Status File::Read(void *buf, size_t &num_bytes) { + Status error; #if defined(MAX_READ_SIZE) if (num_bytes > MAX_READ_SIZE) { @@ -524,8 +524,8 @@ Error File::Read(void *buf, size_t &num_bytes) { return error; } -Error File::Write(const void *buf, size_t &num_bytes) { - Error error; +Status File::Write(const void *buf, size_t &num_bytes) { + Status error; #if defined(MAX_WRITE_SIZE) if (num_bytes > MAX_WRITE_SIZE) { @@ -588,8 +588,8 @@ Error File::Write(const void *buf, size_t &num_bytes) { return error; } -Error File::Read(void *buf, size_t &num_bytes, off_t &offset) { - Error error; +Status File::Read(void *buf, size_t &num_bytes, off_t &offset) { + Status error; #if defined(MAX_READ_SIZE) if (num_bytes > MAX_READ_SIZE) { @@ -650,9 +650,9 @@ Error File::Read(void *buf, size_t &num_bytes, off_t &offset) { return error; } -Error File::Read(size_t &num_bytes, off_t &offset, bool null_terminate, - DataBufferSP &data_buffer_sp) { - Error error; +Status File::Read(size_t &num_bytes, off_t &offset, bool null_terminate, + DataBufferSP &data_buffer_sp) { + Status error; if (num_bytes > 0) { int fd = GetDescriptor(); @@ -694,8 +694,8 @@ Error File::Read(size_t &num_bytes, off_t &offset, bool null_terminate, return error; } -Error File::Write(const void *buf, size_t &num_bytes, off_t &offset) { - Error error; +Status File::Write(const void *buf, size_t &num_bytes, off_t &offset) { + Status error; #if defined(MAX_WRITE_SIZE) if (num_bytes > MAX_WRITE_SIZE) { diff --git a/contrib/llvm/tools/lldb/source/Host/common/FileCache.cpp b/contrib/llvm/tools/lldb/source/Host/common/FileCache.cpp index db71813e4ffb..b4629255c852 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/FileCache.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/FileCache.cpp @@ -24,7 +24,7 @@ FileCache &FileCache::GetInstance() { } lldb::user_id_t FileCache::OpenFile(const FileSpec &file_spec, uint32_t flags, - uint32_t mode, Error &error) { + uint32_t mode, Status &error) { std::string path(file_spec.GetPath()); if (path.empty()) { error.SetErrorString("empty path"); @@ -39,7 +39,7 @@ lldb::user_id_t FileCache::OpenFile(const FileSpec &file_spec, uint32_t flags, return fd; } -bool FileCache::CloseFile(lldb::user_id_t fd, Error &error) { +bool FileCache::CloseFile(lldb::user_id_t fd, Status &error) { if (fd == UINT64_MAX) { error.SetErrorString("invalid file descriptor"); return false; @@ -60,7 +60,8 @@ bool FileCache::CloseFile(lldb::user_id_t fd, Error &error) { } uint64_t FileCache::WriteFile(lldb::user_id_t fd, uint64_t offset, - const void *src, uint64_t src_len, Error &error) { + const void *src, uint64_t src_len, + Status &error) { if (fd == UINT64_MAX) { error.SetErrorString("invalid file descriptor"); return UINT64_MAX; @@ -86,7 +87,7 @@ uint64_t FileCache::WriteFile(lldb::user_id_t fd, uint64_t offset, } uint64_t FileCache::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Error &error) { + uint64_t dst_len, Status &error) { if (fd == UINT64_MAX) { error.SetErrorString("invalid file descriptor"); return UINT64_MAX; diff --git a/contrib/llvm/tools/lldb/source/Host/common/Host.cpp b/contrib/llvm/tools/lldb/source/Host/common/Host.cpp index 7754d96ad331..da35022c813c 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Host.cpp @@ -63,9 +63,9 @@ #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/CleanUp.h" #include "lldb/Utility/DataBufferLLVM.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private-forward.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" @@ -484,19 +484,19 @@ MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid, return true; } -Error Host::RunShellCommand(const char *command, const FileSpec &working_dir, - int *status_ptr, int *signo_ptr, - std::string *command_output_ptr, - uint32_t timeout_sec, bool run_in_default_shell) { +Status Host::RunShellCommand(const char *command, const FileSpec &working_dir, + int *status_ptr, int *signo_ptr, + std::string *command_output_ptr, + uint32_t timeout_sec, bool run_in_default_shell) { return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, command_output_ptr, timeout_sec, run_in_default_shell); } -Error Host::RunShellCommand(const Args &args, const FileSpec &working_dir, - int *status_ptr, int *signo_ptr, - std::string *command_output_ptr, - uint32_t timeout_sec, bool run_in_default_shell) { - Error error; +Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, + int *status_ptr, int *signo_ptr, + std::string *command_output_ptr, + uint32_t timeout_sec, bool run_in_default_shell) { + Status error; ProcessLaunchInfo launch_info; launch_info.SetArchitecture(HostInfo::GetArchitecture()); if (run_in_default_shell) { @@ -654,10 +654,10 @@ short Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info) { return flags; } -Error Host::LaunchProcessPosixSpawn(const char *exe_path, - const ProcessLaunchInfo &launch_info, - lldb::pid_t &pid) { - Error error; +Status Host::LaunchProcessPosixSpawn(const char *exe_path, + const ProcessLaunchInfo &launch_info, + lldb::pid_t &pid) { + Status error; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS)); @@ -866,7 +866,7 @@ Error Host::LaunchProcessPosixSpawn(const char *exe_path, } bool Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, - Log *log, Error &error) { + Log *log, Status &error) { if (info == NULL) return false; @@ -947,7 +947,7 @@ bool Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, // The functions below implement process launching via posix_spawn() for Linux, // FreeBSD and NetBSD. -Error Host::LaunchProcess(ProcessLaunchInfo &launch_info) { +Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) { std::unique_ptr<ProcessLauncher> delegate_launcher; #if defined(_WIN32) delegate_launcher.reset(new ProcessLauncherWindows()); @@ -958,7 +958,7 @@ Error Host::LaunchProcess(ProcessLaunchInfo &launch_info) { #endif MonitoringProcessLauncher launcher(std::move(delegate_launcher)); - Error error; + Status error; HostProcess process = launcher.LaunchProcess(launch_info, error); // TODO(zturner): It would be better if the entire HostProcess were returned diff --git a/contrib/llvm/tools/lldb/source/Host/common/HostProcess.cpp b/contrib/llvm/tools/lldb/source/Host/common/HostProcess.cpp index 2d99d8e1fc99..154033321514 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/HostProcess.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/HostProcess.cpp @@ -21,9 +21,9 @@ HostProcess::HostProcess(lldb::process_t process) HostProcess::~HostProcess() {} -Error HostProcess::Terminate() { return m_native_process->Terminate(); } +Status HostProcess::Terminate() { return m_native_process->Terminate(); } -Error HostProcess::GetMainModule(FileSpec &file_spec) const { +Status HostProcess::GetMainModule(FileSpec &file_spec) const { return m_native_process->GetMainModule(file_spec); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/HostThread.cpp b/contrib/llvm/tools/lldb/source/Host/common/HostThread.cpp index 738b7ef72f16..02882c523908 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/HostThread.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/HostThread.cpp @@ -18,11 +18,11 @@ HostThread::HostThread() : m_native_thread(new HostNativeThread) {} HostThread::HostThread(lldb::thread_t thread) : m_native_thread(new HostNativeThread(thread)) {} -Error HostThread::Join(lldb::thread_result_t *result) { +Status HostThread::Join(lldb::thread_result_t *result) { return m_native_thread->Join(result); } -Error HostThread::Cancel() { return m_native_thread->Cancel(); } +Status HostThread::Cancel() { return m_native_thread->Cancel(); } void HostThread::Reset() { return m_native_thread->Reset(); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/LockFileBase.cpp b/contrib/llvm/tools/lldb/source/Host/common/LockFileBase.cpp index b30acc5d5044..a8d7881ab896 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/LockFileBase.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/LockFileBase.cpp @@ -14,9 +14,9 @@ using namespace lldb_private; namespace { -Error AlreadyLocked() { return Error("Already locked"); } +Status AlreadyLocked() { return Status("Already locked"); } -Error NotLocked() { return Error("Not locked"); } +Status NotLocked() { return Status("Not locked"); } } LockFileBase::LockFileBase(int fd) @@ -24,31 +24,31 @@ LockFileBase::LockFileBase(int fd) bool LockFileBase::IsLocked() const { return m_locked; } -Error LockFileBase::WriteLock(const uint64_t start, const uint64_t len) { +Status LockFileBase::WriteLock(const uint64_t start, const uint64_t len) { return DoLock([&](const uint64_t start, const uint64_t len) { return DoWriteLock(start, len); }, start, len); } -Error LockFileBase::TryWriteLock(const uint64_t start, const uint64_t len) { +Status LockFileBase::TryWriteLock(const uint64_t start, const uint64_t len) { return DoLock([&](const uint64_t start, const uint64_t len) { return DoTryWriteLock(start, len); }, start, len); } -Error LockFileBase::ReadLock(const uint64_t start, const uint64_t len) { +Status LockFileBase::ReadLock(const uint64_t start, const uint64_t len) { return DoLock([&](const uint64_t start, const uint64_t len) { return DoReadLock(start, len); }, start, len); } -Error LockFileBase::TryReadLock(const uint64_t start, const uint64_t len) { +Status LockFileBase::TryReadLock(const uint64_t start, const uint64_t len) { return DoLock([&](const uint64_t start, const uint64_t len) { return DoTryReadLock(start, len); }, start, len); } -Error LockFileBase::Unlock() { +Status LockFileBase::Unlock() { if (!IsLocked()) return NotLocked(); @@ -63,10 +63,10 @@ Error LockFileBase::Unlock() { bool LockFileBase::IsValidFile() const { return m_fd != -1; } -Error LockFileBase::DoLock(const Locker &locker, const uint64_t start, - const uint64_t len) { +Status LockFileBase::DoLock(const Locker &locker, const uint64_t start, + const uint64_t len) { if (!IsValidFile()) - return Error("File is invalid"); + return Status("File is invalid"); if (IsLocked()) return AlreadyLocked(); diff --git a/contrib/llvm/tools/lldb/source/Host/common/MainLoop.cpp b/contrib/llvm/tools/lldb/source/Host/common/MainLoop.cpp index abd52f7f46fb..7de6f7fa865d 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/MainLoop.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/MainLoop.cpp @@ -10,13 +10,13 @@ #include "llvm/Config/llvm-config.h" #include "lldb/Host/MainLoop.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include <algorithm> #include <cassert> #include <cerrno> #include <csignal> -#include <vector> #include <time.h> +#include <vector> // Multiplexing is implemented using kqueue on systems that support it (BSD // variants including OSX). On linux we use ppoll, while android uses pselect @@ -73,7 +73,7 @@ public: RunImpl(MainLoop &loop); ~RunImpl() = default; - Error Poll(); + Status Poll(); void ProcessEvents(); private: @@ -100,7 +100,7 @@ MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { in_events.reserve(loop.m_read_fds.size()); } -Error MainLoop::RunImpl::Poll() { +Status MainLoop::RunImpl::Poll() { in_events.resize(loop.m_read_fds.size()); unsigned i = 0; for (auto &fd : loop.m_read_fds) @@ -110,8 +110,8 @@ Error MainLoop::RunImpl::Poll() { out_events, llvm::array_lengthof(out_events), nullptr); if (num_events < 0) - return Error("kevent() failed with error %d\n", num_events); - return Error(); + return Status("kevent() failed with error %d\n", num_events); + return Status(); } void MainLoop::RunImpl::ProcessEvents() { @@ -154,7 +154,7 @@ sigset_t MainLoop::RunImpl::get_sigmask() { } #ifdef FORCE_PSELECT -Error MainLoop::RunImpl::Poll() { +Status MainLoop::RunImpl::Poll() { FD_ZERO(&read_fd_set); int nfds = 0; for (const auto &fd : loop.m_read_fds) { @@ -165,12 +165,12 @@ Error MainLoop::RunImpl::Poll() { sigset_t sigmask = get_sigmask(); if (pselect(nfds, &read_fd_set, nullptr, nullptr, nullptr, &sigmask) == -1 && errno != EINTR) - return Error(errno, eErrorTypePOSIX); + return Status(errno, eErrorTypePOSIX); - return Error(); + return Status(); } #else -Error MainLoop::RunImpl::Poll() { +Status MainLoop::RunImpl::Poll() { read_fds.clear(); sigset_t sigmask = get_sigmask(); @@ -185,9 +185,9 @@ Error MainLoop::RunImpl::Poll() { if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 && errno != EINTR) - return Error(errno, eErrorTypePOSIX); + return Status(errno, eErrorTypePOSIX); - return Error(); + return Status(); } #endif @@ -234,9 +234,9 @@ MainLoop::~MainLoop() { assert(m_signals.size() == 0); } -MainLoop::ReadHandleUP -MainLoop::RegisterReadObject(const IOObjectSP &object_sp, - const Callback &callback, Error &error) { +MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp, + const Callback &callback, + Status &error) { #ifdef LLVM_ON_WIN32 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) { error.SetErrorString("MainLoop: non-socket types unsupported on Windows"); @@ -263,8 +263,7 @@ MainLoop::RegisterReadObject(const IOObjectSP &object_sp, // be unblocked in // the Run() function to check for signal delivery. MainLoop::SignalHandleUP -MainLoop::RegisterSignal(int signo, const Callback &callback, - Error &error) { +MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) { #ifdef SIGNAL_POLLING_UNSUPPORTED error.SetErrorString("Signal polling is not supported on this platform."); return nullptr; @@ -318,7 +317,7 @@ void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) { void MainLoop::UnregisterSignal(int signo) { #if SIGNAL_POLLING_UNSUPPORTED - Error("Signal polling is not supported on this platform."); + Status("Signal polling is not supported on this platform."); #else auto it = m_signals.find(signo); assert(it != m_signals.end()); @@ -344,10 +343,10 @@ void MainLoop::UnregisterSignal(int signo) { #endif } -Error MainLoop::Run() { +Status MainLoop::Run() { m_terminate_request = false; - - Error error; + + Status error; RunImpl impl(*this); // run until termination or until we run out of things to listen to @@ -360,9 +359,9 @@ Error MainLoop::Run() { impl.ProcessEvents(); if (m_terminate_request) - return Error(); + return Status(); } - return Error(); + return Status(); } void MainLoop::ProcessSignal(int signo) { diff --git a/contrib/llvm/tools/lldb/source/Host/common/MonitoringProcessLauncher.cpp b/contrib/llvm/tools/lldb/source/Host/common/MonitoringProcessLauncher.cpp index 2aa6c7f50b66..f1fcd0b44c15 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/MonitoringProcessLauncher.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/MonitoringProcessLauncher.cpp @@ -14,8 +14,8 @@ #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/ProcessLaunchInfo.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/FileSystem.h" @@ -28,7 +28,7 @@ MonitoringProcessLauncher::MonitoringProcessLauncher( HostProcess MonitoringProcessLauncher::LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) { + Status &error) { ProcessLaunchInfo resolved_info(launch_info); error.Clear(); diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpoint.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpoint.cpp index 8a3ee72179c3..5eee3de482c1 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpoint.cpp @@ -9,8 +9,8 @@ #include "lldb/Host/common/NativeBreakpoint.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-defines.h" using namespace lldb_private; @@ -44,7 +44,7 @@ int32_t NativeBreakpoint::DecRef() { return m_ref_count; } -Error NativeBreakpoint::Enable() { +Status NativeBreakpoint::Enable() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (m_enabled) { @@ -53,7 +53,7 @@ Error NativeBreakpoint::Enable() { log->Printf("NativeBreakpoint::%s addr = 0x%" PRIx64 " already enabled, ignoring.", __FUNCTION__, m_addr); - return Error(); + return Status(); } // Log and enable. @@ -61,7 +61,7 @@ Error NativeBreakpoint::Enable() { log->Printf("NativeBreakpoint::%s addr = 0x%" PRIx64 " enabling...", __FUNCTION__, m_addr); - Error error = DoEnable(); + Status error = DoEnable(); if (error.Success()) { m_enabled = true; if (log) @@ -76,7 +76,7 @@ Error NativeBreakpoint::Enable() { return error; } -Error NativeBreakpoint::Disable() { +Status NativeBreakpoint::Disable() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (!m_enabled) { @@ -85,7 +85,7 @@ Error NativeBreakpoint::Disable() { log->Printf("NativeBreakpoint::%s addr = 0x%" PRIx64 " already disabled, ignoring.", __FUNCTION__, m_addr); - return Error(); + return Status(); } // Log and disable. @@ -93,7 +93,7 @@ Error NativeBreakpoint::Disable() { log->Printf("NativeBreakpoint::%s addr = 0x%" PRIx64 " disabling...", __FUNCTION__, m_addr); - Error error = DoDisable(); + Status error = DoDisable(); if (error.Success()) { m_enabled = false; if (log) diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpointList.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpointList.cpp index 60608a0bbc55..ce5eb94a8d1f 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpointList.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeBreakpointList.cpp @@ -19,9 +19,9 @@ using namespace lldb_private; NativeBreakpointList::NativeBreakpointList() : m_mutex() {} -Error NativeBreakpointList::AddRef(lldb::addr_t addr, size_t size_hint, - bool hardware, - CreateBreakpointFunc create_func) { +Status NativeBreakpointList::AddRef(lldb::addr_t addr, size_t size_hint, + bool hardware, + CreateBreakpointFunc create_func) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64 @@ -40,7 +40,7 @@ Error NativeBreakpointList::AddRef(lldb::addr_t addr, size_t size_hint, __FUNCTION__, addr); iter->second->AddRef(); - return Error(); + return Status(); } // Create a new breakpoint using the given create func. @@ -51,7 +51,7 @@ Error NativeBreakpointList::AddRef(lldb::addr_t addr, size_t size_hint, __FUNCTION__, addr, size_hint, hardware ? "true" : "false"); NativeBreakpointSP breakpoint_sp; - Error error = create_func(addr, size_hint, hardware, breakpoint_sp); + Status error = create_func(addr, size_hint, hardware, breakpoint_sp); if (error.Fail()) { if (log) log->Printf( @@ -70,8 +70,8 @@ Error NativeBreakpointList::AddRef(lldb::addr_t addr, size_t size_hint, return error; } -Error NativeBreakpointList::DecRef(lldb::addr_t addr) { - Error error; +Status NativeBreakpointList::DecRef(lldb::addr_t addr) { + Status error; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) @@ -142,7 +142,7 @@ Error NativeBreakpointList::DecRef(lldb::addr_t addr) { return error; } -Error NativeBreakpointList::EnableBreakpoint(lldb::addr_t addr) { +Status NativeBreakpointList::EnableBreakpoint(lldb::addr_t addr) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, @@ -157,14 +157,14 @@ Error NativeBreakpointList::EnableBreakpoint(lldb::addr_t addr) { if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64 " -- NOT FOUND", __FUNCTION__, addr); - return Error("breakpoint not found"); + return Status("breakpoint not found"); } // Enable it. return iter->second->Enable(); } -Error NativeBreakpointList::DisableBreakpoint(lldb::addr_t addr) { +Status NativeBreakpointList::DisableBreakpoint(lldb::addr_t addr) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, @@ -179,15 +179,15 @@ Error NativeBreakpointList::DisableBreakpoint(lldb::addr_t addr) { if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64 " -- NOT FOUND", __FUNCTION__, addr); - return Error("breakpoint not found"); + return Status("breakpoint not found"); } // Disable it. return iter->second->Disable(); } -Error NativeBreakpointList::GetBreakpoint(lldb::addr_t addr, - NativeBreakpointSP &breakpoint_sp) { +Status NativeBreakpointList::GetBreakpoint(lldb::addr_t addr, + NativeBreakpointSP &breakpoint_sp) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) log->Printf("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, @@ -200,16 +200,16 @@ Error NativeBreakpointList::GetBreakpoint(lldb::addr_t addr, if (iter == m_breakpoints.end()) { // Not found! breakpoint_sp.reset(); - return Error("breakpoint not found"); + return Status("breakpoint not found"); } // Disable it. breakpoint_sp = iter->second; - return Error(); + return Status(); } -Error NativeBreakpointList::RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, - size_t size) const { +Status NativeBreakpointList::RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, + size_t size) const { for (const auto &map : m_breakpoints) { lldb::addr_t bp_addr = map.first; // Breapoint not in range, ignore @@ -225,5 +225,5 @@ Error NativeBreakpointList::RemoveTrapsFromBuffer(lldb::addr_t addr, void *buf, auto opcode_size = software_bp_sp->m_opcode_size; ::memcpy(opcode_addr, saved_opcodes, opcode_size); } - return Error(); + return Status(); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeProcessProtocol.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeProcessProtocol.cpp index 9d4149d700ba..6f1a9f895b61 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeProcessProtocol.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeProcessProtocol.cpp @@ -36,8 +36,8 @@ NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid) m_delegates_mutex(), m_delegates(), m_breakpoint_list(), m_watchpoint_list(), m_terminal_fd(-1), m_stop_id(0) {} -lldb_private::Error NativeProcessProtocol::Interrupt() { - Error error; +lldb_private::Status NativeProcessProtocol::Interrupt() { + Status error; #if !defined(SIGSTOP) error.SetErrorString("local host does not support signaling"); return error; @@ -46,17 +46,17 @@ lldb_private::Error NativeProcessProtocol::Interrupt() { #endif } -Error NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) { +Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) { m_signals_to_ignore.clear(); m_signals_to_ignore.insert(signals.begin(), signals.end()); - return Error(); + return Status(); } -lldb_private::Error +lldb_private::Status NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) { // Default: not implemented. - return Error("not implemented"); + return Status("not implemented"); } bool NativeProcessProtocol::GetExitStatus(ExitType *exit_type, int *status, @@ -173,9 +173,9 @@ NativeProcessProtocol::GetHardwareDebugSupportInfo() const { reg_ctx_sp->NumSupportedHardwareWatchpoints()); } -Error NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, - uint32_t watch_flags, - bool hardware) { +Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, + uint32_t watch_flags, + bool hardware) { // This default implementation assumes setting the watchpoint for // the process will require setting the watchpoint for each of the // threads. Furthermore, it will track watchpoints set for the @@ -205,7 +205,7 @@ Error NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, if (!thread_sp) continue; - Error thread_error = + Status thread_error = thread_sp->SetWatchpoint(addr, size, watch_flags, hardware); if (thread_error.Fail() && hardware) { // Try software watchpoints since we failed on hardware watchpoint setting @@ -227,7 +227,7 @@ Error NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, // set so that we get back to a consistent state of "not // set" for the watchpoint. for (auto unwatch_thread_sp : watchpoint_established_threads) { - Error remove_error = unwatch_thread_sp->RemoveWatchpoint(addr); + Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr); if (remove_error.Fail() && log) { log->Warning("NativeProcessProtocol::%s (): RemoveWatchpoint failed " "for pid=%" PRIu64 ", tid=%" PRIu64 ": %s", @@ -242,11 +242,11 @@ Error NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, return m_watchpoint_list.Add(addr, size, watch_flags, hardware); } -Error NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { +Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { // Update the thread list UpdateThreads(); - Error overall_error; + Status overall_error; std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); for (auto thread_sp : m_threads) { @@ -254,7 +254,7 @@ Error NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { if (!thread_sp) continue; - const Error thread_error = thread_sp->RemoveWatchpoint(addr); + const Status thread_error = thread_sp->RemoveWatchpoint(addr); if (thread_error.Fail()) { // Keep track of the first thread error if any threads // fail. We want to try to remove the watchpoint from @@ -263,7 +263,7 @@ Error NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { overall_error = thread_error; } } - const Error error = m_watchpoint_list.Remove(addr); + const Status error = m_watchpoint_list.Remove(addr); return overall_error.Fail() ? overall_error : error; } @@ -272,8 +272,8 @@ NativeProcessProtocol::GetHardwareBreakpointMap() const { return m_hw_breakpoints_map; } -Error NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, - size_t size) { +Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, + size_t size) { // This default implementation assumes setting a hardware breakpoint for // this process will require setting same hardware breakpoint for each // of its existing threads. New thread will do the same once created. @@ -287,7 +287,7 @@ Error NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 || hw_debug_cap->first <= m_hw_breakpoints_map.size()) - return Error("Target does not have required no of hardware breakpoints"); + return Status("Target does not have required no of hardware breakpoints"); // Vector below stores all thread pointer for which we have we successfully // set this hardware breakpoint. If any of the current process threads fails @@ -302,7 +302,7 @@ Error NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, if (!thread_sp) continue; - Error thread_error = thread_sp->SetHardwareBreakpoint(addr, size); + Status thread_error = thread_sp->SetHardwareBreakpoint(addr, size); if (thread_error.Success()) { // Remember that we set this breakpoint successfully in // case we need to clear it later. @@ -312,7 +312,8 @@ Error NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, // set so that we get back to a consistent state of "not // set" for this hardware breakpoint. for (auto rollback_thread_sp : breakpoint_established_threads) { - Error remove_error = rollback_thread_sp->RemoveHardwareBreakpoint(addr); + Status remove_error = + rollback_thread_sp->RemoveHardwareBreakpoint(addr); if (remove_error.Fail() && log) { log->Warning("NativeProcessProtocol::%s (): RemoveHardwareBreakpoint" " failed for pid=%" PRIu64 ", tid=%" PRIu64 ": %s", @@ -329,14 +330,14 @@ Error NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, // process. m_hw_breakpoints_map[addr] = {addr, size}; - return Error(); + return Status(); } -Error NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) { +Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) { // Update the thread list UpdateThreads(); - Error error; + Status error; std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); for (auto thread_sp : m_threads) { @@ -413,8 +414,8 @@ void NativeProcessProtocol::NotifyDidExec() { } } -Error NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, - uint32_t size_hint) { +Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, + uint32_t size_hint) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); if (log) log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__, @@ -423,25 +424,25 @@ Error NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, return m_breakpoint_list.AddRef( addr, size_hint, false, [this](lldb::addr_t addr, size_t size_hint, bool /* hardware */, - NativeBreakpointSP &breakpoint_sp) -> Error { + NativeBreakpointSP &breakpoint_sp) -> Status { return SoftwareBreakpoint::CreateSoftwareBreakpoint( *this, addr, size_hint, breakpoint_sp); }); } -Error NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr, - bool hardware) { +Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr, + bool hardware) { if (hardware) return RemoveHardwareBreakpoint(addr); else return m_breakpoint_list.DecRef(addr); } -Error NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) { +Status NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) { return m_breakpoint_list.EnableBreakpoint(addr); } -Error NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) { +Status NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) { return m_breakpoint_list.DisableBreakpoint(addr); } @@ -483,25 +484,26 @@ void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) { // Default implementation does nothing. } -Error NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid, - ArchSpec &arch) { +Status NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid, + ArchSpec &arch) { // Grab process info for the running process. ProcessInstanceInfo process_info; if (!Host::GetProcessInfo(pid, process_info)) - return Error("failed to get process info"); + return Status("failed to get process info"); // Resolve the executable module. ModuleSpecList module_specs; if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs)) - return Error("failed to get module specifications"); + return Status("failed to get module specifications"); lldbassert(module_specs.GetSize() == 1); arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture(); if (arch.IsValid()) - return Error(); + return Status(); else - return Error("failed to retrieve a valid architecture from the exe module"); + return Status( + "failed to retrieve a valid architecture from the exe module"); } #if !defined(__linux__) && !defined(__NetBSD__) @@ -509,17 +511,17 @@ Error NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid, // Stubs are // provided to make the rest of the code link on non-supported platforms. -Error NativeProcessProtocol::Launch(ProcessLaunchInfo &launch_info, - NativeDelegate &native_delegate, - MainLoop &mainloop, - NativeProcessProtocolSP &process_sp) { +Status NativeProcessProtocol::Launch(ProcessLaunchInfo &launch_info, + NativeDelegate &native_delegate, + MainLoop &mainloop, + NativeProcessProtocolSP &process_sp) { llvm_unreachable("Platform has no NativeProcessProtocol support"); } -Error NativeProcessProtocol::Attach(lldb::pid_t pid, - NativeDelegate &native_delegate, - MainLoop &mainloop, - NativeProcessProtocolSP &process_sp) { +Status NativeProcessProtocol::Attach(lldb::pid_t pid, + NativeDelegate &native_delegate, + MainLoop &mainloop, + NativeProcessProtocolSP &process_sp) { llvm_unreachable("Platform has no NativeProcessProtocol support"); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeRegisterContext.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeRegisterContext.cpp index 3bc0a0d9705c..2ca95d707963 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeRegisterContext.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeRegisterContext.cpp @@ -138,7 +138,7 @@ NativeRegisterContext::GetPCfromBreakpointLocation(lldb::addr_t fail_value) { return GetPC(fail_value); } -Error NativeRegisterContext::SetPC(lldb::addr_t pc) { +Status NativeRegisterContext::SetPC(lldb::addr_t pc) { uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); return WriteRegisterFromUnsigned(reg, pc); @@ -150,7 +150,7 @@ lldb::addr_t NativeRegisterContext::GetSP(lldb::addr_t fail_value) { return ReadRegisterAsUnsigned(reg, fail_value); } -Error NativeRegisterContext::SetSP(lldb::addr_t sp) { +Status NativeRegisterContext::SetSP(lldb::addr_t sp) { uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP); return WriteRegisterFromUnsigned(reg, sp); @@ -162,7 +162,7 @@ lldb::addr_t NativeRegisterContext::GetFP(lldb::addr_t fail_value) { return ReadRegisterAsUnsigned(reg, fail_value); } -Error NativeRegisterContext::SetFP(lldb::addr_t fp) { +Status NativeRegisterContext::SetFP(lldb::addr_t fp) { uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP); return WriteRegisterFromUnsigned(reg, fp); @@ -195,7 +195,7 @@ NativeRegisterContext::ReadRegisterAsUnsigned(const RegisterInfo *reg_info, if (reg_info) { RegisterValue value; - Error error = ReadRegister(reg_info, value); + Status error = ReadRegister(reg_info, value); if (error.Success()) { if (log) log->Printf("NativeRegisterContext::%s ReadRegister() succeeded, value " @@ -215,22 +215,23 @@ NativeRegisterContext::ReadRegisterAsUnsigned(const RegisterInfo *reg_info, return fail_value; } -Error NativeRegisterContext::WriteRegisterFromUnsigned(uint32_t reg, - uint64_t uval) { +Status NativeRegisterContext::WriteRegisterFromUnsigned(uint32_t reg, + uint64_t uval) { if (reg == LLDB_INVALID_REGNUM) - return Error("NativeRegisterContext::%s (): reg is invalid", __FUNCTION__); + return Status("NativeRegisterContext::%s (): reg is invalid", __FUNCTION__); return WriteRegisterFromUnsigned(GetRegisterInfoAtIndex(reg), uval); } -Error NativeRegisterContext::WriteRegisterFromUnsigned( - const RegisterInfo *reg_info, uint64_t uval) { +Status +NativeRegisterContext::WriteRegisterFromUnsigned(const RegisterInfo *reg_info, + uint64_t uval) { assert(reg_info); if (!reg_info) - return Error("reg_info is nullptr"); + return Status("reg_info is nullptr"); RegisterValue value; if (!value.SetUInt(uval, reg_info->byte_size)) - return Error("RegisterValue::SetUInt () failed"); + return Status("RegisterValue::SetUInt () failed"); return WriteRegister(reg_info, value); } @@ -246,18 +247,18 @@ uint32_t NativeRegisterContext::SetHardwareBreakpoint(lldb::addr_t addr, return LLDB_INVALID_INDEX32; } -Error NativeRegisterContext::ClearAllHardwareBreakpoints() { - return Error("not implemented"); +Status NativeRegisterContext::ClearAllHardwareBreakpoints() { + return Status("not implemented"); } bool NativeRegisterContext::ClearHardwareBreakpoint(uint32_t hw_idx) { return false; } -Error NativeRegisterContext::GetHardwareBreakHitIndex(uint32_t &bp_index, - lldb::addr_t trap_addr) { +Status NativeRegisterContext::GetHardwareBreakHitIndex(uint32_t &bp_index, + lldb::addr_t trap_addr) { bp_index = LLDB_INVALID_INDEX32; - return Error("not implemented"); + return Status("not implemented"); } uint32_t NativeRegisterContext::NumSupportedHardwareWatchpoints() { return 0; } @@ -272,25 +273,25 @@ bool NativeRegisterContext::ClearHardwareWatchpoint(uint32_t hw_index) { return false; } -Error NativeRegisterContext::ClearAllHardwareWatchpoints() { - return Error("not implemented"); +Status NativeRegisterContext::ClearAllHardwareWatchpoints() { + return Status("not implemented"); } -Error NativeRegisterContext::IsWatchpointHit(uint32_t wp_index, bool &is_hit) { +Status NativeRegisterContext::IsWatchpointHit(uint32_t wp_index, bool &is_hit) { is_hit = false; - return Error("not implemented"); + return Status("not implemented"); } -Error NativeRegisterContext::GetWatchpointHitIndex(uint32_t &wp_index, - lldb::addr_t trap_addr) { +Status NativeRegisterContext::GetWatchpointHitIndex(uint32_t &wp_index, + lldb::addr_t trap_addr) { wp_index = LLDB_INVALID_INDEX32; - return Error("not implemented"); + return Status("not implemented"); } -Error NativeRegisterContext::IsWatchpointVacant(uint32_t wp_index, - bool &is_vacant) { +Status NativeRegisterContext::IsWatchpointVacant(uint32_t wp_index, + bool &is_vacant) { is_vacant = false; - return Error("not implemented"); + return Status("not implemented"); } lldb::addr_t NativeRegisterContext::GetWatchpointAddress(uint32_t wp_index) { @@ -303,10 +304,10 @@ lldb::addr_t NativeRegisterContext::GetWatchpointHitAddress(uint32_t wp_index) { bool NativeRegisterContext::HardwareSingleStep(bool enable) { return false; } -Error NativeRegisterContext::ReadRegisterValueFromMemory( +Status NativeRegisterContext::ReadRegisterValueFromMemory( const RegisterInfo *reg_info, lldb::addr_t src_addr, size_t src_len, RegisterValue ®_value) { - Error error; + Status error; if (reg_info == nullptr) { error.SetErrorString("invalid register info argument."); return error; @@ -321,7 +322,7 @@ Error NativeRegisterContext::ReadRegisterValueFromMemory( // // Case 2: src_len > dst_len // - // Error! (The register should always be big enough to hold the data) + // Status! (The register should always be big enough to hold the data) // // Case 3: src_len < dst_len // @@ -383,13 +384,13 @@ Error NativeRegisterContext::ReadRegisterValueFromMemory( return error; } -Error NativeRegisterContext::WriteRegisterValueToMemory( +Status NativeRegisterContext::WriteRegisterValueToMemory( const RegisterInfo *reg_info, lldb::addr_t dst_addr, size_t dst_len, const RegisterValue ®_value) { uint8_t dst[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; NativeProcessProtocolSP process_sp(m_thread.GetProcess()); if (process_sp) { @@ -400,7 +401,7 @@ Error NativeRegisterContext::WriteRegisterValueToMemory( // they are the same. lldb::ByteOrder byte_order; if (!process_sp->GetByteOrder(byte_order)) - return Error("NativeProcessProtocol::GetByteOrder () failed"); + return Status("NativeProcessProtocol::GetByteOrder () failed"); const size_t bytes_copied = reg_value.GetAsMemoryData(reg_info, dst, dst_len, byte_order, error); diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeThreadProtocol.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeThreadProtocol.cpp index 2e76cff0d670..29e25bbc5692 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeThreadProtocol.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeThreadProtocol.cpp @@ -20,46 +20,46 @@ NativeThreadProtocol::NativeThreadProtocol(NativeProcessProtocol *process, lldb::tid_t tid) : m_process_wp(process->shared_from_this()), m_tid(tid) {} -Error NativeThreadProtocol::ReadRegister(uint32_t reg, - RegisterValue ®_value) { +Status NativeThreadProtocol::ReadRegister(uint32_t reg, + RegisterValue ®_value) { NativeRegisterContextSP register_context_sp = GetRegisterContext(); if (!register_context_sp) - return Error("no register context"); + return Status("no register context"); const RegisterInfo *const reg_info = register_context_sp->GetRegisterInfoAtIndex(reg); if (!reg_info) - return Error("no register info for reg num %" PRIu32, reg); + return Status("no register info for reg num %" PRIu32, reg); return register_context_sp->ReadRegister(reg_info, reg_value); ; } -Error NativeThreadProtocol::WriteRegister(uint32_t reg, - const RegisterValue ®_value) { +Status NativeThreadProtocol::WriteRegister(uint32_t reg, + const RegisterValue ®_value) { NativeRegisterContextSP register_context_sp = GetRegisterContext(); if (!register_context_sp) - return Error("no register context"); + return Status("no register context"); const RegisterInfo *const reg_info = register_context_sp->GetRegisterInfoAtIndex(reg); if (!reg_info) - return Error("no register info for reg num %" PRIu32, reg); + return Status("no register info for reg num %" PRIu32, reg); return register_context_sp->WriteRegister(reg_info, reg_value); } -Error NativeThreadProtocol::SaveAllRegisters(lldb::DataBufferSP &data_sp) { +Status NativeThreadProtocol::SaveAllRegisters(lldb::DataBufferSP &data_sp) { NativeRegisterContextSP register_context_sp = GetRegisterContext(); if (!register_context_sp) - return Error("no register context"); + return Status("no register context"); return register_context_sp->WriteAllRegisterValues(data_sp); } -Error NativeThreadProtocol::RestoreAllRegisters(lldb::DataBufferSP &data_sp) { +Status NativeThreadProtocol::RestoreAllRegisters(lldb::DataBufferSP &data_sp) { NativeRegisterContextSP register_context_sp = GetRegisterContext(); if (!register_context_sp) - return Error("no register context"); + return Status("no register context"); return register_context_sp->ReadAllRegisterValues(data_sp); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/NativeWatchpointList.cpp b/contrib/llvm/tools/lldb/source/Host/common/NativeWatchpointList.cpp index 168e5b42b961..e6ef7300eb22 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/NativeWatchpointList.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/NativeWatchpointList.cpp @@ -14,15 +14,15 @@ using namespace lldb; using namespace lldb_private; -Error NativeWatchpointList::Add(addr_t addr, size_t size, uint32_t watch_flags, - bool hardware) { +Status NativeWatchpointList::Add(addr_t addr, size_t size, uint32_t watch_flags, + bool hardware) { m_watchpoints[addr] = {addr, size, watch_flags, hardware}; - return Error(); + return Status(); } -Error NativeWatchpointList::Remove(addr_t addr) { +Status NativeWatchpointList::Remove(addr_t addr) { m_watchpoints.erase(addr); - return Error(); + return Status(); } const NativeWatchpointList::WatchpointMap & diff --git a/contrib/llvm/tools/lldb/source/Host/common/PipeBase.cpp b/contrib/llvm/tools/lldb/source/Host/common/PipeBase.cpp index cf7e6c97c3c3..632bfcb3a2e0 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/PipeBase.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/PipeBase.cpp @@ -13,12 +13,13 @@ using namespace lldb_private; PipeBase::~PipeBase() = default; -Error PipeBase::OpenAsWriter(llvm::StringRef name, bool child_process_inherit) { +Status PipeBase::OpenAsWriter(llvm::StringRef name, + bool child_process_inherit) { return OpenAsWriterWithTimeout(name, child_process_inherit, std::chrono::microseconds::zero()); } -Error PipeBase::Read(void *buf, size_t size, size_t &bytes_read) { +Status PipeBase::Read(void *buf, size_t size, size_t &bytes_read) { return ReadWithTimeout(buf, size, std::chrono::microseconds::zero(), bytes_read); } diff --git a/contrib/llvm/tools/lldb/source/Host/common/Socket.cpp b/contrib/llvm/tools/lldb/source/Host/common/Socket.cpp index d73b5d0ad073..0df9dc02c70f 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Socket.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Socket.cpp @@ -79,7 +79,7 @@ Socket::~Socket() { Close(); } std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, bool child_processes_inherit, - Error &error) { + Status &error) { error.Clear(); std::unique_ptr<Socket> socket_up; @@ -118,14 +118,14 @@ std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, return socket_up; } -Error Socket::TcpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket) { +Status Socket::TcpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data()); - Error error; + Status error; std::unique_ptr<Socket> connect_socket( Create(ProtocolTcp, child_processes_inherit, error)); if (error.Fail()) @@ -138,14 +138,14 @@ Error Socket::TcpConnect(llvm::StringRef host_and_port, return error; } -Error Socket::TcpListen(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket, - Predicate<uint16_t> *predicate, int backlog) { +Status Socket::TcpListen(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket, + Predicate<uint16_t> *predicate, int backlog) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data()); - Error error; + Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; @@ -179,8 +179,8 @@ Error Socket::TcpListen(llvm::StringRef host_and_port, return error; } -Error Socket::UdpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket) { +Status Socket::UdpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit, Socket *&socket) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, @@ -189,9 +189,10 @@ Error Socket::UdpConnect(llvm::StringRef host_and_port, return UDPSocket::Connect(host_and_port, child_processes_inherit, socket); } -Error Socket::UnixDomainConnect(llvm::StringRef name, - bool child_processes_inherit, Socket *&socket) { - Error error; +Status Socket::UnixDomainConnect(llvm::StringRef name, + bool child_processes_inherit, + Socket *&socket) { + Status error; std::unique_ptr<Socket> connect_socket( Create(ProtocolUnixDomain, child_processes_inherit, error)); if (error.Fail()) @@ -204,9 +205,9 @@ Error Socket::UnixDomainConnect(llvm::StringRef name, return error; } -Error Socket::UnixDomainAccept(llvm::StringRef name, - bool child_processes_inherit, Socket *&socket) { - Error error; +Status Socket::UnixDomainAccept(llvm::StringRef name, + bool child_processes_inherit, Socket *&socket) { + Status error; std::unique_ptr<Socket> listen_socket( Create(ProtocolUnixDomain, child_processes_inherit, error)); if (error.Fail()) @@ -220,10 +221,10 @@ Error Socket::UnixDomainAccept(llvm::StringRef name, return error; } -Error Socket::UnixAbstractConnect(llvm::StringRef name, - bool child_processes_inherit, - Socket *&socket) { - Error error; +Status Socket::UnixAbstractConnect(llvm::StringRef name, + bool child_processes_inherit, + Socket *&socket) { + Status error; std::unique_ptr<Socket> connect_socket( Create(ProtocolUnixAbstract, child_processes_inherit, error)); if (error.Fail()) @@ -235,10 +236,10 @@ Error Socket::UnixAbstractConnect(llvm::StringRef name, return error; } -Error Socket::UnixAbstractAccept(llvm::StringRef name, - bool child_processes_inherit, - Socket *&socket) { - Error error; +Status Socket::UnixAbstractAccept(llvm::StringRef name, + bool child_processes_inherit, + Socket *&socket) { + Status error; std::unique_ptr<Socket> listen_socket( Create(ProtocolUnixAbstract, child_processes_inherit, error)); if (error.Fail()) @@ -254,7 +255,7 @@ Error Socket::UnixAbstractAccept(llvm::StringRef name, bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port, std::string &host_str, std::string &port_str, - int32_t &port, Error *error_ptr) { + int32_t &port, Status *error_ptr) { static RegularExpression g_regex( llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)")); RegularExpression::Match regex_match(2); @@ -304,8 +305,8 @@ IOObject::WaitableHandle Socket::GetWaitableHandle() { return m_socket; } -Error Socket::Read(void *buf, size_t &num_bytes) { - Error error; +Status Socket::Read(void *buf, size_t &num_bytes) { + Status error; int bytes_received = 0; do { bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0); @@ -330,8 +331,8 @@ Error Socket::Read(void *buf, size_t &num_bytes) { return error; } -Error Socket::Write(const void *buf, size_t &num_bytes) { - Error error; +Status Socket::Write(const void *buf, size_t &num_bytes) { + Status error; int bytes_sent = 0; do { bytes_sent = Send(buf, num_bytes); @@ -356,13 +357,13 @@ Error Socket::Write(const void *buf, size_t &num_bytes) { return error; } -Error Socket::PreDisconnect() { - Error error; +Status Socket::PreDisconnect() { + Status error; return error; } -Error Socket::Close() { - Error error; +Status Socket::Close() { + Status error; if (!IsValid() || !m_should_close_fd) return error; @@ -404,7 +405,7 @@ size_t Socket::Send(const void *buf, const size_t num_bytes) { return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0); } -void Socket::SetLastError(Error &error) { +void Socket::SetLastError(Status &error) { #if defined(_WIN32) error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32); #else @@ -414,7 +415,7 @@ void Socket::SetLastError(Error &error) { NativeSocket Socket::CreateSocket(const int domain, const int type, const int protocol, - bool child_processes_inherit, Error &error) { + bool child_processes_inherit, Status &error) { error.Clear(); auto socket_type = type; #ifdef SOCK_CLOEXEC @@ -430,7 +431,7 @@ NativeSocket Socket::CreateSocket(const int domain, const int type, NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, - bool child_processes_inherit, Error &error) { + bool child_processes_inherit, Status &error) { error.Clear(); #if defined(ANDROID_USE_ACCEPT_WORKAROUND) // Hack: diff --git a/contrib/llvm/tools/lldb/source/Host/common/SoftwareBreakpoint.cpp b/contrib/llvm/tools/lldb/source/Host/common/SoftwareBreakpoint.cpp index 436cb2bb112e..14dbafd94c03 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/SoftwareBreakpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/SoftwareBreakpoint.cpp @@ -10,8 +10,8 @@ #include "lldb/Host/common/SoftwareBreakpoint.h" #include "lldb/Host/Debug.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Host/common/NativeProcessProtocol.h" @@ -21,7 +21,7 @@ using namespace lldb_private; // static members // ------------------------------------------------------------------- -Error SoftwareBreakpoint::CreateSoftwareBreakpoint( +Status SoftwareBreakpoint::CreateSoftwareBreakpoint( NativeProcessProtocol &process, lldb::addr_t addr, size_t size_hint, NativeBreakpointSP &breakpoint_sp) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); @@ -30,15 +30,15 @@ Error SoftwareBreakpoint::CreateSoftwareBreakpoint( // Validate the address. if (addr == LLDB_INVALID_ADDRESS) - return Error("SoftwareBreakpoint::%s invalid load address specified.", - __FUNCTION__); + return Status("SoftwareBreakpoint::%s invalid load address specified.", + __FUNCTION__); // Ask the NativeProcessProtocol subclass to fill in the correct software // breakpoint // trap for the breakpoint site. size_t bp_opcode_size = 0; const uint8_t *bp_opcode_bytes = NULL; - Error error = process.GetSoftwareBreakpointTrapOpcode( + Status error = process.GetSoftwareBreakpointTrapOpcode( size_hint, bp_opcode_size, bp_opcode_bytes); if (error.Fail()) { @@ -54,10 +54,10 @@ Error SoftwareBreakpoint::CreateSoftwareBreakpoint( if (log) log->Printf("SoftwareBreakpoint::%s failed to retrieve any trap opcodes", __FUNCTION__); - return Error("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " - "returned zero, unable to get breakpoint trap for address " - "0x%" PRIx64, - addr); + return Status("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " + "returned zero, unable to get breakpoint trap for address " + "0x%" PRIx64, + addr); } if (bp_opcode_size > MAX_TRAP_OPCODE_SIZE) { @@ -65,10 +65,10 @@ Error SoftwareBreakpoint::CreateSoftwareBreakpoint( log->Printf("SoftwareBreakpoint::%s cannot support %zu trapcode bytes, " "max size is %zu", __FUNCTION__, bp_opcode_size, MAX_TRAP_OPCODE_SIZE); - return Error("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " - "returned too many trap opcode bytes: requires %zu but we " - "only support a max of %zu", - bp_opcode_size, MAX_TRAP_OPCODE_SIZE); + return Status("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " + "returned too many trap opcode bytes: requires %zu but we " + "only support a max of %zu", + bp_opcode_size, MAX_TRAP_OPCODE_SIZE); } // Validate that we received opcodes. @@ -76,10 +76,10 @@ Error SoftwareBreakpoint::CreateSoftwareBreakpoint( if (log) log->Printf("SoftwareBreakpoint::%s failed to retrieve trap opcode bytes", __FUNCTION__); - return Error("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " - "returned NULL trap opcode bytes, unable to get breakpoint " - "trap for address 0x%" PRIx64, - addr); + return Status("SoftwareBreakpoint::GetSoftwareBreakpointTrapOpcode() " + "returned NULL trap opcode bytes, unable to get breakpoint " + "trap for address 0x%" PRIx64, + addr); } // Enable the breakpoint. @@ -103,10 +103,10 @@ Error SoftwareBreakpoint::CreateSoftwareBreakpoint( // breakpoint. breakpoint_sp.reset(new SoftwareBreakpoint(process, addr, saved_opcode_bytes, bp_opcode_bytes, bp_opcode_size)); - return Error(); + return Status(); } -Error SoftwareBreakpoint::EnableSoftwareBreakpoint( +Status SoftwareBreakpoint::EnableSoftwareBreakpoint( NativeProcessProtocol &process, lldb::addr_t addr, size_t bp_opcode_size, const uint8_t *bp_opcode_bytes, uint8_t *saved_opcode_bytes) { assert(bp_opcode_size <= MAX_TRAP_OPCODE_SIZE && @@ -121,7 +121,7 @@ Error SoftwareBreakpoint::EnableSoftwareBreakpoint( // Save the original opcodes by reading them so we can restore later. size_t bytes_read = 0; - Error error = + Status error = process.ReadMemory(addr, saved_opcode_bytes, bp_opcode_size, bytes_read); if (error.Fail()) { if (log) @@ -138,10 +138,10 @@ Error SoftwareBreakpoint::EnableSoftwareBreakpoint( "attempting to set breakpoint: attempted to read %zu bytes " "but only read %zu", __FUNCTION__, bp_opcode_size, bytes_read); - return Error("SoftwareBreakpoint::%s failed to read memory while " - "attempting to set breakpoint: attempted to read %zu bytes " - "but only read %zu", - __FUNCTION__, bp_opcode_size, bytes_read); + return Status("SoftwareBreakpoint::%s failed to read memory while " + "attempting to set breakpoint: attempted to read %zu bytes " + "but only read %zu", + __FUNCTION__, bp_opcode_size, bytes_read); } // Log what we read. @@ -197,10 +197,11 @@ Error SoftwareBreakpoint::EnableSoftwareBreakpoint( "attempting to verify breakpoint: attempted to read %zu " "bytes but only read %zu", __FUNCTION__, bp_opcode_size, verify_bytes_read); - return Error("SoftwareBreakpoint::%s failed to read memory while " - "attempting to verify breakpoint: attempted to read %zu bytes " - "but only read %zu", - __FUNCTION__, bp_opcode_size, verify_bytes_read); + return Status( + "SoftwareBreakpoint::%s failed to read memory while " + "attempting to verify breakpoint: attempted to read %zu bytes " + "but only read %zu", + __FUNCTION__, bp_opcode_size, verify_bytes_read); } if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) != 0) { @@ -209,17 +210,17 @@ Error SoftwareBreakpoint::EnableSoftwareBreakpoint( "writing failed - trap opcodes not successfully read back " "after writing when setting breakpoint at 0x%" PRIx64, __FUNCTION__, addr); - return Error("SoftwareBreakpoint::%s: verification of software breakpoint " - "writing failed - trap opcodes not successfully read back " - "after writing when setting breakpoint at 0x%" PRIx64, - __FUNCTION__, addr); + return Status("SoftwareBreakpoint::%s: verification of software breakpoint " + "writing failed - trap opcodes not successfully read back " + "after writing when setting breakpoint at 0x%" PRIx64, + __FUNCTION__, addr); } if (log) log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64 " -- SUCCESS", __FUNCTION__, addr); - return Error(); + return Status(); } // ------------------------------------------------------------------- @@ -240,13 +241,13 @@ SoftwareBreakpoint::SoftwareBreakpoint(NativeProcessProtocol &process, ::memcpy(m_trap_opcodes, trap_opcodes, opcode_size); } -Error SoftwareBreakpoint::DoEnable() { +Status SoftwareBreakpoint::DoEnable() { return EnableSoftwareBreakpoint(m_process, m_addr, m_opcode_size, m_trap_opcodes, m_saved_opcodes); } -Error SoftwareBreakpoint::DoDisable() { - Error error; +Status SoftwareBreakpoint::DoDisable() { + Status error; assert(m_addr && (m_addr != LLDB_INVALID_ADDRESS) && "can't remove a software breakpoint for an invalid address"); diff --git a/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp b/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp index 9e0a3b5bf4df..1d9180bf528e 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp @@ -151,8 +151,9 @@ FileSpec LocateExecutableSymbolFileDsym(const ModuleSpec &module_spec) { const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "LocateExecutableSymbolFileDsym (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); @@ -175,9 +176,9 @@ ModuleSpec Symbols::LocateExecutableObjectFile(const ModuleSpec &module_spec) { const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, - "LocateExecutableObjectFile (file = %s, arch = %s, uuid = %p)", + func_cat, "LocateExecutableObjectFile (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); diff --git a/contrib/llvm/tools/lldb/source/Host/common/TCPSocket.cpp b/contrib/llvm/tools/lldb/source/Host/common/TCPSocket.cpp index 55db4bb0c456..c013334ce23a 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/TCPSocket.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/TCPSocket.cpp @@ -117,8 +117,8 @@ std::string TCPSocket::GetRemoteIPAddress() const { return ""; } -Error TCPSocket::CreateSocket(int domain) { - Error error; +Status TCPSocket::CreateSocket(int domain) { + Status error; if (IsValid()) error = Close(); if (error.Fail()) @@ -128,13 +128,13 @@ Error TCPSocket::CreateSocket(int domain) { return error; } -Error TCPSocket::Connect(llvm::StringRef name) { +Status TCPSocket::Connect(llvm::StringRef name) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data()); - Error error; + Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; @@ -166,12 +166,12 @@ Error TCPSocket::Connect(llvm::StringRef name) { return error; } -Error TCPSocket::Listen(llvm::StringRef name, int backlog) { +Status TCPSocket::Listen(llvm::StringRef name, int backlog) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("TCPSocket::%s (%s)", __FUNCTION__, name.data()); - Error error; + Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; @@ -227,8 +227,8 @@ void TCPSocket::CloseListenSockets() { m_listen_sockets.clear(); } -Error TCPSocket::Accept(Socket *&conn_socket) { - Error error; +Status TCPSocket::Accept(Socket *&conn_socket) { + Status error; if (m_listen_sockets.size() == 0) { error.SetErrorString("No open listening sockets!"); return error; diff --git a/contrib/llvm/tools/lldb/source/Host/common/ThreadLauncher.cpp b/contrib/llvm/tools/lldb/source/Host/common/ThreadLauncher.cpp index 32641efe408a..f3401016393f 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/ThreadLauncher.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/ThreadLauncher.cpp @@ -24,9 +24,9 @@ using namespace lldb_private; HostThread ThreadLauncher::LaunchThread(llvm::StringRef name, lldb::thread_func_t thread_function, lldb::thread_arg_t thread_arg, - Error *error_ptr, + Status *error_ptr, size_t min_stack_byte_size) { - Error error; + Status error; if (error_ptr) error_ptr->Clear(); diff --git a/contrib/llvm/tools/lldb/source/Host/common/UDPSocket.cpp b/contrib/llvm/tools/lldb/source/Host/common/UDPSocket.cpp index ce8d90891b2b..21dacbc626ee 100644 --- a/contrib/llvm/tools/lldb/source/Host/common/UDPSocket.cpp +++ b/contrib/llvm/tools/lldb/source/Host/common/UDPSocket.cpp @@ -42,27 +42,27 @@ size_t UDPSocket::Send(const void *buf, const size_t num_bytes) { m_sockaddr, m_sockaddr.GetLength()); } -Error UDPSocket::Connect(llvm::StringRef name) { - return Error("%s", g_not_supported_error); +Status UDPSocket::Connect(llvm::StringRef name) { + return Status("%s", g_not_supported_error); } -Error UDPSocket::Listen(llvm::StringRef name, int backlog) { - return Error("%s", g_not_supported_error); +Status UDPSocket::Listen(llvm::StringRef name, int backlog) { + return Status("%s", g_not_supported_error); } -Error UDPSocket::Accept(Socket *&socket) { - return Error("%s", g_not_supported_error); +Status UDPSocket::Accept(Socket *&socket) { + return Status("%s", g_not_supported_error); } -Error UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, - Socket *&socket) { +Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, + Socket *&socket) { std::unique_ptr<UDPSocket> final_socket; Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("UDPSocket::%s (host/port = %s)", __FUNCTION__, name.data()); - Error error; + Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; diff --git a/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp index f1abb49055e5..bd547bbeb9c5 100644 --- a/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/freebsd/Host.cpp @@ -34,8 +34,8 @@ #include "lldb/Target/Process.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/CleanUp.h" @@ -248,6 +248,6 @@ size_t Host::GetEnvironment(StringList &env) { return i; } -Error Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { - return Error("unimplemented"); +Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { + return Status("unimplemented"); } diff --git a/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp index 6a6b8ab51a17..bbe34a83d999 100644 --- a/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/netbsd/Host.cpp @@ -33,8 +33,8 @@ #include "lldb/Target/Process.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/CleanUp.h" @@ -254,6 +254,6 @@ bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { return false; } -Error Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { - return Error("unimplemented"); +Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { + return Status("unimplemented"); } diff --git a/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp b/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp index c9ff69366c2f..7e4a64fbd9ae 100644 --- a/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp +++ b/contrib/llvm/tools/lldb/source/Host/openbsd/Host.cpp @@ -30,8 +30,8 @@ #include "lldb/Target/Process.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/CleanUp.h" @@ -220,6 +220,6 @@ bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { return false; } -Error Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { - return Error("unimplemented"); +Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { + return Status("unimplemented"); } diff --git a/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp index befc847d8a86..7a0c92b44918 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp @@ -123,7 +123,7 @@ void ConnectionFileDescriptor::OpenCommandPipe() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); // Make the command file descriptor here: - Error result = m_pipe.CreateNew(m_child_processes_inherit); + Status result = m_pipe.CreateNew(m_child_processes_inherit); if (!result.Success()) { if (log) log->Printf("%p ConnectionFileDescriptor::OpenCommandPipe () - could not " @@ -153,7 +153,7 @@ bool ConnectionFileDescriptor::IsConnected() const { } ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path, - Error *error_ptr) { + Status *error_ptr) { std::lock_guard<std::recursive_mutex> guard(m_mutex); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) @@ -299,11 +299,11 @@ ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path, bool ConnectionFileDescriptor::InterruptRead() { size_t bytes_written = 0; - Error result = m_pipe.Write("i", 1, bytes_written); + Status result = m_pipe.Write("i", 1, bytes_written); return result.Success(); } -ConnectionStatus ConnectionFileDescriptor::Disconnect(Error *error_ptr) { +ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf("%p ConnectionFileDescriptor::Disconnect ()", @@ -337,7 +337,7 @@ ConnectionStatus ConnectionFileDescriptor::Disconnect(Error *error_ptr) { if (!locker.try_lock()) { if (m_pipe.CanWrite()) { size_t bytes_written = 0; - Error result = m_pipe.Write("q", 1, bytes_written); + Status result = m_pipe.Write("q", 1, bytes_written); if (log) log->Printf("%p ConnectionFileDescriptor::Disconnect(): Couldn't get " "the lock, sent 'q' to %d, error = '%s'.", @@ -351,8 +351,8 @@ ConnectionStatus ConnectionFileDescriptor::Disconnect(Error *error_ptr) { locker.lock(); } - Error error = m_read_sp->Close(); - Error error2 = m_write_sp->Close(); + Status error = m_read_sp->Close(); + Status error2 = m_write_sp->Close(); if (error.Fail() || error2.Fail()) status = eConnectionStatusError; if (error_ptr) @@ -369,7 +369,7 @@ ConnectionStatus ConnectionFileDescriptor::Disconnect(Error *error_ptr) { size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len, const Timeout<std::micro> &timeout, ConnectionStatus &status, - Error *error_ptr) { + Status *error_ptr) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock); @@ -394,7 +394,7 @@ size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len, if (status != eConnectionStatusSuccess) return 0; - Error error; + Status error; size_t bytes_read = dst_len; error = m_read_sp->Read(dst, bytes_read); @@ -476,7 +476,7 @@ size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len, size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len, ConnectionStatus &status, - Error *error_ptr) { + Status *error_ptr) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); if (log) log->Printf( @@ -491,7 +491,7 @@ size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len, return 0; } - Error error; + Status error; size_t bytes_sent = src_len; error = m_write_sp->Write(src, bytes_sent); @@ -553,7 +553,7 @@ std::string ConnectionFileDescriptor::GetURI() { return m_uri; } ConnectionStatus ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout, - Error *error_ptr) { + Status *error_ptr) { // Don't need to take the mutex here separately since we are only called from // Read. If we // ever get used more generally we will need to lock here as well. @@ -588,7 +588,7 @@ ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout, while (handle == m_read_sp->GetWaitableHandle()) { - Error error = select_helper.Select(); + Status error = select_helper.Select(); if (error_ptr) *error_ptr = error; @@ -653,9 +653,9 @@ ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout, ConnectionStatus ConnectionFileDescriptor::NamedSocketAccept(llvm::StringRef socket_name, - Error *error_ptr) { + Status *error_ptr) { Socket *socket = nullptr; - Error error = + Status error = Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; @@ -670,9 +670,9 @@ ConnectionFileDescriptor::NamedSocketAccept(llvm::StringRef socket_name, ConnectionStatus ConnectionFileDescriptor::NamedSocketConnect(llvm::StringRef socket_name, - Error *error_ptr) { + Status *error_ptr) { Socket *socket = nullptr; - Error error = + Status error = Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; @@ -687,10 +687,10 @@ ConnectionFileDescriptor::NamedSocketConnect(llvm::StringRef socket_name, lldb::ConnectionStatus ConnectionFileDescriptor::UnixAbstractSocketConnect(llvm::StringRef socket_name, - Error *error_ptr) { + Status *error_ptr) { Socket *socket = nullptr; - Error error = Socket::UnixAbstractConnect(socket_name, - m_child_processes_inherit, socket); + Status error = Socket::UnixAbstractConnect(socket_name, + m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); @@ -704,13 +704,13 @@ ConnectionFileDescriptor::UnixAbstractSocketConnect(llvm::StringRef socket_name, ConnectionStatus ConnectionFileDescriptor::SocketListenAndAccept(llvm::StringRef s, - Error *error_ptr) { + Status *error_ptr) { m_port_predicate.SetValue(0, eBroadcastNever); Socket *socket = nullptr; m_waiting_for_accept = true; - Error error = Socket::TcpListen(s, m_child_processes_inherit, socket, - &m_port_predicate); + Status error = Socket::TcpListen(s, m_child_processes_inherit, socket, + &m_port_predicate); if (error_ptr) *error_ptr = error; if (error.Fail()) @@ -732,9 +732,9 @@ ConnectionFileDescriptor::SocketListenAndAccept(llvm::StringRef s, } ConnectionStatus ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s, - Error *error_ptr) { + Status *error_ptr) { Socket *socket = nullptr; - Error error = Socket::TcpConnect(s, m_child_processes_inherit, socket); + Status error = Socket::TcpConnect(s, m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); @@ -747,9 +747,9 @@ ConnectionStatus ConnectionFileDescriptor::ConnectTCP(llvm::StringRef s, } ConnectionStatus ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s, - Error *error_ptr) { + Status *error_ptr) { Socket *socket = nullptr; - Error error = Socket::UdpConnect(s, m_child_processes_inherit, socket); + Status error = Socket::UdpConnect(s, m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); diff --git a/contrib/llvm/tools/lldb/source/Host/posix/DomainSocket.cpp b/contrib/llvm/tools/lldb/source/Host/posix/DomainSocket.cpp index 33c71268c2e3..3e3abadc2e5a 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/DomainSocket.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/DomainSocket.cpp @@ -72,13 +72,13 @@ DomainSocket::DomainSocket(NativeSocket socket, m_socket = socket; } -Error DomainSocket::Connect(llvm::StringRef name) { +Status DomainSocket::Connect(llvm::StringRef name) { sockaddr_un saddr_un; socklen_t saddr_un_len; if (!SetSockAddr(name, GetNameOffset(), &saddr_un, saddr_un_len)) - return Error("Failed to set socket address"); + return Status("Failed to set socket address"); - Error error; + Status error; m_socket = CreateSocket(kDomain, kType, 0, m_child_processes_inherit, error); if (error.Fail()) return error; @@ -89,15 +89,15 @@ Error DomainSocket::Connect(llvm::StringRef name) { return error; } -Error DomainSocket::Listen(llvm::StringRef name, int backlog) { +Status DomainSocket::Listen(llvm::StringRef name, int backlog) { sockaddr_un saddr_un; socklen_t saddr_un_len; if (!SetSockAddr(name, GetNameOffset(), &saddr_un, saddr_un_len)) - return Error("Failed to set socket address"); + return Status("Failed to set socket address"); DeleteSocketFile(name); - Error error; + Status error; m_socket = CreateSocket(kDomain, kType, 0, m_child_processes_inherit, error); if (error.Fail()) return error; @@ -110,8 +110,8 @@ Error DomainSocket::Listen(llvm::StringRef name, int backlog) { return error; } -Error DomainSocket::Accept(Socket *&socket) { - Error error; +Status DomainSocket::Accept(Socket *&socket) { + Status error; auto conn_fd = AcceptSocket(GetNativeSocket(), nullptr, nullptr, m_child_processes_inherit, error); if (error.Success()) diff --git a/contrib/llvm/tools/lldb/source/Host/posix/FileSystem.cpp b/contrib/llvm/tools/lldb/source/Host/posix/FileSystem.cpp index 22f337fcfec5..e5a99e1aa754 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/FileSystem.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/FileSystem.cpp @@ -26,7 +26,7 @@ // lldb Includes #include "lldb/Host/Host.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "llvm/Support/FileSystem.h" @@ -36,15 +36,15 @@ using namespace lldb_private; const char *FileSystem::DEV_NULL = "/dev/null"; -Error FileSystem::Symlink(const FileSpec &src, const FileSpec &dst) { - Error error; +Status FileSystem::Symlink(const FileSpec &src, const FileSpec &dst) { + Status error; if (::symlink(dst.GetCString(), src.GetCString()) == -1) error.SetErrorToErrno(); return error; } -Error FileSystem::Readlink(const FileSpec &src, FileSpec &dst) { - Error error; +Status FileSystem::Readlink(const FileSpec &src, FileSpec &dst) { + Status error; char buf[PATH_MAX]; ssize_t count = ::readlink(src.GetCString(), buf, sizeof(buf) - 1); if (count < 0) @@ -56,22 +56,22 @@ Error FileSystem::Readlink(const FileSpec &src, FileSpec &dst) { return error; } -Error FileSystem::ResolveSymbolicLink(const FileSpec &src, FileSpec &dst) { +Status FileSystem::ResolveSymbolicLink(const FileSpec &src, FileSpec &dst) { char resolved_path[PATH_MAX]; if (!src.GetPath(resolved_path, sizeof(resolved_path))) { - return Error("Couldn't get the canonical path for %s", src.GetCString()); + return Status("Couldn't get the canonical path for %s", src.GetCString()); } char real_path[PATH_MAX + 1]; if (realpath(resolved_path, real_path) == nullptr) { - Error err; + Status err; err.SetErrorToErrno(); return err; } dst = FileSpec(real_path, false); - return Error(); + return Status(); } FILE *FileSystem::Fopen(const char *path, const char *mode) { diff --git a/contrib/llvm/tools/lldb/source/Host/posix/HostProcessPosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/HostProcessPosix.cpp index 9dd9fef94cdb..b5505dbec65b 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/HostProcessPosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/HostProcessPosix.cpp @@ -29,9 +29,9 @@ HostProcessPosix::HostProcessPosix(lldb::process_t process) HostProcessPosix::~HostProcessPosix() {} -Error HostProcessPosix::Signal(int signo) const { +Status HostProcessPosix::Signal(int signo) const { if (m_process == kInvalidPosixProcess) { - Error error; + Status error; error.SetErrorString("HostProcessPosix refers to an invalid process"); return error; } @@ -39,8 +39,8 @@ Error HostProcessPosix::Signal(int signo) const { return HostProcessPosix::Signal(m_process, signo); } -Error HostProcessPosix::Signal(lldb::process_t process, int signo) { - Error error; +Status HostProcessPosix::Signal(lldb::process_t process, int signo) { + Status error; if (-1 == ::kill(process, signo)) error.SetErrorToErrno(); @@ -48,10 +48,10 @@ Error HostProcessPosix::Signal(lldb::process_t process, int signo) { return error; } -Error HostProcessPosix::Terminate() { return Signal(SIGKILL); } +Status HostProcessPosix::Terminate() { return Signal(SIGKILL); } -Error HostProcessPosix::GetMainModule(FileSpec &file_spec) const { - Error error; +Status HostProcessPosix::GetMainModule(FileSpec &file_spec) const { + Status error; // Use special code here because proc/[pid]/exe is a symbolic link. char link_path[PATH_MAX]; @@ -82,7 +82,7 @@ bool HostProcessPosix::IsRunning() const { return false; // Send this process the null signal. If it succeeds the process is running. - Error error = Signal(0); + Status error = Signal(0); return error.Success(); } diff --git a/contrib/llvm/tools/lldb/source/Host/posix/HostThreadPosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/HostThreadPosix.cpp index 073b7b0b11e8..0f4434d25e2e 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/HostThreadPosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/HostThreadPosix.cpp @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// #include "lldb/Host/posix/HostThreadPosix.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include <errno.h> #include <pthread.h> @@ -23,8 +23,8 @@ HostThreadPosix::HostThreadPosix(lldb::thread_t thread) HostThreadPosix::~HostThreadPosix() {} -Error HostThreadPosix::Join(lldb::thread_result_t *result) { - Error error; +Status HostThreadPosix::Join(lldb::thread_result_t *result) { + Status error; if (IsJoinable()) { int err = ::pthread_join(m_thread, result); error.SetError(err, lldb::eErrorTypePOSIX); @@ -38,8 +38,8 @@ Error HostThreadPosix::Join(lldb::thread_result_t *result) { return error; } -Error HostThreadPosix::Cancel() { - Error error; +Status HostThreadPosix::Cancel() { + Status error; if (IsJoinable()) { #ifndef __ANDROID__ #ifndef __FreeBSD__ @@ -54,8 +54,8 @@ Error HostThreadPosix::Cancel() { return error; } -Error HostThreadPosix::Detach() { - Error error; +Status HostThreadPosix::Detach() { + Status error; if (IsJoinable()) { int err = ::pthread_detach(m_thread); error.SetError(err, eErrorTypePOSIX); diff --git a/contrib/llvm/tools/lldb/source/Host/posix/LockFilePosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/LockFilePosix.cpp index d1cc617146d0..2b7d548a021c 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/LockFilePosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/LockFilePosix.cpp @@ -16,8 +16,8 @@ using namespace lldb_private; namespace { -Error fileLock(int fd, int cmd, int lock_type, const uint64_t start, - const uint64_t len) { +Status fileLock(int fd, int cmd, int lock_type, const uint64_t start, + const uint64_t len) { struct flock fl; fl.l_type = lock_type; @@ -26,7 +26,7 @@ Error fileLock(int fd, int cmd, int lock_type, const uint64_t start, fl.l_len = len; fl.l_pid = ::getpid(); - Error error; + Status error; if (::fcntl(fd, cmd, &fl) == -1) error.SetErrorToErrno(); @@ -39,22 +39,22 @@ LockFilePosix::LockFilePosix(int fd) : LockFileBase(fd) {} LockFilePosix::~LockFilePosix() { Unlock(); } -Error LockFilePosix::DoWriteLock(const uint64_t start, const uint64_t len) { +Status LockFilePosix::DoWriteLock(const uint64_t start, const uint64_t len) { return fileLock(m_fd, F_SETLKW, F_WRLCK, start, len); } -Error LockFilePosix::DoTryWriteLock(const uint64_t start, const uint64_t len) { +Status LockFilePosix::DoTryWriteLock(const uint64_t start, const uint64_t len) { return fileLock(m_fd, F_SETLK, F_WRLCK, start, len); } -Error LockFilePosix::DoReadLock(const uint64_t start, const uint64_t len) { +Status LockFilePosix::DoReadLock(const uint64_t start, const uint64_t len) { return fileLock(m_fd, F_SETLKW, F_RDLCK, start, len); } -Error LockFilePosix::DoTryReadLock(const uint64_t start, const uint64_t len) { +Status LockFilePosix::DoTryReadLock(const uint64_t start, const uint64_t len) { return fileLock(m_fd, F_SETLK, F_RDLCK, start, len); } -Error LockFilePosix::DoUnlock() { +Status LockFilePosix::DoUnlock() { return fileLock(m_fd, F_SETLK, F_UNLCK, m_start, m_len); } diff --git a/contrib/llvm/tools/lldb/source/Host/posix/PipePosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/PipePosix.cpp index 3ac5d480de89..da99fd702424 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/PipePosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/PipePosix.cpp @@ -82,11 +82,11 @@ PipePosix &PipePosix::operator=(PipePosix &&pipe_posix) { PipePosix::~PipePosix() { Close(); } -Error PipePosix::CreateNew(bool child_processes_inherit) { +Status PipePosix::CreateNew(bool child_processes_inherit) { if (CanRead() || CanWrite()) - return Error(EINVAL, eErrorTypePOSIX); + return Status(EINVAL, eErrorTypePOSIX); - Error error; + Status error; #if PIPE2_SUPPORTED if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0) return error; @@ -111,20 +111,20 @@ Error PipePosix::CreateNew(bool child_processes_inherit) { return error; } -Error PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit) { +Status PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit) { if (CanRead() || CanWrite()) - return Error("Pipe is already opened"); + return Status("Pipe is already opened"); - Error error; + Status error; if (::mkfifo(name.data(), 0660) != 0) error.SetErrorToErrno(); return error; } -Error PipePosix::CreateWithUniqueName(llvm::StringRef prefix, - bool child_process_inherit, - llvm::SmallVectorImpl<char> &name) { +Status PipePosix::CreateWithUniqueName(llvm::StringRef prefix, + bool child_process_inherit, + llvm::SmallVectorImpl<char> &name) { llvm::SmallString<PATH_MAX> named_pipe_path; llvm::SmallString<PATH_MAX> pipe_spec((prefix + ".%%%%%%").str()); FileSpec tmpdir_file_spec; @@ -139,7 +139,7 @@ Error PipePosix::CreateWithUniqueName(llvm::StringRef prefix, // It's possible that another process creates the target path after we've // verified it's available but before we create it, in which case we // should try again. - Error error; + Status error; do { llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(), named_pipe_path); @@ -151,16 +151,16 @@ Error PipePosix::CreateWithUniqueName(llvm::StringRef prefix, return error; } -Error PipePosix::OpenAsReader(llvm::StringRef name, - bool child_process_inherit) { +Status PipePosix::OpenAsReader(llvm::StringRef name, + bool child_process_inherit) { if (CanRead() || CanWrite()) - return Error("Pipe is already opened"); + return Status("Pipe is already opened"); int flags = O_RDONLY | O_NONBLOCK; if (!child_process_inherit) flags |= O_CLOEXEC; - Error error; + Status error; int fd = ::open(name.data(), flags); if (fd != -1) m_fds[READ] = fd; @@ -170,11 +170,12 @@ Error PipePosix::OpenAsReader(llvm::StringRef name, return error; } -Error PipePosix::OpenAsWriterWithTimeout( - llvm::StringRef name, bool child_process_inherit, - const std::chrono::microseconds &timeout) { +Status +PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, + bool child_process_inherit, + const std::chrono::microseconds &timeout) { if (CanRead() || CanWrite()) - return Error("Pipe is already opened"); + return Status("Pipe is already opened"); int flags = O_WRONLY | O_NONBLOCK; if (!child_process_inherit) @@ -187,7 +188,7 @@ Error PipePosix::OpenAsWriterWithTimeout( if (timeout != microseconds::zero()) { const auto dur = duration_cast<microseconds>(finish_time - Now()).count(); if (dur <= 0) - return Error("timeout exceeded - reader hasn't opened so far"); + return Status("timeout exceeded - reader hasn't opened so far"); } errno = 0; @@ -196,7 +197,7 @@ Error PipePosix::OpenAsWriterWithTimeout( const auto errno_copy = errno; // We may get ENXIO if a reader side of the pipe hasn't opened yet. if (errno_copy != ENXIO) - return Error(errno_copy, eErrorTypePOSIX); + return Status(errno_copy, eErrorTypePOSIX); std::this_thread::sleep_for( milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS)); @@ -205,7 +206,7 @@ Error PipePosix::OpenAsWriterWithTimeout( } } - return Error(); + return Status(); } int PipePosix::GetReadFileDescriptor() const { return m_fds[READ]; } @@ -229,7 +230,7 @@ void PipePosix::Close() { CloseWriteFileDescriptor(); } -Error PipePosix::Delete(llvm::StringRef name) { +Status PipePosix::Delete(llvm::StringRef name) { return llvm::sys::fs::remove(name); } @@ -255,12 +256,12 @@ void PipePosix::CloseWriteFileDescriptor() { } } -Error PipePosix::ReadWithTimeout(void *buf, size_t size, - const std::chrono::microseconds &timeout, - size_t &bytes_read) { +Status PipePosix::ReadWithTimeout(void *buf, size_t size, + const std::chrono::microseconds &timeout, + size_t &bytes_read) { bytes_read = 0; if (!CanRead()) - return Error(EINVAL, eErrorTypePOSIX); + return Status(EINVAL, eErrorTypePOSIX); const int fd = GetReadFileDescriptor(); @@ -268,7 +269,7 @@ Error PipePosix::ReadWithTimeout(void *buf, size_t size, select_helper.SetTimeout(timeout); select_helper.FDSetRead(fd); - Error error; + Status error; while (error.Success()) { error = select_helper.Select(); if (error.Success()) { @@ -287,17 +288,17 @@ Error PipePosix::ReadWithTimeout(void *buf, size_t size, return error; } -Error PipePosix::Write(const void *buf, size_t size, size_t &bytes_written) { +Status PipePosix::Write(const void *buf, size_t size, size_t &bytes_written) { bytes_written = 0; if (!CanWrite()) - return Error(EINVAL, eErrorTypePOSIX); + return Status(EINVAL, eErrorTypePOSIX); const int fd = GetWriteFileDescriptor(); SelectHelper select_helper; select_helper.SetTimeout(std::chrono::seconds(0)); select_helper.FDSetWrite(fd); - Error error; + Status error; while (error.Success()) { error = select_helper.Select(); if (error.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosix.cpp b/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosix.cpp index f90bf0cd88a2..6d07be1eec64 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosix.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosix.cpp @@ -20,7 +20,7 @@ using namespace lldb_private; HostProcess ProcessLauncherPosix::LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) { + Status &error) { lldb::pid_t pid; char exe_path[PATH_MAX]; diff --git a/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp b/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp index 91c32d6e6426..378670cd2a9a 100644 --- a/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp +++ b/contrib/llvm/tools/lldb/source/Host/posix/ProcessLauncherPosixFork.cpp @@ -190,7 +190,7 @@ static void LLVM_ATTRIBUTE_NORETURN ChildFunc(int error_fd, HostProcess ProcessLauncherPosixFork::LaunchProcess(const ProcessLaunchInfo &launch_info, - Error &error) { + Status &error) { char exe_path[PATH_MAX]; launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path)); diff --git a/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp b/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp index ce19e29c19af..a548a96cc4f1 100644 --- a/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp +++ b/contrib/llvm/tools/lldb/source/Initialization/SystemInitializerCommon.cpp @@ -72,7 +72,8 @@ void SystemInitializerCommon::Initialize() { llvm::EnablePrettyStackTrace(); InitializeLog(); HostInfo::Initialize(); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); process_gdb_remote::ProcessGDBRemoteLog::Initialize(); @@ -102,7 +103,8 @@ void SystemInitializerCommon::Initialize() { } void SystemInitializerCommon::Terminate() { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); ObjectContainerBSDArchive::Terminate(); ObjectFileELF::Terminate(); //ObjectFilePECOFF::Terminate(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/Args.cpp b/contrib/llvm/tools/lldb/source/Interpreter/Args.cpp index 5bfe13f55e49..a23ba3094b22 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/Args.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/Args.cpp @@ -420,10 +420,10 @@ void Args::SetArguments(const char **argv) { SetArguments(ArgvToArgc(argv), argv); } -Error Args::ParseOptions(Options &options, ExecutionContext *execution_context, - PlatformSP platform_sp, bool require_validation) { +Status Args::ParseOptions(Options &options, ExecutionContext *execution_context, + PlatformSP platform_sp, bool require_validation) { StreamString sstr; - Error error; + Status error; Option *long_options = options.GetLongOptions(); if (long_options == nullptr) { error.SetErrorStringWithFormat("invalid long options"); @@ -547,7 +547,7 @@ void Args::Clear() { lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, - Error *error_ptr) { + Status *error_ptr) { bool error_set = false; if (s.empty()) { if (error_ptr) @@ -630,7 +630,7 @@ lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx, if (regex_match.GetMatchAtIndex(s, 3, str)) { if (!llvm::StringRef(str).getAsInteger(0, offset)) { - Error error; + Status error; addr = StringToAddress(exe_ctx, name.c_str(), LLDB_INVALID_ADDRESS, &error); if (addr != LLDB_INVALID_ADDRESS) { @@ -774,7 +774,7 @@ const char *Args::GetShellSafeArgument(const FileSpec &shell, int64_t Args::StringToOptionEnum(llvm::StringRef s, OptionEnumValueElement *enum_values, - int32_t fail_value, Error &error) { + int32_t fail_value, Status &error) { error.Clear(); if (!enum_values) { error.SetErrorString("invalid enumeration argument"); @@ -819,10 +819,10 @@ Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value, return fail_value; } -Error Args::StringToFormat(const char *s, lldb::Format &format, - size_t *byte_size_ptr) { +Status Args::StringToFormat(const char *s, lldb::Format &format, + size_t *byte_size_ptr) { format = eFormatInvalid; - Error error; + Status error; if (s && s[0]) { if (byte_size_ptr) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp b/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp index 8703bc97f06e..a1d8eded09f5 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp @@ -169,7 +169,8 @@ bool CommandInterpreter::GetSpaceReplPrompts() const { } void CommandInterpreter::Initialize() { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); CommandReturnObject result; @@ -391,7 +392,8 @@ const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) { } void CommandInterpreter::LoadCommandDictionary() { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); @@ -1373,7 +1375,7 @@ CommandObject *CommandInterpreter::BuildAliasResult( return alias_cmd_obj; } -Error CommandInterpreter::PreprocessCommand(std::string &command) { +Status CommandInterpreter::PreprocessCommand(std::string &command) { // The command preprocessor needs to do things to the command // line before any parsing of arguments or anything else is done. // The only current stuff that gets preprocessed is anything enclosed @@ -1381,7 +1383,7 @@ Error CommandInterpreter::PreprocessCommand(std::string &command) { // the result of the expression must be a scalar that can be substituted // into the command. An example would be: // (lldb) memory read `$rsp + 20` - Error error; // Error for any expressions that might not evaluate + Status error; // Status for any expressions that might not evaluate size_t start_backtick; size_t pos = 0; while ((start_backtick = command.find('`', pos)) != std::string::npos) { @@ -1533,8 +1535,8 @@ bool CommandInterpreter::HandleCommand(const char *command_line, if (log) log->Printf("Processing command: %s", command_line); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "Handling command: %s.", - command_line); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Handling command: %s.", command_line); if (!no_context_switching) UpdateExecutionContext(override_context); @@ -1601,7 +1603,7 @@ bool CommandInterpreter::HandleCommand(const char *command_line, return true; } - Error error(PreprocessCommand(command_string)); + Status error(PreprocessCommand(command_string)); if (error.Fail()) { result.AppendError(error.AsCString()); @@ -2355,8 +2357,8 @@ void CommandInterpreter::HandleCommandsFromFile( StreamFileSP input_file_sp(new StreamFile()); std::string cmd_file_path = cmd_file.GetPath(); - Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), - File::eOpenOptionRead); + Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), + File::eOpenOptionRead); if (error.Success()) { Debugger &debugger = GetDebugger(); @@ -2653,7 +2655,7 @@ size_t CommandInterpreter::GetProcessOutput() { char stdio_buffer[1024]; size_t len; size_t total_bytes = 0; - Error error; + Status error; TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget()); if (target_sp) { ProcessSP process_sp(target_sp->GetProcessSP()); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/CommandObject.cpp b/contrib/llvm/tools/lldb/source/Interpreter/CommandObject.cpp index 2a6c77d7deba..f9a5b10bb4b8 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/CommandObject.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/CommandObject.cpp @@ -99,7 +99,7 @@ bool CommandObject::ParseOptions(Args &args, CommandReturnObject &result) { // See if the subclass has options? Options *options = GetOptions(); if (options != nullptr) { - Error error; + Status error; auto exe_ctx = GetCommandInterpreter().GetExecutionContext(); options->NotifyOptionParsingStarting(&exe_ctx); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/CommandReturnObject.cpp b/contrib/llvm/tools/lldb/source/Interpreter/CommandReturnObject.cpp index 00fcff510cff..75c02588066c 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/CommandReturnObject.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/CommandReturnObject.cpp @@ -13,7 +13,7 @@ // C++ Includes // Other libraries and framework includes // Project includes -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" using namespace lldb; @@ -111,7 +111,7 @@ void CommandReturnObject::AppendError(llvm::StringRef in_string) { GetErrorStream() << "error: " << in_string << "\n"; } -void CommandReturnObject::SetError(const Error &error, +void CommandReturnObject::SetError(const Status &error, const char *fallback_error_cstr) { const char *error_cstr = error.AsCString(); if (error_cstr == nullptr) @@ -127,7 +127,7 @@ void CommandReturnObject::SetError(llvm::StringRef error_str) { SetStatus(eReturnStatusFailed); } -// Similar to AppendError, but do not prepend 'Error: ' to message, and +// Similar to AppendError, but do not prepend 'Status: ' to message, and // don't append "\n" to the end of it. void CommandReturnObject::AppendRawError(llvm::StringRef in_string) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupArchitecture.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupArchitecture.cpp index 4a6bf48a24d4..d5354fe0739c 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupArchitecture.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupArchitecture.cpp @@ -41,10 +41,11 @@ bool OptionGroupArchitecture::GetArchitecture(Platform *platform, return arch.IsValid(); } -Error OptionGroupArchitecture::SetOptionValue( - uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status +OptionGroupArchitecture::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupBoolean.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupBoolean.cpp index 4956b83c8f7a..5fd4ce7aecfa 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupBoolean.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupBoolean.cpp @@ -40,10 +40,10 @@ OptionGroupBoolean::OptionGroupBoolean(uint32_t usage_mask, bool required, OptionGroupBoolean::~OptionGroupBoolean() {} -Error OptionGroupBoolean::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_value, - ExecutionContext *execution_context) { - Error error; +Status OptionGroupBoolean::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_value, + ExecutionContext *execution_context) { + Status error; if (m_option_definition.option_has_arg == OptionParser::eNoArgument) { // Not argument, toggle the default value and mark the option as having been // set diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFile.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFile.cpp index 995a6a46e48e..d45f00a66616 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFile.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFile.cpp @@ -38,10 +38,10 @@ OptionGroupFile::OptionGroupFile(uint32_t usage_mask, bool required, OptionGroupFile::~OptionGroupFile() {} -Error OptionGroupFile::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error(m_file.SetValueFromString(option_arg)); +Status OptionGroupFile::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error(m_file.SetValueFromString(option_arg)); return error; } @@ -69,10 +69,11 @@ OptionGroupFileList::OptionGroupFileList( OptionGroupFileList::~OptionGroupFileList() {} -Error OptionGroupFileList::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_value, - ExecutionContext *execution_context) { - Error error(m_file_list.SetValueFromString(option_value)); +Status +OptionGroupFileList::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_value, + ExecutionContext *execution_context) { + Status error(m_file_list.SetValueFromString(option_value)); return error; } diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFormat.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFormat.cpp index df5e2b3cd346..7c4239f92642 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFormat.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupFormat.cpp @@ -58,10 +58,10 @@ llvm::ArrayRef<OptionDefinition> OptionGroupFormat::GetDefinitions() { return result.take_front(2); } -Error OptionGroupFormat::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status OptionGroupFormat::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupOutputFile.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupOutputFile.cpp index 7b0ee61dd7eb..fd406494ea97 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupOutputFile.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupOutputFile.cpp @@ -38,10 +38,11 @@ llvm::ArrayRef<OptionDefinition> OptionGroupOutputFile::GetDefinitions() { return llvm::makeArrayRef(g_option_table); } -Error OptionGroupOutputFile::SetOptionValue( - uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status +OptionGroupOutputFile::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupPlatform.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupPlatform.cpp index f6edca82a142..5747c6a8815d 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupPlatform.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupPlatform.cpp @@ -22,7 +22,7 @@ using namespace lldb_private; PlatformSP OptionGroupPlatform::CreatePlatformWithOptions( CommandInterpreter &interpreter, const ArchSpec &arch, bool make_selected, - Error &error, ArchSpec &platform_arch) const { + Status &error, ArchSpec &platform_arch) const { PlatformSP platform_sp; if (!m_platform_name.empty()) { @@ -92,10 +92,11 @@ llvm::ArrayRef<OptionDefinition> OptionGroupPlatform::GetDefinitions() { return result.drop_front(); } -Error OptionGroupPlatform::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status +OptionGroupPlatform::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; if (!m_include_platform_option) ++option_idx; diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupString.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupString.cpp index 5705264dba20..1a161945a17f 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupString.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupString.cpp @@ -39,10 +39,10 @@ OptionGroupString::OptionGroupString(uint32_t usage_mask, bool required, OptionGroupString::~OptionGroupString() {} -Error OptionGroupString::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error(m_value.SetValueFromString(option_arg)); +Status OptionGroupString::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error(m_value.SetValueFromString(option_arg)); return error; } diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUInt64.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUInt64.cpp index a6a0d49232c1..ae4828c3e926 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUInt64.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUInt64.cpp @@ -39,10 +39,10 @@ OptionGroupUInt64::OptionGroupUInt64(uint32_t usage_mask, bool required, OptionGroupUInt64::~OptionGroupUInt64() {} -Error OptionGroupUInt64::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error(m_value.SetValueFromString(option_arg)); +Status OptionGroupUInt64::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error(m_value.SetValueFromString(option_arg)); return error; } diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUUID.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUUID.cpp index 32a9962b5b97..bf02d1b660cf 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUUID.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupUUID.cpp @@ -31,10 +31,10 @@ llvm::ArrayRef<OptionDefinition> OptionGroupUUID::GetDefinitions() { return llvm::makeArrayRef(g_option_table); } -Error OptionGroupUUID::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status OptionGroupUUID::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp index 89acf3f0d3f9..ce27d948c93c 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupValueObjectDisplay.cpp @@ -75,10 +75,10 @@ OptionGroupValueObjectDisplay::GetDefinitions() { return llvm::makeArrayRef(g_option_table); } -Error OptionGroupValueObjectDisplay::SetOptionValue( +Status OptionGroupValueObjectDisplay::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = g_option_table[option_idx].short_option; bool success = false; diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupVariable.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupVariable.cpp index 760563071d7d..0793d3731446 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupVariable.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupVariable.cpp @@ -17,7 +17,7 @@ #include "lldb/Host/OptionParser.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -52,20 +52,20 @@ static OptionDefinition g_variable_options[] = { "Specify a summary string to use to format the variable output."}, }; -static Error ValidateNamedSummary(const char *str, void *) { +static Status ValidateNamedSummary(const char *str, void *) { if (!str || !str[0]) - return Error("must specify a valid named summary"); + return Status("must specify a valid named summary"); TypeSummaryImplSP summary_sp; if (DataVisualization::NamedSummaryFormats::GetSummaryFormat( ConstString(str), summary_sp) == false) - return Error("must specify a valid named summary"); - return Error(); + return Status("must specify a valid named summary"); + return Status(); } -static Error ValidateSummaryString(const char *str, void *) { +static Status ValidateSummaryString(const char *str, void *) { if (!str || !str[0]) - return Error("must specify a non-empty summary string"); - return Error(); + return Status("must specify a non-empty summary string"); + return Status(); } OptionGroupVariable::OptionGroupVariable(bool show_frame_options) @@ -74,10 +74,11 @@ OptionGroupVariable::OptionGroupVariable(bool show_frame_options) OptionGroupVariable::~OptionGroupVariable() {} -Error OptionGroupVariable::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status +OptionGroupVariable::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; if (!include_frame_options) option_idx += 3; const int short_option = g_variable_options[option_idx].short_option; diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupWatchpoint.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupWatchpoint.cpp index 1e6fab929ca7..dd4b8c86c910 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupWatchpoint.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionGroupWatchpoint.cpp @@ -56,10 +56,11 @@ OptionGroupWatchpoint::OptionGroupWatchpoint() : OptionGroup() {} OptionGroupWatchpoint::~OptionGroupWatchpoint() {} -Error OptionGroupWatchpoint::SetOptionValue( - uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) { - Error error; +Status +OptionGroupWatchpoint::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_arg, + ExecutionContext *execution_context) { + Status error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { case 'w': { diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValue.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValue.cpp index 5f42f7f7056a..afcace2567ce 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValue.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValue.cpp @@ -42,10 +42,10 @@ uint64_t OptionValue::GetUInt64Value(uint64_t fail_value, bool *success_ptr) { return fail_value; } -Error OptionValue::SetSubValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, llvm::StringRef name, - llvm::StringRef value) { - Error error; +Status OptionValue::SetSubValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, llvm::StringRef name, + llvm::StringRef value) { + Status error; error.SetErrorStringWithFormat("SetSubValue is not supported"); return error; } @@ -507,7 +507,7 @@ const char *OptionValue::GetBuiltinTypeAsCString(Type t) { } lldb::OptionValueSP OptionValue::CreateValueFromCStringForTypeMask( - const char *value_cstr, uint32_t type_mask, Error &error) { + const char *value_cstr, uint32_t type_mask, Status &error) { // If only 1 bit is set in the type mask for a dictionary or array // then we know how to decode a value from a cstring lldb::OptionValueSP value_sp; @@ -582,9 +582,9 @@ size_t OptionValue::AutoComplete(CommandInterpreter &interpreter, return matches.GetSize(); } -Error OptionValue::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValue::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationReplace: error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArch.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArch.cpp index 3e41300a4182..1d920a114723 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArch.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArch.cpp @@ -38,9 +38,9 @@ void OptionValueArch::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueArch::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueArch::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArray.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArray.cpp index 0d1825cec28b..8b62070352a6 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArray.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueArray.cpp @@ -70,18 +70,19 @@ void OptionValueArray::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueArray::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { +Status OptionValueArray::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { Args args(value.str()); - Error error = SetArgs(args, op); + Status error = SetArgs(args, op); if (error.Success()) NotifyValueChanged(); return error; } lldb::OptionValueSP -OptionValueArray::GetSubValue(const ExecutionContext *exe_ctx, llvm::StringRef name, - bool will_modify, Error &error) const { +OptionValueArray::GetSubValue(const ExecutionContext *exe_ctx, + llvm::StringRef name, bool will_modify, + Status &error) const { if (name.empty() || name.front() != '[') { error.SetErrorStringWithFormat( "invalid value path '%s', %s values only support '[<index>]' subvalues " @@ -149,8 +150,8 @@ size_t OptionValueArray::GetArgs(Args &args) const { return args.GetArgumentCount(); } -Error OptionValueArray::SetArgs(const Args &args, VarSetOperationType op) { - Error error; +Status OptionValueArray::SetArgs(const Args &args, VarSetOperationType op) { + Status error; const size_t argc = args.GetArgumentCount(); switch (op) { case eVarSetOperationInvalid: diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueBoolean.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueBoolean.cpp index 92e4d891c1a8..2cb84cd6abb3 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueBoolean.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueBoolean.cpp @@ -35,9 +35,9 @@ void OptionValueBoolean::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueBoolean::SetValueFromString(llvm::StringRef value_str, - VarSetOperationType op) { - Error error; +Status OptionValueBoolean::SetValueFromString(llvm::StringRef value_str, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueChar.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueChar.cpp index 1f6acf61c68c..27684a27264d 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueChar.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueChar.cpp @@ -36,9 +36,9 @@ void OptionValueChar::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueChar::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueChar::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueDictionary.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueDictionary.cpp index dfba435603bb..b245a09c1951 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueDictionary.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueDictionary.cpp @@ -90,8 +90,9 @@ size_t OptionValueDictionary::GetArgs(Args &args) const { return args.GetArgumentCount(); } -Error OptionValueDictionary::SetArgs(const Args &args, VarSetOperationType op) { - Error error; +Status OptionValueDictionary::SetArgs(const Args &args, + VarSetOperationType op) { + Status error; const size_t argc = args.GetArgumentCount(); switch (op) { case eVarSetOperationClear: @@ -197,10 +198,10 @@ Error OptionValueDictionary::SetArgs(const Args &args, VarSetOperationType op) { return error; } -Error OptionValueDictionary::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { +Status OptionValueDictionary::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { Args args(value.str()); - Error error = SetArgs(args, op); + Status error = SetArgs(args, op); if (error.Success()) NotifyValueChanged(); return error; @@ -208,8 +209,8 @@ Error OptionValueDictionary::SetValueFromString(llvm::StringRef value, lldb::OptionValueSP OptionValueDictionary::GetSubValue(const ExecutionContext *exe_ctx, - llvm::StringRef name, bool will_modify, - Error &error) const { + llvm::StringRef name, bool will_modify, + Status &error) const { lldb::OptionValueSP value_sp; if (name.empty()) return nullptr; @@ -258,10 +259,11 @@ OptionValueDictionary::GetSubValue(const ExecutionContext *exe_ctx, return value_sp->GetSubValue(exe_ctx, sub_name, will_modify, error); } -Error OptionValueDictionary::SetSubValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, - llvm::StringRef name, llvm::StringRef value) { - Error error; +Status OptionValueDictionary::SetSubValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, + llvm::StringRef name, + llvm::StringRef value) { + Status error; const bool will_modify = true; lldb::OptionValueSP value_sp(GetSubValue(exe_ctx, name, will_modify, error)); if (value_sp) diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueEnumeration.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueEnumeration.cpp index 2bff0bdcec37..9510f4a671d1 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueEnumeration.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueEnumeration.cpp @@ -45,9 +45,9 @@ void OptionValueEnumeration::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueEnumeration::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueEnumeration::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpec.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpec.cpp index 0df581af5d67..b235d4ac6863 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpec.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpec.cpp @@ -54,9 +54,9 @@ void OptionValueFileSpec::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueFileSpec::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueFileSpec::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp index 9cddf32206e4..7773bdc5ea9c 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFileSpecLIst.cpp @@ -38,9 +38,9 @@ void OptionValueFileSpecList::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueFileSpecList::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueFileSpecList::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; Args args(value.str()); const size_t argc = args.GetArgumentCount(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormat.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormat.cpp index 7d58f63a381e..24dd8fd5f71c 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormat.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormat.cpp @@ -31,9 +31,9 @@ void OptionValueFormat::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueFormat::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueFormat::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormatEntity.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormatEntity.cpp index 5259398dcd33..e9431d4562ec 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormatEntity.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueFormatEntity.cpp @@ -25,7 +25,7 @@ OptionValueFormatEntity::OptionValueFormatEntity(const char *default_format) m_default_entry() { if (default_format && default_format[0]) { llvm::StringRef default_format_str(default_format); - Error error = FormatEntity::Parse(default_format_str, m_default_entry); + Status error = FormatEntity::Parse(default_format_str, m_default_entry); if (error.Success()) { m_default_format = default_format; m_current_format = default_format; @@ -52,9 +52,9 @@ void OptionValueFormatEntity::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueFormatEntity::SetValueFromString(llvm::StringRef value_str, - VarSetOperationType op) { - Error error; +Status OptionValueFormatEntity::SetValueFromString(llvm::StringRef value_str, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueLanguage.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueLanguage.cpp index 2ea152c436c7..3290e88c1815 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueLanguage.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueLanguage.cpp @@ -32,9 +32,9 @@ void OptionValueLanguage::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueLanguage::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueLanguage::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValuePathMappings.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValuePathMappings.cpp index 54797422cba3..5f805720bd3f 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValuePathMappings.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValuePathMappings.cpp @@ -40,9 +40,9 @@ void OptionValuePathMappings::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValuePathMappings::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValuePathMappings::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; Args args(value.str()); const size_t argc = args.GetArgumentCount(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueProperties.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueProperties.cpp index 732769f6e6df..ae7669605592 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueProperties.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueProperties.cpp @@ -116,8 +116,8 @@ OptionValueProperties::GetValueForKey(const ExecutionContext *exe_ctx, lldb::OptionValueSP OptionValueProperties::GetSubValue(const ExecutionContext *exe_ctx, - llvm::StringRef name, bool will_modify, - Error &error) const { + llvm::StringRef name, bool will_modify, + Status &error) const { lldb::OptionValueSP value_sp; if (name.empty()) return OptionValueSP(); @@ -201,10 +201,11 @@ OptionValueProperties::GetSubValue(const ExecutionContext *exe_ctx, return value_sp; } -Error OptionValueProperties::SetSubValue(const ExecutionContext *exe_ctx, - VarSetOperationType op, - llvm::StringRef name, llvm::StringRef value) { - Error error; +Status OptionValueProperties::SetSubValue(const ExecutionContext *exe_ctx, + VarSetOperationType op, + llvm::StringRef name, + llvm::StringRef value) { + Status error; const bool will_modify = true; lldb::OptionValueSP value_sp(GetSubValue(exe_ctx, name, will_modify, error)); if (value_sp) @@ -523,9 +524,9 @@ bool OptionValueProperties::Clear() { return true; } -Error OptionValueProperties::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueProperties::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; // Args args(value_cstr); // const size_t argc = args.GetArgumentCount(); @@ -564,11 +565,11 @@ void OptionValueProperties::DumpValue(const ExecutionContext *exe_ctx, } } -Error OptionValueProperties::DumpPropertyValue(const ExecutionContext *exe_ctx, - Stream &strm, - llvm::StringRef property_path, - uint32_t dump_mask) { - Error error; +Status OptionValueProperties::DumpPropertyValue(const ExecutionContext *exe_ctx, + Stream &strm, + llvm::StringRef property_path, + uint32_t dump_mask) { + Status error; const bool will_modify = false; lldb::OptionValueSP value_sp( GetSubValue(exe_ctx, property_path, will_modify, error)); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueRegex.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueRegex.cpp index 6823300c515a..aee8f97db163 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueRegex.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueRegex.cpp @@ -32,9 +32,9 @@ void OptionValueRegex::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueRegex::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueRegex::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationInvalid: case eVarSetOperationInsertBefore: diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueSInt64.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueSInt64.cpp index 3bdbfb9e2fae..9dbcd58dc3e9 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueSInt64.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueSInt64.cpp @@ -34,9 +34,9 @@ void OptionValueSInt64::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueSInt64::SetValueFromString(llvm::StringRef value_ref, - VarSetOperationType op) { - Error error; +Status OptionValueSInt64::SetValueFromString(llvm::StringRef value_ref, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueString.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueString.cpp index 149ccbc7b518..1d7332dd41a6 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueString.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueString.cpp @@ -47,9 +47,9 @@ void OptionValueString::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueString::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueString::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; std::string value_str = value.str(); value = value.trim(); @@ -127,27 +127,27 @@ lldb::OptionValueSP OptionValueString::DeepCopy() const { return OptionValueSP(new OptionValueString(*this)); } -Error OptionValueString::SetCurrentValue(llvm::StringRef value) { +Status OptionValueString::SetCurrentValue(llvm::StringRef value) { if (m_validator) { - Error error(m_validator(value.str().c_str(), m_validator_baton)); + Status error(m_validator(value.str().c_str(), m_validator_baton)); if (error.Fail()) return error; } m_current_value.assign(value); - return Error(); + return Status(); } -Error OptionValueString::AppendToCurrentValue(const char *value) { +Status OptionValueString::AppendToCurrentValue(const char *value) { if (value && value[0]) { if (m_validator) { std::string new_value(m_current_value); new_value.append(value); - Error error(m_validator(value, m_validator_baton)); + Status error(m_validator(value, m_validator_baton)); if (error.Fail()) return error; m_current_value.assign(new_value); } else m_current_value.append(value); } - return Error(); + return Status(); } diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUInt64.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUInt64.cpp index 826c9e5ba887..c8db1bd532c6 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUInt64.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUInt64.cpp @@ -21,7 +21,7 @@ using namespace lldb; using namespace lldb_private; lldb::OptionValueSP OptionValueUInt64::Create(llvm::StringRef value_str, - Error &error) { + Status &error) { lldb::OptionValueSP value_sp(new OptionValueUInt64()); error = value_sp->SetValueFromString(value_str); if (error.Fail()) @@ -40,9 +40,9 @@ void OptionValueUInt64::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueUInt64::SetValueFromString(llvm::StringRef value_ref, - VarSetOperationType op) { - Error error; +Status OptionValueUInt64::SetValueFromString(llvm::StringRef value_ref, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUUID.cpp b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUUID.cpp index 7378195a2f94..bec04cba8c37 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUUID.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/OptionValueUUID.cpp @@ -32,9 +32,9 @@ void OptionValueUUID::DumpValue(const ExecutionContext *exe_ctx, Stream &strm, } } -Error OptionValueUUID::SetValueFromString(llvm::StringRef value, - VarSetOperationType op) { - Error error; +Status OptionValueUUID::SetValueFromString(llvm::StringRef value, + VarSetOperationType op) { + Status error; switch (op) { case eVarSetOperationClear: Clear(); diff --git a/contrib/llvm/tools/lldb/source/Interpreter/Options.cpp b/contrib/llvm/tools/lldb/source/Interpreter/Options.cpp index b8b9bdf54a0d..f8b1a8d6beba 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/Options.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/Options.cpp @@ -42,8 +42,8 @@ void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) { OptionParsingStarting(execution_context); } -Error Options::NotifyOptionParsingFinished( - ExecutionContext *execution_context) { +Status +Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) { return OptionParsingFinished(execution_context); } @@ -905,13 +905,13 @@ void OptionGroupOptions::Finalize() { m_did_finalize = true; } -Error OptionGroupOptions::SetOptionValue(uint32_t option_idx, - llvm::StringRef option_value, - ExecutionContext *execution_context) { +Status OptionGroupOptions::SetOptionValue(uint32_t option_idx, + llvm::StringRef option_value, + ExecutionContext *execution_context) { // After calling OptionGroupOptions::Append(...), you must finalize the groups // by calling OptionGroupOptions::Finlize() assert(m_did_finalize); - Error error; + Status error; if (option_idx < m_option_infos.size()) { error = m_option_infos[option_idx].option_group->SetOptionValue( m_option_infos[option_idx].option_index, option_value, @@ -935,10 +935,10 @@ void OptionGroupOptions::OptionParsingStarting( } } } -Error OptionGroupOptions::OptionParsingFinished( - ExecutionContext *execution_context) { +Status +OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) { std::set<OptionGroup *> group_set; - Error error; + Status error; OptionInfos::iterator pos, end = m_option_infos.end(); for (pos = m_option_infos.begin(); pos != end; ++pos) { OptionGroup *group = pos->option_group; diff --git a/contrib/llvm/tools/lldb/source/Interpreter/ScriptInterpreter.cpp b/contrib/llvm/tools/lldb/source/Interpreter/ScriptInterpreter.cpp index 0f7e1f8d74f4..57f7eea6e4c1 100644 --- a/contrib/llvm/tools/lldb/source/Interpreter/ScriptInterpreter.cpp +++ b/contrib/llvm/tools/lldb/source/Interpreter/ScriptInterpreter.cpp @@ -15,7 +15,7 @@ #include "lldb/Host/PseudoTerminal.h" #include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StringList.h" @@ -75,10 +75,10 @@ ScriptInterpreter::StringToLanguage(const llvm::StringRef &language) { return eScriptLanguageUnknown; } -Error ScriptInterpreter::SetBreakpointCommandCallback( +Status ScriptInterpreter::SetBreakpointCommandCallback( std::vector<BreakpointOptions *> &bp_options_vec, const char *callback_text) { - Error return_error; + Status return_error; for (BreakpointOptions *bp_options : bp_options_vec) { return_error = SetBreakpointCommandCallback(bp_options, callback_text); if (return_error.Success()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp index dc1c8dcf4ab0..06b1c7054c1f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.cpp @@ -30,7 +30,7 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "Plugins/Process/Utility/ARMDefines.h" #include "Utility/ARM_DWARF_Registers.h" @@ -1533,7 +1533,7 @@ bool ABIMacOSX_arm::GetArgumentValues(Thread &thread, ValueList &values) const { // Arguments 5 on up are on the stack const uint32_t arg_byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (!exe_ctx.GetProcessRef().ReadScalarIntegerFromMemory( sp, arg_byte_size, is_signed, value->GetScalar(), error)) return false; @@ -1619,7 +1619,7 @@ ValueObjectSP ABIMacOSX_arm::GetReturnValueObjectImpl( reg_ctx->ReadRegister(r1_reg_info, r1_reg_value) && reg_ctx->ReadRegister(r2_reg_info, r2_reg_value) && reg_ctx->ReadRegister(r3_reg_info, r3_reg_value)) { - Error error; + Status error; if (r0_reg_value.GetAsMemoryData(r0_reg_info, heap_data_ap->GetBytes() + 0, 4, byte_order, error) && @@ -1702,9 +1702,9 @@ ValueObjectSP ABIMacOSX_arm::GetReturnValueObjectImpl( return return_valobj_sp; } -Error ABIMacOSX_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABIMacOSX_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -1728,7 +1728,7 @@ Error ABIMacOSX_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (compiler_type.IsIntegerOrEnumerationType(is_signed) || compiler_type.IsPointerType()) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h index 39f57a0c5ee2..5aa817c20ec2 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h @@ -30,7 +30,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp index c5e53361bf99..a545dfc837da 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.cpp @@ -22,7 +22,6 @@ #include "lldb/Core/RegisterValue.h" #include "lldb/Core/Scalar.h" #include "lldb/Core/Value.h" -#include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Symbol/UnwindPlan.h" #include "lldb/Target/Process.h" @@ -30,8 +29,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "Utility/ARM64_DWARF_Registers.h" @@ -1841,7 +1840,7 @@ bool ABIMacOSX_arm64::GetArgumentValues(Thread &thread, // Arguments 5 on up are on the stack const uint32_t arg_byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (!exe_ctx.GetProcessRef().ReadScalarIntegerFromMemory( sp, arg_byte_size, is_signed, value->GetScalar(), error)) return false; @@ -1860,9 +1859,10 @@ bool ABIMacOSX_arm64::GetArgumentValues(Thread &thread, return true; } -Error ABIMacOSX_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status +ABIMacOSX_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -1880,7 +1880,7 @@ Error ABIMacOSX_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (reg_ctx) { DataExtractor data; - Error data_error; + Status data_error; const uint64_t byte_size = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -2124,7 +2124,7 @@ static bool LoadValueFromConsecutiveGPRRegisters( std::unique_ptr<DataBufferHeap> heap_data_ap( new DataBufferHeap(byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); - Error error; + Status error; CompilerType base_type; const uint32_t homogeneous_count = @@ -2305,7 +2305,7 @@ ValueObjectSP ABIMacOSX_arm64::GetReturnValueObjectImpl( RegisterValue x1_reg_value; if (reg_ctx->ReadRegister(x0_reg_info, x0_reg_value) && reg_ctx->ReadRegister(x1_reg_info, x1_reg_value)) { - Error error; + Status error; if (x0_reg_value.GetAsMemoryData( x0_reg_info, heap_data_ap->GetBytes() + 0, 8, byte_order, error) && @@ -2402,7 +2402,7 @@ ValueObjectSP ABIMacOSX_arm64::GetReturnValueObjectImpl( const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(v0_info, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData(v0_info, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h index 93a548a79682..589e2ea468ef 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-arm64/ABIMacOSX_arm64.h @@ -92,7 +92,7 @@ public: uint32_t GetPluginVersion() override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp index bbaec25b37b8..c393ac9c916b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.cpp @@ -29,7 +29,7 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -746,7 +746,7 @@ bool ABIMacOSX_i386::PrepareTrivialCall(Thread &thread, addr_t sp, // Make room for the argument(s) on the stack - Error error; + Status error; RegisterValue reg_value; // Write any arguments onto the stack @@ -793,7 +793,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, addr_t ¤t_stack_argument) { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (process->ReadScalarIntegerFromMemory(current_stack_argument, byte_size, is_signed, scalar, error)) { current_stack_argument += byte_size; @@ -849,9 +849,9 @@ bool ABIMacOSX_i386::GetArgumentValues(Thread &thread, return true; } -Error ABIMacOSX_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABIMacOSX_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -875,7 +875,7 @@ Error ABIMacOSX_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (compiler_type.IsIntegerOrEnumerationType(is_signed) || compiler_type.IsPointerType()) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h index 4a2555ac61a2..88fb6ffd7a40 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp index 3df225cc895d..614c6e893806 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.cpp @@ -30,7 +30,7 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "Plugins/Process/Utility/ARMDefines.h" #include "Utility/ARM_DWARF_Registers.h" @@ -1518,7 +1518,7 @@ bool ABISysV_arm::GetArgumentValues(Thread &thread, ValueList &values) const { // Arguments 5 on up are on the stack const uint32_t arg_byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (!exe_ctx.GetProcessRef().ReadScalarIntegerFromMemory( sp, arg_byte_size, is_signed, value->GetScalar(), error)) return false; @@ -1534,7 +1534,7 @@ bool ABISysV_arm::GetArgumentValues(Thread &thread, ValueList &values) const { static bool GetReturnValuePassedInMemory(Thread &thread, RegisterContext *reg_ctx, size_t byte_size, Value &value) { - Error error; + Status error; DataBufferHeap buffer(byte_size, 0); const RegisterInfo *r0_reg_info = @@ -1815,7 +1815,7 @@ ValueObjectSP ABISysV_arm::GetReturnValueObjectImpl( // Make sure we have enough room in "data_sp" if ((data_offset + vfp_byte_size) <= data_sp->GetByteSize()) { - Error error; + Status error; const size_t bytes_copied = reg_value.GetAsMemoryData( reg_info, data_sp->GetBytes() + data_offset, vfp_byte_size, byte_order, error); @@ -1846,9 +1846,9 @@ ValueObjectSP ABISysV_arm::GetReturnValueObjectImpl( return return_valobj_sp; } -Error ABISysV_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -1872,7 +1872,7 @@ Error ABISysV_arm::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (compiler_type.IsIntegerOrEnumerationType(is_signed) || compiler_type.IsPointerType()) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h index d85b3dff0ca5..81f1277419a6 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm/ABISysV_arm.h @@ -30,7 +30,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp index 65cbd271e979..b202c8395776 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.cpp @@ -30,8 +30,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "Utility/ARM64_DWARF_Registers.h" @@ -1813,7 +1813,7 @@ bool ABISysV_arm64::GetArgumentValues(Thread &thread, ValueList &values) const { // Arguments 5 on up are on the stack const uint32_t arg_byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (!exe_ctx.GetProcessRef().ReadScalarIntegerFromMemory( sp, arg_byte_size, is_signed, value->GetScalar(), error)) return false; @@ -1832,9 +1832,9 @@ bool ABISysV_arm64::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -Error ABISysV_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -1852,7 +1852,7 @@ Error ABISysV_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (reg_ctx) { DataExtractor data; - Error data_error; + Status data_error; const uint64_t byte_size = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -2101,7 +2101,7 @@ static bool LoadValueFromConsecutiveGPRRegisters( std::unique_ptr<DataBufferHeap> heap_data_ap( new DataBufferHeap(byte_size, 0)); const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); - Error error; + Status error; CompilerType base_type; const uint32_t homogeneous_count = @@ -2277,7 +2277,7 @@ ValueObjectSP ABISysV_arm64::GetReturnValueObjectImpl( RegisterValue x1_reg_value; if (reg_ctx->ReadRegister(x0_reg_info, x0_reg_value) && reg_ctx->ReadRegister(x1_reg_info, x1_reg_value)) { - Error error; + Status error; if (x0_reg_value.GetAsMemoryData( x0_reg_info, heap_data_ap->GetBytes() + 0, 8, byte_order, error) && @@ -2372,7 +2372,7 @@ ValueObjectSP ABISysV_arm64::GetReturnValueObjectImpl( const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(v0_info, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData(v0_info, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h index 68c300c0909d..c048e8634ae5 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-arm64/ABISysV_arm64.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp index 0b024dbac07d..425bf2ce0bf6 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -1073,7 +1073,7 @@ bool ABISysV_hexagon::PrepareTrivialCall( llvm::Type &prototype, llvm::ArrayRef<ABI::CallArgument> args) const { // default number of register passed arguments for varg functions const int nVArgRegParams = 1; - Error error; + Status error; // grab the process so we have access to the memory for spilling lldb::ProcessSP proc = thread.GetProcess(); @@ -1195,9 +1195,10 @@ bool ABISysV_hexagon::GetArgumentValues(Thread &thread, return false; } -Error ABISysV_hexagon::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status +ABISysV_hexagon::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h index aed3dd71b69a..5f808291eac0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-hexagon/ABISysV_hexagon.h @@ -39,7 +39,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp index aee102c16ba1..cb3644d46af4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -237,7 +237,7 @@ bool ABISysV_i386::PrepareTrivialCall(Thread &thread, addr_t sp, if (!reg_info_32) return false; // TODO this should actually never happen - Error error; + Status error; RegisterValue reg_value; // Make room for the argument(s) on the stack @@ -280,7 +280,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, bool is_signed, Process *process, addr_t ¤t_stack_argument) { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (!process) return false; @@ -333,9 +333,9 @@ bool ABISysV_i386::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -Error ABISysV_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -351,7 +351,7 @@ Error ABISysV_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, Thread *thread = frame_sp->GetThread().get(); RegisterContext *reg_ctx = thread->GetRegisterContext().get(); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); bool register_write_successful = true; @@ -661,7 +661,7 @@ ValueObjectSP ABISysV_i386::GetReturnValueObjectSimple( const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(vec_reg, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { @@ -688,7 +688,7 @@ ValueObjectSP ABISysV_i386::GetReturnValueObjectSimple( if (reg_ctx->ReadRegister(vec_reg, reg_value) && reg_ctx->ReadRegister(vec_reg2, reg_value2)) { - Error error; + Status error; if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), vec_reg->byte_size, byte_order, error) && diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h index 8d1d76b5dfd9..038bf656b1f1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.h @@ -33,7 +33,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp index 69725e30b063..a77252a20499 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -654,7 +654,7 @@ bool ABISysV_mips::PrepareTrivialCall(Thread &thread, addr_t sp, } } - Error error; + Status error; const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); const RegisterInfo *sp_reg_info = @@ -710,9 +710,9 @@ bool ABISysV_mips::GetArgumentValues(Thread &thread, ValueList &values) const { return false; } -Error ABISysV_mips::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_mips::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -736,7 +736,7 @@ Error ABISysV_mips::SetReturnValueObject(lldb::StackFrameSP &frame_sp, if (compiler_type.IsIntegerOrEnumerationType(is_signed) || compiler_type.IsPointerType()) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h index 7ac51463e6eb..980553c506bd 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips/ABISysV_mips.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp index bbcf2e575825..baa478ea1106 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -617,7 +617,7 @@ bool ABISysV_mips64::PrepareTrivialCall(Thread &thread, addr_t sp, sp &= ~(0xfull); // 16-byte alignment - Error error; + Status error; const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); const RegisterInfo *sp_reg_info = @@ -674,9 +674,9 @@ bool ABISysV_mips64::GetArgumentValues(Thread &thread, return false; } -Error ABISysV_mips64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_mips64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -696,7 +696,7 @@ Error ABISysV_mips64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, error.SetErrorString("no registers are available"); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -754,7 +754,7 @@ ValueObjectSP ABISysV_mips64::GetReturnValueObjectImpl( Thread &thread, CompilerType &return_compiler_type) const { ValueObjectSP return_valobj_sp; Value value; - Error error; + Status error; ExecutionContext exe_ctx(thread.shared_from_this()); if (exe_ctx.GetTargetPtr() == nullptr || exe_ctx.GetProcessPtr() == nullptr) diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h index 672a43825625..ac7d9b871946 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-mips64/ABISysV_mips64.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp index 2dff0d203611..00adfe1be82d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -282,7 +282,7 @@ bool ABISysV_ppc::PrepareTrivialCall(Thread &thread, addr_t sp, sp -= 8; - Error error; + Status error; const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); const RegisterInfo *sp_reg_info = @@ -376,7 +376,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, scalar.SignExtend(bit_width); } else { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (thread.GetProcess()->ReadScalarIntegerFromMemory( current_stack_argument, byte_size, is_signed, scalar, error)) { current_stack_argument += byte_size; @@ -464,9 +464,9 @@ bool ABISysV_ppc::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -Error ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -492,7 +492,7 @@ Error ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp, const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r3", 0); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -518,7 +518,7 @@ Error ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp, size_t bit_width = compiler_type.GetBitSize(frame_sp.get()); if (bit_width <= 64) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -663,7 +663,7 @@ ValueObjectSP ABISysV_ppc::GetReturnValueObjectSimple( const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(altivec_reg, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData( altivec_reg, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h index c9c1c985f679..8cb9bf24881f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc/ABISysV_ppc.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp index 59430caa6e37..449990d71304 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -282,7 +282,7 @@ bool ABISysV_ppc64::PrepareTrivialCall(Thread &thread, addr_t sp, sp -= 8; - Error error; + Status error; const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); const RegisterInfo *sp_reg_info = @@ -376,7 +376,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, scalar.SignExtend(bit_width); } else { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (thread.GetProcess()->ReadScalarIntegerFromMemory( current_stack_argument, byte_size, is_signed, scalar, error)) { current_stack_argument += byte_size; @@ -464,9 +464,9 @@ bool ABISysV_ppc64::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -Error ABISysV_ppc64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_ppc64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -492,7 +492,7 @@ Error ABISysV_ppc64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r3", 0); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -518,7 +518,7 @@ Error ABISysV_ppc64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, size_t bit_width = compiler_type.GetBitSize(frame_sp.get()); if (bit_width <= 64) { DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -663,7 +663,7 @@ ValueObjectSP ABISysV_ppc64::GetReturnValueObjectSimple( const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(altivec_reg, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData( altivec_reg, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h index 7f321dff49c1..29237a68fc9e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-ppc64/ABISysV_ppc64.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp index a899b24cea5c..7f76d49bfb0f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -268,7 +268,7 @@ bool ABISysV_s390x::PrepareTrivialCall(Thread &thread, addr_t sp, if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i])) return false; } else { - Error error; + Status error; if (log) log->Printf("About to write arg%" PRIu64 " (0x%" PRIx64 ") onto stack", static_cast<uint64_t>(i + 1), args[i]); @@ -321,7 +321,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, scalar.SignExtend(bit_width); } else { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (thread.GetProcess()->ReadScalarIntegerFromMemory( current_stack_argument + 8 - byte_size, byte_size, is_signed, scalar, error)) { @@ -401,9 +401,9 @@ bool ABISysV_s390x::GetArgumentValues(Thread &thread, ValueList &values) const { return true; } -Error ABISysV_s390x::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_s390x::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -429,7 +429,7 @@ Error ABISysV_s390x::SetReturnValueObject(lldb::StackFrameSP &frame_sp, const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r2", 0); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -457,7 +457,7 @@ Error ABISysV_s390x::SetReturnValueObject(lldb::StackFrameSP &frame_sp, const RegisterInfo *f0_info = reg_ctx->GetRegisterInfoByName("f0", 0); RegisterValue f0_value; DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h index 6ccabd6f75ec..e233a900e395 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-s390x/ABISysV_s390x.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp index 42bb9d057e61..deccca8c29e9 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -1152,7 +1152,7 @@ bool ABISysV_x86_64::PrepareTrivialCall(Thread &thread, addr_t sp, sp -= 8; - Error error; + Status error; const RegisterInfo *pc_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); const RegisterInfo *sp_reg_info = @@ -1246,7 +1246,7 @@ static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, scalar.SignExtend(bit_width); } else { uint32_t byte_size = (bit_width + (8 - 1)) / 8; - Error error; + Status error; if (thread.GetProcess()->ReadScalarIntegerFromMemory( current_stack_argument, byte_size, is_signed, scalar, error)) { current_stack_argument += byte_size; @@ -1329,9 +1329,9 @@ bool ABISysV_x86_64::GetArgumentValues(Thread &thread, return true; } -Error ABISysV_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, - lldb::ValueObjectSP &new_value_sp) { - Error error; +Status ABISysV_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, + lldb::ValueObjectSP &new_value_sp) { + Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; @@ -1357,7 +1357,7 @@ Error ABISysV_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("rax", 0); DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -1386,7 +1386,7 @@ Error ABISysV_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp, reg_ctx->GetRegisterInfoByName("xmm0", 0); RegisterValue xmm0_value; DataExtractor data; - Error data_error; + Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); if (data_error.Fail()) { error.SetErrorStringWithFormat( @@ -1542,7 +1542,7 @@ ValueObjectSP ABISysV_x86_64::GetReturnValueObjectSimple( const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(altivec_reg, reg_value)) { - Error error; + Status error; if (reg_value.GetAsMemoryData( altivec_reg, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { @@ -1569,7 +1569,7 @@ ValueObjectSP ABISysV_x86_64::GetReturnValueObjectSimple( if (reg_ctx->ReadRegister(altivec_reg, reg_value) && reg_ctx->ReadRegister(altivec_reg2, reg_value2)) { - Error error; + Status error; if (reg_value.GetAsMemoryData( altivec_reg, heap_data_ap->GetBytes(), altivec_reg->byte_size, byte_order, error) && diff --git a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h index 29f2ce133d42..8d420e88167c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h @@ -31,7 +31,7 @@ public: bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; - lldb_private::Error + lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp b/contrib/llvm/tools/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp index e144ef18b413..21e19bf2b127 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp @@ -885,9 +885,9 @@ DisassemblerLLVMC::LLVMCDisassembler::LLVMCDisassembler( const char *triple, const char *cpu, const char *features_str, unsigned flavor, DisassemblerLLVMC &owner) : m_is_valid(true) { - std::string Error; + std::string Status; const llvm::Target *curr_target = - llvm::TargetRegistry::lookupTarget(triple, Error); + llvm::TargetRegistry::lookupTarget(triple, Status); if (!curr_target) { m_is_valid = false; return; diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp index 25bf6e9a7296..d0d60017e869 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp @@ -213,7 +213,7 @@ ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() { } // AD: Needs to be updated? -Error DynamicLoaderHexagonDYLD::CanLoadImage() { return Error(); } +Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); } void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr, @@ -558,7 +558,7 @@ const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule( } static int ReadInt(Process *process, addr_t addr) { - Error error; + Status error; int value = (int)process->ReadUnsignedIntegerFromMemory( addr, sizeof(uint32_t), 0, error); if (error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h index 05709d07fd67..200a4171bd1c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.h @@ -47,7 +47,7 @@ public: lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread, bool stop_others) override; - lldb_private::Error CanLoadImage() override; + lldb_private::Status CanLoadImage() override; lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp index f22644aec107..1ef1be5d0adb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/HexagonDYLDRendezvous.cpp @@ -16,8 +16,8 @@ #include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Process.h" @@ -33,7 +33,7 @@ using namespace lldb_private; static addr_t ResolveRendezvousAddress(Process *process) { addr_t info_location; addr_t info_addr; - Error error; + Status error; info_location = process->GetImageInfoAddress(); @@ -222,7 +222,7 @@ bool HexagonDYLDRendezvous::TakeSnapshot(SOEntryList &entry_list) { addr_t HexagonDYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) { - Error error; + Status error; *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error); if (error.Fail()) @@ -232,7 +232,7 @@ addr_t HexagonDYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, } addr_t HexagonDYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) { - Error error; + Status error; *dst = m_process->ReadPointerFromMemory(addr, error); if (error.Fail()) @@ -243,7 +243,7 @@ addr_t HexagonDYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) { std::string HexagonDYLDRendezvous::ReadStringFromMemory(addr_t addr) { std::string str; - Error error; + Status error; size_t size; char c; @@ -304,7 +304,7 @@ bool HexagonDYLDRendezvous::FindMetadata(const char *name, PThreadField field, if (addr == LLDB_INVALID_ADDRESS) return false; - Error error; + Status error; value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory( addr + field * sizeof(uint32_t), sizeof(uint32_t), 0, error); if (error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp index c4917c08fa90..c1986976b0fc 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp @@ -18,8 +18,8 @@ #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/Path.h" @@ -34,7 +34,7 @@ static addr_t ResolveRendezvousAddress(Process *process) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); addr_t info_location; addr_t info_addr; - Error error; + Status error; if (!process) { if (log) @@ -420,7 +420,7 @@ bool DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list) { } addr_t DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) { - Error error; + Status error; *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error); if (error.Fail()) @@ -430,7 +430,7 @@ addr_t DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) { } addr_t DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) { - Error error; + Status error; *dst = m_process->ReadPointerFromMemory(addr, error); if (error.Fail()) @@ -441,7 +441,7 @@ addr_t DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) { std::string DYLDRendezvous::ReadStringFromMemory(addr_t addr) { std::string str; - Error error; + Status error; if (addr == LLDB_INVALID_ADDRESS) return std::string(); @@ -479,7 +479,7 @@ void DYLDRendezvous::UpdateBaseAddrIfNecessary(SOEntry &entry, if (isLoadBiasIncorrect(m_process->GetTarget(), file_path)) { lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; bool is_loaded = false; - Error error = + Status error = m_process->GetFileLoadAddress(entry.file_spec, is_loaded, load_addr); if (error.Success() && is_loaded) entry.base_addr = load_addr; @@ -545,7 +545,7 @@ bool DYLDRendezvous::FindMetadata(const char *name, PThreadField field, if (addr == LLDB_INVALID_ADDRESS) return false; - Error error; + Status error; value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory( addr + field * sizeof(uint32_t), sizeof(uint32_t), 0, error); if (error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp index c809d2c77834..5f56bfc027a4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.cpp @@ -222,7 +222,7 @@ void DynamicLoaderPOSIXDYLD::DidLaunch() { } } -Error DynamicLoaderPOSIXDYLD::CanLoadImage() { return Error(); } +Status DynamicLoaderPOSIXDYLD::CanLoadImage() { return Status(); } void DynamicLoaderPOSIXDYLD::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr, diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h index 8e4be1d4a06a..86e0311c2919 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h @@ -52,7 +52,7 @@ public: lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread, bool stop_others) override; - lldb_private::Error CanLoadImage() override; + lldb_private::Status CanLoadImage() override; lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp index 04f1f3390570..291695cb68c1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.cpp @@ -132,8 +132,8 @@ DynamicLoaderStatic::GetStepThroughTrampolinePlan(Thread &thread, return ThreadPlanSP(); } -Error DynamicLoaderStatic::CanLoadImage() { - Error error; +Status DynamicLoaderStatic::CanLoadImage() { + Status error; error.SetErrorString("can't load images on with a static debug session"); return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h index 413ad80a2fd9..2d18ec86afd3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Static/DynamicLoaderStatic.h @@ -52,7 +52,7 @@ public: lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread, bool stop_others) override; - lldb_private::Error CanLoadImage() override; + lldb_private::Status CanLoadImage() override; //------------------------------------------------------------------ // PluginInterface protocol diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp index 20bf3609f46f..c381326ebf4f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.cpp @@ -61,7 +61,7 @@ void DynamicLoaderWindowsDYLD::DidAttach() {} void DynamicLoaderWindowsDYLD::DidLaunch() {} -Error DynamicLoaderWindowsDYLD::CanLoadImage() { return Error(); } +Status DynamicLoaderWindowsDYLD::CanLoadImage() { return Status(); } ConstString DynamicLoaderWindowsDYLD::GetPluginName() { return GetPluginNameStatic(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h index 3494082eea8d..de6e295f7891 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h @@ -34,7 +34,7 @@ public: void DidAttach() override; void DidLaunch() override; - Error CanLoadImage() override; + Status CanLoadImage() override; lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, bool stop) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp index 1f78fb96bc34..256d46a15420 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp @@ -43,8 +43,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" @@ -191,7 +191,7 @@ bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl, return false; if (m_parser_vars->m_materializer && is_result) { - Error err; + Status err; ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx; Target *target = exe_ctx.GetTargetPtr(); @@ -364,7 +364,7 @@ bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl, if (m_parser_vars->m_materializer) { uint32_t offset = 0; - Error err; + Status err; if (is_persistent_variable) { ExpressionVariableSP var_sp(var->shared_from_this()); @@ -1630,7 +1630,7 @@ bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var, DWARFExpression &var_location_expr = var->LocationExpression(); Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); - Error err; + Status err; if (var->GetLocationIsConstantValueData()) { DataExtractor const_value_extractor; @@ -1987,8 +1987,33 @@ void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context, .GetOpaqueDeclContext(); clang::FunctionDecl *src_function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context); - - if (src_function_decl) { + if (src_function_decl && + src_function_decl->getTemplateSpecializationInfo()) { + clang::FunctionTemplateDecl *function_template = + src_function_decl->getTemplateSpecializationInfo()->getTemplate(); + clang::FunctionTemplateDecl *copied_function_template = + llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>( + m_ast_importer_sp->CopyDecl(m_ast_context, + src_ast->getASTContext(), + function_template)); + if (copied_function_template) { + if (log) { + ASTDumper ast_dumper((clang::Decl *)copied_function_template); + + StreamString ss; + + function->DumpSymbolContext(&ss); + + log->Printf(" CEDM::FEVD[%u] Imported decl for function template" + " %s (description %s), returned %s", + current_id, + copied_function_template->getNameAsString().c_str(), + ss.GetData(), ast_dumper.GetCString()); + } + + context.AddNamedDecl(copied_function_template); + } + } else if (src_function_decl) { if (clang::FunctionDecl *copied_function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>( m_ast_importer_sp->CopyDecl(m_ast_context, diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp index 6c923ced1ec2..4e20be79f68b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp @@ -756,7 +756,7 @@ static bool FindFunctionInModule(ConstString &mangled_name, return false; } -lldb_private::Error ClangExpressionParser::PrepareForExecution( +lldb_private::Status ClangExpressionParser::PrepareForExecution( lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, ExecutionPolicy execution_policy) { @@ -764,7 +764,7 @@ lldb_private::Error ClangExpressionParser::PrepareForExecution( func_end = LLDB_INVALID_ADDRESS; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - lldb_private::Error err; + lldb_private::Status err; std::unique_ptr<llvm::Module> llvm_module_ap( m_code_generator->ReleaseModule()); @@ -857,7 +857,7 @@ lldb_private::Error ClangExpressionParser::PrepareForExecution( if (execution_policy != eExecutionPolicyAlways && execution_policy != eExecutionPolicyTopLevel) { - lldb_private::Error interpret_error; + lldb_private::Status interpret_error; bool interpret_function_calls = !process ? false : process->CanInterpretFunctionCalls(); @@ -941,9 +941,9 @@ lldb_private::Error ClangExpressionParser::PrepareForExecution( return err; } -lldb_private::Error ClangExpressionParser::RunStaticInitializers( +lldb_private::Status ClangExpressionParser::RunStaticInitializers( lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) { - lldb_private::Error err; + lldb_private::Status err; lldbassert(execution_unit_sp.get()); lldbassert(exe_ctx.HasThreadScope()); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h index f0203f36e59b..3e6a109a4af3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.h @@ -14,7 +14,7 @@ #include "lldb/Core/ClangForward.h" #include "lldb/Expression/DiagnosticManager.h" #include "lldb/Expression/ExpressionParser.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-public.h" #include <string> @@ -110,7 +110,7 @@ public: /// An error code indicating the success or failure of the operation. /// Test with Success(). //------------------------------------------------------------------ - Error + Status PrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, @@ -128,8 +128,8 @@ public: /// @return /// The error code indicating the //------------------------------------------------------------------ - Error RunStaticInitializers(lldb::IRExecutionUnitSP &execution_unit_sp, - ExecutionContext &exe_ctx); + Status RunStaticInitializers(lldb::IRExecutionUnitSP &execution_unit_sp, + ExecutionContext &exe_ctx); //------------------------------------------------------------------ /// Returns a string representing current ABI. diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp index 95d81db12801..2a6261a6df4d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.cpp @@ -83,7 +83,7 @@ ClangUserExpression::ClangUserExpression( ClangUserExpression::~ClangUserExpression() {} -void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err) { +void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); if (log) @@ -315,7 +315,7 @@ bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, bool generate_debug_info) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); - Error err; + Status err; InstallContext(exe_ctx); @@ -501,7 +501,7 @@ bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, // { - Error jit_error = parser.PrepareForExecution( + Status jit_error = parser.PrepareForExecution( m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx, m_can_interpret, execution_policy); @@ -517,7 +517,7 @@ bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager, } if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) { - Error static_init_error = + Status static_init_error = parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx); if (!static_init_error.Success()) { @@ -603,7 +603,7 @@ bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx, return false; } - Error object_ptr_error; + Status object_ptr_error; object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h index 155c153b873c..88a78798b657 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUserExpression.h @@ -168,7 +168,7 @@ private: //------------------------------------------------------------------ void ScanContext(ExecutionContext &exe_ctx, - lldb_private::Error &err) override; + lldb_private::Status &err) override; bool AddArguments(ExecutionContext &exe_ctx, std::vector<lldb::addr_t> &args, lldb::addr_t struct_address, diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp index a54ab4a2267a..065e5db4c9f8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/ClangUtilityFunction.cpp @@ -118,7 +118,7 @@ bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager, bool can_interpret = false; // should stay that way - Error jit_error = parser.PrepareForExecution( + Status jit_error = parser.PrepareForExecution( m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx, can_interpret, eExecutionPolicyAlways); diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp index 68a214ee4683..13f5657eedd8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp @@ -1263,7 +1263,7 @@ bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) { lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc( llvm::NextPowerOf2(constant_size) * 8); - lldb_private::Error get_data_error; + lldb_private::Status get_data_error; if (!scalar.GetAsMemoryData(data, constant_size, lldb_private::endian::InlHostByteOrder(), get_data_error)) diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h index eb52730f3a87..93ce8aa44eb2 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.h @@ -13,7 +13,7 @@ #include "lldb/Symbol/TaggedASTType.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/lldb-public.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.cpp index 0bae4a4574d9..538bd05e25f8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.cpp @@ -12,7 +12,7 @@ #include "GoParser.h" #include "Plugins/ExpressionParser/Go/GoAST.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/ADT/SmallString.h" using namespace lldb_private; @@ -860,7 +860,7 @@ llvm::StringRef GoParser::CopyString(llvm::StringRef s) { return m_strings.insert(std::make_pair(s, 'x')).first->getKey(); } -void GoParser::GetError(Error &error) { +void GoParser::GetError(Status &error) { llvm::StringRef want; if (m_failed) want = diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.h b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.h index bd1285580228..9ed2ae2033bd 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoParser.h @@ -82,7 +82,7 @@ public: return m_lexer.BytesRemaining() == 0 && m_pos == m_tokens.size(); } - void GetError(Error &error); + void GetError(Status &error); private: class Rule; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoUserExpression.cpp b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoUserExpression.cpp index 50d45a1ad1e7..f4b8cfbe03d4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoUserExpression.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/GoUserExpression.cpp @@ -150,7 +150,7 @@ public: CompilerType EvaluateType(const GoASTExpr *e); - Error &error() { return m_error; } + Status &error() { return m_error; } private: std::nullptr_t NotImplemented(const GoASTExpr *e) { @@ -163,7 +163,7 @@ private: lldb::StackFrameSP m_frame; GoParser m_parser; DynamicValueType m_use_dynamic; - Error m_error; + Status m_error; llvm::StringRef m_package; std::vector<std::unique_ptr<GoASTStmt>> m_statements; }; @@ -254,7 +254,7 @@ GoUserExpression::DoExecute(DiagnosticManager &diagnostic_manager, m_interpreter->set_use_dynamic(options.GetUseDynamic()); ValueObjectSP result_val_sp = m_interpreter->Evaluate(exe_ctx); - Error err = m_interpreter->error(); + Status err = m_interpreter->error(); m_interpreter.reset(); if (!result_val_sp) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h index 40a31169ecd8..fb1867c6362a 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM/EmulateInstructionARM.h @@ -13,7 +13,7 @@ #include "Plugins/Process/Utility/ARMDefines.h" #include "lldb/Core/EmulateInstruction.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" namespace lldb_private { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp index 655fada3a4b3..54dd237eb4b7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.cpp @@ -846,7 +846,7 @@ bool EmulateInstructionARM64::EmulateLDPSTP(const uint32_t opcode) { Context context_t2; uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; switch (memop) { case MemOp_STORE: { @@ -992,7 +992,7 @@ bool EmulateInstructionARM64::EmulateLDRSTRImm(const uint32_t opcode) { return false; } - Error error; + Status error; bool success = false; uint64_t address; uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h index 475410ab2d13..253bb935bca7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/ARM64/EmulateInstructionARM64.h @@ -17,7 +17,7 @@ #include "Plugins/Process/Utility/ARMDefines.h" #include "lldb/Core/EmulateInstruction.h" #include "lldb/Interpreter/OptionValue.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" class EmulateInstructionARM64 : public lldb_private::EmulateInstruction { public: diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp index aa7c6e5d1fe0..4d1d89abb1d0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp @@ -63,10 +63,10 @@ EmulateInstructionMIPS::EmulateInstructionMIPS( const lldb_private::ArchSpec &arch) : EmulateInstruction(arch) { /* Create instance of llvm::MCDisassembler */ - std::string Error; + std::string Status; llvm::Triple triple = arch.GetTriple(); const llvm::Target *target = - llvm::TargetRegistry::lookupTarget(triple.getTriple(), Error); + llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status); /* * If we fail to get the target then we haven't registered it. The @@ -83,7 +83,7 @@ EmulateInstructionMIPS::EmulateInstructionMIPS( LLVMInitializeMipsAsmPrinter(); LLVMInitializeMipsTargetMC(); LLVMInitializeMipsDisassembler(); - target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Error); + target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status); } #endif @@ -1019,7 +1019,7 @@ bool EmulateInstructionMIPS::SetInstruction(const Opcode &insn_opcode, if (EmulateInstruction::SetInstruction(insn_opcode, inst_addr, target)) { if (inst_addr.GetAddressClass() == eAddressClassCodeAlternateISA) { - Error error; + Status error; lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; /* @@ -1297,7 +1297,7 @@ bool EmulateInstructionMIPS::Emulate_SW(llvm::MCInst &insn) { context.SetRegisterToRegisterPlusOffset(reg_info_src, reg_info_base, 0); uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; if (!ReadRegister(®_info_base, data_src)) return false; @@ -1563,7 +1563,7 @@ bool EmulateInstructionMIPS::Emulate_SWSP(llvm::MCInst &insn) { context.SetRegisterToRegisterPlusOffset(reg_info_src, reg_info_base, 0); uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; if (!ReadRegister(®_info_base, data_src)) return false; @@ -1646,7 +1646,7 @@ bool EmulateInstructionMIPS::Emulate_SWM16_32(llvm::MCInst &insn) { context.SetRegisterToRegisterPlusOffset(reg_info_src, reg_info_base, 0); uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; if (!ReadRegister(®_info_base, data_src)) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h index 0375056f87c7..8d6e0be3cd78 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.h @@ -23,7 +23,7 @@ class MCInst; #include "lldb/Core/EmulateInstruction.h" #include "lldb/Interpreter/OptionValue.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" class EmulateInstructionMIPS : public lldb_private::EmulateInstruction { public: diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp index 4c90a1901da7..1e6d98756958 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp @@ -63,10 +63,10 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64( const lldb_private::ArchSpec &arch) : EmulateInstruction(arch) { /* Create instance of llvm::MCDisassembler */ - std::string Error; + std::string Status; llvm::Triple triple = arch.GetTriple(); const llvm::Target *target = - llvm::TargetRegistry::lookupTarget(triple.getTriple(), Error); + llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status); /* * If we fail to get the target then we haven't registered it. The @@ -83,7 +83,7 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64( LLVMInitializeMipsAsmPrinter(); LLVMInitializeMipsTargetMC(); LLVMInitializeMipsDisassembler(); - target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Error); + target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status); } #endif @@ -1141,7 +1141,7 @@ bool EmulateInstructionMIPS64::Emulate_SD(llvm::MCInst &insn) { context.SetRegisterToRegisterPlusOffset(reg_info_src, reg_info_base, 0); uint8_t buffer[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; if (!ReadRegister(®_info_base, data_src)) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h index 1e5be516d130..c2433d59830e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h @@ -16,7 +16,7 @@ // Project includes #include "lldb/Core/EmulateInstruction.h" #include "lldb/Interpreter/OptionValue.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" namespace llvm { class MCDisassembler; diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp index 96370528f260..91c5d6ce3d60 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/AddressSanitizer/AddressSanitizerRuntime.cpp @@ -134,7 +134,7 @@ StructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() { ValueObjectSP return_value_sp; ExecutionContext exe_ctx; - Error eval_error; + Status eval_error; frame_sp->CalculateExecutionContext(exe_ctx); ExpressionResults result = UserExpression::Evaluate( exe_ctx, options, address_sanitizer_retrieve_report_data_command, "", @@ -171,7 +171,7 @@ StructuredData::ObjectSP AddressSanitizerRuntime::RetrieveReportData() { return_value_sp->GetValueForExpressionPath(".description") ->GetValueAsUnsigned(0); std::string description; - Error error; + Status error; process_sp->ReadCStringFromMemory(description_ptr, description, error); StructuredData::Dictionary *dict = new StructuredData::Dictionary(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp index 562d988be837..d7b518982fcf 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/InstrumentationRuntime/ThreadSanitizer/ThreadSanitizerRuntime.cpp @@ -256,7 +256,7 @@ static std::string RetrieveString(ValueObjectSP return_value_sp, return_value_sp->GetValueForExpressionPath(expression_path.c_str()) ->GetValueAsUnsigned(0); std::string str; - Error error; + Status error; process_sp->ReadCStringFromMemory(ptr, str, error); return str; } @@ -325,7 +325,7 @@ ThreadSanitizerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) { ValueObjectSP main_value; ExecutionContext exe_ctx; - Error eval_error; + Status eval_error; frame_sp->CalculateExecutionContext(exe_ctx); ExpressionResults result = UserExpression::Evaluate( exe_ctx, options, thread_sanitizer_retrieve_report_data_command, "", diff --git a/contrib/llvm/tools/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp b/contrib/llvm/tools/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp index b97d67a0bb42..7ef3aecdb89f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp @@ -103,7 +103,7 @@ bool ReadJITEntry(const addr_t from_addr, Process *process, const size_t data_byte_size = llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t); - Error error; + Status error; DataBufferHeap data(data_byte_size, 0); size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(), data.GetByteSize(), error); @@ -277,7 +277,7 @@ bool JITLoaderGDB::ReadJITDescriptorImpl(bool all_entries) { jit_descriptor<ptr_t> jit_desc; const size_t jit_desc_size = sizeof(jit_desc); - Error error; + Status error; size_t bytes_read = m_process->DoReadMemory(m_jit_descriptor_addr, &jit_desc, jit_desc_size, error); if (bytes_read != jit_desc_size || !error.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp index db7c24675825..5e8f051dec98 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/BlockPointer.cpp @@ -44,7 +44,7 @@ public: return; } - Error err; + Status err; TypeSystem *type_system = target_sp->GetScratchTypeSystemForLanguage( &err, lldb::eLanguageTypeC_plus_plus); @@ -133,7 +133,7 @@ public: return lldb::ValueObjectSP(); } - Error err; + Status err; ValueObjectSP struct_sp = struct_pointer_sp->Dereference(err); if (!struct_sp || !err.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp index b69b69530428..0f6fb54e8384 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/CxxStringTypes.cpp @@ -24,7 +24,7 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include <algorithm> @@ -129,7 +129,7 @@ bool lldb_private::formatters::WCharStringSummaryProvider( bool lldb_private::formatters::Char16SummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &) { DataExtractor data; - Error error; + Status error; valobj.GetData(data, error); if (error.Fail()) @@ -155,7 +155,7 @@ bool lldb_private::formatters::Char16SummaryProvider( bool lldb_private::formatters::Char32SummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &) { DataExtractor data; - Error error; + Status error; valobj.GetData(data, error); if (error.Fail()) @@ -181,7 +181,7 @@ bool lldb_private::formatters::Char32SummaryProvider( bool lldb_private::formatters::WCharSummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &) { DataExtractor data; - Error error; + Status error; valobj.GetData(data, error); if (error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp index 659a12b7eecf..11245e1310b7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp @@ -26,7 +26,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -53,7 +53,7 @@ bool lldb_private::formatters::LibcxxSmartPointerSummaryProvider( return true; } else { bool print_pointee = false; - Error error; + Status error; ValueObjectSP pointee_sp = ptr_sp->Dereference(error); if (pointee_sp && error.Success()) { if (pointee_sp->DumpPrintableRepresentation( @@ -181,7 +181,7 @@ bool lldb_private::formatters::LibCxxMapIteratorSyntheticFrontEnd::Update() { }); DataBufferSP buffer_sp(new DataBufferHeap(tree_node_type.GetByteSize(nullptr),0)); ProcessSP process_sp(target_sp->GetProcessSP()); - Error error; + Status error; process_sp->ReadMemory(addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp index 4ad3df3d6038..56d8edaba72a 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -291,7 +291,7 @@ lldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetChildAtIndex( // we need to copy current_sp into a new object otherwise we will end up with // all items named __value_ DataExtractor data; - Error error; + Status error; current_sp->GetData(data, error); if (error.Fail()) return lldb::ValueObjectSP(); @@ -312,7 +312,7 @@ bool lldb_private::formatters::LibcxxStdListSyntheticFrontEnd::Update() { m_slow_runner.SetEntry(nullptr); m_fast_runner.SetEntry(nullptr); - Error err; + Status err; ValueObjectSP backend_addr(m_backend.AddressOf(err)); m_list_capping_size = 0; if (m_backend.GetTargetSP()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp index 293d64075921..b7215dbcbb48 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxMap.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -259,7 +259,7 @@ bool lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetDataType() { return true; m_element_type.Clear(); ValueObjectSP deref; - Error error; + Status error; deref = m_root_node->Dereference(error); if (!deref || error.Fail()) return false; @@ -365,7 +365,7 @@ lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetChildAtIndex( } if (GetDataType()) { if (!need_to_skip) { - Error error; + Status error; iterated_sp = iterated_sp->Dereference(error); if (!iterated_sp || error.Fail()) { m_tree = nullptr; @@ -406,7 +406,7 @@ lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetChildAtIndex( // we need to copy current_sp into a new object otherwise we will end up with // all items named __value_ DataExtractor data; - Error error; + Status error; iterated_sp->GetData(data, error); if (error.Fail()) { m_tree = nullptr; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp index 526bae6900f5..190b5f64381e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxUnorderedMap.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -83,7 +83,7 @@ lldb::ValueObjectSP lldb_private::formatters:: if (m_next_element == nullptr) return lldb::ValueObjectSP(); - Error error; + Status error; ValueObjectSP node_sp = m_next_element->Dereference(error); if (!node_sp || error.Fail()) return lldb::ValueObjectSP(); @@ -153,7 +153,7 @@ lldb::ValueObjectSP lldb_private::formatters:: StreamString stream; stream.Printf("[%" PRIu64 "]", (uint64_t)idx); DataExtractor data; - Error error; + Status error; val_hash.first->GetData(data, error); if (error.Fail()) return lldb::ValueObjectSP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp index 96d7e51deba4..6f601c9f6ccb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibCxxVector.cpp @@ -209,7 +209,7 @@ lldb_private::formatters::LibcxxVectorBoolSyntheticFrontEnd::GetChildAtIndex( return ValueObjectSP(); uint8_t byte = 0; uint8_t mask = 0; - Error err; + Status err; size_t bytes_read = process_sp->ReadMemory(byte_location, &byte, 1, err); if (err.Fail() || bytes_read == 0) return ValueObjectSP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp index a4633db8157e..e3018a1884be 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcpp.cpp @@ -21,7 +21,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -209,7 +209,7 @@ bool VectorIteratorSyntheticFrontEnd::Update() { return false; if (item_ptr->GetValueAsUnsigned(0) == 0) return false; - Error err; + Status err; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); m_item_sp = CreateValueObjectFromAddress( "item", item_ptr->GetValueAsUnsigned(0), m_exe_ctx_ref, @@ -251,7 +251,7 @@ bool lldb_private::formatters::LibStdcppStringSummaryProvider( return false; StringPrinter::ReadStringAndDumpToStreamOptions options(valobj); - Error error; + Status error; lldb::addr_t addr_of_data = process_sp->ReadPointerFromMemory(addr_of_string, error); if (error.Fail() || addr_of_data == 0 || @@ -308,7 +308,7 @@ bool lldb_private::formatters::LibStdcppWStringSummaryProvider( nullptr); // Safe to pass NULL for exe_scope here StringPrinter::ReadStringAndDumpToStreamOptions options(valobj); - Error error; + Status error; lldb::addr_t addr_of_data = process_sp->ReadPointerFromMemory(addr_of_string, error); if (error.Fail() || addr_of_data == 0 || @@ -414,7 +414,7 @@ bool lldb_private::formatters::LibStdcppSmartPointerSummaryProvider( return true; } - Error error; + Status error; ValueObjectSP pointee_sp = ptr_sp->Dereference(error); if (pointee_sp && error.Success()) { if (pointee_sp->DumpPrintableRepresentation( diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp index 7693961cae17..b6d664df16ef 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/CPlusPlus/LibStdcppUniquePointer.cpp @@ -79,7 +79,7 @@ bool LibStdcppUniquePtrSyntheticFrontEnd::Update() { m_del_obj = del_obj->Clone(ConstString("deleter")); if (m_ptr_obj) { - Error error; + Status error; ValueObjectSP obj_obj = m_ptr_obj->Dereference(error); if (error.Success()) { m_obj_obj = obj_obj->Clone(ConstString("object")); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/Go/GoFormatterFunctions.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/Go/GoFormatterFunctions.cpp index 0f78f643321b..aac75205c6ef 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/Go/GoFormatterFunctions.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/Go/GoFormatterFunctions.cpp @@ -96,7 +96,7 @@ bool lldb_private::formatters::GoStringSummaryProvider( return false; if (valobj.IsPointerType()) { - Error err; + Status err; ValueObjectSP deref = valobj.Dereference(err); if (!err.Success()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/Java/JavaFormatterFunctions.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/Java/JavaFormatterFunctions.cpp index 286651a64409..498795c90be8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/Java/JavaFormatterFunctions.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/Java/JavaFormatterFunctions.cpp @@ -57,7 +57,7 @@ public: valobj->GetAddressOf() + JavaASTContext::CalculateArrayElementOffset(type, idx); - Error error; + Status error; size_t byte_size = element_type.GetByteSize(nullptr); DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0)); size_t bytes_read = process_sp->ReadMemory(address, buffer_sp->GetBytes(), @@ -86,7 +86,7 @@ private: if (!m_backend.IsPointerOrReferenceType()) return m_backend.GetSP(); - Error error; + Status error; return m_backend.Dereference(error); } }; @@ -96,7 +96,7 @@ private: bool lldb_private::formatters::JavaStringSummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &opts) { if (valobj.IsPointerOrReferenceType()) { - Error error; + Status error; ValueObjectSP deref = valobj.Dereference(error); if (error.Fail()) return false; @@ -145,7 +145,7 @@ bool lldb_private::formatters::JavaStringSummaryProvider( bool lldb_private::formatters::JavaArraySummaryProvider( ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) { if (valobj.IsPointerOrReferenceType()) { - Error error; + Status error; ValueObjectSP deref = valobj.Dereference(error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/CF.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/CF.cpp index a75c034afa9f..9bb8eeab1d2e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/CF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/CF.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -88,7 +88,7 @@ bool lldb_private::formatters::CFBagSummaryProvider( if (is_type_ok) { lldb::addr_t offset = 2 * ptr_size + 4 + valobj_addr; - Error error; + Status error; count = process_sp->ReadUnsignedIntegerFromMemory(offset, 4, 0, error); if (error.Fail()) return false; @@ -152,7 +152,7 @@ bool lldb_private::formatters::CFBitVectorSummaryProvider( if (is_type_ok == false) return false; - Error error; + Status error; count = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + 2 * ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -281,7 +281,7 @@ bool lldb_private::formatters::CFBinaryHeapSummaryProvider( if (is_type_ok) { lldb::addr_t offset = 2 * ptr_size + valobj_addr; - Error error; + Status error; count = process_sp->ReadUnsignedIntegerFromMemory(offset, 4, 0, error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp index 0fc690606d16..dd3dc434f753 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/Cocoa.cpp @@ -28,7 +28,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.h" @@ -218,7 +218,7 @@ bool lldb_private::formatters::NSMachPortSummaryProvider( if (!strcmp(class_name, "NSMachPort")) { uint64_t offset = (ptr_size == 4 ? 12 : 20); - Error error; + Status error; port_number = process_sp->ReadUnsignedIntegerFromMemory( offset + valobj_addr, 4, 0, error); if (error.Success()) { @@ -267,7 +267,7 @@ bool lldb_private::formatters::NSIndexSetSummaryProvider( do { if (!strcmp(class_name, "NSIndexSet") || !strcmp(class_name, "NSMutableIndexSet")) { - Error error; + Status error; uint32_t mode = process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + ptr_size, 4, 0, error); if (error.Fail()) @@ -461,7 +461,7 @@ bool lldb_private::formatters::NSNumberSummaryProvider( } return true; } else { - Error error; + Status error; uint8_t data_type = (process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + ptr_size, 1, 0, error) & 0x1F); @@ -653,7 +653,7 @@ bool lldb_private::formatters::NSDateSummaryProvider( process_sp->GetTarget().GetArchitecture().GetTriple()); uint32_t delta = (triple.isWatchOS() && triple.isWatchABI()) ? 8 : ptr_size; - Error error; + Status error; date_value_bits = process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + delta, 8, 0, error); memcpy(&date_value, &date_value_bits, sizeof(date_value_bits)); @@ -661,7 +661,7 @@ bool lldb_private::formatters::NSDateSummaryProvider( return false; } } else if (class_name == g_NSCalendarDate) { - Error error; + Status error; date_value_bits = process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + 2 * ptr_size, 8, 0, error); memcpy(&date_value, &date_value_bits, sizeof(date_value_bits)); @@ -788,14 +788,14 @@ bool lldb_private::formatters::NSDataSummaryProvider( !strcmp(class_name, "NSConcreteMutableData") || !strcmp(class_name, "__NSCFData")) { uint32_t offset = (is_64bit ? 16 : 8); - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + offset, is_64bit ? 8 : 4, 0, error); if (error.Fail()) return false; } else if (!strcmp(class_name, "_NSInlineData")) { uint32_t offset = (is_64bit ? 8 : 4); - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + offset, 2, 0, error); if (error.Fail()) @@ -818,7 +818,7 @@ bool lldb_private::formatters::ObjCBOOLSummaryProvider( ValueObjectSP real_guy_sp = valobj.GetSP(); if (type_info & eTypeIsPointer) { - Error err; + Status err; real_guy_sp = valobj.Dereference(err); if (err.Fail() || !real_guy_sp) return false; @@ -893,7 +893,7 @@ bool lldb_private::formatters::ObjCSELSummaryProvider( exe_ctx, charstar); } else { DataExtractor data; - Error error; + Status error; valobj.GetData(data, error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSArray.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSArray.cpp index 79773fdf1d15..b07b9ba5888f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSArray.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSArray.cpp @@ -26,7 +26,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -262,13 +262,13 @@ bool lldb_private::formatters::NSArraySummaryProvider( return false; if (class_name == g_NSArrayI) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) return false; } else if (class_name == g_NSArrayM) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -278,7 +278,7 @@ bool lldb_private::formatters::NSArraySummaryProvider( } else if (class_name == g_NSArray1) { value = 1; } else if (class_name == g_NSArrayCF) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory( valobj_addr + 2 * ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -364,7 +364,7 @@ bool lldb_private::formatters::NSArrayMSyntheticFrontEnd_109::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; error.Clear(); lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) @@ -395,7 +395,7 @@ bool lldb_private::formatters::NSArrayMSyntheticFrontEnd_1010::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; error.Clear(); lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) @@ -538,7 +538,7 @@ bool lldb_private::formatters::NSArrayISyntheticFrontEnd::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; error.Clear(); lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) @@ -566,7 +566,7 @@ lldb_private::formatters::NSArrayISyntheticFrontEnd::GetChildAtIndex( ProcessSP process_sp = m_exe_ctx_ref.GetProcessSP(); if (!process_sp) return lldb::ValueObjectSP(); - Error error; + Status error; if (error.Fail()) return lldb::ValueObjectSP(); StreamString idx_name; @@ -665,7 +665,7 @@ lldb_private::formatters::NSArraySyntheticFrontEndCreator( Flags flags(valobj_type.GetTypeInfo()); if (flags.IsClear(eTypeIsPointer)) { - Error error; + Status error; valobj_sp = valobj_sp->AddressOf(error); if (error.Fail() || !valobj_sp) return nullptr; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp index 672cc1a26f4e..6df83d52acca 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSDictionary.cpp @@ -27,7 +27,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -256,14 +256,14 @@ bool lldb_private::formatters::NSDictionarySummaryProvider( return false; if (class_name == g_DictionaryI) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) return false; value &= (is_64bit ? ~0xFC00000000000000UL : ~0xFC000000U); } else if (class_name == g_DictionaryM) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -274,7 +274,7 @@ bool lldb_private::formatters::NSDictionarySummaryProvider( } /*else if (!strcmp(class_name,"__NSCFDictionary")) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + (is_64bit ? 20 : 12), 4, 0, error); if (error.Fail()) @@ -321,7 +321,7 @@ lldb_private::formatters::NSDictionarySyntheticFrontEndCreator( Flags flags(valobj_type.GetTypeInfo()); if (flags.IsClear(eTypeIsPointer)) { - Error error; + Status error; valobj_sp = valobj_sp->AddressOf(error); if (error.Fail() || !valobj_sp) return nullptr; @@ -400,7 +400,7 @@ bool lldb_private::formatters::NSDictionaryISyntheticFrontEnd::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; error.Clear(); lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) @@ -449,7 +449,7 @@ lldb_private::formatters::NSDictionaryISyntheticFrontEnd::GetChildAtIndex( ProcessSP process_sp = m_exe_ctx_ref.GetProcessSP(); if (!process_sp) return lldb::ValueObjectSP(); - Error error; + Status error; key_at_idx = process_sp->ReadPointerFromMemory(key_at_idx, error); if (error.Fail()) return lldb::ValueObjectSP(); @@ -553,7 +553,7 @@ lldb_private::formatters::NSDictionary1SyntheticFrontEnd::GetChildAtIndex( m_backend.GetValueAsUnsigned(LLDB_INVALID_ADDRESS) + ptr_size; lldb::addr_t value_ptr = key_ptr + ptr_size; - Error error; + Status error; lldb::addr_t value_at_idx = process_sp->ReadPointerFromMemory(key_ptr, error); if (error.Fail()) @@ -625,7 +625,7 @@ bool lldb_private::formatters::NSDictionaryMSyntheticFrontEnd::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; error.Clear(); lldb::ProcessSP process_sp(valobj_sp->GetProcessSP()); if (!process_sp) @@ -679,7 +679,7 @@ lldb_private::formatters::NSDictionaryMSyntheticFrontEnd::GetChildAtIndex( ProcessSP process_sp = m_exe_ctx_ref.GetProcessSP(); if (!process_sp) return lldb::ValueObjectSP(); - Error error; + Status error; key_at_idx = process_sp->ReadPointerFromMemory(key_at_idx, error); if (error.Fail()) return lldb::ValueObjectSP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSError.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSError.cpp index e8044d3b0013..4365a12b54e1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSError.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSError.cpp @@ -24,7 +24,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "Plugins/Language/ObjC/NSString.h" @@ -46,7 +46,7 @@ static lldb::addr_t DerefToNSErrorPointer(ValueObject &valobj) { Flags pointee_flags(pointee_type.GetTypeInfo()); if (pointee_flags.AllSet(eTypeIsPointer)) { if (ProcessSP process_sp = valobj.GetProcessSP()) { - Error error; + Status error; ptr_value = process_sp->ReadPointerFromMemory(ptr_value, error); } } @@ -71,7 +71,7 @@ bool lldb_private::formatters::NSError_SummaryProvider( lldb::addr_t code_location = ptr_value + 2 * ptr_size; lldb::addr_t domain_location = ptr_value + 3 * ptr_size; - Error error; + Status error; uint64_t code = process_sp->ReadUnsignedIntegerFromMemory(code_location, ptr_size, 0, error); if (error.Fail()) @@ -152,7 +152,7 @@ public: size_t ptr_size = process_sp->GetAddressByteSize(); userinfo_location += 4 * ptr_size; - Error error; + Status error; lldb::addr_t userinfo = process_sp->ReadPointerFromMemory(userinfo_location, error); if (userinfo == LLDB_INVALID_ADDRESS || error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSException.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSException.cpp index aa86e207783d..1da4f6de19a0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSException.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSException.cpp @@ -24,7 +24,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "Plugins/Language/ObjC/NSString.h" @@ -55,7 +55,7 @@ bool lldb_private::formatters::NSException_SummaryProvider( lldb::addr_t name_location = ptr_value + 1 * ptr_size; lldb::addr_t reason_location = ptr_value + 2 * ptr_size; - Error error; + Status error; lldb::addr_t name = process_sp->ReadPointerFromMemory(name_location, error); if (error.Fail() || name == LLDB_INVALID_ADDRESS) return false; @@ -146,7 +146,7 @@ public: size_t ptr_size = process_sp->GetAddressByteSize(); userinfo_location += 3 * ptr_size; - Error error; + Status error; lldb::addr_t userinfo = process_sp->ReadPointerFromMemory(userinfo_location, error); if (userinfo == LLDB_INVALID_ADDRESS || error.Fail()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp index adefba902b61..b6f6ff7af19d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSSet.cpp @@ -22,7 +22,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -185,14 +185,14 @@ bool lldb_private::formatters::NSSetSummaryProvider( return false; if (!strcmp(class_name, "__NSSetI")) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) return false; value &= (is_64bit ? ~0xFC00000000000000UL : ~0xFC000000U); } else if (!strcmp(class_name, "__NSSetM")) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -201,7 +201,7 @@ bool lldb_private::formatters::NSSetSummaryProvider( } /*else if (!strcmp(class_name,"__NSCFSet")) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + (is_64bit ? 20 : 12), 4, 0, error); if (error.Fail()) @@ -211,7 +211,7 @@ bool lldb_private::formatters::NSSetSummaryProvider( } else if (!strcmp(class_name,"NSCountedSet")) { - Error error; + Status error; value = process_sp->ReadUnsignedIntegerFromMemory(valobj_addr + ptr_size, ptr_size, 0, error); if (error.Fail()) @@ -262,7 +262,7 @@ lldb_private::formatters::NSSetSyntheticFrontEndCreator( Flags flags(valobj_type.GetTypeInfo()); if (flags.IsClear(eTypeIsPointer)) { - Error error; + Status error; valobj_sp = valobj_sp->AddressOf(error); if (error.Fail() || !valobj_sp) return nullptr; @@ -338,7 +338,7 @@ bool lldb_private::formatters::NSSetISyntheticFrontEnd::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; if (valobj_sp->IsPointerType()) { valobj_sp = valobj_sp->Dereference(error); if (error.Fail() || !valobj_sp) @@ -391,7 +391,7 @@ lldb_private::formatters::NSSetISyntheticFrontEnd::GetChildAtIndex(size_t idx) { obj_at_idx = m_data_ptr + (test_idx * m_ptr_size); if (!process_sp) return lldb::ValueObjectSP(); - Error error; + Status error; obj_at_idx = process_sp->ReadPointerFromMemory(obj_at_idx, error); if (error.Fail()) return lldb::ValueObjectSP(); @@ -487,7 +487,7 @@ bool lldb_private::formatters::NSSetMSyntheticFrontEnd::Update() { if (!valobj_sp) return false; m_exe_ctx_ref = valobj_sp->GetExecutionContextRef(); - Error error; + Status error; if (valobj_sp->IsPointerType()) { valobj_sp = valobj_sp->Dereference(error); if (error.Fail() || !valobj_sp) @@ -542,7 +542,7 @@ lldb_private::formatters::NSSetMSyntheticFrontEnd::GetChildAtIndex(size_t idx) { obj_at_idx = m_objs_addr + (test_idx * m_ptr_size); if (!process_sp) return lldb::ValueObjectSP(); - Error error; + Status error; obj_at_idx = process_sp->ReadPointerFromMemory(obj_at_idx, error); if (error.Fail()) return lldb::ValueObjectSP(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSString.cpp b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSString.cpp index d0258be8211e..3b4edf68e063 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSString.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Language/ObjC/NSString.cpp @@ -20,7 +20,7 @@ #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/Endian.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -103,7 +103,7 @@ bool lldb_private::formatters::NSStringSummaryProvider( if (process_sp->GetByteOrder() != lldb::eByteOrderLittle) info_bits_location += 3; - Error error; + Status error; uint8_t info_bits = process_sp->ReadUnsignedIntegerFromMemory( info_bits_location, 1, 0, error); @@ -258,7 +258,7 @@ bool lldb_private::formatters::NSStringSummaryProvider( // in this kind of string, the byte before the string content is a length // byte // so let's try and use it to handle the embedded NUL case - Error error; + Status error; explicit_length = process_sp->ReadUnsignedIntegerFromMemory(location, 1, 0, error); if (error.Fail() || explicit_length == 0) @@ -319,7 +319,7 @@ bool lldb_private::formatters::NSAttributedStringSummaryProvider( if (!child_ptr_sp) return false; DataExtractor data; - Error error; + Status error; child_ptr_sp->GetData(data, error); if (error.Fail()) return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp index e308747378d3..e5a459dfe861 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include <vector> @@ -217,7 +217,7 @@ bool ItaniumABILanguageRuntime::GetDynamicTypeAndAddress( if (process == nullptr) return false; - Error error; + Status error; const lldb::addr_t vtable_address_point = process->ReadPointerFromMemory(original_ptr, error); diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/Go/GoLanguageRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/Go/GoLanguageRuntime.cpp index c52fc1e121d8..6670f89dde5f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/Go/GoLanguageRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/Go/GoLanguageRuntime.cpp @@ -27,8 +27,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "llvm/ADT/Twine.h" #include <vector> @@ -42,7 +42,7 @@ ValueObjectSP GetChild(ValueObject &obj, const char *name, ConstString name_const_str(name); ValueObjectSP result = obj.GetChildMemberWithName(name_const_str, true); if (dereference && result && result->IsPointerType()) { - Error err; + Status err; result = result->Dereference(err); if (err.Fail()) result.reset(); @@ -55,7 +55,7 @@ ConstString ReadString(ValueObject &str, Process *process) { ValueObjectSP data = GetChild(str, "str", false); ValueObjectSP len = GetChild(str, "len"); if (len && data) { - Error err; + Status err; lldb::addr_t addr = data->GetPointerValue(); if (addr == LLDB_INVALID_ADDRESS) return result; @@ -97,7 +97,7 @@ CompilerType LookupRuntimeType(ValueObjectSP type, ExecutionContext *exe_ctx, *is_direct = GoASTContext::IsDirectIface(kind); if (GoASTContext::IsPointerKind(kind)) { CompilerType type_ptr = type->GetCompilerType().GetPointerType(); - Error err; + Status err; ValueObjectSP elem = type->CreateValueObjectFromAddress("elem", type->GetAddressOf() + type->GetByteSize(), @@ -138,7 +138,7 @@ bool GoLanguageRuntime::GetDynamicTypeAndAddress( value_type = Value::eValueTypeScalar; class_type_or_name.Clear(); if (CouldHaveDynamicValue(in_value)) { - Error err; + Status err; ValueObjectSP iface = in_value.GetStaticValue(); ValueObjectSP data_sp = GetChild(*iface, "data", false); if (!data_sp) diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp index 6b5e6b1eb764..ecb0b64f2346 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp @@ -52,7 +52,7 @@ bool ClassDescriptorV2::objc_class_t::Read(Process *process, + ptr_size; // uintptr_t data_NEVER_USE; DataBufferHeap objc_class_buf(objc_class_size, '\0'); - Error error; + Status error; process->ReadMemory(addr, objc_class_buf.GetBytes(), objc_class_size, error); if (error.Fail()) { @@ -92,7 +92,7 @@ bool ClassDescriptorV2::class_rw_t::Read(Process *process, lldb::addr_t addr) { + ptr_size; // Class nextSiblingClass; DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -132,7 +132,7 @@ bool ClassDescriptorV2::class_ro_t::Read(Process *process, lldb::addr_t addr) { + ptr_size; // const property_list_t *baseProperties; DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -180,7 +180,7 @@ bool ClassDescriptorV2::Read_class_row( class_ro.reset(); class_rw.reset(); - Error error; + Status error; uint32_t class_row_t_flags = process->ReadUnsignedIntegerFromMemory( objc_class.m_data_ptr, sizeof(uint32_t), 0, error); if (!error.Success()) @@ -219,7 +219,7 @@ bool ClassDescriptorV2::method_list_t::Read(Process *process, + sizeof(uint32_t); // uint32_t count; DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -242,7 +242,7 @@ bool ClassDescriptorV2::method_t::Read(Process *process, lldb::addr_t addr) { size_t size = GetSize(process); DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -276,7 +276,7 @@ bool ClassDescriptorV2::ivar_list_t::Read(Process *process, lldb::addr_t addr) { + sizeof(uint32_t); // uint32_t count; DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -299,7 +299,7 @@ bool ClassDescriptorV2::ivar_t::Read(Process *process, lldb::addr_t addr) { size_t size = GetSize(process); DataBufferHeap buffer(size, '\0'); - Error error; + Status error; process->ReadMemory(addr, buffer.GetBytes(), size, error); if (error.Fail()) { @@ -527,7 +527,7 @@ void ClassDescriptorV2::iVarsStorage::fill(AppleObjCRuntimeV2 &runtime, "{3}, type_size = {4}", name, type, offset_ptr, size, ivar_type.GetByteSize(nullptr)); Scalar offset_scalar; - Error error; + Status error; const int offset_ptr_size = 4; const bool is_signed = false; size_t read = process->ReadScalarIntegerFromMemory( diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp index 6b27009a0727..eacc98a07193 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntime.cpp @@ -31,8 +31,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include <vector> @@ -145,7 +145,7 @@ bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value, lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS; if (!m_print_object_caller_up) { - Error error; + Status error; m_print_object_caller_up.reset( exe_scope->CalculateTarget()->GetFunctionCallerForLanguage( eLanguageTypeObjC, return_compiler_type, *function_address, @@ -185,7 +185,7 @@ bool AppleObjCRuntime::GetObjectDescription(Stream &strm, Value &value, size_t full_buffer_len = sizeof(buf) - 1; size_t curr_len = full_buffer_len; while (curr_len == full_buffer_len) { - Error error; + Status error; curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error); strm.Write(buf, curr_len); diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp index 2c92b922b9df..566fefaf7984 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.cpp @@ -28,8 +28,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include <vector> @@ -172,7 +172,7 @@ UtilityFunction *AppleObjCRuntimeV1::CreateObjectChecker(const char *name) { name); assert(strformatsize < (int)sizeof(buf->contents)); - Error error; + Status error; return GetTargetRef().GetUtilityFunctionForLanguage( buf->contents, eLanguageTypeObjC, name, error); } @@ -196,7 +196,7 @@ void AppleObjCRuntimeV1::ClassDescriptorV1::Initialize( m_valid = true; - Error error; + Status error; m_isa = process_sp->ReadPointerFromMemory(isa, error); @@ -302,7 +302,7 @@ lldb::addr_t AppleObjCRuntimeV1::GetISAHashTablePointer() { symbol->GetAddressRef().GetLoadAddress(&process->GetTarget()); if (objc_debug_class_hash_addr != LLDB_INVALID_ADDRESS) { - Error error; + Status error; lldb::addr_t objc_debug_class_hash_ptr = process->ReadPointerFromMemory(objc_debug_class_hash_addr, error); if (objc_debug_class_hash_ptr != 0 && @@ -348,7 +348,7 @@ void AppleObjCRuntimeV1::UpdateISAToDescriptorMapIfNeeded() { // const void *info; // } NXHashTable; - Error error; + Status error; DataBufferHeap buffer(1024, 0); if (process->ReadMemory(hash_table_ptr, buffer.GetBytes(), 20, error) == 20) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp index 42c5fe9248f6..f15bcaa13844 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.cpp @@ -51,8 +51,8 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" @@ -338,7 +338,7 @@ __lldb_apple_objc_v2_get_shared_cache_class_info (void *objc_opt_ro_ptr, static uint64_t ExtractRuntimeGlobalSymbol(Process *process, ConstString name, - const ModuleSP &module_sp, Error &error, + const ModuleSP &module_sp, Status &error, bool read_value = true, uint8_t byte_size = 0, uint64_t default_value = LLDB_INVALID_ADDRESS, SymbolType sym_type = lldb::eSymbolTypeData) { @@ -483,9 +483,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { case 'v': @@ -676,7 +676,7 @@ protected: const char *arg_str = command.GetArgumentAtIndex(i); if (!arg_str) continue; - Error error; + Status error; lldb::addr_t arg_addr = Args::StringToAddress( &exe_ctx, arg_str, LLDB_INVALID_ADDRESS, &error); if (arg_addr == 0 || arg_addr == LLDB_INVALID_ADDRESS || error.Fail()) @@ -895,7 +895,7 @@ UtilityFunction *AppleObjCRuntimeV2::CreateObjectChecker(const char *name) { assert(len < (int)sizeof(check_function_code)); UNUSED_IF_ASSERT_DISABLED(len); - Error error; + Status error; return GetTargetRef().GetUtilityFunctionForLanguage( check_function_code, eLanguageTypeObjC, name, error); } @@ -927,7 +927,7 @@ size_t AppleObjCRuntimeV2::GetByteOffsetForIvar(CompilerType &parent_ast_type, addr_t ivar_offset_address = LLDB_INVALID_ADDRESS; - Error error; + Status error; SymbolContext ivar_offset_symbol; if (sc_list.GetSize() == 1 && sc_list.GetContextAtIndex(0, ivar_offset_symbol)) { @@ -984,7 +984,7 @@ public: m_map_pair_size = m_process->GetAddressByteSize() * 2; m_invalid_key = m_process->GetAddressByteSize() == 8 ? UINT64_MAX : UINT32_MAX; - Error err; + Status err; // This currently holds true for all platforms we support, but we might // need to change this to use get the actually byte size of "unsigned" @@ -1077,7 +1077,7 @@ public: size_t map_pair_size = m_parent.m_map_pair_size; lldb::addr_t pair_ptr = pairs_ptr + (m_index * map_pair_size); - Error err; + Status err; lldb::addr_t key = m_parent.m_process->ReadPointerFromMemory(pair_ptr, err); @@ -1106,7 +1106,7 @@ public: const lldb::addr_t pairs_ptr = m_parent.m_buckets_ptr; const size_t map_pair_size = m_parent.m_map_pair_size; const lldb::addr_t invalid_key = m_parent.m_invalid_key; - Error err; + Status err; while (m_index--) { lldb::addr_t pair_ptr = pairs_ptr + (m_index * map_pair_size); @@ -1218,7 +1218,7 @@ AppleObjCRuntimeV2::GetClassDescriptor(ValueObject &valobj) { Process *process = exe_ctx.GetProcessPtr(); if (process) { - Error error; + Status error; ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error); if (isa != LLDB_INVALID_ADDRESS) { objc_class_sp = GetClassDescriptorFromISA(isa); @@ -1255,7 +1255,7 @@ lldb::addr_t AppleObjCRuntimeV2::GetISAHashTablePointer() { symbol->GetLoadAddress(&process->GetTarget()); if (gdb_objc_realized_classes_ptr != LLDB_INVALID_ADDRESS) { - Error error; + Status error; m_isa_hash_table_ptr = process->ReadPointerFromMemory( gdb_objc_realized_classes_ptr, error); } @@ -1295,7 +1295,7 @@ AppleObjCRuntimeV2::UpdateISAToDescriptorMapDynamic( const uint32_t addr_size = process->GetAddressByteSize(); - Error err; + Status err; // Read the total number of classes from the hash table const uint32_t num_classes = hash_table.GetCount(); @@ -1315,7 +1315,7 @@ AppleObjCRuntimeV2::UpdateISAToDescriptorMapDynamic( FunctionCaller *get_class_info_function = nullptr; if (!m_get_class_info_code.get()) { - Error error; + Status error; m_get_class_info_code.reset(GetTargetRef().GetUtilityFunctionForLanguage( g_get_dynamic_class_info_body, eLanguageTypeObjC, g_get_dynamic_class_info_name, error)); @@ -1547,7 +1547,7 @@ AppleObjCRuntimeV2::UpdateISAToDescriptorMapSharedCache() { const uint32_t addr_size = process->GetAddressByteSize(); - Error err; + Status err; uint32_t num_class_infos = 0; @@ -1568,7 +1568,7 @@ AppleObjCRuntimeV2::UpdateISAToDescriptorMapSharedCache() { FunctionCaller *get_shared_cache_class_info_function = nullptr; if (!m_get_shared_cache_class_info_code.get()) { - Error error; + Status error; m_get_shared_cache_class_info_code.reset( GetTargetRef().GetUtilityFunctionForLanguage( g_get_shared_cache_class_info_body, eLanguageTypeObjC, @@ -1803,7 +1803,8 @@ lldb::addr_t AppleObjCRuntimeV2::GetSharedCacheReadOnlyAddress() { void AppleObjCRuntimeV2::UpdateISAToDescriptorMapIfNeeded() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_TYPES)); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); // Else we need to check with our process to see when the map was updated. Process *process = GetProcess(); @@ -2019,7 +2020,7 @@ AppleObjCRuntimeV2::NonPointerISACache::CreateInstance( AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp) { Process *process(runtime.GetProcess()); - Error error; + Status error; auto objc_debug_isa_magic_mask = ExtractRuntimeGlobalSymbol( process, ConstString("objc_debug_isa_magic_mask"), objc_module_sp, error); @@ -2050,7 +2051,7 @@ AppleObjCRuntimeV2::TaggedPointerVendorV2::CreateInstance( AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp) { Process *process(runtime.GetProcess()); - Error error; + Status error; auto objc_debug_taggedpointer_mask = ExtractRuntimeGlobalSymbol( process, ConstString("objc_debug_taggedpointer_mask"), objc_module_sp, @@ -2262,7 +2263,7 @@ AppleObjCRuntimeV2::TaggedPointerVendorRuntimeAssisted::GetClassDescriptor( Process *process(m_runtime.GetProcess()); uintptr_t slot_ptr = slot * process->GetAddressByteSize() + m_objc_debug_taggedpointer_classes; - Error error; + Status error; uintptr_t slot_data = process->ReadPointerFromMemory(slot_ptr, error); if (error.Fail() || slot_data == 0 || slot_data == uintptr_t(LLDB_INVALID_ADDRESS)) @@ -2349,7 +2350,7 @@ AppleObjCRuntimeV2::TaggedPointerVendorExtended::GetClassDescriptor( Process *process(m_runtime.GetProcess()); uintptr_t slot_ptr = slot * process->GetAddressByteSize() + m_objc_debug_taggedpointer_ext_classes; - Error error; + Status error; uintptr_t slot_data = process->ReadPointerFromMemory(slot_ptr, error); if (error.Fail() || slot_data == 0 || slot_data == uintptr_t(LLDB_INVALID_ADDRESS)) diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp index 8ce65b07684f..a6e9c0c16f16 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCTrampolineHandler.cpp @@ -299,7 +299,7 @@ void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() { process_sp->GetByteOrder(), process_sp->GetAddressByteSize()); size_t actual_size = 8 + process_sp->GetAddressByteSize(); - Error error; + Status error; size_t bytes_read = process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error); if (bytes_read != actual_size) { @@ -534,7 +534,7 @@ bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines( return false; // Now get a pointer value from the zeroth argument. - Error error; + Status error; DataExtractor data; error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data, 0, NULL); @@ -555,7 +555,7 @@ bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() { m_regions.clear(); if (!InitializeVTableSymbols()) return false; - Error error; + Status error; ProcessSP process_sp = GetProcessSP(); if (process_sp) { lldb::addr_t region_addr = @@ -770,7 +770,7 @@ AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread, if (!m_impl_code.get()) { if (m_lookup_implementation_function_code != NULL) { - Error error; + Status error; m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( m_lookup_implementation_function_code, eLanguageTypeObjC, g_lookup_implementation_function_name, error)); @@ -802,7 +802,7 @@ AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread, thread.GetProcess()->GetTarget().GetScratchClangASTContext(); CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); - Error error; + Status error; impl_function_caller = m_impl_code->MakeFunctionCaller( clang_void_ptr_type, dispatch_values, thread_sp, error); diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp index 7a9e66cf5481..7e46afcccdab 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp @@ -42,9 +42,9 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataBufferLLVM.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/RegularExpression.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -123,7 +123,7 @@ struct GetArgsCtx { bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); - Error err; + Status err; // get the current stack pointer uint64_t sp = ctx.reg_ctx->GetSP(); @@ -136,7 +136,7 @@ bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { size_t arg_size = sizeof(uint32_t); // read the argument from memory arg.value = 0; - Error err; + Status err; size_t read = ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err); if (read != arg_size || !err.Success()) { @@ -166,7 +166,7 @@ bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 4, // eBool, }}; - Error err; + Status err; // get the current stack pointer uint64_t sp = ctx.reg_ctx->GetSP(); @@ -230,7 +230,7 @@ bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); - Error err; + Status err; // get the current stack pointer uint64_t sp = ctx.reg_ctx->GetSP(); @@ -310,7 +310,7 @@ bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); - Error err; + Status err; // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space) uint64_t sp = ctx.reg_ctx->GetSP() + 16; @@ -355,7 +355,7 @@ bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); - Error err; + Status err; // get the current stack pointer uint64_t sp = ctx.reg_ctx->GetSP(); @@ -1189,7 +1189,7 @@ void RenderScriptRuntime::CaptureDebugHintScriptGroup2( // parse script group name ConstString group_name; { - Error err; + Status err; const uint64_t len = uint64_t(args[eGroupNameSize]); std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]); m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err); @@ -1238,7 +1238,7 @@ void RenderScriptRuntime::CaptureDebugHintScriptGroup2( // extract script group kernel addresses from the target const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size; uint64_t kernel_addr = 0; - Error err; + Status err; size_t read = m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err); if (!err.Success() || read != target_ptr_size) { @@ -1337,7 +1337,7 @@ void RenderScriptRuntime::CaptureScriptInvokeForEachMulti( } const uint32_t target_ptr_size = m_process->GetAddressByteSize(); - Error err; + Status err; std::vector<uint64_t> allocs; // traverse allocation list @@ -1524,7 +1524,7 @@ void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook, ExecutionContext &exe_ctx) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); - Error err; + Status err; Process *process = exe_ctx.GetProcessPtr(); enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr }; @@ -1756,7 +1756,7 @@ bool RenderScriptRuntime::EvalRSExpression(const char *expr, // The result of the expression is invalid if (!expr_result->GetError().Success()) { - Error err = expr_result->GetError(); + Status err = expr_result->GetError(); // Expression returned is void, so this is actually a success if (err.GetError() == UserExpression::kNoResult) { if (log) @@ -2140,7 +2140,7 @@ bool RenderScriptRuntime::JITSubelements(Element &elem, case 1: // Name of child { lldb::addr_t address = static_cast<addr_t>(results); - Error err; + Status err; std::string name; GetProcess()->ReadCStringFromMemory(address, name, err); if (!err.Fail()) @@ -2386,7 +2386,7 @@ void RenderScriptRuntime::FindStructTypeName(Element &elem, if (found) { // Dereference since our Element type isn't a pointer. if (valobj_sp->IsPointerType()) { - Error err; + Status err; ValueObjectSP deref_valobj = valobj_sp->Dereference(err); if (!err.Fail()) valobj_sp = deref_valobj; @@ -2482,7 +2482,7 @@ RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc, } // Read the inferior memory - Error err; + Status err; lldb::addr_t data_ptr = *alloc->data_ptr.get(); GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err); if (err.Fail()) { @@ -2643,7 +2643,7 @@ bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, // Copy file data from our buffer into the target allocation. lldb::addr_t alloc_data = *alloc->data_ptr.get(); - Error err; + Status err; size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err); if (!err.Success() || written != size) { strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString()); @@ -2795,7 +2795,7 @@ bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes); - Error err = file.Write(&head, num_bytes); + Status err = file.Write(&head, num_bytes); if (!err.Success()) { strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path); strm.EOL(); @@ -2900,7 +2900,7 @@ bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) { const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType( gDbgPresentStr, eSymbolTypeData); if (debug_present) { - Error err; + Status err; uint32_t flag = 0x00000001U; Target &target = GetProcess()->GetTarget(); addr_t addr = debug_present->GetLoadAddress(&target); @@ -3179,7 +3179,7 @@ bool RSModuleDescriptor::ParseRSInfo() { return info_lines.size() > 0; } -void RenderScriptRuntime::Status(Stream &strm) const { +void RenderScriptRuntime::DumpStatus(Stream &strm) const { if (m_libRS) { strm.Printf("Runtime Library discovered."); strm.EOL(); @@ -3620,7 +3620,7 @@ RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) { // Give RS breakpoints a specific name, so the user can manipulate them as a // group. - Error err; + Status err; if (!bp->AddName("RenderScriptKernel", err)) if (log) log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, @@ -3648,7 +3648,7 @@ RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name, // Give RS breakpoints a specific name, so the user can manipulate them as a // group. - Error err; + Status err; if (!bp->AddName("RenderScriptReduction", err)) if (log) log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, @@ -3664,7 +3664,7 @@ bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char *var_name, uint64_t &val) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE)); - Error err; + Status err; VariableSP var_sp; // Find variable in stack frame @@ -3889,7 +3889,7 @@ RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name, m_filtersp, resolver_sp, false, false, false); // Give RS breakpoints a specific name, so the user can manipulate them as a // group. - Error err; + Status err; if (!bp->AddName(name.AsCString(), err)) if (log) log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, @@ -4213,9 +4213,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *exe_ctx) override { - Error err; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *exe_ctx) override { + Status err; StreamString err_str; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -4369,9 +4369,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *exe_ctx) override { - Error err; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *exe_ctx) override { + Status err; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -4650,9 +4650,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *exe_ctx) override { - Error err; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *exe_ctx) override { + Status err; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -4772,9 +4772,9 @@ public: ~CommandOptions() override = default; - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *exe_ctx) override { - Error err; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *exe_ctx) override { + Status err; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -4993,7 +4993,7 @@ public: RenderScriptRuntime *runtime = (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( eLanguageTypeExtRenderScript); - runtime->Status(result.GetOutputStream()); + runtime->DumpStatus(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h index 5b2bb57ac8c8..0fe9134ce9e4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h @@ -374,7 +374,7 @@ public: void SetBreakAllKernels(bool do_break, lldb::TargetSP target); - void Status(Stream &strm) const; + void DumpStatus(Stream &strm) const; void ModulesDidLoad(const ModuleList &module_list) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp index 9ca8fb4444c0..fe4ae21a0c39 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptScriptGroup.cpp @@ -21,8 +21,8 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "RenderScriptRuntime.h" #include "RenderScriptScriptGroup.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp b/contrib/llvm/tools/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp index 35247edfbd56..b9e49d1faa1b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp @@ -170,7 +170,7 @@ HistoryThreads MemoryHistoryASan::GetHistoryThreads(lldb::addr_t address) { ExecutionContext exe_ctx(frame_sp); ValueObjectSP return_value_sp; StreamString expr; - Error eval_error; + Status eval_error; expr.Printf(memory_history_asan_command_format, address, address); EvaluateExpressionOptions options; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp b/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp index 928157516808..8a388a667372 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp @@ -301,8 +301,9 @@ ObjectContainer *ObjectContainerBSDArchive::CreateInstance( DataExtractor data; data.SetData(data_sp, data_offset, length); if (file && data_sp && ObjectContainerBSDArchive::MagicBytesMatch(data)) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "ObjectContainerBSDArchive::CreateInstance (module = %s, file = " "%p, file_offset = 0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")", module_sp->GetFileSpec().GetPath().c_str(), diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp index 0720cca27341..b71d6fa4ebea 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp @@ -25,8 +25,8 @@ #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferLLVM.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "llvm/ADT/PointerUnion.h" @@ -727,8 +727,9 @@ size_t ObjectFileELF::GetModuleSpecifications( uint32_t core_notes_crc = 0; if (!gnu_debuglink_crc) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); lldb_private::Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "Calculating module crc32 %s with size %" PRIu64 " KiB", file.GetLastPathComponent().AsCString(), (file.GetByteSize() - file_offset) / 1024); @@ -1079,7 +1080,7 @@ Address ObjectFileELF::GetImageInfoAddress(Target *target) { if (dyn_base == LLDB_INVALID_ADDRESS) return Address(); - Error error; + Status error; if (symbol.d_tag == DT_MIPS_RLD_MAP) { // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer. Address addr; @@ -1232,12 +1233,12 @@ size_t ObjectFileELF::ParseProgramHeaders() { m_header); } -lldb_private::Error +lldb_private::Status ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data, lldb_private::ArchSpec &arch_spec, lldb_private::UUID &uuid) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES)); - Error error; + Status error; lldb::offset_t offset = 0; @@ -1763,7 +1764,7 @@ size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl §ion_headers, DataExtractor data; if (section_size && (set_data(data, sheader.sh_offset, section_size) == section_size)) { - Error error = RefineModuleDetailsFromNote(data, arch_spec, uuid); + Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid); if (error.Fail()) { if (log) log->Printf("ObjectFileELF::%s ELF note processing failed: %s", diff --git a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h index 9b2d58b7be82..06f1a4d22d2d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.h @@ -375,7 +375,7 @@ private: unsigned PLTRelocationType(); - static lldb_private::Error + static lldb_private::Status RefineModuleDetailsFromNote(lldb_private::DataExtractor &data, lldb_private::ArchSpec &arch_spec, lldb_private::UUID &uuid); diff --git a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.cpp b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.cpp index 1a0c32729865..75bc518f7538 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.cpp @@ -315,7 +315,7 @@ bool OperatingSystemGo::UpdateThreadList(ThreadList &old_thread_list, // the // lldb_private::Process subclass, no memory threads will be in this list. - Error err; + Status err; for (uint64_t i = 0; i < allglen; ++i) { goroutines.push_back(CreateGoroutineAtIndex(i, err)); if (err.Fail()) { @@ -340,8 +340,8 @@ bool OperatingSystemGo::UpdateThreadList(ThreadList &old_thread_list, memory_thread->IsValid()) { memory_thread->ClearBackingThread(); } else { - memory_thread.reset(new ThreadMemory( - *m_process, goroutine.m_goid, nullptr, nullptr, goroutine.m_gobuf)); + memory_thread.reset(new ThreadMemory(*m_process, goroutine.m_goid, "", "", + goroutine.m_gobuf)); } // Search for the backing thread if the goroutine is running. if (2 == (goroutine.m_status & 0xfff)) { @@ -448,7 +448,7 @@ TypeSP OperatingSystemGo::FindType(TargetSP target_sp, const char *name) { } OperatingSystemGo::Goroutine -OperatingSystemGo::CreateGoroutineAtIndex(uint64_t idx, Error &err) { +OperatingSystemGo::CreateGoroutineAtIndex(uint64_t idx, Status &err) { err.Clear(); Goroutine result = {}; ValueObjectSP g = diff --git a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.h b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.h index d289985c72ad..5d255a348a63 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.h +++ b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Go/OperatingSystemGo.h @@ -80,7 +80,7 @@ private: bool Init(lldb_private::ThreadList &threads); - Goroutine CreateGoroutineAtIndex(uint64_t idx, lldb_private::Error &err); + Goroutine CreateGoroutineAtIndex(uint64_t idx, lldb_private::Status &err); std::unique_ptr<DynamicRegisterInfo> m_reginfo; lldb::ValueObjectSP m_allg_sp; diff --git a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp index dbbb55e474f8..14bf0784dc2c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp @@ -94,7 +94,7 @@ OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process, char python_module_path_cstr[PATH_MAX]; python_module_path.GetPath(python_module_path_cstr, sizeof(python_module_path_cstr)); - Error error; + Status error; if (m_interpreter->LoadScriptingModule( python_module_path_cstr, allow_reload, init_session, error)) { // Strip the ".py" extension if there is one @@ -240,8 +240,8 @@ ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo( uint32_t core_number; addr_t reg_data_addr; - std::string name; - std::string queue; + llvm::StringRef name; + llvm::StringRef queue; thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX); thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr, @@ -266,8 +266,8 @@ ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo( if (!thread_sp) { if (did_create_ptr) *did_create_ptr = true; - thread_sp.reset(new ThreadMemory(*m_process, tid, name.c_str(), - queue.c_str(), reg_data_addr)); + thread_sp.reset( + new ThreadMemory(*m_process, tid, name, queue, reg_data_addr)); } if (core_number < core_thread_list.GetSize(false)) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp index 2a150b5d452b..53cec45f986e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp @@ -27,9 +27,9 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from FreeBSD mman.h for use when targeting @@ -255,8 +255,8 @@ PlatformFreeBSD::GetSoftwareBreakpointTrapOpcode(Target &target, } } -Error PlatformFreeBSD::LaunchProcess(ProcessLaunchInfo &launch_info) { - Error error; +Status PlatformFreeBSD::LaunchProcess(ProcessLaunchInfo &launch_info) { + Status error; if (IsHost()) { error = Platform::LaunchProcess(launch_info); } else { @@ -270,7 +270,7 @@ Error PlatformFreeBSD::LaunchProcess(ProcessLaunchInfo &launch_info) { lldb::ProcessSP PlatformFreeBSD::Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, - Error &error) { + Status &error) { lldb::ProcessSP process_sp; if (IsHost()) { if (target == NULL) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h index c8ac7b29f3a2..4bde2148a4d4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h @@ -54,10 +54,10 @@ public: size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) override; - Error LaunchProcess(ProcessLaunchInfo &launch_info) override; + Status LaunchProcess(ProcessLaunchInfo &launch_info) override; lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, - Target *target, Error &error) override; + Target *target, Status &error) override; void CalculateTrapHandlerSymbolNames() override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp index 409f12deefca..9df5b9fac380 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp @@ -25,9 +25,9 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from NetBSD mman.h for use when targeting @@ -262,11 +262,11 @@ bool PlatformNetBSD::CanDebugProcess() { // lldb-launch, llgs-attach. This differs from current lldb-launch, // debugserver-attach // approach on MacOSX. -lldb::ProcessSP -PlatformNetBSD::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, - Target *target, // Can be NULL, if NULL create a new - // target, else use existing one - Error &error) { +lldb::ProcessSP PlatformNetBSD::DebugProcess( + ProcessLaunchInfo &launch_info, Debugger &debugger, + Target *target, // Can be NULL, if NULL create a new + // target, else use existing one + Status &error) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("PlatformNetBSD::%s entered (target %p)", __FUNCTION__, diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h index 500c61dab970..b1aaa4ab5f59 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h @@ -55,7 +55,7 @@ public: lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, - Error &error) override; + Status &error) override; void CalculateTrapHandlerSymbolNames() override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp index e3816d0276b2..edb8ec951d37 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp @@ -25,9 +25,9 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from OpenBSD mman.h for use when targeting diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp b/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp index 0032c804987c..f4cf22ad7583 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.cpp @@ -88,7 +88,7 @@ bool PlatformPOSIX::IsConnected() const { return false; } -lldb_private::Error PlatformPOSIX::RunShellCommand( +lldb_private::Status PlatformPOSIX::RunShellCommand( const char *command, // Shouldn't be NULL const FileSpec & working_dir, // Pass empty FileSpec to use the current working directory @@ -109,14 +109,15 @@ lldb_private::Error PlatformPOSIX::RunShellCommand( status_ptr, signo_ptr, command_output, timeout_sec); else - return Error("unable to run a remote command without a platform"); + return Status("unable to run a remote command without a platform"); } } -Error PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec, - lldb::ModuleSP &exe_module_sp, - const FileSpecList *module_search_paths_ptr) { - Error error; +Status +PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec, + lldb::ModuleSP &exe_module_sp, + const FileSpecList *module_search_paths_ptr) { + Status error; // Nothing special to do here, just use the actual file and architecture char exe_path[PATH_MAX]; @@ -250,16 +251,16 @@ Error PlatformPOSIX::ResolveExecutable(const ModuleSpec &module_spec, return error; } -Error PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, - FileSpec &local_file) { +Status PlatformPOSIX::GetFileWithUUID(const FileSpec &platform_file, + const UUID *uuid_ptr, + FileSpec &local_file) { if (IsRemote() && m_remote_platform_sp) return m_remote_platform_sp->GetFileWithUUID(platform_file, uuid_ptr, local_file); // Default to the local case local_file = platform_file; - return Error(); + return Status(); } bool PlatformPOSIX::GetProcessInfo(lldb::pid_t pid, @@ -282,16 +283,16 @@ PlatformPOSIX::FindProcesses(const ProcessInstanceInfoMatch &match_info, return 0; } -Error PlatformPOSIX::MakeDirectory(const FileSpec &file_spec, - uint32_t file_permissions) { +Status PlatformPOSIX::MakeDirectory(const FileSpec &file_spec, + uint32_t file_permissions) { if (m_remote_platform_sp) return m_remote_platform_sp->MakeDirectory(file_spec, file_permissions); else return Platform::MakeDirectory(file_spec, file_permissions); } -Error PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions) { +Status PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) { if (m_remote_platform_sp) return m_remote_platform_sp->GetFilePermissions(file_spec, file_permissions); @@ -299,8 +300,8 @@ Error PlatformPOSIX::GetFilePermissions(const FileSpec &file_spec, return Platform::GetFilePermissions(file_spec, file_permissions); } -Error PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions) { +Status PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) { if (m_remote_platform_sp) return m_remote_platform_sp->SetFilePermissions(file_spec, file_permissions); @@ -310,7 +311,7 @@ Error PlatformPOSIX::SetFilePermissions(const FileSpec &file_spec, lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec, uint32_t flags, uint32_t mode, - Error &error) { + Status &error) { if (IsHost()) return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error); else if (m_remote_platform_sp) @@ -319,7 +320,7 @@ lldb::user_id_t PlatformPOSIX::OpenFile(const FileSpec &file_spec, return Platform::OpenFile(file_spec, flags, mode, error); } -bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Error &error) { +bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Status &error) { if (IsHost()) return FileCache::GetInstance().CloseFile(fd, error); else if (m_remote_platform_sp) @@ -329,7 +330,7 @@ bool PlatformPOSIX::CloseFile(lldb::user_id_t fd, Error &error) { } uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Error &error) { + uint64_t dst_len, Status &error) { if (IsHost()) return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error); else if (m_remote_platform_sp) @@ -340,7 +341,7 @@ uint64_t PlatformPOSIX::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t PlatformPOSIX::WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, - Error &error) { + Status &error) { if (IsHost()) return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error); else if (m_remote_platform_sp) @@ -370,7 +371,7 @@ static uint32_t chown_file(Platform *platform, const char *path, return status; } -lldb_private::Error +lldb_private::Status PlatformPOSIX::PutFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination, uint32_t uid, uint32_t gid) { @@ -378,34 +379,34 @@ PlatformPOSIX::PutFile(const lldb_private::FileSpec &source, if (IsHost()) { if (FileSpec::Equal(source, destination, true)) - return Error(); + return Status(); // cp src dst // chown uid:gid dst std::string src_path(source.GetPath()); if (src_path.empty()) - return Error("unable to get file path for source"); + return Status("unable to get file path for source"); std::string dst_path(destination.GetPath()); if (dst_path.empty()) - return Error("unable to get file path for destination"); + return Status("unable to get file path for destination"); StreamString command; command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); int status; RunShellCommand(command.GetData(), NULL, &status, NULL, NULL, 10); if (status != 0) - return Error("unable to perform copy"); + return Status("unable to perform copy"); if (uid == UINT32_MAX && gid == UINT32_MAX) - return Error(); + return Status(); if (chown_file(this, dst_path.c_str(), uid, gid) != 0) - return Error("unable to perform chown"); - return Error(); + return Status("unable to perform chown"); + return Status(); } else if (m_remote_platform_sp) { if (GetSupportsRSync()) { std::string src_path(source.GetPath()); if (src_path.empty()) - return Error("unable to get file path for source"); + return Status("unable to get file path for source"); std::string dst_path(destination.GetPath()); if (dst_path.empty()) - return Error("unable to get file path for destination"); + return Status("unable to get file path for destination"); StreamString command; if (GetIgnoresRemoteHostname()) { if (!GetRSyncPrefix()) @@ -424,8 +425,8 @@ PlatformPOSIX::PutFile(const lldb_private::FileSpec &source, if (retcode == 0) { // Don't chown a local file for a remote system // if (chown_file(this,dst_path.c_str(),uid,gid) != 0) - // return Error("unable to perform chown"); - return Error(); + // return Status("unable to perform chown"); + return Status(); } // if we are still here rsync has failed - let's try the slow way before // giving up @@ -446,7 +447,7 @@ lldb::user_id_t PlatformPOSIX::GetFileSize(const FileSpec &file_spec) { return Platform::GetFileSize(file_spec); } -Error PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) { +Status PlatformPOSIX::CreateSymlink(const FileSpec &src, const FileSpec &dst) { if (IsHost()) return FileSystem::Symlink(src, dst); else if (m_remote_platform_sp) @@ -464,7 +465,7 @@ bool PlatformPOSIX::GetFileExists(const FileSpec &file_spec) { return Platform::GetFileExists(file_spec); } -Error PlatformPOSIX::Unlink(const FileSpec &file_spec) { +Status PlatformPOSIX::Unlink(const FileSpec &file_spec) { if (IsHost()) return llvm::sys::fs::remove(file_spec.GetPath()); else if (m_remote_platform_sp) @@ -473,7 +474,7 @@ Error PlatformPOSIX::Unlink(const FileSpec &file_spec) { return Platform::Unlink(file_spec); } -lldb_private::Error PlatformPOSIX::GetFile( +lldb_private::Status PlatformPOSIX::GetFile( const lldb_private::FileSpec &source, // remote file path const lldb_private::FileSpec &destination) // local file path { @@ -482,22 +483,22 @@ lldb_private::Error PlatformPOSIX::GetFile( // Check the args, first. std::string src_path(source.GetPath()); if (src_path.empty()) - return Error("unable to get file path for source"); + return Status("unable to get file path for source"); std::string dst_path(destination.GetPath()); if (dst_path.empty()) - return Error("unable to get file path for destination"); + return Status("unable to get file path for destination"); if (IsHost()) { if (FileSpec::Equal(source, destination, true)) - return Error("local scenario->source and destination are the same file " - "path: no operation performed"); + return Status("local scenario->source and destination are the same file " + "path: no operation performed"); // cp src dst StreamString cp_command; cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str()); int status; RunShellCommand(cp_command.GetData(), NULL, &status, NULL, NULL, 10); if (status != 0) - return Error("unable to perform copy"); - return Error(); + return Status("unable to perform copy"); + return Status(); } else if (m_remote_platform_sp) { if (GetSupportsRSync()) { StreamString command; @@ -517,7 +518,7 @@ lldb_private::Error PlatformPOSIX::GetFile( int retcode; Host::RunShellCommand(command.GetData(), NULL, &retcode, NULL, NULL, 60); if (retcode == 0) - return Error(); + return Status(); // If we are here, rsync has failed - let's try the slow way before giving // up } @@ -527,12 +528,12 @@ lldb_private::Error PlatformPOSIX::GetFile( // close dst if (log) log->Printf("[GetFile] Using block by block transfer....\n"); - Error error; + Status error; user_id_t fd_src = OpenFile(source, File::eOpenOptionRead, lldb::eFilePermissionsFileDefault, error); if (fd_src == UINT64_MAX) - return Error("unable to open source file"); + return Status("unable to open source file"); uint32_t permissions = 0; error = GetFilePermissions(source, permissions); @@ -710,8 +711,8 @@ const char *PlatformPOSIX::GetGroupName(uint32_t gid) { return NULL; } -Error PlatformPOSIX::ConnectRemote(Args &args) { - Error error; +Status PlatformPOSIX::ConnectRemote(Args &args) { + Status error; if (IsHost()) { error.SetErrorStringWithFormat( "can't connect to the host platform '%s', always connected", @@ -753,8 +754,8 @@ Error PlatformPOSIX::ConnectRemote(Args &args) { return error; } -Error PlatformPOSIX::DisconnectRemote() { - Error error; +Status PlatformPOSIX::DisconnectRemote() { + Status error; if (IsHost()) { error.SetErrorStringWithFormat( @@ -769,8 +770,8 @@ Error PlatformPOSIX::DisconnectRemote() { return error; } -Error PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) { - Error error; +Status PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) { + Status error; if (IsHost()) { error = Platform::LaunchProcess(launch_info); @@ -783,19 +784,19 @@ Error PlatformPOSIX::LaunchProcess(ProcessLaunchInfo &launch_info) { return error; } -lldb_private::Error PlatformPOSIX::KillProcess(const lldb::pid_t pid) { +lldb_private::Status PlatformPOSIX::KillProcess(const lldb::pid_t pid) { if (IsHost()) return Platform::KillProcess(pid); if (m_remote_platform_sp) return m_remote_platform_sp->KillProcess(pid); - return Error("the platform is not currently connected"); + return Status("the platform is not currently connected"); } lldb::ProcessSP PlatformPOSIX::Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, - Error &error) { + Status &error) { lldb::ProcessSP process_sp; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); @@ -855,7 +856,7 @@ lldb::ProcessSP PlatformPOSIX::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a new // target, else use existing one - Error &error) { + Status &error) { ProcessSP process_sp; if (IsHost()) { @@ -881,23 +882,23 @@ void PlatformPOSIX::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } -Error PlatformPOSIX::EvaluateLibdlExpression( +Status PlatformPOSIX::EvaluateLibdlExpression( lldb_private::Process *process, const char *expr_cstr, const char *expr_prefix, lldb::ValueObjectSP &result_valobj_sp) { DynamicLoader *loader = process->GetDynamicLoader(); if (loader) { - Error error = loader->CanLoadImage(); + Status error = loader->CanLoadImage(); if (error.Fail()) return error; } ThreadSP thread_sp(process->GetThreadList().GetExpressionExecutionThread()); if (!thread_sp) - return Error("Selected thread isn't valid"); + return Status("Selected thread isn't valid"); StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0)); if (!frame_sp) - return Error("Frame 0 isn't valid"); + return Status("Frame 0 isn't valid"); ExecutionContext exe_ctx; frame_sp->CalculateExecutionContext(exe_ctx); @@ -910,7 +911,7 @@ Error PlatformPOSIX::EvaluateLibdlExpression( // don't do the work to trap them. expr_options.SetTimeout(std::chrono::seconds(2)); - Error expr_error; + Status expr_error; ExpressionResults result = UserExpression::Evaluate(exe_ctx, expr_options, expr_cstr, expr_prefix, result_valobj_sp, expr_error); @@ -919,12 +920,12 @@ Error PlatformPOSIX::EvaluateLibdlExpression( if (result_valobj_sp->GetError().Fail()) return result_valobj_sp->GetError(); - return Error(); + return Status(); } uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error) { + lldb_private::Status &error) { char path[PATH_MAX]; remote_file.GetPath(path, sizeof(path)); @@ -983,18 +984,18 @@ uint32_t PlatformPOSIX::DoLoadImage(lldb_private::Process *process, return LLDB_INVALID_IMAGE_TOKEN; } -Error PlatformPOSIX::UnloadImage(lldb_private::Process *process, - uint32_t image_token) { +Status PlatformPOSIX::UnloadImage(lldb_private::Process *process, + uint32_t image_token) { const addr_t image_addr = process->GetImagePtrFromToken(image_token); if (image_addr == LLDB_INVALID_ADDRESS) - return Error("Invalid image token"); + return Status("Invalid image token"); StreamString expr; expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr); const char *prefix = GetLibdlFunctionDeclarations(); lldb::ValueObjectSP result_valobj_sp; - Error error = EvaluateLibdlExpression(process, expr.GetData(), prefix, - result_valobj_sp); + Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix, + result_valobj_sp); if (error.Fail()) return error; @@ -1004,17 +1005,17 @@ Error PlatformPOSIX::UnloadImage(lldb_private::Process *process, Scalar scalar; if (result_valobj_sp->ResolveValue(scalar)) { if (scalar.UInt(1)) - return Error("expression failed: \"%s\"", expr.GetData()); + return Status("expression failed: \"%s\"", expr.GetData()); process->ResetImageToken(image_token); } - return Error(); + return Status(); } lldb::ProcessSP PlatformPOSIX::ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error) { + lldb_private::Status &error) { if (m_remote_platform_sp) return m_remote_platform_sp->ConnectProcess(connect_url, plugin_name, debugger, target, error); @@ -1033,7 +1034,7 @@ const char *PlatformPOSIX::GetLibdlFunctionDeclarations() const { } size_t PlatformPOSIX::ConnectToWaitingProcesses(Debugger &debugger, - Error &error) { + Status &error) { if (m_remote_platform_sp) return m_remote_platform_sp->ConnectToWaitingProcesses(debugger, error); return Platform::ConnectToWaitingProcesses(debugger, error); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h b/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h index 6c5c62797a6e..742702b07b88 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/POSIX/PlatformPOSIX.h @@ -43,29 +43,30 @@ public: const char *GetGroupName(uint32_t gid) override; - lldb_private::Error PutFile(const lldb_private::FileSpec &source, - const lldb_private::FileSpec &destination, - uint32_t uid = UINT32_MAX, - uint32_t gid = UINT32_MAX) override; + lldb_private::Status PutFile(const lldb_private::FileSpec &source, + const lldb_private::FileSpec &destination, + uint32_t uid = UINT32_MAX, + uint32_t gid = UINT32_MAX) override; lldb::user_id_t OpenFile(const lldb_private::FileSpec &file_spec, uint32_t flags, uint32_t mode, - lldb_private::Error &error) override; + lldb_private::Status &error) override; - bool CloseFile(lldb::user_id_t fd, lldb_private::Error &error) override; + bool CloseFile(lldb::user_id_t fd, lldb_private::Status &error) override; uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, lldb_private::Error &error) override; + uint64_t dst_len, lldb_private::Status &error) override; uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, - uint64_t src_len, lldb_private::Error &error) override; + uint64_t src_len, lldb_private::Status &error) override; lldb::user_id_t GetFileSize(const lldb_private::FileSpec &file_spec) override; - lldb_private::Error CreateSymlink(const lldb_private::FileSpec &src, - const lldb_private::FileSpec &dst) override; + lldb_private::Status + CreateSymlink(const lldb_private::FileSpec &src, + const lldb_private::FileSpec &dst) override; - lldb_private::Error + lldb_private::Status GetFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination) override; @@ -88,7 +89,7 @@ public: bool IsConnected() const override; - lldb_private::Error RunShellCommand( + lldb_private::Status RunShellCommand( const char *command, // Shouldn't be nullptr const lldb_private::FileSpec &working_dir, // Pass empty FileSpec to use // the current working @@ -101,37 +102,39 @@ public: uint32_t timeout_sec) override; // Timeout in seconds to wait for shell program to finish - lldb_private::Error ResolveExecutable(const lldb_private::ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, + lldb_private::Status ResolveExecutable( + const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const lldb_private::FileSpecList *module_search_paths_ptr) override; - lldb_private::Error GetFileWithUUID(const lldb_private::FileSpec &platform_file, const lldb_private::UUID *uuid, - lldb_private::FileSpec &local_file) override; + lldb_private::Status + GetFileWithUUID(const lldb_private::FileSpec &platform_file, + const lldb_private::UUID *uuid, + lldb_private::FileSpec &local_file) override; bool GetProcessInfo(lldb::pid_t pid, lldb_private::ProcessInstanceInfo &proc_info) override; uint32_t FindProcesses(const lldb_private::ProcessInstanceInfoMatch &match_info, lldb_private::ProcessInstanceInfoList &process_infos) override; - lldb_private::Error MakeDirectory(const lldb_private::FileSpec &file_spec, - uint32_t mode) override; + lldb_private::Status MakeDirectory(const lldb_private::FileSpec &file_spec, + uint32_t mode) override; - lldb_private::Error + lldb_private::Status GetFilePermissions(const lldb_private::FileSpec &file_spec, uint32_t &file_permissions) override; - lldb_private::Error + lldb_private::Status SetFilePermissions(const lldb_private::FileSpec &file_spec, uint32_t file_permissions) override; bool GetFileExists(const lldb_private::FileSpec &file_spec) override; - lldb_private::Error Unlink(const lldb_private::FileSpec &file_spec) override; + lldb_private::Status Unlink(const lldb_private::FileSpec &file_spec) override; - lldb_private::Error + lldb_private::Status LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) override; - lldb_private::Error KillProcess(const lldb::pid_t pid) override; + lldb_private::Status KillProcess(const lldb::pid_t pid) override; lldb::ProcessSP Attach(lldb_private::ProcessAttachInfo &attach_info, lldb_private::Debugger &debugger, @@ -139,7 +142,7 @@ public: // nullptr create a new // target, else use // existing one - lldb_private::Error &error) override; + lldb_private::Status &error) override; lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, @@ -148,7 +151,7 @@ public: // create a new // target, else use // existing one - lldb_private::Error &error) override; + lldb_private::Status &error) override; std::string GetPlatformSpecificConnectionInformation() override; @@ -157,25 +160,25 @@ public: void CalculateTrapHandlerSymbolNames() override; - lldb_private::Error ConnectRemote(lldb_private::Args &args) override; + lldb_private::Status ConnectRemote(lldb_private::Args &args) override; - lldb_private::Error DisconnectRemote() override; + lldb_private::Status DisconnectRemote() override; uint32_t DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error) override; + lldb_private::Status &error) override; - lldb_private::Error UnloadImage(lldb_private::Process *process, - uint32_t image_token) override; + lldb_private::Status UnloadImage(lldb_private::Process *process, + uint32_t image_token) override; lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error) override; + lldb_private::Status &error) override; size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, - lldb_private::Error &error) override; + lldb_private::Status &error) override; lldb_private::ConstString GetFullNameForDylib(lldb_private::ConstString basename) override; @@ -193,7 +196,7 @@ protected: lldb::PlatformSP m_remote_platform_sp; // Allow multiple ways to connect to a // remote POSIX-compliant OS - lldb_private::Error + lldb_private::Status EvaluateLibdlExpression(lldb_private::Process *process, const char *expr_cstr, const char *expr_prefix, lldb::ValueObjectSP &result_valobj_sp); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp b/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp index 218c62860114..645bfdfa770d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp @@ -25,9 +25,9 @@ #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/UriParser.h" @@ -93,12 +93,12 @@ const char *PlatformRemoteGDBServer::GetDescription() { return GetDescriptionStatic(); } -Error PlatformRemoteGDBServer::ResolveExecutable( +Status PlatformRemoteGDBServer::ResolveExecutable( const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp, const FileSpecList *module_search_paths_ptr) { // copied from PlatformRemoteiOS - Error error; + Status error; // Nothing special to do here, just use the actual file and architecture ModuleSpec resolved_module_spec(module_spec); @@ -189,12 +189,12 @@ bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec, return true; } -Error PlatformRemoteGDBServer::GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, - FileSpec &local_file) { +Status PlatformRemoteGDBServer::GetFileWithUUID(const FileSpec &platform_file, + const UUID *uuid_ptr, + FileSpec &local_file) { // Default to the local case local_file = platform_file; - return Error(); + return Status(); } //------------------------------------------------------------------ @@ -291,8 +291,8 @@ bool PlatformRemoteGDBServer::IsConnected() const { return m_gdb_client.IsConnected(); } -Error PlatformRemoteGDBServer::ConnectRemote(Args &args) { - Error error; +Status PlatformRemoteGDBServer::ConnectRemote(Args &args) { + Status error; if (IsConnected()) { error.SetErrorStringWithFormat("the platform is already connected to '%s', " "execute 'platform disconnect' to close the " @@ -306,10 +306,10 @@ Error PlatformRemoteGDBServer::ConnectRemote(Args &args) { std::string path; const char *url = args.GetArgumentAtIndex(0); if (!url) - return Error("URL is null."); + return Status("URL is null."); llvm::StringRef scheme, hostname, pathname; if (!UriParser::Parse(url, scheme, hostname, port, pathname)) - return Error("Invalid URL: %s", url); + return Status("Invalid URL: %s", url); m_platform_scheme = scheme; m_platform_hostname = hostname; path = pathname; @@ -336,8 +336,8 @@ Error PlatformRemoteGDBServer::ConnectRemote(Args &args) { return error; } -Error PlatformRemoteGDBServer::DisconnectRemote() { - Error error; +Status PlatformRemoteGDBServer::DisconnectRemote() { + Status error; m_gdb_client.Disconnect(&error); m_remote_signals_sp.reset(); return error; @@ -386,9 +386,9 @@ bool PlatformRemoteGDBServer::GetProcessInfo( return m_gdb_client.GetProcessInfo(pid, process_info); } -Error PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) { +Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); - Error error; + Status error; if (log) log->Printf("PlatformRemoteGDBServer::%s() called", __FUNCTION__); @@ -480,17 +480,17 @@ Error PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) { return error; } -Error PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) { +Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) { if (!KillSpawnedProcess(pid)) - return Error("failed to kill remote spawned process"); - return Error(); + return Status("failed to kill remote spawned process"); + return Status(); } lldb::ProcessSP PlatformRemoteGDBServer::DebugProcess( ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a new target, else use // existing one - Error &error) { + Status &error) { lldb::ProcessSP process_sp; if (IsRemote()) { if (IsConnected()) { @@ -577,7 +577,7 @@ lldb::ProcessSP PlatformRemoteGDBServer::Attach( ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a new target, else use // existing one - Error &error) { + Status &error) { lldb::ProcessSP process_sp; if (IsRemote()) { if (IsConnected()) { @@ -625,9 +625,9 @@ lldb::ProcessSP PlatformRemoteGDBServer::Attach( return process_sp; } -Error PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec, - uint32_t mode) { - Error error = m_gdb_client.MakeDirectory(file_spec, mode); +Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec, + uint32_t mode) { + Status error = m_gdb_client.MakeDirectory(file_spec, mode); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) " @@ -637,9 +637,9 @@ Error PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec, return error; } -Error PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions) { - Error error = m_gdb_client.GetFilePermissions(file_spec, file_permissions); +Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) { + Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("PlatformRemoteGDBServer::GetFilePermissions(path='%s', " @@ -649,9 +649,9 @@ Error PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec, return error; } -Error PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions) { - Error error = m_gdb_client.SetFilePermissions(file_spec, file_permissions); +Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) { + Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("PlatformRemoteGDBServer::SetFilePermissions(path='%s', " @@ -663,11 +663,11 @@ Error PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec, lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec, uint32_t flags, uint32_t mode, - Error &error) { + Status &error) { return m_gdb_client.OpenFile(file_spec, flags, mode, error); } -bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Error &error) { +bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) { return m_gdb_client.CloseFile(fd, error); } @@ -678,27 +678,27 @@ PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) { uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, - Error &error) { + Status &error) { return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error); } uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, - Error &error) { + Status &error) { return m_gdb_client.WriteFile(fd, offset, src, src_len, error); } -Error PlatformRemoteGDBServer::PutFile(const FileSpec &source, - const FileSpec &destination, - uint32_t uid, uint32_t gid) { +Status PlatformRemoteGDBServer::PutFile(const FileSpec &source, + const FileSpec &destination, + uint32_t uid, uint32_t gid) { return Platform::PutFile(source, destination, uid, gid); } -Error PlatformRemoteGDBServer::CreateSymlink( +Status PlatformRemoteGDBServer::CreateSymlink( const FileSpec &src, // The name of the link is in src const FileSpec &dst) // The symlink points to dst { - Error error = m_gdb_client.CreateSymlink(src, dst); + Status error = m_gdb_client.CreateSymlink(src, dst); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') " @@ -708,8 +708,8 @@ Error PlatformRemoteGDBServer::CreateSymlink( return error; } -Error PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) { - Error error = m_gdb_client.Unlink(file_spec); +Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) { + Status error = m_gdb_client.Unlink(file_spec); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)", @@ -721,7 +721,7 @@ bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) { return m_gdb_client.GetFileExists(file_spec); } -Error PlatformRemoteGDBServer::RunShellCommand( +Status PlatformRemoteGDBServer::RunShellCommand( const char *command, // Shouldn't be NULL const FileSpec & working_dir, // Pass empty FileSpec to use the current working directory @@ -784,7 +784,7 @@ const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() { if (!dict->GetValueForKeyAsInteger("signo", signo)) return false; - std::string name; + llvm::StringRef name; if (!dict->GetValueForKeyAsString("name", name)) return false; @@ -809,7 +809,7 @@ const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() { if (object_sp && object_sp->IsValid()) description = object_sp->GetStringValue(); - remote_signals_sp->AddSignal(signo, name.c_str(), suppress, stop, + remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop, notify, description.c_str()); return true; }); @@ -852,7 +852,7 @@ std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme, lldb::ProcessSP PlatformRemoteGDBServer::ConnectProcess( llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error) { + lldb_private::Status &error) { if (!IsRemote() || !IsConnected()) { error.SetErrorString("Not connected to remote gdb server"); return nullptr; @@ -862,7 +862,7 @@ lldb::ProcessSP PlatformRemoteGDBServer::ConnectProcess( } size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger, - Error &error) { + Status &error) { std::vector<std::string> connection_urls; GetPendingGdbServerList(connection_urls); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h b/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h index edc223a2d7fb..210544f752e6 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h @@ -50,38 +50,38 @@ public: //------------------------------------------------------------ // lldb_private::Platform functions //------------------------------------------------------------ - Error ResolveExecutable(const ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr) override; + Status + ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr) override; bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) override; const char *GetDescription() override; - Error GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, - FileSpec &local_file) override; + Status GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, + FileSpec &local_file) override; bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info) override; uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) override; - Error LaunchProcess(ProcessLaunchInfo &launch_info) override; + Status LaunchProcess(ProcessLaunchInfo &launch_info) override; - Error KillProcess(const lldb::pid_t pid) override; + Status KillProcess(const lldb::pid_t pid) override; lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a // new target, else use existing // one - Error &error) override; + Status &error) override; lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a new // target, else use existing one - Error &error) override; + Status &error) override; bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override; @@ -111,42 +111,42 @@ public: bool IsConnected() const override; - Error ConnectRemote(Args &args) override; + Status ConnectRemote(Args &args) override; - Error DisconnectRemote() override; + Status DisconnectRemote() override; - Error MakeDirectory(const FileSpec &file_spec, - uint32_t file_permissions) override; + Status MakeDirectory(const FileSpec &file_spec, + uint32_t file_permissions) override; - Error GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions) override; + Status GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) override; - Error SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions) override; + Status SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) override; lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, - uint32_t mode, Error &error) override; + uint32_t mode, Status &error) override; - bool CloseFile(lldb::user_id_t fd, Error &error) override; + bool CloseFile(lldb::user_id_t fd, Status &error) override; uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *data_ptr, - uint64_t len, Error &error) override; + uint64_t len, Status &error) override; uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *data, - uint64_t len, Error &error) override; + uint64_t len, Status &error) override; lldb::user_id_t GetFileSize(const FileSpec &file_spec) override; - Error PutFile(const FileSpec &source, const FileSpec &destination, - uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX) override; + Status PutFile(const FileSpec &source, const FileSpec &destination, + uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX) override; - Error CreateSymlink(const FileSpec &src, const FileSpec &dst) override; + Status CreateSymlink(const FileSpec &src, const FileSpec &dst) override; bool GetFileExists(const FileSpec &file_spec) override; - Error Unlink(const FileSpec &path) override; + Status Unlink(const FileSpec &path) override; - Error RunShellCommand( + Status RunShellCommand( const char *command, // Shouldn't be NULL const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory @@ -166,10 +166,10 @@ public: llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error) override; + lldb_private::Status &error) override; size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, - lldb_private::Error &error) override; + lldb_private::Status &error) override; virtual size_t GetPendingGdbServerList(std::vector<std::string> &connection_urls); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp index feb7a11584f8..6845a36730c9 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.cpp @@ -32,8 +32,8 @@ #include "lldb/Host/PseudoTerminal.h" #include "lldb/Target/ProcessLaunchInfo.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "CFBundle.h" @@ -131,10 +131,10 @@ static bool ResolveExecutablePath(const char *path, char *resolved_path, // TODO check if we have a general purpose fork and exec. We may be // able to get rid of this entirely. -static Error ForkChildForPTraceDebugging(const char *path, char const *argv[], - char const *envp[], ::pid_t *pid, - int *pty_fd) { - Error error; +static Status ForkChildForPTraceDebugging(const char *path, char const *argv[], + char const *envp[], ::pid_t *pid, + int *pty_fd) { + Status error; if (!path || !argv || !envp || !pid || !pty_fd) { error.SetErrorString("invalid arguments"); return error; @@ -149,7 +149,7 @@ static Error ForkChildForPTraceDebugging(const char *path, char const *argv[], *pid = static_cast<::pid_t>(pty.Fork(fork_error, sizeof(fork_error))); if (*pid < 0) { //-------------------------------------------------------------- - // Error during fork. + // Status during fork. //-------------------------------------------------------------- *pid = static_cast<::pid_t>(LLDB_INVALID_PROCESS_ID); error.SetErrorStringWithFormat("%s(): fork failed: %s", __FUNCTION__, @@ -205,10 +205,10 @@ static Error ForkChildForPTraceDebugging(const char *path, char const *argv[], return error; } -static Error +static Status CreatePosixSpawnFileAction(const FileAction &action, posix_spawn_file_actions_t *file_actions) { - Error error; + Status error; // Log it. Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); @@ -270,11 +270,11 @@ CreatePosixSpawnFileAction(const FileAction &action, return error; } -static Error PosixSpawnChildForPTraceDebugging(const char *path, - ProcessLaunchInfo &launch_info, - ::pid_t *pid, - cpu_type_t *actual_cpu_type) { - Error error; +static Status PosixSpawnChildForPTraceDebugging(const char *path, + ProcessLaunchInfo &launch_info, + ::pid_t *pid, + cpu_type_t *actual_cpu_type) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (!pid) { @@ -436,9 +436,9 @@ static Error PosixSpawnChildForPTraceDebugging(const char *path, return error; } -Error LaunchInferior(ProcessLaunchInfo &launch_info, int *pty_master_fd, - LaunchFlavor *launch_flavor) { - Error error; +Status LaunchInferior(ProcessLaunchInfo &launch_info, int *pty_master_fd, + LaunchFlavor *launch_flavor) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (!launch_flavor) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h index d1af4d09f8b7..a0e8ce5cb9dc 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/DarwinProcessLauncher.h @@ -39,8 +39,9 @@ namespace darwin_process_launcher { /// @param[out] launch_flavor /// Contains the launch flavor used when launching the process. // ============================================================================= -Error LaunchInferior(ProcessLaunchInfo &launch_info, int *pty_master_fd, - lldb_private::process_darwin::LaunchFlavor *launch_flavor); +Status +LaunchInferior(ProcessLaunchInfo &launch_info, int *pty_master_fd, + lldb_private::process_darwin::LaunchFlavor *launch_flavor); } // darwin_process_launcher } // lldb_private diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.cpp index 5a97a4b01be3..7d956dfc6506 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.cpp @@ -23,9 +23,9 @@ // LLDB includes #include "lldb/Target/UnixSignals.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; @@ -211,11 +211,11 @@ bool MachException::Data::GetStopInfo(struct ThreadStopInfo *stop_info, return true; } -Error MachException::Message::Receive(mach_port_t port, - mach_msg_option_t options, - mach_msg_timeout_t timeout, - mach_port_t notify_port) { - Error error; +Status MachException::Message::Receive(mach_port_t port, + mach_msg_option_t options, + mach_msg_timeout_t timeout, + mach_port_t notify_port) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); mach_msg_timeout_t mach_msg_timeout = @@ -312,10 +312,10 @@ bool MachException::Message::CatchExceptionRaise(task_t task) { return success; } -Error MachException::Message::Reply(::pid_t inferior_pid, task_t inferior_task, - int signal) { +Status MachException::Message::Reply(::pid_t inferior_pid, task_t inferior_task, + int signal) { // Reply to the exception... - Error error; + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); @@ -412,8 +412,8 @@ Error MachException::Message::Reply(::pid_t inferior_pid, task_t inferior_task, #define LLDB_EXC_MASK (EXC_MASK_ALL & ~EXC_MASK_RESOURCE) -Error MachException::PortInfo::Save(task_t task) { - Error error; +Status MachException::PortInfo::Save(task_t task) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); if (log) @@ -471,8 +471,8 @@ Error MachException::PortInfo::Save(task_t task) { return error; } -Error MachException::PortInfo::Restore(task_t task) { - Error error; +Status MachException::PortInfo::Restore(task_t task) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.h index ac8cd7030c55..2da6a36a921e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/MachException.h @@ -40,9 +40,9 @@ public: thread_state_flavor_t flavors[EXC_TYPES_COUNT]; mach_msg_type_number_t count; - Error Save(task_t task); + Status Save(task_t task); - Error Restore(task_t task); + Status Restore(task_t task); }; struct Data { @@ -96,11 +96,11 @@ public: bool CatchExceptionRaise(task_t task); - Error Reply(::pid_t inferior_pid, task_t inferior_task, int signal); + Status Reply(::pid_t inferior_pid, task_t inferior_task, int signal); - Error Receive(mach_port_t receive_port, mach_msg_option_t options, - mach_msg_timeout_t timeout, - mach_port_t notify_port = MACH_PORT_NULL); + Status Receive(mach_port_t receive_port, mach_msg_option_t options, + mach_msg_timeout_t timeout, + mach_port_t notify_port = MACH_PORT_NULL); void Dump(Stream &stream) const; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp index 65ab12fe1adf..f6c8c78ccb73 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.cpp @@ -53,13 +53,13 @@ struct hack_task_dyld_info { // Public Static Methods // ----------------------------------------------------------------------------- -Error NativeProcessProtocol::Launch( +Status NativeProcessProtocol::Launch( ProcessLaunchInfo &launch_info, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); - Error error; + Status error; // Verify the working directory is valid if one was specified. FileSpec working_dir(launch_info.GetWorkingDirectory()); @@ -120,7 +120,7 @@ Error NativeProcessProtocol::Launch( return error; } -Error NativeProcessProtocol::Attach( +Status NativeProcessProtocol::Attach( lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); @@ -130,7 +130,7 @@ Error NativeProcessProtocol::Attach( // Retrieve the architecture for the running process. ArchSpec process_arch; - Error error = ResolveProcessArchitecture(pid, process_arch); + Status error = ResolveProcessArchitecture(pid, process_arch); if (!error.Success()) return error; @@ -174,9 +174,9 @@ NativeProcessDarwin::~NativeProcessDarwin() {} // Instance methods // ----------------------------------------------------------------------------- -Error NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor, - MainLoop &main_loop) { - Error error; +Status NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor, + MainLoop &main_loop) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); #if 0 @@ -261,7 +261,7 @@ Error NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor, return error; } -Error NativeProcessDarwin::SaveExceptionPortInfo() { +Status NativeProcessDarwin::SaveExceptionPortInfo() { return m_exc_port_info.Save(m_task); } @@ -348,7 +348,7 @@ void *NativeProcessDarwin::DoExceptionThread() { // polling is expensive. On devices, we need to minimize overhead caused // by the process monitor. uint32_t num_exceptions_received = 0; - Error error; + Status error; task_t task = m_task; mach_msg_timeout_t periodic_timeout = 0; @@ -550,8 +550,8 @@ void *NativeProcessDarwin::DoExceptionThread() { return nullptr; } -Error NativeProcessDarwin::StartExceptionThread() { - Error error; +Status NativeProcessDarwin::StartExceptionThread() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (log) log->Printf("NativeProcessDarwin::%s() called", __FUNCTION__); @@ -640,7 +640,7 @@ Error NativeProcessDarwin::StartExceptionThread() { } lldb::addr_t -NativeProcessDarwin::GetDYLDAllImageInfosAddress(Error &error) const { +NativeProcessDarwin::GetDYLDAllImageInfosAddress(Status &error) const { error.Clear(); struct hack_task_dyld_info dyld_info; @@ -694,7 +694,7 @@ uint32_t NativeProcessDarwin::GetCPUType() const { task_t NativeProcessDarwin::ExceptionMessageBundleComplete() { // We have a complete bundle of exceptions for our child process. - Error error; + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex); @@ -737,7 +737,7 @@ task_t NativeProcessDarwin::ExceptionMessageBundleComplete() { const addr_t info_array_count_addr = aii_addr + 4; uint32_t info_array_count = 0; size_t bytes_read = 0; - Error read_error; + Status read_error; read_error = ReadMemory(info_array_count_addr, // source addr &info_array_count, // dest addr 4, // byte count @@ -885,8 +885,8 @@ void NativeProcessDarwin::StartSTDIOThread() { // TODO implement } -Error NativeProcessDarwin::StartWaitpidThread(MainLoop &main_loop) { - Error error; +Status NativeProcessDarwin::StartWaitpidThread(MainLoop &main_loop) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); // Strategy: create a thread that sits on waitpid(), waiting for the @@ -973,7 +973,7 @@ void *NativeProcessDarwin::DoWaitpidThread() { // Ensure we don't get CPU starved. MaybeRaiseThreadPriority(); - Error error; + Status error; int status = -1; while (1) { @@ -1038,9 +1038,9 @@ void *NativeProcessDarwin::DoWaitpidThread() { return nullptr; } -Error NativeProcessDarwin::SendInferiorExitStatusToMainLoop(::pid_t pid, - int status) { - Error error; +Status NativeProcessDarwin::SendInferiorExitStatusToMainLoop(::pid_t pid, + int status) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); size_t bytes_written = 0; @@ -1069,8 +1069,8 @@ Error NativeProcessDarwin::SendInferiorExitStatusToMainLoop(::pid_t pid, return error; } -Error NativeProcessDarwin::HandleWaitpidResult() { - Error error; +Status NativeProcessDarwin::HandleWaitpidResult() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); // Read the pid. @@ -1126,7 +1126,7 @@ Error NativeProcessDarwin::HandleWaitpidResult() { return error; } -task_t NativeProcessDarwin::TaskPortForProcessID(Error &error, +task_t NativeProcessDarwin::TaskPortForProcessID(Status &error, bool force) const { if ((m_task == TASK_NULL) || force) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); @@ -1178,12 +1178,12 @@ task_t NativeProcessDarwin::TaskPortForProcessID(Error &error, } void NativeProcessDarwin::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, - Error &error) { + Status &error) { error.SetErrorString("TODO: implement"); } -Error NativeProcessDarwin::PrivateResume() { - Error error; +Status NativeProcessDarwin::PrivateResume() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex); @@ -1225,8 +1225,8 @@ Error NativeProcessDarwin::PrivateResume() { return error; } -Error NativeProcessDarwin::ReplyToAllExceptions() { - Error error; +Status NativeProcessDarwin::ReplyToAllExceptions() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE)); TaskPortForProcessID(error); @@ -1282,8 +1282,8 @@ Error NativeProcessDarwin::ReplyToAllExceptions() { return error; } -Error NativeProcessDarwin::ResumeTask() { - Error error; +Status NativeProcessDarwin::ResumeTask() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); TaskPortForProcessID(error); @@ -1364,9 +1364,10 @@ bool NativeProcessDarwin::IsExceptionPortValid() const { return MACH_PORT_VALID(m_exception_port); } -Error NativeProcessDarwin::GetTaskBasicInfo( - task_t task, struct task_basic_info *info) const { - Error error; +Status +NativeProcessDarwin::GetTaskBasicInfo(task_t task, + struct task_basic_info *info) const { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); // Validate args. @@ -1412,8 +1413,8 @@ Error NativeProcessDarwin::GetTaskBasicInfo( return error; } -Error NativeProcessDarwin::SuspendTask() { - Error error; +Status NativeProcessDarwin::SuspendTask() { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (m_task == TASK_NULL) { @@ -1432,8 +1433,8 @@ Error NativeProcessDarwin::SuspendTask() { return error; } -Error NativeProcessDarwin::Resume(const ResumeActionList &resume_actions) { - Error error; +Status NativeProcessDarwin::Resume(const ResumeActionList &resume_actions) { + Status error; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (log) @@ -1461,74 +1462,74 @@ Error NativeProcessDarwin::Resume(const ResumeActionList &resume_actions) { return error; } -Error NativeProcessDarwin::Halt() { - Error error; +Status NativeProcessDarwin::Halt() { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::Detach() { - Error error; +Status NativeProcessDarwin::Detach() { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::Signal(int signo) { - Error error; +Status NativeProcessDarwin::Signal(int signo) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::Interrupt() { - Error error; +Status NativeProcessDarwin::Interrupt() { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::Kill() { - Error error; +Status NativeProcessDarwin::Kill() { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) { - Error error; +Status NativeProcessDarwin::GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::ReadMemory(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) { - Error error; +Status NativeProcessDarwin::ReadMemory(lldb::addr_t addr, void *buf, + size_t size, size_t &bytes_read) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, - size_t size, - size_t &bytes_read) { - Error error; +Status NativeProcessDarwin::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, + size_t size, + size_t &bytes_read) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::WriteMemory(lldb::addr_t addr, const void *buf, - size_t size, size_t &bytes_written) { - Error error; +Status NativeProcessDarwin::WriteMemory(lldb::addr_t addr, const void *buf, + size_t size, size_t &bytes_written) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::AllocateMemory(size_t size, uint32_t permissions, - lldb::addr_t &addr) { - Error error; +Status NativeProcessDarwin::AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::DeallocateMemory(lldb::addr_t addr) { - Error error; +Status NativeProcessDarwin::DeallocateMemory(lldb::addr_t addr) { + Status error; error.SetErrorString("TODO: implement"); return error; } @@ -1543,25 +1544,25 @@ bool NativeProcessDarwin::GetArchitecture(ArchSpec &arch) const { return false; } -Error NativeProcessDarwin::SetBreakpoint(lldb::addr_t addr, uint32_t size, - bool hardware) { - Error error; +Status NativeProcessDarwin::SetBreakpoint(lldb::addr_t addr, uint32_t size, + bool hardware) { + Status error; error.SetErrorString("TODO: implement"); return error; } void NativeProcessDarwin::DoStopIDBumped(uint32_t newBumpId) {} -Error NativeProcessDarwin::GetLoadedModuleFileSpec(const char *module_path, - FileSpec &file_spec) { - Error error; +Status NativeProcessDarwin::GetLoadedModuleFileSpec(const char *module_path, + FileSpec &file_spec) { + Status error; error.SetErrorString("TODO: implement"); return error; } -Error NativeProcessDarwin::GetFileLoadAddress(const llvm::StringRef &file_name, - lldb::addr_t &load_addr) { - Error error; +Status NativeProcessDarwin::GetFileLoadAddress(const llvm::StringRef &file_name, + lldb::addr_t &load_addr) { + Status error; error.SetErrorString("TODO: implement"); return error; } @@ -1569,10 +1570,10 @@ Error NativeProcessDarwin::GetFileLoadAddress(const llvm::StringRef &file_name, // ----------------------------------------------------------------- // NativeProcessProtocol protected interface // ----------------------------------------------------------------- -Error NativeProcessDarwin::GetSoftwareBreakpointTrapOpcode( +Status NativeProcessDarwin::GetSoftwareBreakpointTrapOpcode( size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) { - Error error; + Status error; error.SetErrorString("TODO: implement"); return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h index 01fdd64b1273..2214bbc52ca4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeProcessDarwin.h @@ -37,7 +37,7 @@ #include "NativeThreadListDarwin.h" namespace lldb_private { -class Error; +class Status; class Scalar; namespace process_darwin { @@ -50,11 +50,11 @@ namespace process_darwin { /// /// Changes in the inferior process state are broadcasted. class NativeProcessDarwin : public NativeProcessProtocol { - friend Error NativeProcessProtocol::Launch( + friend Status NativeProcessProtocol::Launch( ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &process_sp); - friend Error NativeProcessProtocol::Attach( + friend Status NativeProcessProtocol::Attach( lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &process_sp); @@ -64,34 +64,34 @@ public: // ----------------------------------------------------------------- // NativeProcessProtocol Interface // ----------------------------------------------------------------- - Error Resume(const ResumeActionList &resume_actions) override; + Status Resume(const ResumeActionList &resume_actions) override; - Error Halt() override; + Status Halt() override; - Error Detach() override; + Status Detach() override; - Error Signal(int signo) override; + Status Signal(int signo) override; - Error Interrupt() override; + Status Interrupt() override; - Error Kill() override; + Status Kill() override; - Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) override; + Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) override; - Error ReadMemory(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) override; + Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read) override; - Error ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) override; + Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read) override; - Error WriteMemory(lldb::addr_t addr, const void *buf, size_t size, - size_t &bytes_written) override; + Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, + size_t &bytes_written) override; - Error AllocateMemory(size_t size, uint32_t permissions, - lldb::addr_t &addr) override; + Status AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) override; - Error DeallocateMemory(lldb::addr_t addr) override; + Status DeallocateMemory(lldb::addr_t addr) override; lldb::addr_t GetSharedLibraryInfoAddress() override; @@ -99,15 +99,16 @@ public: bool GetArchitecture(ArchSpec &arch) const override; - Error SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override; + Status SetBreakpoint(lldb::addr_t addr, uint32_t size, + bool hardware) override; void DoStopIDBumped(uint32_t newBumpId) override; - Error GetLoadedModuleFileSpec(const char *module_path, - FileSpec &file_spec) override; + Status GetLoadedModuleFileSpec(const char *module_path, + FileSpec &file_spec) override; - Error GetFileLoadAddress(const llvm::StringRef &file_name, - lldb::addr_t &load_addr) override; + Status GetFileLoadAddress(const llvm::StringRef &file_name, + lldb::addr_t &load_addr) override; NativeThreadDarwinSP GetThreadByID(lldb::tid_t id); @@ -116,9 +117,9 @@ public: // ----------------------------------------------------------------- // Interface used by NativeRegisterContext-derived classes. // ----------------------------------------------------------------- - static Error PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, - void *data = nullptr, size_t data_size = 0, - long *result = nullptr); + static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, + void *data = nullptr, size_t data_size = 0, + long *result = nullptr); bool SupportHardwareSingleStepping() const; @@ -126,7 +127,7 @@ protected: // ----------------------------------------------------------------- // NativeProcessProtocol protected interface // ----------------------------------------------------------------- - Error + Status GetSoftwareBreakpointTrapOpcode(size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override; @@ -236,19 +237,19 @@ private: /// operations. Failure here will force termination of the /// launched process and debugging session. // ----------------------------------------------------------------- - Error FinalizeLaunch(LaunchFlavor launch_flavor, MainLoop &main_loop); + Status FinalizeLaunch(LaunchFlavor launch_flavor, MainLoop &main_loop); - Error SaveExceptionPortInfo(); + Status SaveExceptionPortInfo(); void ExceptionMessageReceived(const MachException::Message &message); void MaybeRaiseThreadPriority(); - Error StartExceptionThread(); + Status StartExceptionThread(); - Error SendInferiorExitStatusToMainLoop(::pid_t pid, int status); + Status SendInferiorExitStatusToMainLoop(::pid_t pid, int status); - Error HandleWaitpidResult(); + Status HandleWaitpidResult(); bool ProcessUsingSpringBoard() const; @@ -258,7 +259,7 @@ private: void *DoExceptionThread(); - lldb::addr_t GetDYLDAllImageInfosAddress(Error &error) const; + lldb::addr_t GetDYLDAllImageInfosAddress(Status &error) const; static uint32_t GetCPUTypeForLocalProcess(::pid_t pid); @@ -268,25 +269,25 @@ private: void StartSTDIOThread(); - Error StartWaitpidThread(MainLoop &main_loop); + Status StartWaitpidThread(MainLoop &main_loop); static void *WaitpidThread(void *arg); void *DoWaitpidThread(); - task_t TaskPortForProcessID(Error &error, bool force = false) const; + task_t TaskPortForProcessID(Status &error, bool force = false) const; /// Attaches to an existing process. Forms the /// implementation of Process::DoAttach. - void AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, Error &error); + void AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, Status &error); - ::pid_t Attach(lldb::pid_t pid, Error &error); + ::pid_t Attach(lldb::pid_t pid, Status &error); - Error PrivateResume(); + Status PrivateResume(); - Error ReplyToAllExceptions(); + Status ReplyToAllExceptions(); - Error ResumeTask(); + Status ResumeTask(); bool IsTaskValid() const; @@ -296,11 +297,11 @@ private: bool IsExceptionPortValid() const; - Error GetTaskBasicInfo(task_t task, struct task_basic_info *info) const; + Status GetTaskBasicInfo(task_t task, struct task_basic_info *info) const; - Error SuspendTask(); + Status SuspendTask(); - static Error SetDefaultPtraceOpts(const lldb::pid_t); + static Status SetDefaultPtraceOpts(const lldb::pid_t); static void *MonitorThread(void *baton); @@ -319,7 +320,7 @@ private: void MonitorSignal(const siginfo_t &info, NativeThreadDarwin &thread, bool exited); - Error SetupSoftwareSingleStepping(NativeThreadDarwin &thread); + Status SetupSoftwareSingleStepping(NativeThreadDarwin &thread); #if 0 static ::ProcessMessage::CrashReason @@ -341,22 +342,22 @@ private: NativeThreadDarwinSP AddThread(lldb::tid_t thread_id); - Error GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size); + Status GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size); - Error FixupBreakpointPCAsNeeded(NativeThreadDarwin &thread); + Status FixupBreakpointPCAsNeeded(NativeThreadDarwin &thread); /// Writes a siginfo_t structure corresponding to the given thread /// ID to the memory region pointed to by @p siginfo. - Error GetSignalInfo(lldb::tid_t tid, void *siginfo); + Status GetSignalInfo(lldb::tid_t tid, void *siginfo); /// Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG) /// corresponding to the given thread ID to the memory pointed to /// by @p message. - Error GetEventMessage(lldb::tid_t tid, unsigned long *message); + Status GetEventMessage(lldb::tid_t tid, unsigned long *message); void NotifyThreadDeath(lldb::tid_t tid); - Error Detach(lldb::tid_t tid); + Status Detach(lldb::tid_t tid); // This method is requests a stop on all threads which are still // running. It sets up a deferred delegate notification, which will @@ -370,8 +371,8 @@ private: // Resume the given thread, optionally passing it the given signal. // The type of resume operation (continue, single-step) depends on // the state parameter. - Error ResumeThread(NativeThreadDarwin &thread, lldb::StateType state, - int signo); + Status ResumeThread(NativeThreadDarwin &thread, lldb::StateType state, + int signo); void ThreadWasCreated(NativeThreadDarwin &thread); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp index b04f9053136b..07398ab7b678 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.cpp @@ -94,15 +94,15 @@ NativeRegisterContextSP NativeThreadDarwin::GetRegisterContext() { return NativeRegisterContextSP(); } -Error NativeThreadDarwin::SetWatchpoint(lldb::addr_t addr, size_t size, - uint32_t watch_flags, bool hardware) { - Error error; +Status NativeThreadDarwin::SetWatchpoint(lldb::addr_t addr, size_t size, + uint32_t watch_flags, bool hardware) { + Status error; error.SetErrorString("not yet implemented"); return error; } -Error NativeThreadDarwin::RemoveWatchpoint(lldb::addr_t addr) { - Error error; +Status NativeThreadDarwin::RemoveWatchpoint(lldb::addr_t addr) { + Status error; error.SetErrorString("not yet implemented"); return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h index b8d9089e673e..f66f8fe8738c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadDarwin.h @@ -58,10 +58,10 @@ public: NativeRegisterContextSP GetRegisterContext() override; - Error SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, - bool hardware) override; + Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, + bool hardware) override; - Error RemoveWatchpoint(lldb::addr_t addr) override; + Status RemoveWatchpoint(lldb::addr_t addr) override; // ----------------------------------------------------------------- // New methods that are fine for others to call. @@ -75,11 +75,11 @@ private: /// Resumes the thread. If @p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. - Error Resume(uint32_t signo); + Status Resume(uint32_t signo); /// Single steps the thread. If @p signo is anything but /// LLDB_INVALID_SIGNAL_NUMBER, deliver that signal to the thread. - Error SingleStep(uint32_t signo); + Status SingleStep(uint32_t signo); bool NotifyException(MachException::Data &exc); @@ -117,7 +117,7 @@ private: void SetExited(); - Error RequestStop(); + Status RequestStop(); // ------------------------------------------------------------------------- /// Return the mach thread port number for this thread. diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp index fa06fb8b2a5f..7d44adeec375 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.cpp @@ -20,8 +20,8 @@ #include <sys/sysctl.h> // LLDB includes -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-enumerations.h" @@ -343,7 +343,7 @@ uint32_t NativeThreadListDarwin::UpdateThreadList(NativeProcessDarwin &process, mach_msg_type_number_t thread_list_count = 0; task_t task = process.GetTask(); - Error error; + Status error; auto mach_err = ::task_threads(task, &thread_list, &thread_list_count); error.SetError(mach_err, eErrorTypeMachKernel); if (error.Fail()) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h index 2b194bcc1537..7b59afb96e95 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Darwin/NativeThreadListDarwin.h @@ -123,7 +123,7 @@ protected: typedef collection::iterator iterator; typedef collection::const_iterator const_iterator; - // Consider having this return an lldb_private::Error. + // Consider having this return an lldb_private::Status. uint32_t UpdateThreadList(NativeProcessDarwin &process, bool update, collection *num_threads = nullptr); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp index 93d294fd040a..3046150e3246 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp @@ -111,8 +111,8 @@ uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; } void ProcessFreeBSD::Terminate() {} -Error ProcessFreeBSD::DoDetach(bool keep_stopped) { - Error error; +Status ProcessFreeBSD::DoDetach(bool keep_stopped) { + Status error; if (keep_stopped) { error.SetErrorString("Detaching with keep_stopped true is not currently " "supported on FreeBSD."); @@ -127,7 +127,7 @@ Error ProcessFreeBSD::DoDetach(bool keep_stopped) { return error; } -Error ProcessFreeBSD::DoResume() { +Status ProcessFreeBSD::DoResume() { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); SetPrivateState(eStateRunning); @@ -147,7 +147,7 @@ Error ProcessFreeBSD::DoResume() { m_monitor->ThreadSuspend(*t_pos, false); do_step = true; if (software_single_step) { - Error error = SetupSoftwareSingleStepping(*t_pos); + Status error = SetupSoftwareSingleStepping(*t_pos); if (error.Fail()) return error; } @@ -168,7 +168,7 @@ Error ProcessFreeBSD::DoResume() { else m_monitor->Resume(GetID(), m_resume_signo); - return Error(); + return Status(); } bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, @@ -209,7 +209,7 @@ bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, return true; } -Error ProcessFreeBSD::WillResume() { +Status ProcessFreeBSD::WillResume() { m_resume_signo = 0; m_suspend_tids.clear(); m_run_tids.clear(); @@ -293,9 +293,10 @@ bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp, return true; } -Error ProcessFreeBSD::DoAttachToProcessWithID( - lldb::pid_t pid, const ProcessAttachInfo &attach_info) { - Error error; +Status +ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid, + const ProcessAttachInfo &attach_info) { + Status error; assert(m_monitor == NULL); Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); @@ -343,8 +344,8 @@ Error ProcessFreeBSD::DoAttachToProcessWithID( return error; } -Error ProcessFreeBSD::WillLaunch(Module *module) { - Error error; +Status ProcessFreeBSD::WillLaunch(Module *module) { + Status error; return error; } @@ -366,8 +367,9 @@ ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action, return file_spec; } -Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) { - Error error; +Status ProcessFreeBSD::DoLaunch(Module *module, + ProcessLaunchInfo &launch_info) { + Status error; assert(m_monitor == NULL); FileSpec working_dir = launch_info.GetWorkingDirectory(); @@ -456,8 +458,8 @@ addr_t ProcessFreeBSD::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; } -Error ProcessFreeBSD::DoHalt(bool &caused_stop) { - Error error; +Status ProcessFreeBSD::DoHalt(bool &caused_stop) { + Status error; if (IsStopped()) { caused_stop = false; @@ -470,8 +472,8 @@ Error ProcessFreeBSD::DoHalt(bool &caused_stop) { return error; } -Error ProcessFreeBSD::DoSignal(int signal) { - Error error; +Status ProcessFreeBSD::DoSignal(int signal) { + Status error; if (kill(GetID(), signal)) error.SetErrorToErrno(); @@ -479,8 +481,8 @@ Error ProcessFreeBSD::DoSignal(int signal) { return error; } -Error ProcessFreeBSD::DoDestroy() { - Error error; +Status ProcessFreeBSD::DoDestroy() { + Status error; if (!HasExited()) { assert(m_monitor); @@ -513,7 +515,7 @@ void ProcessFreeBSD::DoDidExec() { target->GetArchitecture()); FileSpecList executable_search_paths( Target::GetDefaultExecutableSearchPaths()); - Error error = platform_sp->ResolveExecutable( + Status error = platform_sp->ResolveExecutable( exe_module_spec, exe_module_sp, executable_search_paths.GetSize() ? &executable_search_paths : NULL); if (!error.Success()) @@ -589,19 +591,19 @@ bool ProcessFreeBSD::IsAlive() { } size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size, - Error &error) { + Status &error) { assert(m_monitor); return m_monitor->ReadMemory(vm_addr, buf, size, error); } size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf, - size_t size, Error &error) { + size_t size, Status &error) { assert(m_monitor); return m_monitor->WriteMemory(vm_addr, buf, size, error); } addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions, - Error &error) { + Status &error) { addr_t allocated_addr = LLDB_INVALID_ADDRESS; unsigned prot = 0; @@ -626,8 +628,8 @@ addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions, return allocated_addr; } -Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) { - Error error; +Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) { + Status error; MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); if (pos != m_addr_to_mmap_size.end() && InferiorCallMunmap(this, addr, pos->second)) @@ -691,16 +693,16 @@ ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) { return opcode_size; } -Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) { +Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) { return EnableSoftwareBreakpoint(bp_site); } -Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) { +Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) { return DisableSoftwareBreakpoint(bp_site); } -Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) { - Error error; +Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) { + Status error; if (wp) { user_id_t watchID = wp->GetID(); addr_t addr = wp->GetLoadAddress(); @@ -754,8 +756,8 @@ Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) { return error; } -Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) { - Error error; +Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) { + Status error; if (wp) { user_id_t watchID = wp->GetID(); addr_t addr = wp->GetLoadAddress(); @@ -797,8 +799,8 @@ Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) { return error; } -Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) { - Error error; +Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) { + Status error; std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); FreeBSDThread *thread = static_cast<FreeBSDThread *>( m_thread_list.GetThreadAtIndex(0, false).get()); @@ -809,8 +811,8 @@ Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) { return error; } -Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) { - Error error = GetWatchpointSupportInfo(num); +Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) { + Status error = GetWatchpointSupportInfo(num); // Watchpoints trigger and halt the inferior after // the corresponding instruction has been executed. after = true; @@ -855,7 +857,7 @@ ByteOrder ProcessFreeBSD::GetByteOrder() const { return m_byte_order; } -size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) { +size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) { ssize_t status; if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) { error.SetErrorToErrno(); @@ -943,7 +945,7 @@ static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, lldb::addr_t addr, void *dst, size_t length) { EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); - Error error; + Status error; size_t bytes_read = emulator_baton->m_process->DoReadMemory(addr, dst, length, error); if (!error.Success()) @@ -998,9 +1000,9 @@ bool ProcessFreeBSD::SingleStepBreakpointHit( return false; } -Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, - lldb::addr_t addr) { - Error error; +Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, + lldb::addr_t addr) { + Status error; Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); if (log) { @@ -1010,8 +1012,8 @@ Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, // Validate the address. if (addr == LLDB_INVALID_ADDRESS) - return Error("ProcessFreeBSD::%s invalid load address specified.", - __FUNCTION__); + return Status("ProcessFreeBSD::%s invalid load address specified.", + __FUNCTION__); Breakpoint *const sw_step_break = m_process->GetTarget().CreateBreakpoint(addr, true, false).get(); @@ -1023,7 +1025,7 @@ Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, __FUNCTION__, addr); m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()}); - return Error(); + return Status(); } bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) { @@ -1063,18 +1065,18 @@ bool ProcessFreeBSD::SupportHardwareSingleStepping() const { return true; } -Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { +Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { std::unique_ptr<EmulateInstruction> emulator_ap( EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(), eInstructionTypePCModifying, nullptr)); if (emulator_ap == nullptr) - return Error("Instruction emulator not found!"); + return Status("Instruction emulator not found!"); FreeBSDThread *thread = static_cast<FreeBSDThread *>( m_thread_list.FindThreadByID(tid, false).get()); if (thread == NULL) - return Error("Thread not found not found!"); + return Status("Thread not found not found!"); lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext(); @@ -1086,7 +1088,7 @@ Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); if (!emulator_ap->ReadInstruction()) - return Error("Read instruction failed!"); + return Status("Read instruction failed!"); bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); @@ -1111,9 +1113,9 @@ Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) { // The instruction emulation failed after it modified the PC. It is an // unknown error where we can't continue because the next instruction is // modifying the PC but we don't know how. - return Error("Instruction emulation failed unexpectedly"); + return Status("Instruction emulation failed unexpectedly"); } SetSoftwareSingleStepBreakpoint(tid, next_pc); - return Error(); + return Status(); } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h index 063eb6f68123..7ed2a56cd549 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.h @@ -47,7 +47,7 @@ public: ~ProcessFreeBSD(); - virtual lldb_private::Error WillResume() override; + virtual lldb_private::Status WillResume() override; //------------------------------------------------------------------ // PluginInterface protocol @@ -65,27 +65,27 @@ public: bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; - lldb_private::Error WillLaunch(lldb_private::Module *module) override; + lldb_private::Status WillLaunch(lldb_private::Module *module) override; - lldb_private::Error DoAttachToProcessWithID( + lldb_private::Status DoAttachToProcessWithID( lldb::pid_t pid, const lldb_private::ProcessAttachInfo &attach_info) override; - lldb_private::Error + lldb_private::Status DoLaunch(lldb_private::Module *exe_module, lldb_private::ProcessLaunchInfo &launch_info) override; void DidLaunch() override; - lldb_private::Error DoResume() override; + lldb_private::Status DoResume() override; - lldb_private::Error DoHalt(bool &caused_stop) override; + lldb_private::Status DoHalt(bool &caused_stop) override; - lldb_private::Error DoDetach(bool keep_stopped) override; + lldb_private::Status DoDetach(bool keep_stopped) override; - lldb_private::Error DoSignal(int signal) override; + lldb_private::Status DoSignal(int signal) override; - lldb_private::Error DoDestroy() override; + lldb_private::Status DoDestroy() override; void DoDidExec() override; @@ -94,35 +94,35 @@ public: bool IsAlive() override; size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, - lldb_private::Error &error) override; + lldb_private::Status &error) override; size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, - lldb_private::Error &error) override; + lldb_private::Status &error) override; lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, - lldb_private::Error &error) override; + lldb_private::Status &error) override; - lldb_private::Error DoDeallocateMemory(lldb::addr_t ptr) override; + lldb_private::Status DoDeallocateMemory(lldb::addr_t ptr) override; virtual size_t GetSoftwareBreakpointTrapOpcode(lldb_private::BreakpointSite *bp_site); - lldb_private::Error + lldb_private::Status EnableBreakpointSite(lldb_private::BreakpointSite *bp_site) override; - lldb_private::Error + lldb_private::Status DisableBreakpointSite(lldb_private::BreakpointSite *bp_site) override; - lldb_private::Error EnableWatchpoint(lldb_private::Watchpoint *wp, - bool notify = true) override; - - lldb_private::Error DisableWatchpoint(lldb_private::Watchpoint *wp, + lldb_private::Status EnableWatchpoint(lldb_private::Watchpoint *wp, bool notify = true) override; - lldb_private::Error GetWatchpointSupportInfo(uint32_t &num) override; + lldb_private::Status DisableWatchpoint(lldb_private::Watchpoint *wp, + bool notify = true) override; + + lldb_private::Status GetWatchpointSupportInfo(uint32_t &num) override; - lldb_private::Error GetWatchpointSupportInfo(uint32_t &num, - bool &after) override; + lldb_private::Status GetWatchpointSupportInfo(uint32_t &num, + bool &after) override; virtual uint32_t UpdateThreadListIfNeeded(); @@ -134,7 +134,7 @@ public: lldb::addr_t GetImageInfoAddress() override; size_t PutSTDIN(const char *buf, size_t len, - lldb_private::Error &error) override; + lldb_private::Status &error) override; const lldb::DataBufferSP GetAuxvData() override; @@ -169,10 +169,10 @@ public: void *baton, lldb_private::StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id); - lldb_private::Error SetupSoftwareSingleStepping(lldb::tid_t tid); + lldb_private::Status SetupSoftwareSingleStepping(lldb::tid_t tid); - lldb_private::Error SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, - lldb::addr_t addr); + lldb_private::Status SetSoftwareSingleStepBreakpoint(lldb::tid_t tid, + lldb::addr_t addr); bool IsSoftwareStepBreakpoint(lldb::tid_t tid); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp index 68ab41651162..1667490f1344 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.cpp @@ -29,7 +29,7 @@ #include "lldb/Target/RegisterContext.h" #include "lldb/Target/Thread.h" #include "lldb/Target/UnixSignals.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "FreeBSDThread.h" #include "Plugins/Process/POSIX/CrashReason.h" @@ -154,7 +154,7 @@ PtraceWrapper((req), (pid), (addr), (data)) // functions without needed to go thru the thread funnel. static size_t DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, - size_t size, Error &error) { + size_t size, Status &error) { struct ptrace_io_desc pi_desc; pi_desc.piod_op = PIOD_READ_D; @@ -168,7 +168,7 @@ static size_t DoReadMemory(lldb::pid_t pid, lldb::addr_t vm_addr, void *buf, } static size_t DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, - const void *buf, size_t size, Error &error) { + const void *buf, size_t size, Status &error) { struct ptrace_io_desc pi_desc; pi_desc.piod_op = PIOD_WRITE_D; @@ -183,7 +183,7 @@ static size_t DoWriteMemory(lldb::pid_t pid, lldb::addr_t vm_addr, // Simple helper function to ensure flags are enabled on the given file // descriptor. -static bool EnsureFDFlags(int fd, int flags, Error &error) { +static bool EnsureFDFlags(int fd, int flags, Status &error) { int status; if ((status = fcntl(fd, F_GETFL)) == -1) { @@ -221,7 +221,7 @@ public: /// @brief Implements ProcessMonitor::ReadMemory. class ReadOperation : public Operation { public: - ReadOperation(lldb::addr_t addr, void *buff, size_t size, Error &error, + ReadOperation(lldb::addr_t addr, void *buff, size_t size, Status &error, size_t &result) : m_addr(addr), m_buff(buff), m_size(size), m_error(error), m_result(result) {} @@ -232,7 +232,7 @@ private: lldb::addr_t m_addr; void *m_buff; size_t m_size; - Error &m_error; + Status &m_error; size_t &m_result; }; @@ -247,8 +247,8 @@ void ReadOperation::Execute(ProcessMonitor *monitor) { /// @brief Implements ProcessMonitor::WriteMemory. class WriteOperation : public Operation { public: - WriteOperation(lldb::addr_t addr, const void *buff, size_t size, Error &error, - size_t &result) + WriteOperation(lldb::addr_t addr, const void *buff, size_t size, + Status &error, size_t &result) : m_addr(addr), m_buff(buff), m_size(size), m_error(error), m_result(result) {} @@ -258,7 +258,7 @@ private: lldb::addr_t m_addr; const void *m_buff; size_t m_size; - Error &m_error; + Status &m_error; size_t &m_result; }; @@ -672,12 +672,12 @@ void KillOperation::Execute(ProcessMonitor *monitor) { /// @brief Implements ProcessMonitor::Detach. class DetachOperation : public Operation { public: - DetachOperation(Error &result) : m_error(result) {} + DetachOperation(Status &result) : m_error(result) {} void Execute(ProcessMonitor *monitor); private: - Error &m_error; + Status &m_error; }; void DetachOperation::Execute(ProcessMonitor *monitor) { @@ -731,7 +731,7 @@ ProcessMonitor::ProcessMonitor( const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec, const FileSpec &working_dir, const lldb_private::ProcessLaunchInfo & /* launch_info */, - lldb_private::Error &error) + lldb_private::Status &error) : m_process(static_cast<ProcessFreeBSD *>(process)), m_pid(LLDB_INVALID_PROCESS_ID), m_terminal_fd(-1), m_operation(0) { using namespace std::placeholders; @@ -777,7 +777,7 @@ WAIT_AGAIN: } ProcessMonitor::ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid, - lldb_private::Error &error) + lldb_private::Status &error) : m_process(static_cast<ProcessFreeBSD *>(process)), m_pid(pid), m_terminal_fd(-1), m_operation(0) { using namespace std::placeholders; @@ -824,7 +824,7 @@ ProcessMonitor::~ProcessMonitor() { StopMonitor(); } //------------------------------------------------------------------------------ // Thread setup and tear down. -void ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error) { +void ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Status &error) { static const char *g_thread_name = "lldb.process.freebsd.operation"; if (m_operation_thread.IsJoinable()) @@ -992,7 +992,7 @@ FINISH: } void ProcessMonitor::StartAttachOpThread(AttachArgs *args, - lldb_private::Error &error) { + lldb_private::Status &error) { static const char *g_thread_name = "lldb.process.freebsd.operation"; if (m_operation_thread.IsJoinable()) @@ -1240,7 +1240,7 @@ void ProcessMonitor::DoOperation(Operation *op) { } size_t ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, - Error &error) { + Status &error) { size_t result; ReadOperation op(vm_addr, buf, size, error, result); DoOperation(&op); @@ -1248,7 +1248,7 @@ size_t ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, } size_t ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, - size_t size, lldb_private::Error &error) { + size_t size, lldb_private::Status &error) { size_t result; WriteOperation op(vm_addr, buf, size, error, result); DoOperation(&op); @@ -1389,8 +1389,8 @@ bool ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message) { return result; } -lldb_private::Error ProcessMonitor::Detach(lldb::tid_t tid) { - lldb_private::Error error; +lldb_private::Status ProcessMonitor::Detach(lldb::tid_t tid) { + lldb_private::Status error; if (tid != LLDB_INVALID_THREAD_ID) { DetachOperation op(error); DoOperation(&op); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h index 58629189b7b8..0963453a31b1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/ProcessMonitor.h @@ -23,7 +23,7 @@ #include "lldb/lldb-types.h" namespace lldb_private { -class Error; +class Status; class Module; class Scalar; } // End lldb_private namespace. @@ -54,10 +54,10 @@ public: const lldb_private::FileSpec &stderr_file_spec, const lldb_private::FileSpec &working_dir, const lldb_private::ProcessLaunchInfo &launch_info, - lldb_private::Error &error); + lldb_private::Status &error); ProcessMonitor(ProcessFreeBSD *process, lldb::pid_t pid, - lldb_private::Error &error); + lldb_private::Status &error); ~ProcessMonitor(); @@ -86,14 +86,14 @@ public: /// /// This method is provided to implement Process::DoReadMemory. size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, - lldb_private::Error &error); + lldb_private::Status &error); /// Writes @p size bytes from address @p vm_adder in the inferior process /// address space. /// /// This method is provided to implement Process::DoWriteMemory. size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, - lldb_private::Error &error); + lldb_private::Status &error); /// Reads the contents from the register identified by the given (architecture /// dependent) offset. @@ -178,7 +178,7 @@ public: /// Terminate the traced process. bool Kill(); - lldb_private::Error Detach(lldb::tid_t tid); + lldb_private::Status Detach(lldb::tid_t tid); void StopMonitor(); @@ -210,7 +210,7 @@ private: ProcessMonitor *m_monitor; // The monitor performing the attach. sem_t m_semaphore; // Posted to once operation complete. - lldb_private::Error m_error; // Set if process operation failed. + lldb_private::Status m_error; // Set if process operation failed. }; /// @class LauchArgs @@ -238,7 +238,7 @@ private: const lldb_private::FileSpec m_working_dir; // Working directory or empty. }; - void StartLaunchOpThread(LaunchArgs *args, lldb_private::Error &error); + void StartLaunchOpThread(LaunchArgs *args, lldb_private::Status &error); static void *LaunchOpThread(void *arg); @@ -252,7 +252,7 @@ private: lldb::pid_t m_pid; // pid of the process to be attached. }; - void StartAttachOpThread(AttachArgs *args, lldb_private::Error &error); + void StartAttachOpThread(AttachArgs *args, lldb_private::Status &error); static void *AttachOpThread(void *args); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp index 14171d614c9e..59d42b9ad72e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm.cpp @@ -75,7 +75,7 @@ bool RegisterContextPOSIXProcessMonitor_arm::WriteRegister( // Read the full register. if (ReadRegister(full_reg_info, full_value)) { - Error error; + Status error; ByteOrder byte_order = GetByteOrder(); uint8_t dst[RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp index 8a8eb0520cca..93ffeb5ea79b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_arm64.cpp @@ -77,7 +77,7 @@ bool RegisterContextPOSIXProcessMonitor_arm64::WriteRegister( // Read the full register. if (ReadRegister(full_reg_info, full_value)) { - lldb_private::Error error; + lldb_private::Status error; lldb::ByteOrder byte_order = GetByteOrder(); uint8_t dst[lldb_private::RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp index ab50a5db3f3e..b911ee222015 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_mips64.cpp @@ -76,7 +76,7 @@ bool RegisterContextPOSIXProcessMonitor_mips64::WriteRegister( // Read the full register. if (ReadRegister(full_reg_info, full_value)) { - Error error; + Status error; ByteOrder byte_order = GetByteOrder(); uint8_t dst[RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp index 70eec945ce8d..bc1d4df89fc8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_powerpc.cpp @@ -88,7 +88,7 @@ bool RegisterContextPOSIXProcessMonitor_powerpc::WriteRegister( // Read the full register. if (ReadRegister(full_reg_info, full_value)) { - Error error; + Status error; ByteOrder byte_order = GetByteOrder(); uint8_t dst[RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp index 036306058ff8..1cd8f1aafa6e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/FreeBSD/RegisterContextPOSIXProcessMonitor_x86.cpp @@ -130,7 +130,7 @@ bool RegisterContextPOSIXProcessMonitor_x86_64::WriteRegister( // Read the full register. if (ReadRegister(full_reg_info, full_value)) { - Error error; + Status error; ByteOrder byte_order = GetByteOrder(); uint8_t dst[RegisterValue::kMaxRegisterByteSize]; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp index 347c12943bd5..80751147b4f5 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp @@ -68,8 +68,8 @@ static int convert_pid_status_to_return_code(int status) { // Simple helper function to ensure flags are enabled on the given file // descriptor. -static Error EnsureFDFlags(int fd, int flags) { - Error error; +static Status EnsureFDFlags(int fd, int flags) { + Status error; int status = fcntl(fd, F_GETFL); if (status == -1) { @@ -89,13 +89,13 @@ static Error EnsureFDFlags(int fd, int flags) { // Public Static Methods // ----------------------------------------------------------------------------- -Error NativeProcessProtocol::Launch( +Status NativeProcessProtocol::Launch( ProcessLaunchInfo &launch_info, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); - Error error; + Status error; // Verify the working directory is valid if one was specified. FileSpec working_dir{launch_info.GetWorkingDirectory()}; @@ -129,7 +129,7 @@ Error NativeProcessProtocol::Launch( return error; } -Error NativeProcessProtocol::Attach( +Status NativeProcessProtocol::Attach( lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); @@ -137,7 +137,7 @@ Error NativeProcessProtocol::Attach( // Retrieve the architecture for the running process. ArchSpec process_arch; - Error error = ResolveProcessArchitecture(pid, process_arch); + Status error = ResolveProcessArchitecture(pid, process_arch); if (!error.Success()) return error; @@ -245,7 +245,7 @@ void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) { SetState(StateType::eStateStopped, true); break; case TRAP_EXEC: { - Error error = ReinitializeThreads(); + Status error = ReinitializeThreads(); if (error.Fail()) { SetState(StateType::eStateInvalid); return; @@ -262,7 +262,7 @@ void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) { case TRAP_DBREG: { // If a watchpoint was hit, report it uint32_t wp_index; - Error error = + Status error = static_pointer_cast<NativeThreadNetBSD>(m_threads[info.psi_lwpid]) ->GetRegisterContext() ->GetWatchpointHitIndex(wp_index, @@ -318,10 +318,10 @@ void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) { SetState(StateType::eStateStopped, true); } -Error NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, - int data, int *result) { +Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, + int data, int *result) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); - Error error; + Status error; int ret; errno = 0; @@ -341,7 +341,7 @@ Error NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, return error; } -Error NativeProcessNetBSD::GetSoftwareBreakpointPCOffset( +Status NativeProcessNetBSD::GetSoftwareBreakpointPCOffset( uint32_t &actual_opcode_size) { // FIXME put this behind a breakpoint protocol class that can be // set per architecture. Need ARM, MIPS support here. @@ -349,17 +349,17 @@ Error NativeProcessNetBSD::GetSoftwareBreakpointPCOffset( switch (m_arch.GetMachine()) { case llvm::Triple::x86_64: actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode)); - return Error(); + return Status(); default: assert(false && "CPU type not supported!"); - return Error("CPU type not supported"); + return Status("CPU type not supported"); } } -Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( - NativeThreadNetBSD &thread) { +Status +NativeProcessNetBSD::FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS)); - Error error; + Status error; // Find out the size of a breakpoint (might depend on where we are in the // code). NativeRegisterContextSP context_sp = thread.GetRegisterContext(); @@ -394,7 +394,7 @@ Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( "pid {0} no lldb breakpoint found at current pc with " "adjustment: {1}", GetID(), breakpoint_addr); - return Error(); + return Status(); } // If the breakpoint is not a software breakpoint, nothing to do. if (!breakpoint_sp->IsSoftwareBreakpoint()) { @@ -402,7 +402,7 @@ Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( log, "pid {0} breakpoint found at {1:x}, not software, nothing to adjust", GetID(), breakpoint_addr); - return Error(); + return Status(); } // // We have a software breakpoint and need to adjust the PC. @@ -414,7 +414,7 @@ Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( "pid {0} breakpoint found at {1:x}, it is software, but the " "size is zero, nothing to do (unexpected)", GetID(), breakpoint_addr); - return Error(); + return Status(); } // // We have a software breakpoint and need to adjust the PC. @@ -426,7 +426,7 @@ Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( "pid {0} breakpoint found at {1:x}, it is software, but the " "size is zero, nothing to do (unexpected)", GetID(), breakpoint_addr); - return Error(); + return Status(); } // Change the program counter. LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), @@ -440,7 +440,7 @@ Error NativeProcessNetBSD::FixupBreakpointPCAsNeeded( return error; } -Error NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { +Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); LLDB_LOG(log, "pid {0}", GetID()); @@ -451,10 +451,10 @@ Error NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { if (action == nullptr) { LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), thread_sp->GetID()); - return Error(); + return Status(); } - Error error; + Status error; switch (action->state) { case eStateRunning: { @@ -486,17 +486,17 @@ Error NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { llvm_unreachable("Unexpected state"); default: - return Error("NativeProcessNetBSD::%s (): unexpected state %s specified " - "for pid %" PRIu64 ", tid %" PRIu64, - __FUNCTION__, StateAsCString(action->state), GetID(), - thread_sp->GetID()); + return Status("NativeProcessNetBSD::%s (): unexpected state %s specified " + "for pid %" PRIu64 ", tid %" PRIu64, + __FUNCTION__, StateAsCString(action->state), GetID(), + thread_sp->GetID()); } - return Error(); + return Status(); } -Error NativeProcessNetBSD::Halt() { - Error error; +Status NativeProcessNetBSD::Halt() { + Status error; if (kill(GetID(), SIGSTOP) != 0) error.SetErrorToErrno(); @@ -504,8 +504,8 @@ Error NativeProcessNetBSD::Halt() { return error; } -Error NativeProcessNetBSD::Detach() { - Error error; +Status NativeProcessNetBSD::Detach() { + Status error; // Stop monitoring the inferior. m_sigchld_handle.reset(); @@ -517,8 +517,8 @@ Error NativeProcessNetBSD::Detach() { return PtraceWrapper(PT_DETACH, GetID()); } -Error NativeProcessNetBSD::Signal(int signo) { - Error error; +Status NativeProcessNetBSD::Signal(int signo) { + Status error; if (kill(GetID(), signo)) error.SetErrorToErrno(); @@ -526,11 +526,11 @@ Error NativeProcessNetBSD::Signal(int signo) { return error; } -Error NativeProcessNetBSD::Kill() { +Status NativeProcessNetBSD::Kill() { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); LLDB_LOG(log, "pid {0}", GetID()); - Error error; + Status error; switch (m_state) { case StateType::eStateInvalid: @@ -562,15 +562,15 @@ Error NativeProcessNetBSD::Kill() { return error; } -Error NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) { +Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) { if (m_supports_mem_region == LazyBool::eLazyBoolNo) { // We're done. - return Error("unsupported"); + return Status("unsupported"); } - Error error = PopulateMemoryRegionCache(); + Status error = PopulateMemoryRegionCache(); if (error.Fail()) { return error; } @@ -619,14 +619,14 @@ Error NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, return error; } -Error NativeProcessNetBSD::PopulateMemoryRegionCache() { +Status NativeProcessNetBSD::PopulateMemoryRegionCache() { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); // If our cache is empty, pull the latest. There should always be at least // one memory region if memory region handling is supported. if (!m_mem_region_cache.empty()) { LLDB_LOG(log, "reusing {0} cached memory region entries", m_mem_region_cache.size()); - return Error(); + return Status(); } struct kinfo_vmentry *vm; @@ -634,7 +634,7 @@ Error NativeProcessNetBSD::PopulateMemoryRegionCache() { vm = kinfo_getvmmap(GetID(), &count); if (vm == NULL) { m_supports_mem_region = LazyBool::eLazyBoolNo; - Error error; + Status error; error.SetErrorString("not supported"); return error; } @@ -674,7 +674,7 @@ Error NativeProcessNetBSD::PopulateMemoryRegionCache() { LLDB_LOG(log, "failed to find any vmmap entries, assuming no support " "for memory region metadata retrieval"); m_supports_mem_region = LazyBool::eLazyBoolNo; - Error error; + Status error; error.SetErrorString("not supported"); return error; } @@ -682,16 +682,16 @@ Error NativeProcessNetBSD::PopulateMemoryRegionCache() { m_mem_region_cache.size(), GetID()); // We support memory retrieval, remember that. m_supports_mem_region = LazyBool::eLazyBoolYes; - return Error(); + return Status(); } -Error NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions, - lldb::addr_t &addr) { - return Error("Unimplemented"); +Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) { + return Status("Unimplemented"); } -Error NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) { - return Error("Unimplemented"); +Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) { + return Status("Unimplemented"); } lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() { @@ -706,15 +706,15 @@ bool NativeProcessNetBSD::GetArchitecture(ArchSpec &arch) const { return true; } -Error NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, - bool hardware) { +Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, + bool hardware) { if (hardware) - return Error("NativeProcessNetBSD does not support hardware breakpoints"); + return Status("NativeProcessNetBSD does not support hardware breakpoints"); else return SetSoftwareBreakpoint(addr, size); } -Error NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode( +Status NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode( size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) { static const uint8_t g_i386_opcode[] = {0xCC}; @@ -724,27 +724,27 @@ Error NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode( case llvm::Triple::x86_64: trap_opcode_bytes = g_i386_opcode; actual_opcode_size = sizeof(g_i386_opcode); - return Error(); + return Status(); default: assert(false && "CPU type not supported!"); - return Error("CPU type not supported"); + return Status("CPU type not supported"); } } -Error NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path, - FileSpec &file_spec) { - return Error("Unimplemented"); +Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path, + FileSpec &file_spec) { + return Status("Unimplemented"); } -Error NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name, - lldb::addr_t &load_addr) { +Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name, + lldb::addr_t &load_addr) { load_addr = LLDB_INVALID_ADDRESS; - return Error(); + return Status(); } -Error NativeProcessNetBSD::LaunchInferior(MainLoop &mainloop, - ProcessLaunchInfo &launch_info) { - Error error; +Status NativeProcessNetBSD::LaunchInferior(MainLoop &mainloop, + ProcessLaunchInfo &launch_info) { + Status error; m_sigchld_handle = mainloop.RegisterSignal( SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error); if (!m_sigchld_handle) @@ -826,7 +826,7 @@ Error NativeProcessNetBSD::LaunchInferior(MainLoop &mainloop, } void NativeProcessNetBSD::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, - Error &error) { + Status &error) { Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); LLDB_LOG(log, "pid = {0:x}", pid); @@ -862,7 +862,7 @@ void NativeProcessNetBSD::SigchldHandler() { if (errno == EINTR) return; - Error error(errno, eErrorTypePOSIX); + Status error(errno, eErrorTypePOSIX); LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error); } @@ -915,7 +915,7 @@ NativeThreadNetBSDSP NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) { return thread_sp; } -::pid_t NativeProcessNetBSD::Attach(lldb::pid_t pid, Error &error) { +::pid_t NativeProcessNetBSD::Attach(lldb::pid_t pid, Status &error) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); if (pid <= 1) { @@ -956,8 +956,8 @@ NativeThreadNetBSDSP NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) { return pid; } -Error NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) { +Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, + size_t size, size_t &bytes_read) { unsigned char *dst = static_cast<unsigned char *>(buf); struct ptrace_io_desc io; @@ -972,7 +972,7 @@ Error NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, size_t size, io.piod_offs = (void *)(addr + bytes_read); io.piod_addr = dst + bytes_read; - Error error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); + Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); if (error.Fail()) return error; @@ -980,22 +980,22 @@ Error NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, size_t size, io.piod_len = size - bytes_read; } while (bytes_read < size); - return Error(); + return Status(); } -Error NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, - size_t size, - size_t &bytes_read) { - Error error = ReadMemory(addr, buf, size, bytes_read); +Status NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, + size_t size, + size_t &bytes_read) { + Status error = ReadMemory(addr, buf, size, bytes_read); if (error.Fail()) return error; return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); } -Error NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, - size_t size, size_t &bytes_written) { +Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, + size_t size, size_t &bytes_written) { const unsigned char *src = static_cast<const unsigned char *>(buf); - Error error; + Status error; struct ptrace_io_desc io; Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); @@ -1009,7 +1009,7 @@ Error NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, io.piod_addr = (void *)(src + bytes_written); io.piod_offs = (void *)(addr + bytes_written); - Error error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); + Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); if (error.Fail()) return error; @@ -1039,7 +1039,7 @@ NativeProcessNetBSD::GetAuxvData() const { .piod_addr = (void *)buf.get()->getBufferStart(), .piod_len = auxv_size}; - Error error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); + Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); if (error.Fail()) return std::error_code(error.GetError(), std::generic_category()); @@ -1050,13 +1050,13 @@ NativeProcessNetBSD::GetAuxvData() const { return buf; } -Error NativeProcessNetBSD::ReinitializeThreads() { +Status NativeProcessNetBSD::ReinitializeThreads() { // Clear old threads m_threads.clear(); // Initialize new thread struct ptrace_lwpinfo info = {}; - Error error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); + Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); if (error.Fail()) { return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h index ae946a8e004d..e18ba162e523 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.h @@ -31,11 +31,11 @@ namespace process_netbsd { /// /// Changes in the inferior process state are broadcasted. class NativeProcessNetBSD : public NativeProcessProtocol { - friend Error NativeProcessProtocol::Launch( + friend Status NativeProcessProtocol::Launch( ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &process_sp); - friend Error NativeProcessProtocol::Attach( + friend Status NativeProcessProtocol::Attach( lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop, NativeProcessProtocolSP &process_sp); @@ -43,32 +43,32 @@ public: // --------------------------------------------------------------------- // NativeProcessProtocol Interface // --------------------------------------------------------------------- - Error Resume(const ResumeActionList &resume_actions) override; + Status Resume(const ResumeActionList &resume_actions) override; - Error Halt() override; + Status Halt() override; - Error Detach() override; + Status Detach() override; - Error Signal(int signo) override; + Status Signal(int signo) override; - Error Kill() override; + Status Kill() override; - Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) override; + Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) override; - Error ReadMemory(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) override; + Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read) override; - Error ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, - size_t &bytes_read) override; + Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, + size_t &bytes_read) override; - Error WriteMemory(lldb::addr_t addr, const void *buf, size_t size, - size_t &bytes_written) override; + Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, + size_t &bytes_written) override; - Error AllocateMemory(size_t size, uint32_t permissions, - lldb::addr_t &addr) override; + Status AllocateMemory(size_t size, uint32_t permissions, + lldb::addr_t &addr) override; - Error DeallocateMemory(lldb::addr_t addr) override; + Status DeallocateMemory(lldb::addr_t addr) override; lldb::addr_t GetSharedLibraryInfoAddress() override; @@ -76,13 +76,14 @@ public: bool GetArchitecture(ArchSpec &arch) const override; - Error SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override; + Status SetBreakpoint(lldb::addr_t addr, uint32_t size, + bool hardware) override; - Error GetLoadedModuleFileSpec(const char *module_path, - FileSpec &file_spec) override; + Status GetLoadedModuleFileSpec(const char *module_path, + FileSpec &file_spec) override; - Error GetFileLoadAddress(const llvm::StringRef &file_name, - lldb::addr_t &load_addr) override; + Status GetFileLoadAddress(const llvm::StringRef &file_name, + lldb::addr_t &load_addr) override; llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GetAuxvData() const override; @@ -90,15 +91,15 @@ public: // --------------------------------------------------------------------- // Interface used by NativeRegisterContext-derived classes. // --------------------------------------------------------------------- - static Error PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, - int data = 0, int *result = nullptr); + static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr = nullptr, + int data = 0, int *result = nullptr); protected: // --------------------------------------------------------------------- // NativeProcessProtocol protected interface // --------------------------------------------------------------------- - Error + Status GetSoftwareBreakpointTrapOpcode(size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) override; @@ -116,8 +117,8 @@ private: NativeThreadNetBSDSP AddThread(lldb::tid_t thread_id); - Error LaunchInferior(MainLoop &mainloop, ProcessLaunchInfo &launch_info); - void AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, Error &error); + Status LaunchInferior(MainLoop &mainloop, ProcessLaunchInfo &launch_info); + void AttachToInferior(MainLoop &mainloop, lldb::pid_t pid, Status &error); void MonitorCallback(lldb::pid_t pid, int signal); void MonitorExited(lldb::pid_t pid, int signal, int status); @@ -125,14 +126,14 @@ private: void MonitorSIGTRAP(lldb::pid_t pid); void MonitorSignal(lldb::pid_t pid, int signal); - Error GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size); - Error FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread); - Error PopulateMemoryRegionCache(); + Status GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size); + Status FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread); + Status PopulateMemoryRegionCache(); void SigchldHandler(); - ::pid_t Attach(lldb::pid_t pid, Error &error); + ::pid_t Attach(lldb::pid_t pid, Status &error); - Error ReinitializeThreads(); + Status ReinitializeThreads(); }; } // namespace process_netbsd diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp index cd47deac73ad..b442fc3462cc 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp @@ -25,80 +25,80 @@ NativeRegisterContextNetBSD::NativeRegisterContextNetBSD( : NativeRegisterContextRegisterInfo(native_thread, concrete_frame_idx, reg_info_interface_p) {} -Error NativeRegisterContextNetBSD::ReadGPR() { +Status NativeRegisterContextNetBSD::ReadGPR() { void *buf = GetGPRBuffer(); if (!buf) - return Error("GPR buffer is NULL"); + return Status("GPR buffer is NULL"); return DoReadGPR(buf); } -Error NativeRegisterContextNetBSD::WriteGPR() { +Status NativeRegisterContextNetBSD::WriteGPR() { void *buf = GetGPRBuffer(); if (!buf) - return Error("GPR buffer is NULL"); + return Status("GPR buffer is NULL"); return DoWriteGPR(buf); } -Error NativeRegisterContextNetBSD::ReadFPR() { +Status NativeRegisterContextNetBSD::ReadFPR() { void *buf = GetFPRBuffer(); if (!buf) - return Error("FPR buffer is NULL"); + return Status("FPR buffer is NULL"); return DoReadFPR(buf); } -Error NativeRegisterContextNetBSD::WriteFPR() { +Status NativeRegisterContextNetBSD::WriteFPR() { void *buf = GetFPRBuffer(); if (!buf) - return Error("FPR buffer is NULL"); + return Status("FPR buffer is NULL"); return DoWriteFPR(buf); } -Error NativeRegisterContextNetBSD::ReadDBR() { +Status NativeRegisterContextNetBSD::ReadDBR() { void *buf = GetDBRBuffer(); if (!buf) - return Error("DBR buffer is NULL"); + return Status("DBR buffer is NULL"); return DoReadDBR(buf); } -Error NativeRegisterContextNetBSD::WriteDBR() { +Status NativeRegisterContextNetBSD::WriteDBR() { void *buf = GetDBRBuffer(); if (!buf) - return Error("DBR buffer is NULL"); + return Status("DBR buffer is NULL"); return DoWriteDBR(buf); } -Error NativeRegisterContextNetBSD::DoReadGPR(void *buf) { +Status NativeRegisterContextNetBSD::DoReadGPR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_GETREGS, GetProcessPid(), buf, m_thread.GetID()); } -Error NativeRegisterContextNetBSD::DoWriteGPR(void *buf) { +Status NativeRegisterContextNetBSD::DoWriteGPR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_SETREGS, GetProcessPid(), buf, m_thread.GetID()); } -Error NativeRegisterContextNetBSD::DoReadFPR(void *buf) { +Status NativeRegisterContextNetBSD::DoReadFPR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_GETFPREGS, GetProcessPid(), buf, m_thread.GetID()); } -Error NativeRegisterContextNetBSD::DoWriteFPR(void *buf) { +Status NativeRegisterContextNetBSD::DoWriteFPR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_SETFPREGS, GetProcessPid(), buf, m_thread.GetID()); } -Error NativeRegisterContextNetBSD::DoReadDBR(void *buf) { +Status NativeRegisterContextNetBSD::DoReadDBR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_GETDBREGS, GetProcessPid(), buf, m_thread.GetID()); } -Error NativeRegisterContextNetBSD::DoWriteDBR(void *buf) { +Status NativeRegisterContextNetBSD::DoWriteDBR(void *buf) { return NativeProcessNetBSD::PtraceWrapper(PT_SETDBREGS, GetProcessPid(), buf, m_thread.GetID()); } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h index d820baac3afa..d96b7aea0048 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h @@ -35,14 +35,14 @@ public: uint32_t concrete_frame_idx); protected: - virtual Error ReadGPR(); - virtual Error WriteGPR(); + virtual Status ReadGPR(); + virtual Status WriteGPR(); - virtual Error ReadFPR(); - virtual Error WriteFPR(); + virtual Status ReadFPR(); + virtual Status WriteFPR(); - virtual Error ReadDBR(); - virtual Error WriteDBR(); + virtual Status ReadDBR(); + virtual Status WriteDBR(); virtual void *GetGPRBuffer() { return nullptr; } virtual size_t GetGPRSize() { @@ -55,14 +55,14 @@ protected: virtual void *GetDBRBuffer() { return nullptr; } virtual size_t GetDBRSize() { return 0; } - virtual Error DoReadGPR(void *buf); - virtual Error DoWriteGPR(void *buf); + virtual Status DoReadGPR(void *buf); + virtual Status DoWriteGPR(void *buf); - virtual Error DoReadFPR(void *buf); - virtual Error DoWriteFPR(void *buf); + virtual Status DoReadFPR(void *buf); + virtual Status DoWriteFPR(void *buf); - virtual Error DoReadDBR(void *buf); - virtual Error DoWriteDBR(void *buf); + virtual Status DoReadDBR(void *buf); + virtual Status DoWriteDBR(void *buf); virtual NativeProcessNetBSD &GetProcess(); virtual ::pid_t GetProcessPid(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp index dc37be7b934b..9690da0e1374 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.cpp @@ -14,8 +14,8 @@ #include "lldb/Core/RegisterValue.h" #include "lldb/Host/HostInfo.h" #include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h" @@ -251,9 +251,10 @@ int NativeRegisterContextNetBSD_x86_64::WriteRegisterSet(uint32_t set) { return -1; } -Error NativeRegisterContextNetBSD_x86_64::ReadRegister( - const RegisterInfo *reg_info, RegisterValue ®_value) { - Error error; +Status +NativeRegisterContextNetBSD_x86_64::ReadRegister(const RegisterInfo *reg_info, + RegisterValue ®_value) { + Status error; if (!reg_info) { error.SetErrorString("reg_info NULL"); @@ -446,10 +447,10 @@ Error NativeRegisterContextNetBSD_x86_64::ReadRegister( return error; } -Error NativeRegisterContextNetBSD_x86_64::WriteRegister( +Status NativeRegisterContextNetBSD_x86_64::WriteRegister( const RegisterInfo *reg_info, const RegisterValue ®_value) { - Error error; + Status error; if (!reg_info) { error.SetErrorString("reg_info NULL"); @@ -645,9 +646,9 @@ Error NativeRegisterContextNetBSD_x86_64::WriteRegister( return error; } -Error NativeRegisterContextNetBSD_x86_64::ReadAllRegisterValues( +Status NativeRegisterContextNetBSD_x86_64::ReadAllRegisterValues( lldb::DataBufferSP &data_sp) { - Error error; + Status error; data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0)); if (!data_sp) { @@ -680,9 +681,9 @@ Error NativeRegisterContextNetBSD_x86_64::ReadAllRegisterValues( return error; } -Error NativeRegisterContextNetBSD_x86_64::WriteAllRegisterValues( +Status NativeRegisterContextNetBSD_x86_64::WriteAllRegisterValues( const lldb::DataBufferSP &data_sp) { - Error error; + Status error; if (!data_sp) { error.SetErrorStringWithFormat( @@ -717,14 +718,14 @@ Error NativeRegisterContextNetBSD_x86_64::WriteAllRegisterValues( return error; } -Error NativeRegisterContextNetBSD_x86_64::IsWatchpointHit(uint32_t wp_index, - bool &is_hit) { +Status NativeRegisterContextNetBSD_x86_64::IsWatchpointHit(uint32_t wp_index, + bool &is_hit) { if (wp_index >= NumSupportedHardwareWatchpoints()) - return Error("Watchpoint index out of range"); + return Status("Watchpoint index out of range"); RegisterValue reg_value; const RegisterInfo *const reg_info = GetRegisterInfoAtIndex(lldb_dr6_x86_64); - Error error = ReadRegister(reg_info, reg_value); + Status error = ReadRegister(reg_info, reg_value); if (error.Fail()) { is_hit = false; return error; @@ -737,12 +738,12 @@ Error NativeRegisterContextNetBSD_x86_64::IsWatchpointHit(uint32_t wp_index, return error; } -Error NativeRegisterContextNetBSD_x86_64::GetWatchpointHitIndex( +Status NativeRegisterContextNetBSD_x86_64::GetWatchpointHitIndex( uint32_t &wp_index, lldb::addr_t trap_addr) { uint32_t num_hw_wps = NumSupportedHardwareWatchpoints(); for (wp_index = 0; wp_index < num_hw_wps; ++wp_index) { bool is_hit; - Error error = IsWatchpointHit(wp_index, is_hit); + Status error = IsWatchpointHit(wp_index, is_hit); if (error.Fail()) { wp_index = LLDB_INVALID_INDEX32; return error; @@ -751,17 +752,17 @@ Error NativeRegisterContextNetBSD_x86_64::GetWatchpointHitIndex( } } wp_index = LLDB_INVALID_INDEX32; - return Error(); + return Status(); } -Error NativeRegisterContextNetBSD_x86_64::IsWatchpointVacant(uint32_t wp_index, - bool &is_vacant) { +Status NativeRegisterContextNetBSD_x86_64::IsWatchpointVacant(uint32_t wp_index, + bool &is_vacant) { if (wp_index >= NumSupportedHardwareWatchpoints()) - return Error("Watchpoint index out of range"); + return Status("Watchpoint index out of range"); RegisterValue reg_value; const RegisterInfo *const reg_info = GetRegisterInfoAtIndex(lldb_dr7_x86_64); - Error error = ReadRegister(reg_info, reg_value); + Status error = ReadRegister(reg_info, reg_value); if (error.Fail()) { is_vacant = false; return error; @@ -774,11 +775,11 @@ Error NativeRegisterContextNetBSD_x86_64::IsWatchpointVacant(uint32_t wp_index, return error; } -Error NativeRegisterContextNetBSD_x86_64::SetHardwareWatchpointWithIndex( +Status NativeRegisterContextNetBSD_x86_64::SetHardwareWatchpointWithIndex( lldb::addr_t addr, size_t size, uint32_t watch_flags, uint32_t wp_index) { if (wp_index >= NumSupportedHardwareWatchpoints()) - return Error("Watchpoint index out of range"); + return Status("Watchpoint index out of range"); // Read only watchpoints aren't supported on x86_64. Fall back to read/write // waitchpoints instead. @@ -788,17 +789,17 @@ Error NativeRegisterContextNetBSD_x86_64::SetHardwareWatchpointWithIndex( watch_flags = 0x3; if (watch_flags != 0x1 && watch_flags != 0x3) - return Error("Invalid read/write bits for watchpoint"); + return Status("Invalid read/write bits for watchpoint"); if (size != 1 && size != 2 && size != 4 && size != 8) - return Error("Invalid size for watchpoint"); + return Status("Invalid size for watchpoint"); bool is_vacant; - Error error = IsWatchpointVacant(wp_index, is_vacant); + Status error = IsWatchpointVacant(wp_index, is_vacant); if (error.Fail()) return error; if (!is_vacant) - return Error("Watchpoint index not vacant"); + return Status("Watchpoint index not vacant"); RegisterValue reg_value; const RegisterInfo *const reg_info_dr7 = @@ -851,7 +852,7 @@ bool NativeRegisterContextNetBSD_x86_64::ClearHardwareWatchpoint( // clear bits 0, 1, 2, or 3 of the debug status register (DR6) const RegisterInfo *const reg_info_dr6 = GetRegisterInfoAtIndex(lldb_dr6_x86_64); - Error error = ReadRegister(reg_info_dr6, reg_value); + Status error = ReadRegister(reg_info_dr6, reg_value); if (error.Fail()) return false; uint64_t bit_mask = 1 << wp_index; @@ -873,13 +874,13 @@ bool NativeRegisterContextNetBSD_x86_64::ClearHardwareWatchpoint( return WriteRegister(reg_info_dr7, RegisterValue(control_bits)).Success(); } -Error NativeRegisterContextNetBSD_x86_64::ClearAllHardwareWatchpoints() { +Status NativeRegisterContextNetBSD_x86_64::ClearAllHardwareWatchpoints() { RegisterValue reg_value; // clear bits {0-4} of the debug status register (DR6) const RegisterInfo *const reg_info_dr6 = GetRegisterInfoAtIndex(lldb_dr6_x86_64); - Error error = ReadRegister(reg_info_dr6, reg_value); + Status error = ReadRegister(reg_info_dr6, reg_value); if (error.Fail()) return error; uint64_t bit_mask = 0xF; @@ -905,7 +906,7 @@ uint32_t NativeRegisterContextNetBSD_x86_64::SetHardwareWatchpoint( const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints(); for (uint32_t wp_index = 0; wp_index < num_hw_watchpoints; ++wp_index) { bool is_vacant; - Error error = IsWatchpointVacant(wp_index, is_vacant); + Status error = IsWatchpointVacant(wp_index, is_vacant); if (is_vacant) { error = SetHardwareWatchpointWithIndex(addr, size, watch_flags, wp_index); if (error.Success()) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h index 35b7cf1c2f19..5f5a6a0792e4 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD_x86_64.h @@ -36,29 +36,30 @@ public: const RegisterSet *GetRegisterSet(uint32_t set_index) const override; - Error ReadRegister(const RegisterInfo *reg_info, - RegisterValue ®_value) override; + Status ReadRegister(const RegisterInfo *reg_info, + RegisterValue ®_value) override; - Error WriteRegister(const RegisterInfo *reg_info, - const RegisterValue ®_value) override; + Status WriteRegister(const RegisterInfo *reg_info, + const RegisterValue ®_value) override; - Error ReadAllRegisterValues(lldb::DataBufferSP &data_sp) override; + Status ReadAllRegisterValues(lldb::DataBufferSP &data_sp) override; - Error WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override; + Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp) override; - Error IsWatchpointHit(uint32_t wp_index, bool &is_hit) override; + Status IsWatchpointHit(uint32_t wp_index, bool &is_hit) override; - Error GetWatchpointHitIndex(uint32_t &wp_index, - lldb::addr_t trap_addr) override; + Status GetWatchpointHitIndex(uint32_t &wp_index, + lldb::addr_t trap_addr) override; - Error IsWatchpointVacant(uint32_t wp_index, bool &is_vacant) override; + Status IsWatchpointVacant(uint32_t wp_index, bool &is_vacant) override; bool ClearHardwareWatchpoint(uint32_t wp_index) override; - Error ClearAllHardwareWatchpoints() override; + Status ClearAllHardwareWatchpoints() override; - Error SetHardwareWatchpointWithIndex(lldb::addr_t addr, size_t size, - uint32_t watch_flags, uint32_t wp_index); + Status SetHardwareWatchpointWithIndex(lldb::addr_t addr, size_t size, + uint32_t watch_flags, + uint32_t wp_index); uint32_t SetHardwareWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp index 9beb65288c2f..8a16431b016d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp @@ -160,40 +160,40 @@ NativeRegisterContextSP NativeThreadNetBSD::GetRegisterContext() { return m_reg_context_sp; } -Error NativeThreadNetBSD::SetWatchpoint(lldb::addr_t addr, size_t size, - uint32_t watch_flags, bool hardware) { +Status NativeThreadNetBSD::SetWatchpoint(lldb::addr_t addr, size_t size, + uint32_t watch_flags, bool hardware) { if (!hardware) - return Error("not implemented"); + return Status("not implemented"); if (m_state == eStateLaunching) - return Error(); - Error error = RemoveWatchpoint(addr); + return Status(); + Status error = RemoveWatchpoint(addr); if (error.Fail()) return error; NativeRegisterContextSP reg_ctx = GetRegisterContext(); uint32_t wp_index = reg_ctx->SetHardwareWatchpoint(addr, size, watch_flags); if (wp_index == LLDB_INVALID_INDEX32) - return Error("Setting hardware watchpoint failed."); + return Status("Setting hardware watchpoint failed."); m_watchpoint_index_map.insert({addr, wp_index}); - return Error(); + return Status(); } -Error NativeThreadNetBSD::RemoveWatchpoint(lldb::addr_t addr) { +Status NativeThreadNetBSD::RemoveWatchpoint(lldb::addr_t addr) { auto wp = m_watchpoint_index_map.find(addr); if (wp == m_watchpoint_index_map.end()) - return Error(); + return Status(); uint32_t wp_index = wp->second; m_watchpoint_index_map.erase(wp); if (GetRegisterContext()->ClearHardwareWatchpoint(wp_index)) - return Error(); - return Error("Clearing hardware watchpoint failed."); + return Status(); + return Status("Clearing hardware watchpoint failed."); } -Error NativeThreadNetBSD::SetHardwareBreakpoint(lldb::addr_t addr, - size_t size) { +Status NativeThreadNetBSD::SetHardwareBreakpoint(lldb::addr_t addr, + size_t size) { if (m_state == eStateLaunching) - return Error(); + return Status(); - Error error = RemoveHardwareBreakpoint(addr); + Status error = RemoveHardwareBreakpoint(addr); if (error.Fail()) return error; @@ -201,22 +201,22 @@ Error NativeThreadNetBSD::SetHardwareBreakpoint(lldb::addr_t addr, uint32_t bp_index = reg_ctx->SetHardwareBreakpoint(addr, size); if (bp_index == LLDB_INVALID_INDEX32) - return Error("Setting hardware breakpoint failed."); + return Status("Setting hardware breakpoint failed."); m_hw_break_index_map.insert({addr, bp_index}); - return Error(); + return Status(); } -Error NativeThreadNetBSD::RemoveHardwareBreakpoint(lldb::addr_t addr) { +Status NativeThreadNetBSD::RemoveHardwareBreakpoint(lldb::addr_t addr) { auto bp = m_hw_break_index_map.find(addr); if (bp == m_hw_break_index_map.end()) - return Error(); + return Status(); uint32_t bp_index = bp->second; if (GetRegisterContext()->ClearHardwareBreakpoint(bp_index)) { m_hw_break_index_map.erase(bp); - return Error(); + return Status(); } - return Error("Clearing hardware breakpoint failed."); + return Status("Clearing hardware breakpoint failed."); } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h index 96d7fd0ce03b..dcd360cdd310 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.h @@ -38,14 +38,14 @@ public: NativeRegisterContextSP GetRegisterContext() override; - Error SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, - bool hardware) override; + Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, + bool hardware) override; - Error RemoveWatchpoint(lldb::addr_t addr) override; + Status RemoveWatchpoint(lldb::addr_t addr) override; - Error SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override; + Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override; - Error RemoveHardwareBreakpoint(lldb::addr_t addr) override; + Status RemoveHardwareBreakpoint(lldb::addr_t addr) override; private: // --------------------------------------------------------------------- diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp index 5e933d3b3dee..0bd90dbf7620 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/DynamicRegisterInfo.cpp @@ -48,10 +48,10 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, if (dict.GetValueForKeyAsArray("sets", sets)) { const uint32_t num_sets = sets->GetSize(); for (uint32_t i = 0; i < num_sets; ++i) { - std::string set_name_str; + llvm::StringRef set_name_str; ConstString set_name; if (sets->GetItemAtIndexAsString(i, set_name_str)) - set_name.SetCString(set_name_str.c_str()); + set_name.SetString(set_name_str); if (set_name) { RegisterSet new_set = {set_name.AsCString(), NULL, 0, NULL}; m_sets.push_back(new_set); @@ -115,7 +115,7 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, // expression // we can calculate the offset bool success = false; - std::string slice_str; + llvm::StringRef slice_str; if (reg_info_dict->GetValueForKeyAsString("slice", slice_str, nullptr)) { // Slices use the following format: // REGNAME[MSBIT:LSBIT] @@ -131,9 +131,9 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, llvm::StringRef reg_name_str; std::string msbit_str; std::string lsbit_str; - if (regex_match.GetMatchAtIndex(slice_str.c_str(), 1, reg_name_str) && - regex_match.GetMatchAtIndex(slice_str.c_str(), 2, msbit_str) && - regex_match.GetMatchAtIndex(slice_str.c_str(), 3, lsbit_str)) { + if (regex_match.GetMatchAtIndex(slice_str, 1, reg_name_str) && + regex_match.GetMatchAtIndex(slice_str, 2, msbit_str) && + regex_match.GetMatchAtIndex(slice_str, 3, lsbit_str)) { const uint32_t msbit = StringConvert::ToUInt32(msbit_str.c_str(), UINT32_MAX); const uint32_t lsbit = @@ -269,17 +269,15 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, reg_info.byte_size = bitsize / 8; - std::string dwarf_opcode_string; + llvm::StringRef dwarf_opcode_string; if (reg_info_dict->GetValueForKeyAsString("dynamic_size_dwarf_expr_bytes", dwarf_opcode_string)) { - reg_info.dynamic_size_dwarf_len = dwarf_opcode_string.length() / 2; + reg_info.dynamic_size_dwarf_len = dwarf_opcode_string.size() / 2; assert(reg_info.dynamic_size_dwarf_len > 0); std::vector<uint8_t> dwarf_opcode_bytes(reg_info.dynamic_size_dwarf_len); uint32_t j; - StringExtractor opcode_extractor; - // Swap "dwarf_opcode_string" over into "opcode_extractor" - opcode_extractor.GetStringRef().swap(dwarf_opcode_string); + StringExtractor opcode_extractor(dwarf_opcode_string); uint32_t ret_val = opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); UNUSED_IF_ASSERT_DISABLED(ret_val); assert(ret_val == reg_info.dynamic_size_dwarf_len); @@ -290,9 +288,9 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, reg_info.dynamic_size_dwarf_expr_bytes = m_dynamic_reg_size_map[i].data(); } - std::string format_str; + llvm::StringRef format_str; if (reg_info_dict->GetValueForKeyAsString("format", format_str, nullptr)) { - if (Args::StringToFormat(format_str.c_str(), reg_info.format, NULL) + if (Args::StringToFormat(format_str.str().c_str(), reg_info.format, NULL) .Fail()) { Clear(); printf("error: invalid 'format' value in register dictionary\n"); @@ -304,7 +302,7 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, eFormatHex); } - std::string encoding_str; + llvm::StringRef encoding_str; if (reg_info_dict->GetValueForKeyAsString("encoding", encoding_str)) reg_info.encoding = Args::StringToEncoding(encoding_str, eEncodingUint); else @@ -334,7 +332,7 @@ DynamicRegisterInfo::SetRegisterInfo(const StructuredData::Dictionary &dict, reg_info.kinds[lldb::eRegisterKindEHFrame] = eh_frame_regno; reg_info_dict->GetValueForKeyAsInteger( "dwarf", reg_info.kinds[lldb::eRegisterKindDWARF], LLDB_INVALID_REGNUM); - std::string generic_str; + llvm::StringRef generic_str; if (reg_info_dict->GetValueForKeyAsString("generic", generic_str)) reg_info.kinds[lldb::eRegisterKindGeneric] = Args::StringToGenericRegister(generic_str); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp index 485a39e6c9a5..312c1887b581 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextLLDB.cpp @@ -1055,7 +1055,7 @@ bool RegisterContextLLDB::ReadRegisterValueFromRegisterLocation( case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation: llvm_unreachable("FIXME debugger inferior function call unwind"); case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: { - Error error(ReadRegisterValueFromMemory( + Status error(ReadRegisterValueFromMemory( reg_info, regloc.location.target_memory_location, reg_info->byte_size, value)); success = error.Success(); @@ -1097,7 +1097,7 @@ bool RegisterContextLLDB::WriteRegisterValueToRegisterLocation( case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation: llvm_unreachable("FIXME debugger inferior function call unwind"); case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: { - Error error(WriteRegisterValueToMemory( + Status error(WriteRegisterValueToMemory( reg_info, regloc.location.target_memory_location, reg_info->byte_size, value)); success = error.Success(); @@ -1514,7 +1514,7 @@ RegisterContextLLDB::SavedLocationForRegister( unwindplan_regloc.GetDWARFExpressionLength()); dwarfexpr.SetRegisterKind(unwindplan_registerkind); Value result; - Error error; + Status error; if (dwarfexpr.Evaluate(&exe_ctx, nullptr, nullptr, this, 0, nullptr, nullptr, result, &error)) { addr_t val; @@ -1769,7 +1769,7 @@ bool RegisterContextLLDB::ReadCFAValueForRow( GetRegisterInfoAtIndex(cfa_reg.GetAsKind(eRegisterKindLLDB)); RegisterValue reg_value; if (reg_info) { - Error error = ReadRegisterValueFromMemory( + Status error = ReadRegisterValueFromMemory( reg_info, cfa_reg_contents, reg_info->byte_size, reg_value); if (error.Success()) { cfa_value = reg_value.GetAsUInt64(); @@ -1824,7 +1824,7 @@ bool RegisterContextLLDB::ReadCFAValueForRow( row->GetCFAValue().GetDWARFExpressionLength()); dwarfexpr.SetRegisterKind(row_register_kind); Value result; - Error error; + Status error; if (dwarfexpr.Evaluate(&exe_ctx, nullptr, nullptr, this, 0, nullptr, nullptr, result, &error)) { cfa_value = result.GetScalar().ULongLong(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp index eed5eec8fae8..8f0dfd2a5b50 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextMemory.cpp @@ -18,7 +18,7 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -101,8 +101,8 @@ bool RegisterContextMemory::WriteRegister(const RegisterInfo *reg_info, if (m_reg_data_addr != LLDB_INVALID_ADDRESS) { const uint32_t reg_num = reg_info->kinds[eRegisterKindLLDB]; addr_t reg_addr = m_reg_data_addr + reg_info->byte_offset; - Error error(WriteRegisterValueToMemory(reg_info, reg_addr, - reg_info->byte_size, reg_value)); + Status error(WriteRegisterValueToMemory(reg_info, reg_addr, + reg_info->byte_size, reg_value)); m_reg_valid[reg_num] = false; return error.Success(); } @@ -113,7 +113,7 @@ bool RegisterContextMemory::ReadAllRegisterValues(DataBufferSP &data_sp) { if (m_reg_data_addr != LLDB_INVALID_ADDRESS) { ProcessSP process_sp(CalculateProcess()); if (process_sp) { - Error error; + Status error; if (process_sp->ReadMemory(m_reg_data_addr, data_sp->GetBytes(), data_sp->GetByteSize(), error) == data_sp->GetByteSize()) { @@ -130,7 +130,7 @@ bool RegisterContextMemory::WriteAllRegisterValues( if (m_reg_data_addr != LLDB_INVALID_ADDRESS) { ProcessSP process_sp(CalculateProcess()); if (process_sp) { - Error error; + Status error; SetAllRegisterValid(false); if (process_sp->WriteMemory(m_reg_data_addr, data_sp->GetBytes(), data_sp->GetByteSize(), diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp index 7d990e73b5be..96ad139f7364 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.cpp @@ -10,7 +10,7 @@ #include "lldb/Target/OperatingSystem.h" #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-private.h" #include "RegisterContextThreadMemory.h" @@ -194,26 +194,26 @@ bool RegisterContextThreadMemory::HardwareSingleStep(bool enable) { return false; } -Error RegisterContextThreadMemory::ReadRegisterValueFromMemory( +Status RegisterContextThreadMemory::ReadRegisterValueFromMemory( const lldb_private::RegisterInfo *reg_info, lldb::addr_t src_addr, uint32_t src_len, RegisterValue ®_value) { UpdateRegisterContext(); if (m_reg_ctx_sp) return m_reg_ctx_sp->ReadRegisterValueFromMemory(reg_info, src_addr, src_len, reg_value); - Error error; + Status error; error.SetErrorString("invalid register context"); return error; } -Error RegisterContextThreadMemory::WriteRegisterValueToMemory( +Status RegisterContextThreadMemory::WriteRegisterValueToMemory( const lldb_private::RegisterInfo *reg_info, lldb::addr_t dst_addr, uint32_t dst_len, const RegisterValue ®_value) { UpdateRegisterContext(); if (m_reg_ctx_sp) return m_reg_ctx_sp->WriteRegisterValueToMemory(reg_info, dst_addr, dst_len, reg_value); - Error error; + Status error; error.SetErrorString("invalid register context"); return error; } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h index 7e0a2a9f7f1e..3b3b0856a4ca 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/RegisterContextThreadMemory.h @@ -80,13 +80,13 @@ public: bool HardwareSingleStep(bool enable) override; - Error ReadRegisterValueFromMemory(const lldb_private::RegisterInfo *reg_info, - lldb::addr_t src_addr, uint32_t src_len, - RegisterValue ®_value) override; + Status ReadRegisterValueFromMemory(const lldb_private::RegisterInfo *reg_info, + lldb::addr_t src_addr, uint32_t src_len, + RegisterValue ®_value) override; - Error WriteRegisterValueToMemory(const lldb_private::RegisterInfo *reg_info, - lldb::addr_t dst_addr, uint32_t dst_len, - const RegisterValue ®_value) override; + Status WriteRegisterValueToMemory(const lldb_private::RegisterInfo *reg_info, + lldb::addr_t dst_addr, uint32_t dst_len, + const RegisterValue ®_value) override; protected: void UpdateRegisterContext(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp index b3cac1c854d1..5ff928c69e59 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.cpp @@ -24,15 +24,11 @@ ThreadMemory::ThreadMemory(Process &process, tid_t tid, : Thread(process, tid), m_backing_thread_sp(), m_thread_info_valobj_sp(thread_info_valobj_sp), m_name(), m_queue() {} -ThreadMemory::ThreadMemory(Process &process, lldb::tid_t tid, const char *name, - const char *queue, lldb::addr_t register_data_addr) +ThreadMemory::ThreadMemory(Process &process, lldb::tid_t tid, + llvm::StringRef name, llvm::StringRef queue, + lldb::addr_t register_data_addr) : Thread(process, tid), m_backing_thread_sp(), m_thread_info_valobj_sp(), - m_name(), m_queue(), m_register_data_addr(register_data_addr) { - if (name) - m_name = name; - if (queue) - m_queue = queue; -} + m_name(name), m_queue(queue), m_register_data_addr(register_data_addr) {} ThreadMemory::~ThreadMemory() { DestroyThread(); } diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.h b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.h index 095544d244ba..89229710da4d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/ThreadMemory.h @@ -24,7 +24,7 @@ public: const lldb::ValueObjectSP &thread_info_valobj_sp); ThreadMemory(lldb_private::Process &process, lldb::tid_t tid, - const char *name, const char *queue, + llvm::StringRef name, llvm::StringRef queue, lldb::addr_t register_data_addr); ~ThreadMemory() override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp index e2691be603ec..f907735d8f58 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/UnwindMacOSXFrameBackchain.cpp @@ -105,7 +105,7 @@ size_t UnwindMacOSXFrameBackchain::GetStackFrameData_i386( m_cursors.push_back(cursor); const size_t k_frame_size = sizeof(frame); - Error error; + Status error; while (frame.fp != 0 && frame.pc != 0 && ((frame.fp & 7) == 0)) { // Read both the FP and PC (8 bytes) if (process->ReadMemory(frame.fp, &frame.fp, k_frame_size, error) != @@ -196,7 +196,7 @@ size_t UnwindMacOSXFrameBackchain::GetStackFrameData_x86_64( Frame_x86_64 frame = {cursor.fp, cursor.pc}; m_cursors.push_back(cursor); - Error error; + Status error; const size_t k_frame_size = sizeof(frame); while (frame.fp != 0 && frame.pc != 0 && ((frame.fp & 7) == 0)) { // Read both the FP and PC (16 bytes) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp index 6561d2a05828..5a459e80348b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp @@ -84,8 +84,8 @@ bool ProcessElfCore::CanDebug(lldb::TargetSP target_sp, // For now we are just making sure the file exists for a given module if (!m_core_module_sp && m_core_file.Exists()) { ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture()); - Error error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp, - NULL, NULL, NULL)); + Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp, + NULL, NULL, NULL)); if (m_core_module_sp) { ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile) @@ -157,8 +157,8 @@ lldb::addr_t ProcessElfCore::AddAddressRangeFromLoadSegment( //---------------------------------------------------------------------- // Process Control //---------------------------------------------------------------------- -Error ProcessElfCore::DoLoadCore() { - Error error; +Status ProcessElfCore::DoLoadCore() { + Status error; if (!m_core_module_sp) { error.SetErrorString("invalid core module"); return error; @@ -289,7 +289,7 @@ bool ProcessElfCore::UpdateThreadList(ThreadList &old_thread_list, void ProcessElfCore::RefreshStateAfterStop() {} -Error ProcessElfCore::DoDestroy() { return Error(); } +Status ProcessElfCore::DoDestroy() { return Status(); } //------------------------------------------------------------------ // Process Queries @@ -301,14 +301,14 @@ bool ProcessElfCore::IsAlive() { return true; } // Process Memory //------------------------------------------------------------------ size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { // Don't allow the caching that lldb_private::Process::ReadMemory does // since in core files we have it all cached our our core file anyway. return DoReadMemory(addr, buf, size, error); } -Error ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo ®ion_info) { +Status ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo ®ion_info) { region_info.Clear(); const VMRangeToPermissions::Entry *permission_entry = m_core_range_infos.FindEntryThatContainsOrFollows(load_addr); @@ -335,7 +335,7 @@ Error ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr, region_info.SetExecutable(MemoryRegionInfo::eNo); region_info.SetMapped(MemoryRegionInfo::eNo); } - return Error(); + return Status(); } region_info.GetRange().SetRangeBase(load_addr); @@ -344,11 +344,11 @@ Error ProcessElfCore::GetMemoryRegionInfo(lldb::addr_t load_addr, region_info.SetWritable(MemoryRegionInfo::eNo); region_info.SetExecutable(MemoryRegionInfo::eNo); region_info.SetMapped(MemoryRegionInfo::eNo); - return Error(); + return Status(); } size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { ObjectFile *core_objfile = m_core_module_sp->GetObjectFile(); if (core_objfile == NULL) @@ -540,7 +540,7 @@ static void ParseOpenBSDProcInfo(ThreadData &thread_data, DataExtractor &data) { /// new thread when it finds NT_PRSTATUS or NT_PRPSINFO NOTE entry. /// For case (b) there may be either one NT_PRPSINFO per thread, or a single /// one that applies to all threads (depending on the platform type). -Error ProcessElfCore::ParseThreadContextsFromNoteSegment( +Status ProcessElfCore::ParseThreadContextsFromNoteSegment( const elf::ELFProgramHeader *segment_header, DataExtractor segment_data) { assert(segment_header && segment_header->p_type == llvm::ELF::PT_NOTE); @@ -555,7 +555,7 @@ Error ProcessElfCore::ParseThreadContextsFromNoteSegment( ELFLinuxSigInfo siginfo; size_t header_size; size_t len; - Error error; + Status error; // Loop through the NOTE entires in the segment while (offset < segment_header->p_filesz) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h index cb2f31bde4c5..dbf7f926f855 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ProcessElfCore.h @@ -26,7 +26,7 @@ // Project includes #include "lldb/Target/Process.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "Plugins/ObjectFile/ELF/ELFHeader.h" @@ -66,7 +66,7 @@ public: //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one //------------------------------------------------------------------ - lldb_private::Error DoLoadCore() override; + lldb_private::Status DoLoadCore() override; lldb_private::DynamicLoader *GetDynamicLoader() override; @@ -80,7 +80,7 @@ public: //------------------------------------------------------------------ // Process Control //------------------------------------------------------------------ - lldb_private::Error DoDestroy() override; + lldb_private::Status DoDestroy() override; void RefreshStateAfterStop() override; @@ -93,12 +93,12 @@ public: // Process Memory //------------------------------------------------------------------ size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, - lldb_private::Error &error) override; + lldb_private::Status &error) override; size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, - lldb_private::Error &error) override; + lldb_private::Status &error) override; - lldb_private::Error + lldb_private::Status GetMemoryRegionInfo(lldb::addr_t load_addr, lldb_private::MemoryRegionInfo ®ion_info) override; @@ -160,7 +160,7 @@ private: std::vector<NT_FILE_Entry> m_nt_file_entries; // Parse thread(s) data structures(prstatus, prpsinfo) from given NOTE segment - lldb_private::Error ParseThreadContextsFromNoteSegment( + lldb_private::Status ParseThreadContextsFromNoteSegment( const elf::ELFProgramHeader *segment_header, lldb_private::DataExtractor segment_data); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp index 260ae15d7a54..5766923186d1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/RegisterContextPOSIXCore_x86_64.cpp @@ -71,7 +71,7 @@ bool RegisterContextCorePOSIX_x86_64::ReadRegister(const RegisterInfo *reg_info, return false; } - Error error; + Status error; value.SetFromMemoryData(reg_info, src + offset, reg_info->byte_size, lldb::eByteOrderLittle, error); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp index a1cc26afb396..2f36622778b8 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp @@ -274,8 +274,8 @@ size_t ELFLinuxPrStatus::GetSize(lldb_private::ArchSpec &arch) { } } -Error ELFLinuxPrStatus::Parse(DataExtractor &data, ArchSpec &arch) { - Error error; +Status ELFLinuxPrStatus::Parse(DataExtractor &data, ArchSpec &arch) { + Status error; if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( "NT_PRSTATUS size should be %zu, but the remaining bytes are: %" PRIu64, @@ -344,8 +344,8 @@ size_t ELFLinuxPrPsInfo::GetSize(lldb_private::ArchSpec &arch) { } } -Error ELFLinuxPrPsInfo::Parse(DataExtractor &data, ArchSpec &arch) { - Error error; +Status ELFLinuxPrPsInfo::Parse(DataExtractor &data, ArchSpec &arch) { + Status error; ByteOrder byteorder = data.GetByteOrder(); if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( @@ -413,8 +413,8 @@ size_t ELFLinuxSigInfo::GetSize(const lldb_private::ArchSpec &arch) { } } -Error ELFLinuxSigInfo::Parse(DataExtractor &data, const ArchSpec &arch) { - Error error; +Status ELFLinuxSigInfo::Parse(DataExtractor &data, const ArchSpec &arch) { + Status error; if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( "NT_SIGINFO size should be %zu, but the remaining bytes are: %" PRIu64, diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h index 38c52658a23a..521875413715 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/elf-core/ThreadElfCore.h @@ -57,8 +57,8 @@ struct ELFLinuxPrStatus { ELFLinuxPrStatus(); - lldb_private::Error Parse(lldb_private::DataExtractor &data, - lldb_private::ArchSpec &arch); + lldb_private::Status Parse(lldb_private::DataExtractor &data, + lldb_private::ArchSpec &arch); // Return the bytesize of the structure // 64 bit - just sizeof @@ -78,8 +78,8 @@ struct ELFLinuxSigInfo { ELFLinuxSigInfo(); - lldb_private::Error Parse(lldb_private::DataExtractor &data, - const lldb_private::ArchSpec &arch); + lldb_private::Status Parse(lldb_private::DataExtractor &data, + const lldb_private::ArchSpec &arch); // Return the bytesize of the structure // 64 bit - just sizeof @@ -113,8 +113,8 @@ struct ELFLinuxPrPsInfo { ELFLinuxPrPsInfo(); - lldb_private::Error Parse(lldb_private::DataExtractor &data, - lldb_private::ArchSpec &arch); + lldb_private::Status Parse(lldb_private::DataExtractor &data, + lldb_private::ArchSpec &arch); // Return the bytesize of the structure // 64 bit - just sizeof diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp index d527b4daaab9..0c4df7e3f306 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp @@ -319,7 +319,7 @@ GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet, Timeout<std::micro> timeout, bool sync_on_timeout) { uint8_t buffer[8192]; - Error error; + Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS)); @@ -933,9 +933,9 @@ GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len, return GDBRemoteCommunication::PacketType::Invalid; } -Error GDBRemoteCommunication::StartListenThread(const char *hostname, - uint16_t port) { - Error error; +Status GDBRemoteCommunication::StartListenThread(const char *hostname, + uint16_t port) { + Status error; if (m_listen_thread.IsJoinable()) { error.SetErrorString("listen thread already running"); } else { @@ -962,7 +962,7 @@ bool GDBRemoteCommunication::JoinListenThread() { lldb::thread_result_t GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) { GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg; - Error error; + Status error; ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection(); @@ -975,7 +975,7 @@ GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) { return NULL; } -Error GDBRemoteCommunication::StartDebugserverProcess( +Status GDBRemoteCommunication::StartDebugserverProcess( const char *url, Platform *platform, ProcessLaunchInfo &launch_info, uint16_t *port, const Args *inferior_args, int pass_comm_fd) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); @@ -984,7 +984,7 @@ Error GDBRemoteCommunication::StartDebugserverProcess( __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0)); - Error error; + Status error; // If we locate debugserver, keep that located version around static FileSpec g_debugserver_file_spec; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h index b49e05e22d95..ce90de3e8470 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.h @@ -65,9 +65,9 @@ public: enum class PacketResult { Success = 0, // Success - ErrorSendFailed, // Error sending the packet + ErrorSendFailed, // Status sending the packet ErrorSendAck, // Didn't get an ack back after sending a packet - ErrorReplyFailed, // Error getting the reply + ErrorReplyFailed, // Status getting the reply ErrorReplyTimeout, // Timed out waiting for reply ErrorReplyInvalid, // Got a reply but it wasn't valid for the packet that // was sent @@ -131,7 +131,7 @@ public: // Start a debugserver instance on the current host using the // supplied connection URL. //------------------------------------------------------------------ - Error StartDebugserverProcess( + Status StartDebugserverProcess( const char *url, Platform *platform, // If non nullptr, then check with the platform for // the GDB server binary if it can't be located @@ -255,8 +255,8 @@ protected: // on m_bytes. The checksum was for the compressed packet. bool DecompressPacket(); - Error StartListenThread(const char *hostname = "127.0.0.1", - uint16_t port = 0); + Status StartListenThread(const char *hostname = "127.0.0.1", + uint16_t port = 0); bool JoinListenThread(); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp index 2e94fa94331d..550ec0ea499a 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp @@ -113,7 +113,7 @@ GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() { Disconnect(); } -bool GDBRemoteCommunicationClient::HandshakeWithServer(Error *error_ptr) { +bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) { ResetDiscoverableSettings(false); // Start the read thread after we send the handshake ack since if we @@ -1394,8 +1394,8 @@ bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) { return false; } -Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) { - Error error; +Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) { + Status error; if (keep_stopped) { if (m_supports_detach_stay_stopped == eLazyBoolCalculate) { @@ -1434,9 +1434,9 @@ Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) { return error; } -Error GDBRemoteCommunicationClient::GetMemoryRegionInfo( +Status GDBRemoteCommunicationClient::GetMemoryRegionInfo( lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) { - Error error; + Status error; region_info.Clear(); if (m_supports_memory_region_info != eLazyBoolNo) { @@ -1529,8 +1529,8 @@ Error GDBRemoteCommunicationClient::GetMemoryRegionInfo( return error; } -Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) { - Error error; +Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) { + Status error; if (m_supports_watchpoint_support_info == eLazyBoolYes) { num = m_num_supported_hardware_watchpoints; @@ -1568,18 +1568,18 @@ Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) { return error; } -lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo( +lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo( uint32_t &num, bool &after, const ArchSpec &arch) { - Error error(GetWatchpointSupportInfo(num)); + Status error(GetWatchpointSupportInfo(num)); if (error.Success()) error = GetWatchpointsTriggerAfterInstruction(after, arch); return error; } -lldb_private::Error +lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction( bool &after, const ArchSpec &arch) { - Error error; + Status error; llvm::Triple::ArchType atype = arch.GetMachine(); // we assume watchpoints will happen after running the relevant opcode @@ -2539,7 +2539,7 @@ uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( if (response.IsOKResponse()) return 0; - // Error while setting breakpoint, send back specific error + // Status while setting breakpoint, send back specific error if (response.IsErrorResponse()) return response.GetError(); @@ -2635,7 +2635,7 @@ lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); } -lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand( +lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( const char *command, // Shouldn't be NULL const FileSpec & working_dir, // Pass empty FileSpec to use the current working directory @@ -2661,32 +2661,32 @@ lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand( if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == PacketResult::Success) { if (response.GetChar() != 'F') - return Error("malformed reply"); + return Status("malformed reply"); if (response.GetChar() != ',') - return Error("malformed reply"); + return Status("malformed reply"); uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); if (exitcode == UINT32_MAX) - return Error("unable to run remote process"); + return Status("unable to run remote process"); else if (status_ptr) *status_ptr = exitcode; if (response.GetChar() != ',') - return Error("malformed reply"); + return Status("malformed reply"); uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); if (signo_ptr) *signo_ptr = signo; if (response.GetChar() != ',') - return Error("malformed reply"); + return Status("malformed reply"); std::string output; response.GetEscapedBinaryData(output); if (command_output) command_output->assign(output); - return Error(); + return Status(); } - return Error("unable to send packet"); + return Status("unable to send packet"); } -Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, - uint32_t file_permissions) { +Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, + uint32_t file_permissions) { std::string path{file_spec.GetPath(false)}; lldb_private::StreamString stream; stream.PutCString("qPlatform_mkdir:"); @@ -2698,16 +2698,17 @@ Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, if (SendPacketAndWaitForResponse(packet, response, false) != PacketResult::Success) - return Error("failed to send '%s' packet", packet.str().c_str()); + return Status("failed to send '%s' packet", packet.str().c_str()); if (response.GetChar() != 'F') - return Error("invalid response to '%s' packet", packet.str().c_str()); + return Status("invalid response to '%s' packet", packet.str().c_str()); - return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX); + return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); } -Error GDBRemoteCommunicationClient::SetFilePermissions( - const FileSpec &file_spec, uint32_t file_permissions) { +Status +GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) { std::string path{file_spec.GetPath(false)}; lldb_private::StreamString stream; stream.PutCString("qPlatform_chmod:"); @@ -2719,16 +2720,16 @@ Error GDBRemoteCommunicationClient::SetFilePermissions( if (SendPacketAndWaitForResponse(packet, response, false) != PacketResult::Success) - return Error("failed to send '%s' packet", stream.GetData()); + return Status("failed to send '%s' packet", stream.GetData()); if (response.GetChar() != 'F') - return Error("invalid response to '%s' packet", stream.GetData()); + return Status("invalid response to '%s' packet", stream.GetData()); - return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX); + return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); } static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, - uint64_t fail_result, Error &error) { + uint64_t fail_result, Status &error) { response.SetFilePos(0); if (response.GetChar() != 'F') return fail_result; @@ -2748,7 +2749,7 @@ static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, lldb::user_id_t GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, uint32_t flags, mode_t mode, - Error &error) { + Status &error) { std::string path(file_spec.GetPath(false)); lldb_private::StreamString stream; stream.PutCString("vFile:open:"); @@ -2767,7 +2768,8 @@ GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, return UINT64_MAX; } -bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) { +bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, + Status &error) { lldb_private::StreamString stream; stream.Printf("vFile:close:%i", (int)fd); StringExtractorGDBRemote response; @@ -2796,10 +2798,11 @@ lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( return UINT64_MAX; } -Error GDBRemoteCommunicationClient::GetFilePermissions( - const FileSpec &file_spec, uint32_t &file_permissions) { +Status +GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) { std::string path{file_spec.GetPath(false)}; - Error error; + Status error; lldb_private::StreamString stream; stream.PutCString("vFile:mode:"); stream.PutCStringAsRawHex8(path.c_str()); @@ -2834,7 +2837,7 @@ Error GDBRemoteCommunicationClient::GetFilePermissions( uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, - Error &error) { + Status &error) { lldb_private::StreamString stream; stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset); @@ -2868,7 +2871,7 @@ uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, - Error &error) { + Status &error) { lldb_private::StreamGDBRemote stream; stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); stream.PutEscapedBytes(src, src_len); @@ -2896,10 +2899,10 @@ uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, return 0; } -Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, - const FileSpec &dst) { +Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, + const FileSpec &dst) { std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; - Error error; + Status error; lldb_private::StreamGDBRemote stream; stream.PutCString("vFile:symlink:"); // the unix symlink() command reverses its parameters where the dst if first, @@ -2930,9 +2933,9 @@ Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, return error; } -Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { +Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { std::string path{file_spec.GetPath(false)}; - Error error; + Status error; lldb_private::StreamGDBRemote stream; stream.PutCString("vFile:unlink:"); // the unix symlink() command reverses its parameters where the dst if first, @@ -3221,12 +3224,12 @@ ParseModuleSpec(StructuredData::Dictionary *dict) { if (!dict) return llvm::None; - std::string string; + llvm::StringRef string; uint64_t integer; if (!dict->GetValueForKeyAsString("uuid", string)) return llvm::None; - result.GetUUID().SetFromCString(string.c_str(), string.size()); + result.GetUUID().SetFromStringRef(string, string.size()); if (!dict->GetValueForKeyAsInteger("file_offset", integer)) return llvm::None; @@ -3238,7 +3241,7 @@ ParseModuleSpec(StructuredData::Dictionary *dict) { if (!dict->GetValueForKeyAsString("triple", string)) return llvm::None; - result.GetArchitecture().SetTriple(string.c_str()); + result.GetArchitecture().SetTriple(string); if (!dict->GetValueForKeyAsString("file_path", string)) return llvm::None; @@ -3311,7 +3314,7 @@ GDBRemoteCommunicationClient::GetModulesInfo( bool GDBRemoteCommunicationClient::ReadExtFeature( const lldb_private::ConstString object, const lldb_private::ConstString annex, std::string &out, - lldb_private::Error &err) { + lldb_private::Status &err) { std::stringstream output; StringExtractorGDBRemote chunk; @@ -3590,7 +3593,7 @@ GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { : nullptr; } -Error GDBRemoteCommunicationClient::SendSignalsToIgnore( +Status GDBRemoteCommunicationClient::SendSignalsToIgnore( llvm::ArrayRef<int32_t> signals) { // Format packet: // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> @@ -3601,18 +3604,18 @@ Error GDBRemoteCommunicationClient::SendSignalsToIgnore( auto send_status = SendPacketAndWaitForResponse(packet, response, false); if (send_status != GDBRemoteCommunication::PacketResult::Success) - return Error("Sending QPassSignals packet failed"); + return Status("Sending QPassSignals packet failed"); if (response.IsOKResponse()) { - return Error(); + return Status(); } else { - return Error("Unknown error happened during sending QPassSignals packet."); + return Status("Unknown error happened during sending QPassSignals packet."); } } -Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( +Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { - Error error; + Status error; if (type_name.GetLength() == 0) { error.SetErrorString("invalid type_name argument"); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h index 63b9708cc9a0..08d0bd5d690b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h @@ -41,7 +41,7 @@ public: // After connecting, send the handshake to the server to make sure // we are communicating with it. //------------------------------------------------------------------ - bool HandshakeWithServer(Error *error_ptr); + bool HandshakeWithServer(Status *error_ptr); // For packets which specify a range of output to be returned, // return all of the output via a series of request packets of the form @@ -230,17 +230,17 @@ public: bool DeallocateMemory(lldb::addr_t addr); - Error Detach(bool keep_stopped); + Status Detach(bool keep_stopped); - Error GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info); + Status GetMemoryRegionInfo(lldb::addr_t addr, MemoryRegionInfo &range_info); - Error GetWatchpointSupportInfo(uint32_t &num); + Status GetWatchpointSupportInfo(uint32_t &num); - Error GetWatchpointSupportInfo(uint32_t &num, bool &after, - const ArchSpec &arch); + Status GetWatchpointSupportInfo(uint32_t &num, bool &after, + const ArchSpec &arch); - Error GetWatchpointsTriggerAfterInstruction(bool &after, - const ArchSpec &arch); + Status GetWatchpointsTriggerAfterInstruction(bool &after, + const ArchSpec &arch); const ArchSpec &GetHostArchitecture(); @@ -365,33 +365,33 @@ public: bool &sequence_mutex_unavailable); lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, - mode_t mode, Error &error); + mode_t mode, Status &error); - bool CloseFile(lldb::user_id_t fd, Error &error); + bool CloseFile(lldb::user_id_t fd, Status &error); lldb::user_id_t GetFileSize(const FileSpec &file_spec); - Error GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions); + Status GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions); - Error SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions); + Status SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions); uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, - uint64_t dst_len, Error &error); + uint64_t dst_len, Status &error); uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, - uint64_t src_len, Error &error); + uint64_t src_len, Status &error); - Error CreateSymlink(const FileSpec &src, const FileSpec &dst); + Status CreateSymlink(const FileSpec &src, const FileSpec &dst); - Error Unlink(const FileSpec &file_spec); + Status Unlink(const FileSpec &file_spec); - Error MakeDirectory(const FileSpec &file_spec, uint32_t mode); + Status MakeDirectory(const FileSpec &file_spec, uint32_t mode); bool GetFileExists(const FileSpec &file_spec); - Error RunShellCommand( + Status RunShellCommand( const char *command, // Shouldn't be nullptr const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory @@ -448,12 +448,12 @@ public: bool ReadExtFeature(const lldb_private::ConstString object, const lldb_private::ConstString annex, std::string &out, - lldb_private::Error &err); + lldb_private::Status &err); void ServeSymbolLookups(lldb_private::Process *process); // Sends QPassSignals packet to the server with given signals to ignore. - Error SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals); + Status SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals); //------------------------------------------------------------------ /// Return the feature set supported by the gdb-remote server. @@ -495,7 +495,7 @@ public: /// /// @see \b Process::ConfigureStructuredData(...) for details. //------------------------------------------------------------------ - Error + Status ConfigureRemoteStructuredData(const ConstString &type_name, const StructuredData::ObjectSP &config_sp); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp index 934824e214dc..dac675ee9432 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp @@ -39,7 +39,7 @@ void GDBRemoteCommunicationServer::RegisterPacketHandler( GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServer::GetPacketAndSendResponse( - Timeout<std::micro> timeout, Error &error, bool &interrupt, bool &quit) { + Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) { StringExtractorGDBRemote packet; PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h index 0c583e62d76b..6eb25f8b9f98 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h @@ -31,8 +31,8 @@ class GDBRemoteCommunicationServer : public GDBRemoteCommunication { public: using PortMap = std::map<uint16_t, lldb::pid_t>; using PacketHandler = - std::function<PacketResult(StringExtractorGDBRemote &packet, Error &error, - bool &interrupt, bool &quit)>; + std::function<PacketResult(StringExtractorGDBRemote &packet, + Status &error, bool &interrupt, bool &quit)>; GDBRemoteCommunicationServer(const char *comm_name, const char *listener_name); @@ -44,7 +44,7 @@ public: PacketHandler handler); PacketResult GetPacketAndSendResponse(Timeout<std::micro> timeout, - Error &error, bool &interrupt, + Status &error, bool &interrupt, bool &quit); // After connecting, do a little handshake with the client to make sure diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp index 66c1b15ff857..de2400c51ba3 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp @@ -523,7 +523,7 @@ GDBRemoteCommunicationServerCommon::Handle_vFile_Open( File::ConvertOpenOptionsForPOSIXOpen(packet.GetHexMaxU32(false, 0)); if (packet.GetChar() == ',') { mode_t mode = packet.GetHexMaxU32(false, 0600); - Error error; + Status error; const FileSpec path_spec{path, true}; int fd = ::open(path_spec.GetCString(), flags, mode); const int save_errno = fd == -1 ? errno : 0; @@ -544,7 +544,7 @@ GDBRemoteCommunicationServerCommon::Handle_vFile_Close( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:close:")); int fd = packet.GetS32(-1); - Error error; + Status error; int err = -1; int save_errno = 0; if (fd >= 0) { @@ -663,7 +663,7 @@ GDBRemoteCommunicationServerCommon::Handle_vFile_Mode( std::string path; packet.GetHexByteString(path); if (!path.empty()) { - Error error; + Status error; const uint32_t mode = File::GetPermissions(FileSpec{path, true}, error); StreamString response; response.Printf("F%u", mode); @@ -702,7 +702,7 @@ GDBRemoteCommunicationServerCommon::Handle_vFile_symlink( packet.GetHexByteStringTerminatedBy(dst, ','); packet.GetChar(); // Skip ',' char packet.GetHexByteString(src); - Error error = FileSystem::Symlink(FileSpec{src, true}, FileSpec{dst, false}); + Status error = FileSystem::Symlink(FileSpec{src, true}, FileSpec{dst, false}); StreamString response; response.Printf("F%u,%u", error.GetError(), error.GetError()); return SendPacketNoLock(response.GetString()); @@ -714,7 +714,7 @@ GDBRemoteCommunicationServerCommon::Handle_vFile_unlink( packet.SetFilePos(::strlen("vFile:unlink:")); std::string path; packet.GetHexByteString(path); - Error error(llvm::sys::fs::remove(path)); + Status error(llvm::sys::fs::remove(path)); StreamString response; response.Printf("F%u,%u", error.GetError(), error.GetError()); return SendPacketNoLock(response.GetString()); @@ -736,7 +736,7 @@ GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell( packet.GetHexByteString(working_dir); int status, signo; std::string output; - Error err = + Status err = Host::RunShellCommand(path.c_str(), FileSpec{working_dir, true}, &status, &signo, &output, timeout); StreamGDBRemote response; @@ -794,7 +794,7 @@ GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir( if (packet.GetChar() == ',') { std::string path; packet.GetHexByteString(path); - Error error(llvm::sys::fs::create_directory(path, mode)); + Status error(llvm::sys::fs::create_directory(path, mode)); StreamGDBRemote response; response.Printf("F%u", error.GetError()); @@ -814,7 +814,7 @@ GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod( if (packet.GetChar() == ',') { std::string path; packet.GetHexByteString(path); - Error error(llvm::sys::fs::setPermissions(path, perms)); + Status error(llvm::sys::fs::setPermissions(path, perms)); StreamGDBRemote response; response.Printf("F%u", error.GetError()); @@ -1140,7 +1140,7 @@ GDBRemoteCommunicationServerCommon::Handle_jModulesInfo( packet_array->GetItemAtIndex(i)->GetAsDictionary(); if (!query) continue; - std::string file, triple; + llvm::StringRef file, triple; if (!query->GetValueForKeyAsString("file", file) || !query->GetValueForKeyAsString("triple", triple)) continue; @@ -1278,9 +1278,10 @@ FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile( #endif } -ModuleSpec GDBRemoteCommunicationServerCommon::GetModuleInfo( - const std::string &module_path, const std::string &triple) { - ArchSpec arch(triple.c_str()); +ModuleSpec +GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path, + llvm::StringRef triple) { + ArchSpec arch(triple); const FileSpec req_module_path_spec(module_path, true); const FileSpec module_path_spec = diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h index 321a92266bdd..e9ab8f1a11de 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.h @@ -38,7 +38,7 @@ public: protected: ProcessLaunchInfo m_process_launch_info; - Error m_process_launch_error; + Status m_process_launch_error; ProcessInstanceInfoList m_proc_infos; uint32_t m_proc_infos_index; bool m_thread_suffix_supported; @@ -130,7 +130,7 @@ protected: PacketResult (T::*handler)(StringExtractorGDBRemote &packet)) { RegisterPacketHandler(packet_type, [this, handler](StringExtractorGDBRemote packet, - Error &error, bool &interrupt, + Status &error, bool &interrupt, bool &quit) { return (static_cast<T *>(this)->*handler)(packet); }); @@ -144,17 +144,16 @@ protected: /// with all the information for a child process to be launched. /// /// @return - /// An Error object indicating the success or failure of the + /// An Status object indicating the success or failure of the /// launch. //------------------------------------------------------------------ - virtual Error LaunchProcess() = 0; + virtual Status LaunchProcess() = 0; virtual FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch); private: - ModuleSpec GetModuleInfo(const std::string &module_path, - const std::string &triple); + ModuleSpec GetModuleInfo(llvm::StringRef module_path, llvm::StringRef triple); }; } // namespace process_gdb_remote diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp index 290889ec662a..ec7c2f5330d7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp @@ -184,35 +184,36 @@ void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() { &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals); RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k, - [this](StringExtractorGDBRemote packet, Error &error, + [this](StringExtractorGDBRemote packet, Status &error, bool &interrupt, bool &quit) { quit = true; return this->Handle_k(packet); }); } -Error GDBRemoteCommunicationServerLLGS::SetLaunchArguments( - const char *const args[], int argc) { +Status +GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[], + int argc) { if ((argc < 1) || !args || !args[0] || !args[0][0]) - return Error("%s: no process command line specified to launch", - __FUNCTION__); + return Status("%s: no process command line specified to launch", + __FUNCTION__); m_process_launch_info.SetArguments(const_cast<const char **>(args), true); - return Error(); + return Status(); } -Error GDBRemoteCommunicationServerLLGS::SetLaunchFlags( - unsigned int launch_flags) { +Status +GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) { m_process_launch_info.GetFlags().Set(launch_flags); - return Error(); + return Status(); } -Error GDBRemoteCommunicationServerLLGS::LaunchProcess() { +Status GDBRemoteCommunicationServerLLGS::LaunchProcess() { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); if (!m_process_launch_info.GetArguments().GetArgumentCount()) - return Error("%s: no process command line specified to launch", - __FUNCTION__); + return Status("%s: no process command line specified to launch", + __FUNCTION__); const bool should_forward_stdio = m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr || @@ -224,7 +225,7 @@ Error GDBRemoteCommunicationServerLLGS::LaunchProcess() { const bool default_to_use_pty = true; m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty); - Error error; + Status error; { std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex); assert(!m_debugged_process_sp && "lldb-server creating debugged " @@ -286,8 +287,8 @@ Error GDBRemoteCommunicationServerLLGS::LaunchProcess() { return error; } -Error GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { - Error error; +Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { + Status error; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); if (log) @@ -298,10 +299,10 @@ Error GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) { // else. if (m_debugged_process_sp && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID) - return Error("cannot attach to a process %" PRIu64 - " when another process with pid %" PRIu64 - " is being debugged.", - pid, m_debugged_process_sp->GetID()); + return Status("cannot attach to a process %" PRIu64 + " when another process with pid %" PRIu64 + " is being debugged.", + pid, m_debugged_process_sp->GetID()); // Try to attach. error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, @@ -420,7 +421,7 @@ static void WriteRegisterValueInHexFixedWidth( lldb::ByteOrder byte_order) { RegisterValue reg_value; if (!reg_value_p) { - Error error = reg_ctx_sp->ReadRegister(®_info, reg_value); + Status error = reg_ctx_sp->ReadRegister(®_info, reg_value); if (error.Success()) reg_value_p = ®_value; // else log. @@ -488,7 +489,7 @@ static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) { // registers. RegisterValue reg_value; - Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); + Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); if (error.Fail()) { if (log) log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", @@ -739,7 +740,7 @@ GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read); RegisterValue reg_value; - Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); + Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); if (error.Fail()) { if (log) log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", @@ -793,7 +794,7 @@ GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread( } else if (reg_info_p->value_regs == nullptr) { // Only expediate registers that are not contained in other registers. RegisterValue reg_value; - Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); + Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value); if (error.Success()) { response.Printf("%.02x:", *reg_num_p); WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, @@ -960,7 +961,7 @@ void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { bool interrupt = false; bool done = false; - Error error; + Status error; while (true) { const PacketResult result = GetPacketAndSendResponse( std::chrono::microseconds(0), error, interrupt, done); @@ -978,12 +979,12 @@ void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() { } } -Error GDBRemoteCommunicationServerLLGS::InitializeConnection( +Status GDBRemoteCommunicationServerLLGS::InitializeConnection( std::unique_ptr<Connection> &&connection) { IOObjectSP read_object_sp = connection->GetReadObject(); GDBRemoteCommunicationServer::SetConnection(connection.release()); - Error error; + Status error; m_network_handle_up = m_mainloop.RegisterReadObject( read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); }, error); @@ -1005,8 +1006,8 @@ GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer, return SendPacketNoLock(response.GetString()); } -Error GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { - Error error; +Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { + Status error; // Set up the reading/handling of process I/O std::unique_ptr<ConnectionFileDescriptor> conn_up( @@ -1024,7 +1025,7 @@ Error GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) { return error; } - return Error(); + return Status(); } void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { @@ -1032,7 +1033,7 @@ void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() { if (!m_stdio_communication.IsConnected()) return; - Error error; + Status error; lldbassert(!m_stdio_handle_up); m_stdio_handle_up = m_mainloop.RegisterReadObject( m_stdio_communication.GetConnection()->GetReadObject(), @@ -1055,7 +1056,7 @@ void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() { void GDBRemoteCommunicationServerLLGS::SendProcessOutput() { char buffer[1024]; ConnectionStatus status; - Error error; + Status error; while (true) { size_t bytes_read = m_stdio_communication.Read( buffer, sizeof buffer, std::chrono::microseconds(0), status, &error); @@ -1140,7 +1141,7 @@ GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) { return PacketResult::Success; } - Error error = m_debugged_process_sp->Kill(); + Status error = m_debugged_process_sp->Kill(); if (error.Fail() && log) log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged " "process %" PRIu64 ": %s", @@ -1223,7 +1224,7 @@ GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) { } ResumeActionList resume_actions(StateType::eStateRunning, 0); - Error error; + Status error; // We have two branches: what to do if a continue thread is specified (in // which case we target @@ -1304,7 +1305,7 @@ GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) { // Build the ResumeActionList ResumeActionList actions(StateType::eStateRunning, 0); - Error error = m_debugged_process_sp->Resume(actions); + Status error = m_debugged_process_sp->Resume(actions); if (error.Fail()) { if (log) { log->Printf( @@ -1428,7 +1429,7 @@ GDBRemoteCommunicationServerLLGS::Handle_vCont( thread_actions.Append(thread_action); } - Error error = m_debugged_process_sp->Resume(thread_actions); + Status error = m_debugged_process_sp->Resume(thread_actions); if (error.Fail()) { if (log) { log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for " @@ -1853,7 +1854,7 @@ GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) { // Retrieve the value RegisterValue reg_value; - Error error = reg_context_sp->ReadRegister(reg_info, reg_value); + Status error = reg_context_sp->ReadRegister(reg_info, reg_value); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of " @@ -1973,7 +1974,7 @@ GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) { StreamGDBRemote response; RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder()); - Error error = reg_context_sp->WriteRegister(reg_info, reg_value); + Status error = reg_context_sp->WriteRegister(reg_info, reg_value); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of " @@ -2088,7 +2089,7 @@ GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) { // TODO: enqueue this block in circular buffer and send window size to // remote host ConnectionStatus status; - Error error; + Status error; m_stdio_communication.Write(tmp, read, status, &error); if (error.Fail()) { return SendErrorResponse(0x15); @@ -2114,7 +2115,7 @@ GDBRemoteCommunicationServerLLGS::Handle_interrupt( } // Interrupt the process. - Error error = m_debugged_process_sp->Interrupt(); + Status error = m_debugged_process_sp->Interrupt(); if (error.Fail()) { if (log) { log->Printf( @@ -2181,7 +2182,7 @@ GDBRemoteCommunicationServerLLGS::Handle_memory_read( // Retrieve the process memory. size_t bytes_read = 0; - Error error = m_debugged_process_sp->ReadMemoryWithoutTrap( + Status error = m_debugged_process_sp->ReadMemoryWithoutTrap( read_addr, &buf[0], byte_count, bytes_read); if (error.Fail()) { if (log) @@ -2282,8 +2283,8 @@ GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) { // Write the process memory. size_t bytes_written = 0; - Error error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0], - byte_count, bytes_written); + Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0], + byte_count, bytes_written); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 @@ -2329,7 +2330,7 @@ GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported( // Test if we can get any region back when asking for the region around NULL. MemoryRegionInfo region_info; - const Error error = + const Status error = m_debugged_process_sp->GetMemoryRegionInfo(0, region_info); if (error.Fail()) { // We don't support memory region info collection for this @@ -2367,7 +2368,7 @@ GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo( // Get the memory region info for the target address. MemoryRegionInfo region_info; - const Error error = + const Status error = m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info); if (error.Fail()) { // Return the error message. @@ -2485,7 +2486,7 @@ GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { if (want_breakpoint) { // Try to set the breakpoint. - const Error error = + const Status error = m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware); if (error.Success()) return SendOKResponse(); @@ -2498,7 +2499,7 @@ GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) { return SendErrorResponse(0x09); } else { // Try to set the watchpoint. - const Error error = m_debugged_process_sp->SetWatchpoint( + const Status error = m_debugged_process_sp->SetWatchpoint( addr, size, watch_flags, want_hardware); if (error.Success()) return SendOKResponse(); @@ -2582,7 +2583,7 @@ GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { if (want_breakpoint) { // Try to clear the breakpoint. - const Error error = + const Status error = m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware); if (error.Success()) return SendOKResponse(); @@ -2595,7 +2596,7 @@ GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) { return SendErrorResponse(0x09); } else { // Try to clear the watchpoint. - const Error error = m_debugged_process_sp->RemoveWatchpoint(addr); + const Status error = m_debugged_process_sp->RemoveWatchpoint(addr); if (error.Success()) return SendOKResponse(); Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); @@ -2646,7 +2647,7 @@ GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) { // All other threads stop while we're single stepping a thread. actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0); - Error error = m_debugged_process_sp->Resume(actions); + Status error = m_debugged_process_sp->Resume(actions); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 @@ -2782,7 +2783,7 @@ GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState( // Save registers to a buffer. DataBufferSP register_data_sp; - Error error = reg_context_sp->ReadAllRegisterValues(register_data_sp); + Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 @@ -2871,7 +2872,7 @@ GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState( m_saved_registers_map.erase(it); } - Error error = reg_context_sp->WriteAllRegisterValues(register_data_sp); + Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 @@ -2906,7 +2907,7 @@ GDBRemoteCommunicationServerLLGS::Handle_vAttach( "pid %" PRIu64, __FUNCTION__, pid); - Error error = AttachToProcess(pid); + Status error = AttachToProcess(pid); if (error.Fail()) { if (log) @@ -2954,7 +2955,7 @@ GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) { return SendIllFormedResponse(packet, "Invalid pid"); } - const Error error = m_debugged_process_sp->Detach(); + const Status error = m_debugged_process_sp->Detach(); if (error.Fail()) { if (log) log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from " @@ -3058,7 +3059,7 @@ GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress( packet.GetHexByteString(file_name); lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS; - Error error = + Status error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address); if (error.Fail()) return SendErrorResponse(69); @@ -3098,7 +3099,7 @@ GDBRemoteCommunicationServerLLGS::Handle_QPassSignals( if (!m_debugged_process_sp) return SendErrorResponse(68); - Error error = m_debugged_process_sp->IgnoreSignals(signals); + Status error = m_debugged_process_sp->IgnoreSignals(signals); if (error.Fail()) return SendErrorResponse(69); @@ -3112,7 +3113,7 @@ void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() { if (m_stdio_communication.IsConnected()) { auto connection = m_stdio_communication.GetConnection(); if (connection) { - Error error; + Status error; connection->Disconnect(&error); if (error.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h index a47927e1c640..ebda9a911d3c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h @@ -51,10 +51,10 @@ public: /// The number of elements in the args array of cstring pointers. /// /// @return - /// An Error object indicating the success or failure of making + /// An Status object indicating the success or failure of making /// the setting. //------------------------------------------------------------------ - Error SetLaunchArguments(const char *const args[], int argc); + Status SetLaunchArguments(const char *const args[], int argc); //------------------------------------------------------------------ /// Specify the launch flags for the process. @@ -63,10 +63,10 @@ public: /// The launch flags to use when launching this process. /// /// @return - /// An Error object indicating the success or failure of making + /// An Status object indicating the success or failure of making /// the setting. //------------------------------------------------------------------ - Error SetLaunchFlags(unsigned int launch_flags); + Status SetLaunchFlags(unsigned int launch_flags); //------------------------------------------------------------------ /// Launch a process with the current launch settings. @@ -76,10 +76,10 @@ public: /// with all the information for a child process to be launched. /// /// @return - /// An Error object indicating the success or failure of the + /// An Status object indicating the success or failure of the /// launch. //------------------------------------------------------------------ - Error LaunchProcess() override; + Status LaunchProcess() override; //------------------------------------------------------------------ /// Attach to a process. @@ -88,10 +88,10 @@ public: /// configured Platform. /// /// @return - /// An Error object indicating the success or failure of the + /// An Status object indicating the success or failure of the /// attach operation. //------------------------------------------------------------------ - Error AttachToProcess(lldb::pid_t pid); + Status AttachToProcess(lldb::pid_t pid); //------------------------------------------------------------------ // NativeProcessProtocol::NativeDelegate overrides @@ -103,7 +103,7 @@ public: void DidExec(NativeProcessProtocol *process) override; - Error InitializeConnection(std::unique_ptr<Connection> &&connection); + Status InitializeConnection(std::unique_ptr<Connection> &&connection); protected: MainLoop &m_mainloop; @@ -213,7 +213,7 @@ protected: lldb::tid_t GetContinueThreadID() const { return m_continue_tid; } - Error SetSTDIOFileDescriptor(int fd); + Status SetSTDIOFileDescriptor(int fd); FileSpec FindModuleFile(const std::string &module_path, const ArchSpec &arch) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp index ae1c1adb5b45..73e3732df3ef 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp @@ -82,7 +82,7 @@ GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform( &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo); RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt, - [](StringExtractorGDBRemote packet, Error &error, + [](StringExtractorGDBRemote packet, Status &error, bool &interrupt, bool &quit) { error.SetErrorString("interrupt received"); interrupt = true; @@ -95,7 +95,7 @@ GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform( //---------------------------------------------------------------------- GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {} -Error GDBRemoteCommunicationServerPlatform::LaunchGDBServer( +Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer( const lldb_private::Args &args, std::string hostname, lldb::pid_t &pid, uint16_t &port, std::string &socket_name) { if (port == UINT16_MAX) @@ -147,7 +147,7 @@ Error GDBRemoteCommunicationServerPlatform::LaunchGDBServer( port_ptr = nullptr; } - Error error = StartDebugserverProcess( + Status error = StartDebugserverProcess( url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1); pid = debugserver_launch_info.GetProcessID(); @@ -192,7 +192,7 @@ GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer( lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID; std::string socket_name; - Error error = + Status error = LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name); if (error.Fail()) { if (log) @@ -439,10 +439,10 @@ bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped( return true; } -Error GDBRemoteCommunicationServerPlatform::LaunchProcess() { +Status GDBRemoteCommunicationServerPlatform::LaunchProcess() { if (!m_process_launch_info.GetArguments().GetArgumentCount()) - return Error("%s: no process command line specified to launch", - __FUNCTION__); + return Status("%s: no process command line specified to launch", + __FUNCTION__); // specify the process monitor if not already set. This should // generally be what happens since we need to reap started @@ -454,7 +454,7 @@ Error GDBRemoteCommunicationServerPlatform::LaunchProcess() { this, std::placeholders::_1), false); - Error error = Host::LaunchProcess(m_process_launch_info); + Status error = Host::LaunchProcess(m_process_launch_info); if (!error.Success()) { fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments().GetArgumentAtIndex(0)); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h index 472d86e3a15c..aed5106272d1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h @@ -34,7 +34,7 @@ public: ~GDBRemoteCommunicationServerPlatform() override; - Error LaunchProcess() override; + Status LaunchProcess() override; // Set both ports to zero to let the platform automatically bind to // a port chosen by the OS. @@ -61,9 +61,9 @@ public: void SetInferiorArguments(const lldb_private::Args &args); - Error LaunchGDBServer(const lldb_private::Args &args, std::string hostname, - lldb::pid_t &pid, uint16_t &port, - std::string &socket_name); + Status LaunchGDBServer(const lldb_private::Args &args, std::string hostname, + lldb::pid_t &pid, uint16_t &port, + std::string &socket_name); void SetPendingGdbServer(lldb::pid_t pid, uint16_t port, const std::string &socket_name); diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp index ea4acc74893a..612c7144451e 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/GDBRemoteRegisterContext.cpp @@ -95,8 +95,8 @@ bool GDBRemoteRegisterContext::ReadRegister(const RegisterInfo *reg_info, // Read the register if (ReadRegisterBytes(reg_info, m_reg_data)) { const bool partial_data_ok = false; - Error error(value.SetValueFromData(reg_info, m_reg_data, - reg_info->byte_offset, partial_data_ok)); + Status error(value.SetValueFromData( + reg_info, m_reg_data, reg_info->byte_offset, partial_data_ok)); return error.Success(); } return false; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp index 10e6b0364783..fd4b5dae8cc2 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp @@ -97,8 +97,8 @@ namespace lldb { // function and get the packet history dumped to a file. void DumpProcessGDBRemotePacketHistory(void *p, const char *path) { StreamFile strm; - Error error(strm.GetFile().Open(path, File::eOpenOptionWrite | - File::eOpenOptionCanCreate)); + Status error(strm.GetFile().Open(path, File::eOpenOptionWrite | + File::eOpenOptionCanCreate)); if (error.Success()) ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm); } @@ -324,7 +324,7 @@ bool ProcessGDBRemote::ParsePythonTargetDefinition( const FileSpec &target_definition_fspec) { ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); - Error error; + Status error; StructuredData::ObjectSP module_object_sp( interpreter->LoadPluginModule(target_definition_fspec, error)); if (module_object_sp) { @@ -639,23 +639,23 @@ void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) { m_register_info.Finalize(GetTarget().GetArchitecture()); } -Error ProcessGDBRemote::WillLaunch(Module *module) { +Status ProcessGDBRemote::WillLaunch(Module *module) { return WillLaunchOrAttach(); } -Error ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) { +Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) { return WillLaunchOrAttach(); } -Error ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name, - bool wait_for_launch) { +Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name, + bool wait_for_launch) { return WillLaunchOrAttach(); } -Error ProcessGDBRemote::DoConnectRemote(Stream *strm, - llvm::StringRef remote_url) { +Status ProcessGDBRemote::DoConnectRemote(Stream *strm, + llvm::StringRef remote_url) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); - Error error(WillLaunchOrAttach()); + Status error(WillLaunchOrAttach()); if (error.Fail()) return error; @@ -744,8 +744,8 @@ Error ProcessGDBRemote::DoConnectRemote(Stream *strm, return error; } -Error ProcessGDBRemote::WillLaunchOrAttach() { - Error error; +Status ProcessGDBRemote::WillLaunchOrAttach() { + Status error; m_stdio_communication.Clear(); return error; } @@ -753,10 +753,10 @@ Error ProcessGDBRemote::WillLaunchOrAttach() { //---------------------------------------------------------------------- // Process Control //---------------------------------------------------------------------- -Error ProcessGDBRemote::DoLaunch(Module *exe_module, - ProcessLaunchInfo &launch_info) { +Status ProcessGDBRemote::DoLaunch(Module *exe_module, + ProcessLaunchInfo &launch_info) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); - Error error; + Status error; if (log) log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__); @@ -965,8 +965,8 @@ Error ProcessGDBRemote::DoLaunch(Module *exe_module, return error; } -Error ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) { - Error error; +Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) { + Status error; // Only connect if we have a valid connect URL Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); @@ -1169,10 +1169,10 @@ void ProcessGDBRemote::DidLaunch() { DidLaunchOrAttach(process_arch); } -Error ProcessGDBRemote::DoAttachToProcessWithID( +Status ProcessGDBRemote::DoAttachToProcessWithID( lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); - Error error; + Status error; if (log) log->Printf("ProcessGDBRemote::%s()", __FUNCTION__); @@ -1197,9 +1197,9 @@ Error ProcessGDBRemote::DoAttachToProcessWithID( return error; } -Error ProcessGDBRemote::DoAttachToProcessWithName( +Status ProcessGDBRemote::DoAttachToProcessWithName( const char *process_name, const ProcessAttachInfo &attach_info) { - Error error; + Status error; // Clear out and clean up from any current state Clear(); @@ -1247,18 +1247,18 @@ void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) { DidLaunchOrAttach(process_arch); } -Error ProcessGDBRemote::WillResume() { +Status ProcessGDBRemote::WillResume() { m_continue_c_tids.clear(); m_continue_C_tids.clear(); m_continue_s_tids.clear(); m_continue_S_tids.clear(); m_jstopinfo_sp.reset(); m_jthreadsinfo_sp.reset(); - return Error(); + return Status(); } -Error ProcessGDBRemote::DoResume() { - Error error; +Status ProcessGDBRemote::DoResume() { + Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (log) log->Printf("ProcessGDBRemote::Resume()"); @@ -2113,9 +2113,9 @@ ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) { if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>( "address", mem_cache_addr)) { if (mem_cache_addr != LLDB_INVALID_ADDRESS) { - StringExtractor bytes; - if (mem_cache_dict->GetValueForKeyAsString( - "bytes", bytes.GetStringRef())) { + llvm::StringRef str; + if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) { + StringExtractor bytes(str); bytes.SetFilePos(0); const size_t byte_size = bytes.GetStringRef().size() / 2; @@ -2400,8 +2400,8 @@ void ProcessGDBRemote::RefreshStateAfterStop() { m_thread_list_real.RefreshStateAfterStop(); } -Error ProcessGDBRemote::DoHalt(bool &caused_stop) { - Error error; +Status ProcessGDBRemote::DoHalt(bool &caused_stop) { + Status error; if (m_public_state.GetValue() == eStateAttaching) { // We are being asked to halt during an attach. We need to just close @@ -2412,8 +2412,8 @@ Error ProcessGDBRemote::DoHalt(bool &caused_stop) { return error; } -Error ProcessGDBRemote::DoDetach(bool keep_stopped) { - Error error; +Status ProcessGDBRemote::DoDetach(bool keep_stopped) { + Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (log) log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); @@ -2441,8 +2441,8 @@ Error ProcessGDBRemote::DoDetach(bool keep_stopped) { return error; } -Error ProcessGDBRemote::DoDestroy() { - Error error; +Status ProcessGDBRemote::DoDestroy() { + Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (log) log->Printf("ProcessGDBRemote::DoDestroy()"); @@ -2724,7 +2724,7 @@ void ProcessGDBRemote::WillPublicStop() { // Process Memory //------------------------------------------------------------------ size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { GetMaxMemorySize(); bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); // M and m packets take 2 bytes for 1 byte of memory @@ -2783,7 +2783,7 @@ size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, } size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, - size_t size, Error &error) { + size_t size, Status &error) { GetMaxMemorySize(); // M and m packets take 2 bytes for 1 byte of memory size_t max_memory_size = m_max_memory_size / 2; @@ -2824,7 +2824,7 @@ size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, uint32_t permissions, - Error &error) { + Status &error) { Log *log( GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS)); addr_t allocated_addr = LLDB_INVALID_ADDRESS; @@ -2868,27 +2868,27 @@ lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, return allocated_addr; } -Error ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr, - MemoryRegionInfo ®ion_info) { +Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr, + MemoryRegionInfo ®ion_info) { - Error error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); + Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); return error; } -Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { +Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { - Error error(m_gdb_comm.GetWatchpointSupportInfo(num)); + Status error(m_gdb_comm.GetWatchpointSupportInfo(num)); return error; } -Error ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { - Error error(m_gdb_comm.GetWatchpointSupportInfo( +Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { + Status error(m_gdb_comm.GetWatchpointSupportInfo( num, after, GetTarget().GetArchitecture())); return error; } -Error ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { - Error error; +Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { + Status error; LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); switch (supported) { @@ -2926,7 +2926,7 @@ Error ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { // Process STDIO //------------------------------------------------------------------ size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, - Error &error) { + Status &error) { if (m_stdio_communication.IsConnected()) { ConnectionStatus status; m_stdio_communication.Write(src, src_len, status, NULL); @@ -2936,8 +2936,8 @@ size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, return 0; } -Error ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { - Error error; +Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { + Status error; assert(bp_site != NULL); // Get logging info @@ -3074,8 +3074,8 @@ Error ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { return EnableSoftwareBreakpoint(bp_site); } -Error ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { - Error error; +Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { + Status error; assert(bp_site != NULL); addr_t addr = bp_site->GetLoadAddress(); user_id_t site_id = bp_site->GetID(); @@ -3143,8 +3143,8 @@ static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { return eWatchpointWrite; } -Error ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { - Error error; +Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { + Status error; if (wp) { user_id_t watchID = wp->GetID(); addr_t addr = wp->GetLoadAddress(); @@ -3180,8 +3180,8 @@ Error ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { return error; } -Error ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { - Error error; +Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { + Status error; if (wp) { user_id_t watchID = wp->GetID(); @@ -3233,8 +3233,8 @@ void ProcessGDBRemote::Clear() { m_thread_list.Clear(); } -Error ProcessGDBRemote::DoSignal(int signo) { - Error error; +Status ProcessGDBRemote::DoSignal(int signo) { + Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (log) log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo); @@ -3244,15 +3244,15 @@ Error ProcessGDBRemote::DoSignal(int signo) { return error; } -Error ProcessGDBRemote::EstablishConnectionIfNeeded( - const ProcessInfo &process_info) { +Status +ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { // Make sure we aren't already connected? if (m_gdb_comm.IsConnected()) - return Error(); + return Status(); PlatformSP platform_sp(GetTarget().GetPlatform()); if (platform_sp && !platform_sp->IsHost()) - return Error("Lost debug server connection"); + return Status("Lost debug server connection"); auto error = LaunchAndConnectToDebugserver(process_info); if (error.Fail()) { @@ -3279,11 +3279,11 @@ static bool SetCloexecFlag(int fd) { } #endif -Error ProcessGDBRemote::LaunchAndConnectToDebugserver( +Status ProcessGDBRemote::LaunchAndConnectToDebugserver( const ProcessInfo &process_info) { using namespace std::placeholders; // For _1, _2, etc. - Error error; + Status error; if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { // If we locate debugserver, keep that located version around static FileSpec g_debugserver_file_spec; @@ -3741,30 +3741,30 @@ bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( return false; } -Error ProcessGDBRemote::UpdateAutomaticSignalFiltering() { +Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOG(log, "Check if need to update ignored signals"); // QPassSignals package is not supported by the server, // there is no way we can ignore any signals on server side. if (!m_gdb_comm.GetQPassSignalsSupported()) - return Error(); + return Status(); // No signals, nothing to send. if (m_unix_signals_sp == nullptr) - return Error(); + return Status(); // Signals' version hasn't changed, no need to send anything. uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); if (new_signals_version == m_last_signals_version) { LLDB_LOG(log, "Signals' version hasn't changed. version={0}", m_last_signals_version); - return Error(); + return Status(); } auto signals_to_ignore = m_unix_signals_sp->GetFilteredSignals(false, false, false); - Error error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); + Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); LLDB_LOG(log, "Signals' version changed. old version={0}, new version={1}, " @@ -3822,11 +3822,11 @@ DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { return m_dyld_ap.get(); } -Error ProcessGDBRemote::SendEventData(const char *data) { +Status ProcessGDBRemote::SendEventData(const char *data) { int return_value; bool was_supported; - Error error; + Status error; return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); if (return_value != 0) { @@ -3997,7 +3997,7 @@ StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { return object_sp; } -Error ProcessGDBRemote::ConfigureStructuredData( +Status ProcessGDBRemote::ConfigureStructuredData( const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); } @@ -4334,7 +4334,7 @@ bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { // request the target xml file std::string raw; - lldb_private::Error lldberr; + lldb_private::Status lldberr; if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"), raw, lldberr)) { return false; @@ -4426,10 +4426,10 @@ bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { return m_register_info.GetNumRegisters() > 0; } -Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { +Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { // Make sure LLDB has an XML parser it can use first if (!XMLDocument::XMLEnabled()) - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS); if (log) @@ -4443,11 +4443,11 @@ Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { // request the loaded library list std::string raw; - lldb_private::Error lldberr; + lldb_private::Status lldberr; if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""), raw, lldberr)) - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); // parse the xml file in memory if (log) @@ -4455,11 +4455,11 @@ Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { XMLDocument doc; if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); XMLNode root_element = doc.GetRootElement("library-list-svr4"); if (!root_element) - return Error(); + return Status(); // main link map structure llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); @@ -4530,22 +4530,22 @@ Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { // request the loaded library list std::string raw; - lldb_private::Error lldberr; + lldb_private::Status lldberr; if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw, lldberr)) - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); if (log) log->Printf("parsing: %s", raw.c_str()); XMLDocument doc; if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); XMLNode root_element = doc.GetRootElement("library-list"); if (!root_element) - return Error(); + return Status(); root_element.ForEachChildElementWithName( "library", [log, &list](const XMLNode &library) -> bool { @@ -4586,10 +4586,10 @@ Error ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) { log->Printf("found %" PRId32 " modules in total", (int)list.m_list.size()); } else { - return Error(0, ErrorType::eErrorTypeGeneric); + return Status(0, ErrorType::eErrorTypeGeneric); } - return Error(); + return Status(); } lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, @@ -4688,15 +4688,15 @@ size_t ProcessGDBRemote::LoadModules() { return LoadModules(module_list); } -Error ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, - bool &is_loaded, - lldb::addr_t &load_addr) { +Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, + bool &is_loaded, + lldb::addr_t &load_addr) { is_loaded = false; load_addr = LLDB_INVALID_ADDRESS; std::string file_path = file.GetPath(false); if (file_path.empty()) - return Error("Empty file name specified"); + return Status("Empty file name specified"); StreamString packet; packet.PutCString("qFileLoadAddress:"); @@ -4706,27 +4706,28 @@ Error ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, false) != GDBRemoteCommunication::PacketResult::Success) - return Error("Sending qFileLoadAddress packet failed"); + return Status("Sending qFileLoadAddress packet failed"); if (response.IsErrorResponse()) { if (response.GetError() == 1) { // The file is not loaded into the inferior is_loaded = false; load_addr = LLDB_INVALID_ADDRESS; - return Error(); + return Status(); } - return Error( + return Status( "Fetching file load address from remote server returned an error"); } if (response.IsNormalResponse()) { is_loaded = true; load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); - return Error(); + return Status(); } - return Error("Unknown error happened during sending the load address packet"); + return Status( + "Unknown error happened during sending the load address packet"); } void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h index a1794d0f5050..60f0464f86bb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h @@ -30,7 +30,7 @@ #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StringExtractor.h" #include "lldb/Utility/StringList.h" @@ -78,25 +78,25 @@ public: //------------------------------------------------------------------ // Creating a new process, or attaching to an existing one //------------------------------------------------------------------ - Error WillLaunch(Module *module) override; + Status WillLaunch(Module *module) override; - Error DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override; + Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override; void DidLaunch() override; - Error WillAttachToProcessWithID(lldb::pid_t pid) override; + Status WillAttachToProcessWithID(lldb::pid_t pid) override; - Error WillAttachToProcessWithName(const char *process_name, - bool wait_for_launch) override; + Status WillAttachToProcessWithName(const char *process_name, + bool wait_for_launch) override; - Error DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override; + Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) override; - Error WillLaunchOrAttach(); + Status WillLaunchOrAttach(); - Error DoAttachToProcessWithID(lldb::pid_t pid, - const ProcessAttachInfo &attach_info) override; + Status DoAttachToProcessWithID(lldb::pid_t pid, + const ProcessAttachInfo &attach_info) override; - Error + Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info) override; @@ -112,19 +112,19 @@ public: //------------------------------------------------------------------ // Process Control //------------------------------------------------------------------ - Error WillResume() override; + Status WillResume() override; - Error DoResume() override; + Status DoResume() override; - Error DoHalt(bool &caused_stop) override; + Status DoHalt(bool &caused_stop) override; - Error DoDetach(bool keep_stopped) override; + Status DoDetach(bool keep_stopped) override; bool DetachRequiresHalt() override { return true; } - Error DoSignal(int signal) override; + Status DoSignal(int signal) override; - Error DoDestroy() override; + Status DoDestroy() override; void RefreshStateAfterStop() override; @@ -143,41 +143,41 @@ public: // Process Memory //------------------------------------------------------------------ size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) override; + Status &error) override; size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, - Error &error) override; + Status &error) override; lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, - Error &error) override; + Status &error) override; - Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo ®ion_info) override; + Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo ®ion_info) override; - Error DoDeallocateMemory(lldb::addr_t ptr) override; + Status DoDeallocateMemory(lldb::addr_t ptr) override; //------------------------------------------------------------------ // Process STDIO //------------------------------------------------------------------ - size_t PutSTDIN(const char *buf, size_t buf_size, Error &error) override; + size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override; //---------------------------------------------------------------------- // Process Breakpoints //---------------------------------------------------------------------- - Error EnableBreakpointSite(BreakpointSite *bp_site) override; + Status EnableBreakpointSite(BreakpointSite *bp_site) override; - Error DisableBreakpointSite(BreakpointSite *bp_site) override; + Status DisableBreakpointSite(BreakpointSite *bp_site) override; //---------------------------------------------------------------------- // Process Watchpoints //---------------------------------------------------------------------- - Error EnableWatchpoint(Watchpoint *wp, bool notify = true) override; + Status EnableWatchpoint(Watchpoint *wp, bool notify = true) override; - Error DisableWatchpoint(Watchpoint *wp, bool notify = true) override; + Status DisableWatchpoint(Watchpoint *wp, bool notify = true) override; - Error GetWatchpointSupportInfo(uint32_t &num) override; + Status GetWatchpointSupportInfo(uint32_t &num) override; - Error GetWatchpointSupportInfo(uint32_t &num, bool &after) override; + Status GetWatchpointSupportInfo(uint32_t &num, bool &after) override; bool StartNoticingNewThreads() override; @@ -185,7 +185,7 @@ public: GDBRemoteCommunicationClient &GetGDBRemote() { return m_gdb_comm; } - Error SendEventData(const char *data) override; + Status SendEventData(const char *data) override; //---------------------------------------------------------------------- // Override DidExit so we can disconnect from the remote GDB server @@ -207,8 +207,8 @@ public: size_t LoadModules() override; - Error GetFileLoadAddress(const FileSpec &file, bool &is_loaded, - lldb::addr_t &load_addr) override; + Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, + lldb::addr_t &load_addr) override; void ModulesDidLoad(ModuleList &module_list) override; @@ -216,7 +216,7 @@ public: GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address, lldb::addr_t image_count) override; - Error + Status ConfigureStructuredData(const ConstString &type_name, const StructuredData::ObjectSP &config_sp) override; @@ -315,9 +315,9 @@ protected: bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override; - Error EstablishConnectionIfNeeded(const ProcessInfo &process_info); + Status EstablishConnectionIfNeeded(const ProcessInfo &process_info); - Error LaunchAndConnectToDebugserver(const ProcessInfo &process_info); + Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info); void KillDebugserverProcess(); @@ -379,7 +379,7 @@ protected: void DidLaunchOrAttach(ArchSpec &process_arch); - Error ConnectToDebugserver(llvm::StringRef host_port); + Status ConnectToDebugserver(llvm::StringRef host_port); const char *GetDispatchQueueNameForThread(lldb::addr_t thread_dispatch_qaddr, std::string &dispatch_queue_name); @@ -390,14 +390,14 @@ protected: bool GetGDBServerRegisterInfo(ArchSpec &arch); // Query remote GDBServer for a detailed loaded library list - Error GetLoadedModuleList(LoadedModuleInfoList &); + Status GetLoadedModuleList(LoadedModuleInfoList &); lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file, lldb::addr_t link_map, lldb::addr_t base_addr, bool value_is_offset); - Error UpdateAutomaticSignalFiltering() override; + Status UpdateAutomaticSignalFiltering() override; private: //------------------------------------------------------------------ diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp index 37b3709c09c1..36350fdb6398 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp @@ -45,7 +45,7 @@ MinidumpParser::Create(const lldb::DataBufferSP &data_buf_sp) { } const MinidumpDirectory *directory = nullptr; - Error error; + Status error; llvm::ArrayRef<uint8_t> directory_data( data_buf_sp->GetBytes() + directory_list_offset, sizeof(MinidumpDirectory) * header->streams_count); @@ -126,7 +126,7 @@ MinidumpParser::GetThreadContextWow64(const MinidumpThread &td) { return {}; const TEB64 *wow64teb; - Error error = consumeObject(teb_mem, wow64teb); + Status error = consumeObject(teb_mem, wow64teb); if (error.Fail()) return {}; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.h b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.h index 189aeb3d64e6..df6deb482afd 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpParser.h @@ -17,7 +17,7 @@ // Other libraries and framework includes #include "lldb/Core/ArchSpec.h" #include "lldb/Utility/DataBuffer.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp index 863d124a7ccc..24ce3f94c094 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.cpp @@ -19,7 +19,7 @@ using namespace minidump; const MinidumpHeader *MinidumpHeader::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpHeader *header = nullptr; - Error error = consumeObject(data, header); + Status error = consumeObject(data, header); const MinidumpHeaderConstants signature = static_cast<const MinidumpHeaderConstants>( @@ -45,7 +45,7 @@ lldb_private::minidump::parseMinidumpString(llvm::ArrayRef<uint8_t> &data) { std::string result; const uint32_t *source_length; - Error error = consumeObject(data, source_length); + Status error = consumeObject(data, source_length); if (error.Fail() || *source_length > data.size() || *source_length % 2 != 0) return llvm::None; @@ -71,7 +71,7 @@ lldb_private::minidump::parseMinidumpString(llvm::ArrayRef<uint8_t> &data) { // MinidumpThread const MinidumpThread *MinidumpThread::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpThread *thread = nullptr; - Error error = consumeObject(data, thread); + Status error = consumeObject(data, thread); if (error.Fail()) return nullptr; @@ -81,7 +81,7 @@ const MinidumpThread *MinidumpThread::Parse(llvm::ArrayRef<uint8_t> &data) { llvm::ArrayRef<MinidumpThread> MinidumpThread::ParseThreadList(llvm::ArrayRef<uint8_t> &data) { const llvm::support::ulittle32_t *thread_count; - Error error = consumeObject(data, thread_count); + Status error = consumeObject(data, thread_count); if (error.Fail() || *thread_count * sizeof(MinidumpThread) > data.size()) return {}; @@ -93,7 +93,7 @@ MinidumpThread::ParseThreadList(llvm::ArrayRef<uint8_t> &data) { const MinidumpSystemInfo * MinidumpSystemInfo::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpSystemInfo *system_info; - Error error = consumeObject(data, system_info); + Status error = consumeObject(data, system_info); if (error.Fail()) return nullptr; @@ -103,7 +103,7 @@ MinidumpSystemInfo::Parse(llvm::ArrayRef<uint8_t> &data) { // MinidumpMiscInfo const MinidumpMiscInfo *MinidumpMiscInfo::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpMiscInfo *misc_info; - Error error = consumeObject(data, misc_info); + Status error = consumeObject(data, misc_info); if (error.Fail()) return nullptr; @@ -147,7 +147,7 @@ lldb::pid_t LinuxProcStatus::GetPid() const { return pid; } // Module stuff const MinidumpModule *MinidumpModule::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpModule *module = nullptr; - Error error = consumeObject(data, module); + Status error = consumeObject(data, module); if (error.Fail()) return nullptr; @@ -158,7 +158,7 @@ llvm::ArrayRef<MinidumpModule> MinidumpModule::ParseModuleList(llvm::ArrayRef<uint8_t> &data) { const llvm::support::ulittle32_t *modules_count; - Error error = consumeObject(data, modules_count); + Status error = consumeObject(data, modules_count); if (error.Fail() || *modules_count * sizeof(MinidumpModule) > data.size()) return {}; @@ -170,7 +170,7 @@ MinidumpModule::ParseModuleList(llvm::ArrayRef<uint8_t> &data) { const MinidumpExceptionStream * MinidumpExceptionStream::Parse(llvm::ArrayRef<uint8_t> &data) { const MinidumpExceptionStream *exception_stream = nullptr; - Error error = consumeObject(data, exception_stream); + Status error = consumeObject(data, exception_stream); if (error.Fail()) return nullptr; @@ -180,7 +180,7 @@ MinidumpExceptionStream::Parse(llvm::ArrayRef<uint8_t> &data) { llvm::ArrayRef<MinidumpMemoryDescriptor> MinidumpMemoryDescriptor::ParseMemoryList(llvm::ArrayRef<uint8_t> &data) { const llvm::support::ulittle32_t *mem_ranges_count; - Error error = consumeObject(data, mem_ranges_count); + Status error = consumeObject(data, mem_ranges_count); if (error.Fail() || *mem_ranges_count * sizeof(MinidumpMemoryDescriptor) > data.size()) return {}; @@ -193,7 +193,7 @@ MinidumpMemoryDescriptor::ParseMemoryList(llvm::ArrayRef<uint8_t> &data) { std::pair<llvm::ArrayRef<MinidumpMemoryDescriptor64>, uint64_t> MinidumpMemoryDescriptor64::ParseMemory64List(llvm::ArrayRef<uint8_t> &data) { const llvm::support::ulittle64_t *mem_ranges_count; - Error error = consumeObject(data, mem_ranges_count); + Status error = consumeObject(data, mem_ranges_count); if (error.Fail() || *mem_ranges_count * sizeof(MinidumpMemoryDescriptor64) > data.size()) return {}; @@ -213,7 +213,7 @@ MinidumpMemoryDescriptor64::ParseMemory64List(llvm::ArrayRef<uint8_t> &data) { std::vector<const MinidumpMemoryInfo *> MinidumpMemoryInfo::ParseMemoryInfoList(llvm::ArrayRef<uint8_t> &data) { const MinidumpMemoryInfoListHeader *header; - Error error = consumeObject(data, header); + Status error = consumeObject(data, header); if (error.Fail() || header->size_of_header < sizeof(MinidumpMemoryInfoListHeader) || header->size_of_entry < sizeof(MinidumpMemoryInfo)) diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.h b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.h index 42de7eaaca03..6de4f55a769d 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/MinidumpTypes.h @@ -13,7 +13,7 @@ // Project includes // Other libraries and framework includes -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/BitmaskEnum.h" @@ -158,8 +158,8 @@ enum class MinidumpMiscInfoFlags : uint32_t { }; template <typename T> -Error consumeObject(llvm::ArrayRef<uint8_t> &Buffer, const T *&Object) { - Error error; +Status consumeObject(llvm::ArrayRef<uint8_t> &Buffer, const T *&Object) { + Status error; if (Buffer.size() < sizeof(T)) { error.SetErrorString("Insufficient buffer!"); return error; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp index f3f4664ad6e1..d4d65c044eab 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp @@ -113,8 +113,8 @@ void ProcessMinidump::Terminate() { PluginManager::UnregisterPlugin(ProcessMinidump::CreateInstance); } -Error ProcessMinidump::DoLoadCore() { - Error error; +Status ProcessMinidump::DoLoadCore() { + Status error; m_thread_list = m_minidump_parser.GetThreads(); m_active_exception = m_minidump_parser.GetExceptionStream(); @@ -141,7 +141,7 @@ ConstString ProcessMinidump::GetPluginName() { return GetPluginNameStatic(); } uint32_t ProcessMinidump::GetPluginVersion() { return 1; } -Error ProcessMinidump::DoDestroy() { return Error(); } +Status ProcessMinidump::DoDestroy() { return Status(); } void ProcessMinidump::RefreshStateAfterStop() { if (!m_active_exception) @@ -184,14 +184,14 @@ bool ProcessMinidump::IsAlive() { return true; } bool ProcessMinidump::WarnBeforeDetach() const { return false; } size_t ProcessMinidump::ReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { // Don't allow the caching that lldb_private::Process::ReadMemory does // since we have it all cached in our dump file anyway. return DoReadMemory(addr, buf, size, error); } size_t ProcessMinidump::DoReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { llvm::ArrayRef<uint8_t> mem = m_minidump_parser.GetMemory(addr, size); if (mem.empty()) { @@ -215,9 +215,9 @@ ArchSpec ProcessMinidump::GetArchitecture() { return ArchSpec(triple); } -Error ProcessMinidump::GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) { - Error error; +Status ProcessMinidump::GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) { + Status error; auto info = m_minidump_parser.GetMemoryRegionInfo(load_addr); if (!info) { error.SetErrorString("No valid MemoryRegionInfo found!"); @@ -278,7 +278,7 @@ void ProcessMinidump::ReadModuleList() { const auto file_spec = FileSpec(name.getValue(), true); ModuleSpec module_spec = file_spec; - Error error; + Status error; lldb::ModuleSP module_sp = GetTarget().GetSharedModule(module_spec, &error); if (!module_sp || error.Fail()) { continue; diff --git a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.h b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.h index 62407f927551..d5c46be97352 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.h +++ b/contrib/llvm/tools/lldb/source/Plugins/Process/minidump/ProcessMinidump.h @@ -19,7 +19,7 @@ #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" @@ -53,7 +53,7 @@ public: bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override; - Error DoLoadCore() override; + Status DoLoadCore() override; DynamicLoader *GetDynamicLoader() override; @@ -61,7 +61,7 @@ public: uint32_t GetPluginVersion() override; - Error DoDestroy() override; + Status DoDestroy() override; void RefreshStateAfterStop() override; @@ -70,15 +70,15 @@ public: bool WarnBeforeDetach() const override; size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) override; + Status &error) override; size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, - Error &error) override; + Status &error) override; ArchSpec GetArchitecture(); - Error GetMemoryRegionInfo(lldb::addr_t load_addr, - MemoryRegionInfo &range_info) override; + Status GetMemoryRegionInfo(lldb::addr_t load_addr, + MemoryRegionInfo &range_info) override; bool GetProcessInfo(ProcessInstanceInfo &info) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp index cfab9b33e662..d6d695fc2e74 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp @@ -723,7 +723,7 @@ bool ScriptInterpreterPython::ExecuteOneLine( // the result object Pipe pipe; - Error pipe_result = pipe.CreateNew(false); + Status pipe_result = pipe.CreateNew(false); if (pipe_result.Success()) { #if defined(_WIN32) lldb::file_t read_file = pipe.GetReadNativeHandle(); @@ -928,7 +928,8 @@ protected: }; void ScriptInterpreterPython::ExecuteInterpreterLoop() { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); Debugger &debugger = GetCommandInterpreter().GetDebugger(); @@ -1133,9 +1134,9 @@ bool ScriptInterpreterPython::ExecuteOneLineWithReturn( return ret_success; } -Error ScriptInterpreterPython::ExecuteMultipleLines( +Status ScriptInterpreterPython::ExecuteMultipleLines( const char *in_string, const ExecuteScriptOptions &options) { - Error error; + Status error; Locker locker(this, ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | @@ -1220,10 +1221,10 @@ void ScriptInterpreterPython::SetBreakpointCommandCallbackFunction( bp_options, oneliner.c_str()); } -Error ScriptInterpreterPython::SetBreakpointCommandCallback( +Status ScriptInterpreterPython::SetBreakpointCommandCallback( BreakpointOptions *bp_options, std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { - Error error; + Status error; error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, cmd_data_up->script_source); if (error.Fail()) { @@ -1237,7 +1238,7 @@ Error ScriptInterpreterPython::SetBreakpointCommandCallback( } // Set a Python one-liner as the callback for the breakpoint. -Error ScriptInterpreterPython::SetBreakpointCommandCallback( +Status ScriptInterpreterPython::SetBreakpointCommandCallback( BreakpointOptions *bp_options, const char *command_body_text) { auto data_ap = llvm::make_unique<CommandDataPython>(); @@ -1248,8 +1249,8 @@ Error ScriptInterpreterPython::SetBreakpointCommandCallback( // the callback will actually invoke. data_ap->user_source.SplitIntoLines(command_body_text); - Error error = GenerateBreakpointCommandCallbackData(data_ap->user_source, - data_ap->script_source); + Status error = GenerateBreakpointCommandCallbackData(data_ap->user_source, + data_ap->script_source); if (error.Success()) { auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_ap)); @@ -1285,20 +1286,20 @@ void ScriptInterpreterPython::SetWatchpointCommandCallback( return; } -Error ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter( +Status ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter( StringList &function_def) { // Convert StringList to one long, newline delimited, const char *. std::string function_def_string(function_def.CopyList()); - Error error = ExecuteMultipleLines( + Status error = ExecuteMultipleLines( function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false)); return error; } -Error ScriptInterpreterPython::GenerateFunction(const char *signature, - const StringList &input) { - Error error; +Status ScriptInterpreterPython::GenerateFunction(const char *signature, + const StringList &input) { + Status error; int num_lines = input.GetSize(); if (num_lines == 0) { error.SetErrorString("No input data."); @@ -1830,7 +1831,7 @@ lldb::StateType ScriptInterpreterPython::ScriptedThreadPlanGetRunState( StructuredData::ObjectSP ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec, - lldb_private::Error &error) { + lldb_private::Status &error) { if (!file_spec.Exists()) { error.SetErrorString("no such file"); return StructuredData::ObjectSP(); @@ -1847,7 +1848,7 @@ ScriptInterpreterPython::LoadPluginModule(const FileSpec &file_spec, StructuredData::DictionarySP ScriptInterpreterPython::GetDynamicSettings( StructuredData::ObjectSP plugin_module_sp, Target *target, - const char *setting_name, lldb_private::Error &error) { + const char *setting_name, lldb_private::Status &error) { if (!plugin_module_sp || !target || !setting_name || !setting_name[0] || !g_swig_plugin_get) return StructuredData::DictionarySP(); @@ -1943,12 +1944,12 @@ bool ScriptInterpreterPython::GenerateTypeSynthClass(const char *oneliner, return GenerateTypeSynthClass(input, output, name_token); } -Error ScriptInterpreterPython::GenerateBreakpointCommandCallbackData( +Status ScriptInterpreterPython::GenerateBreakpointCommandCallbackData( StringList &user_input, std::string &output) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); StreamString sstr; - Error error; + Status error; if (user_input.GetSize() == 0) { error.SetErrorString("No input data."); return error; @@ -1995,7 +1996,8 @@ bool ScriptInterpreterPython::GetScriptedSummary( StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); if (!valobj.get()) { retval.assign("<no object>"); @@ -2019,8 +2021,8 @@ bool ScriptInterpreterPython::GetScriptedSummary( { TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); - Timer scoped_timer("g_swig_typescript_callback", - "g_swig_typescript_callback"); + static Timer::Category func_cat("g_swig_typescript_callback"); + Timer scoped_timer(func_cat, "g_swig_typescript_callback"); ret_val = g_swig_typescript_callback( python_function_name, GetSessionDictionary().get(), valobj, &new_callee, options_sp, retval); @@ -2395,7 +2397,7 @@ ConstString ScriptInterpreterPython::GetSyntheticTypeName( bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, - Error &error) { + Status &error) { bool ret_val; if (!process) { error.SetErrorString("no process"); @@ -2424,7 +2426,7 @@ bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, Thread *thread, std::string &output, - Error &error) { + Status &error) { bool ret_val; if (!thread) { error.SetErrorString("no thread"); @@ -2453,7 +2455,7 @@ bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, Target *target, std::string &output, - Error &error) { + Status &error) { bool ret_val; if (!target) { error.SetErrorString("no thread"); @@ -2482,7 +2484,7 @@ bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, std::string &output, - Error &error) { + Status &error) { bool ret_val; if (!frame) { error.SetErrorString("no frame"); @@ -2511,7 +2513,7 @@ bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, bool ScriptInterpreterPython::RunScriptFormatKeyword(const char *impl_function, ValueObject *value, std::string &output, - Error &error) { + Status &error) { bool ret_val; if (!value) { error.SetErrorString("no value"); @@ -2551,7 +2553,7 @@ uint64_t replace_all(std::string &str, const std::string &oldStr, bool ScriptInterpreterPython::LoadScriptingModule( const char *pathname, bool can_reload, bool init_session, - lldb_private::Error &error, StructuredData::ObjectSP *module_sp) { + lldb_private::Status &error, StructuredData::ObjectSP *module_sp) { if (!pathname || !pathname[0]) { error.SetErrorString("invalid pathname"); return false; @@ -2742,7 +2744,7 @@ ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler() { bool ScriptInterpreterPython::RunScriptBasedCommand( const char *impl_function, const char *args, ScriptedCommandSynchronicity synchronicity, - lldb_private::CommandReturnObject &cmd_retobj, Error &error, + lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) { if (!impl_function) { error.SetErrorString("no function to execute"); @@ -2790,7 +2792,7 @@ bool ScriptInterpreterPython::RunScriptBasedCommand( bool ScriptInterpreterPython::RunScriptBasedCommand( StructuredData::GenericSP impl_obj_sp, const char *args, ScriptedCommandSynchronicity synchronicity, - lldb_private::CommandReturnObject &cmd_retobj, Error &error, + lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) { if (!impl_obj_sp || !impl_obj_sp->IsValid()) { error.SetErrorString("no function to execute"); @@ -3102,7 +3104,8 @@ void ScriptInterpreterPython::InitializePrivate() { g_initialized = true; - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); // RAII-based initialization which correctly handles multiple-initialization, // version- diff --git a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h index 7b0e1b000d6f..a71fcea7519c 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h +++ b/contrib/llvm/tools/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h @@ -161,11 +161,11 @@ public: void *ret_value, const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; - lldb_private::Error ExecuteMultipleLines( + lldb_private::Status ExecuteMultipleLines( const char *in_string, const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; - Error + Status ExportFunctionDefinitionToInterpreter(StringList &function_def) override; bool GenerateTypeScriptFunction(StringList &input, std::string &output, @@ -229,12 +229,12 @@ public: StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, - lldb_private::Error &error) override; + lldb_private::Status &error) override; StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, - lldb_private::Error &error) override; + lldb_private::Status &error) override; size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override; @@ -262,21 +262,21 @@ public: RunScriptBasedCommand(const char *impl_function, const char *args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, - Error &error, + Status &error, const lldb_private::ExecutionContext &exe_ctx) override; bool RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp, const char *args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, - Error &error, + Status &error, const lldb_private::ExecutionContext &exe_ctx) override; - Error GenerateFunction(const char *signature, - const StringList &input) override; + Status GenerateFunction(const char *signature, + const StringList &input) override; - Error GenerateBreakpointCommandCallbackData(StringList &input, - std::string &output) override; + Status GenerateBreakpointCommandCallbackData(StringList &input, + std::string &output) override; bool GenerateWatchpointCommandCallbackData(StringList &input, std::string &output) override; @@ -332,23 +332,23 @@ public: } bool RunScriptFormatKeyword(const char *impl_function, Process *process, - std::string &output, Error &error) override; + std::string &output, Status &error) override; bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, - std::string &output, Error &error) override; + std::string &output, Status &error) override; bool RunScriptFormatKeyword(const char *impl_function, Target *target, - std::string &output, Error &error) override; + std::string &output, Status &error) override; bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, - std::string &output, Error &error) override; + std::string &output, Status &error) override; bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, - std::string &output, Error &error) override; + std::string &output, Status &error) override; bool LoadScriptingModule(const char *filename, bool can_reload, bool init_session, - lldb_private::Error &error, + lldb_private::Status &error, StructuredData::ObjectSP *module_sp = nullptr) override; bool IsReservedWord(const char *word) override; @@ -364,14 +364,14 @@ public: CommandReturnObject &result) override; /// Set the callback body text into the callback for the breakpoint. - Error SetBreakpointCommandCallback(BreakpointOptions *bp_options, - const char *callback_body) override; + Status SetBreakpointCommandCallback(BreakpointOptions *bp_options, + const char *callback_body) override; void SetBreakpointCommandCallbackFunction(BreakpointOptions *bp_options, const char *function_name) override; /// This one is for deserialization: - Error SetBreakpointCommandCallback( + Status SetBreakpointCommandCallback( BreakpointOptions *bp_options, std::unique_ptr<BreakpointOptions::CommandData> &data_up) override; diff --git a/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp b/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp index 041d827d526b..f1450c31b36b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp @@ -209,7 +209,7 @@ public: using OperationCreationFunc = std::function<FilterRuleSP(bool accept, size_t attribute_index, - const std::string &op_arg, Error &error)>; + const std::string &op_arg, Status &error)>; static void RegisterOperation(const ConstString &operation, const OperationCreationFunc &creation_func) { @@ -218,7 +218,7 @@ public: static FilterRuleSP CreateRule(bool match_accepts, size_t attribute, const ConstString &operation, - const std::string &op_arg, Error &error) { + const std::string &op_arg, Status &error) { // Find the creation func for this type of filter rule. auto map = GetCreationFuncMap(); auto find_it = map.find(operation); @@ -304,7 +304,8 @@ protected: private: static FilterRuleSP CreateOperation(bool accept, size_t attribute_index, - const std::string &op_arg, Error &error) { + const std::string &op_arg, + Status &error) { // We treat the op_arg as a regex. Validate it. if (op_arg.empty()) { error.SetErrorString("regex filter type requires a regex " @@ -358,7 +359,8 @@ protected: private: static FilterRuleSP CreateOperation(bool accept, size_t attribute_index, - const std::string &op_arg, Error &error) { + const std::string &op_arg, + Status &error) { if (op_arg.empty()) { error.SetErrorString("exact match filter type requires an " "argument containing the text that must " @@ -524,9 +526,9 @@ public: m_filter_rules.clear(); } - Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, - ExecutionContext *execution_context) override { - Error error; + Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, + ExecutionContext *execution_context) override { + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -664,8 +666,8 @@ public: bool GetBroadcastEvents() const { return m_broadcast_events; } private: - Error ParseFilterRule(llvm::StringRef rule_text) { - Error error; + Status ParseFilterRule(llvm::StringRef rule_text) { + Status error; if (rule_text.empty()) { error.SetErrorString("invalid rule_text"); @@ -899,7 +901,7 @@ protected: // Send configuration to the feature by way of the process. // Construct the options we will use. auto config_sp = m_options_sp->BuildConfigurationData(m_enable); - const Error error = + const Status error = process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp); // Report results. @@ -1040,7 +1042,7 @@ public: } }; -EnableOptionsSP ParseAutoEnableOptions(Error &error, Debugger &debugger) { +EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger) { // We are abusing the options data model here so that we can parse // options without requiring the Debugger instance. @@ -1212,7 +1214,7 @@ void StructuredDataDarwinLog::HandleArrivalOfStructuredData( // to inspect, including showing backtraces. } -static void SetErrorWithJSON(Error &error, const char *message, +static void SetErrorWithJSON(Status &error, const char *message, StructuredData::Object &object) { if (!message) { error.SetErrorString("Internal error: message not set."); @@ -1226,9 +1228,9 @@ static void SetErrorWithJSON(Error &error, const char *message, error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData()); } -Error StructuredDataDarwinLog::GetDescription( +Status StructuredDataDarwinLog::GetDescription( const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) { - Error error; + Status error; if (!object_sp) { error.SetErrorString("No structured data."); @@ -1483,9 +1485,9 @@ void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) { } } -Error StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info, - Target *target) { - Error error; +Status StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info, + Target *target) { + Status error; // If we're not debugging this launched process, there's nothing for us // to do here. @@ -1815,7 +1817,7 @@ StructuredDataDarwinLog::DumpHeader(Stream &output_stream, } if (options_sp->GetDisplayActivityChain()) { - std::string activity_chain; + llvm::StringRef activity_chain; if (event.GetValueForKeyAsString("activity-chain", activity_chain) && !activity_chain.empty()) { if (header_count > 0) @@ -1854,7 +1856,7 @@ StructuredDataDarwinLog::DumpHeader(Stream &output_stream, } if (options_sp->GetDisplaySubsystem()) { - std::string subsystem; + llvm::StringRef subsystem; if (event.GetValueForKeyAsString("subsystem", subsystem) && !subsystem.empty()) { if (header_count > 0) @@ -1866,7 +1868,7 @@ StructuredDataDarwinLog::DumpHeader(Stream &output_stream, } if (options_sp->GetDisplayCategory()) { - std::string category; + llvm::StringRef category; if (event.GetValueForKeyAsString("category", category) && !category.empty()) { if (header_count > 0) @@ -1899,16 +1901,16 @@ size_t StructuredDataDarwinLog::HandleDisplayOfEvent( size_t total_bytes = 0; // Grab the message content. - std::string message; + llvm::StringRef message; if (!event.GetValueForKeyAsString("message", message)) return true; // Display the log entry. - const auto len = message.length(); + const auto len = message.size(); total_bytes += DumpHeader(stream, event); - stream.Write(message.c_str(), len); + stream.Write(message.data(), len); total_bytes += len; // Add an end of line. @@ -1991,7 +1993,7 @@ void StructuredDataDarwinLog::EnableNow() { // We can run it directly. // Send configuration to the feature by way of the process. - const Error error = + const Status error = process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp); // Report results. diff --git a/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h b/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h index 7eaab127c3f3..77b6e7be71c7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h +++ b/contrib/llvm/tools/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h @@ -67,8 +67,8 @@ public: Process &process, const ConstString &type_name, const StructuredData::ObjectSP &object_sp) override; - Error GetDescription(const StructuredData::ObjectSP &object_sp, - lldb_private::Stream &stream) override; + Status GetDescription(const StructuredData::ObjectSP &object_sp, + lldb_private::Stream &stream) override; bool GetEnabled(const ConstString &type_name) const override; @@ -96,7 +96,8 @@ private: lldb::user_id_t break_id, lldb::user_id_t break_loc_id); - static Error FilterLaunchInfo(ProcessLaunchInfo &launch_info, Target *target); + static Status FilterLaunchInfo(ProcessLaunchInfo &launch_info, + Target *target); // ------------------------------------------------------------------------- // Internal helper methods used by friend classes diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp index 8aec35d09ce5..cb00e840673f 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp @@ -1595,24 +1595,17 @@ TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc, : containing_decl_ctx, type_name_cstr, clang_type, storage, is_inline); - // if (template_param_infos.GetSize() > - // 0) - // { - // clang::FunctionTemplateDecl - // *func_template_decl = - // CreateFunctionTemplateDecl - // (containing_decl_ctx, - // function_decl, - // type_name_cstr, - // template_param_infos); - // - // CreateFunctionTemplateSpecializationInfo - // (function_decl, - // func_template_decl, - // template_param_infos); - // } - // Add the decl to our DIE to decl context map - + if (has_template_params) { + ClangASTContext::TemplateParameterInfos template_param_infos; + ParseTemplateParameterInfos(die, template_param_infos); + clang::FunctionTemplateDecl *func_template_decl = + m_ast.CreateFunctionTemplateDecl( + containing_decl_ctx, function_decl, type_name_cstr, + template_param_infos); + m_ast.CreateFunctionTemplateSpecializationInfo( + function_decl, func_template_decl, template_param_infos); + } + lldbassert(function_decl); if (function_decl) { @@ -1951,6 +1944,19 @@ bool DWARFASTParserClang::ParseTemplateDIE( const dw_tag_t tag = die.Tag(); switch (tag) { + case DW_TAG_GNU_template_parameter_pack: { + template_param_infos.packed_args.reset( + new ClangASTContext::TemplateParameterInfos); + for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid(); + child_die = child_die.GetSibling()) { + if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args)) + return false; + } + if (const char *name = die.GetName()) { + template_param_infos.pack_name = name; + } + return true; + } case DW_TAG_template_type_parameter: case DW_TAG_template_value_parameter: { DWARFAttributes attributes; @@ -2040,6 +2046,7 @@ bool DWARFASTParserClang::ParseTemplateParameterInfos( switch (tag) { case DW_TAG_template_type_parameter: case DW_TAG_template_value_parameter: + case DW_TAG_GNU_template_parameter_pack: ParseTemplateDIE(die, template_param_infos); break; @@ -3450,6 +3457,7 @@ size_t DWARFASTParserClang::ParseChildParameters( case DW_TAG_template_type_parameter: case DW_TAG_template_value_parameter: + case DW_TAG_GNU_template_parameter_pack: // The one caller of this was never using the template_param_infos, // and the local variable was taking up a large amount of stack space // in SymbolFileDWARF::ParseType() so this was removed. If we ever need diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserOCaml.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserOCaml.cpp index 2e5be393dea2..3b1466df21b0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserOCaml.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserOCaml.cpp @@ -8,8 +8,8 @@ #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/Type.h" #include "lldb/Symbol/TypeList.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp index ef499a6d5615..fc97a76de59b 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFCompileUnit.cpp @@ -135,8 +135,9 @@ size_t DWARFCompileUnit::ExtractDIEsIfNeeded(bool cu_die_only) { if ((cu_die_only && initial_die_array_size > 0) || initial_die_array_size > 1) return 0; // Already parsed + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "%8.8x: DWARFCompileUnit::ExtractDIEsIfNeeded( cu_die_only = %i )", m_offset, cu_die_only); diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp index d571c512658e..e923225f1d98 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAranges.cpp @@ -110,7 +110,8 @@ void DWARFDebugAranges::AppendRange(dw_offset_t offset, dw_addr_t low_pc, } void DWARFDebugAranges::Sort(bool minimize) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s this = %p", LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_ARANGES)); diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp index e00eda4f35c5..8d87c201eceb 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp @@ -202,7 +202,7 @@ bool DWARFDebugInfoEntry::Extract(SymbolFileDWARF *dwarf2Data, const uint32_t cu_end_offset = cu->GetNextCompileUnitOffset(); lldb::offset_t offset = *offset_ptr; // if (offset >= cu_end_offset) - // Log::Error("DIE at offset 0x%8.8x is beyond the end of the current + // Log::Status("DIE at offset 0x%8.8x is beyond the end of the current // compile unit (0x%8.8x)", m_offset, cu_end_offset); if ((offset < cu_end_offset) && debug_info_data.ValidOffset(offset)) { m_offset = offset; @@ -1647,6 +1647,8 @@ bool DWARFDebugInfoEntry::LookupAddress(const dw_addr_t address, break; case DW_TAG_template_value_parameter: break; + case DW_TAG_GNU_template_parameter_pack: + break; case DW_TAG_thrown_type: break; case DW_TAG_try_block: diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp index 077675be2271..67d8828c4516 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp @@ -484,9 +484,9 @@ bool DWARFDebugLine::ParseStatementTable( const dw_offset_t debug_line_offset = *offset_ptr; + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, - "DWARFDebugLine::ParseStatementTable (.debug_line[0x%8.8x])", + func_cat, "DWARFDebugLine::ParseStatementTable (.debug_line[0x%8.8x])", debug_line_offset); if (!ParsePrologue(debug_line_data, offset_ptr, prologue.get())) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp index 81e27f2bc95e..04bc2f497075 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnames.cpp @@ -25,7 +25,8 @@ using namespace lldb_private; DWARFDebugPubnames::DWARFDebugPubnames() : m_sets() {} bool DWARFDebugPubnames::Extract(const DWARFDataExtractor &data) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "DWARFDebugPubnames::Extract (byte_size = %" PRIu64 ")", (uint64_t)data.GetByteSize()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_PUBNAMES)); @@ -52,7 +53,8 @@ bool DWARFDebugPubnames::Extract(const DWARFDataExtractor &data) { } bool DWARFDebugPubnames::GeneratePubnames(SymbolFileDWARF *dwarf2Data) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "DWARFDebugPubnames::GeneratePubnames (data = %p)", static_cast<void *>(dwarf2Data)); diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp index f0d66720c55c..2ff0fe3aac41 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/DWARFDefines.cpp @@ -610,6 +610,8 @@ DW_TAG_CategoryEnum get_tag_category(uint16_t tag) { return TagCategoryType; case DW_TAG_template_value_parameter: return TagCategoryType; + case DW_TAG_GNU_template_parameter_pack: + return TagCategoryType; case DW_TAG_thrown_type: return TagCategoryType; case DW_TAG_try_block: diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp index ad6af8dfebd5..279efe320a46 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp @@ -666,8 +666,9 @@ const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const { DWARFDebugInfo *SymbolFileDWARF::DebugInfo() { if (m_info.get() == NULL) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s this = %p", - LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, + static_cast<void *>(this)); if (get_debug_info_data().GetByteSize() > 0) { m_info.reset(new DWARFDebugInfo()); if (m_info.get()) { @@ -703,8 +704,9 @@ SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) { DWARFDebugRanges *SymbolFileDWARF::DebugRanges() { if (m_ranges.get() == NULL) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s this = %p", - LLVM_PRETTY_FUNCTION, static_cast<void *>(this)); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, + static_cast<void *>(this)); if (get_debug_ranges_data().GetByteSize() > 0) { m_ranges.reset(new DWARFDebugRanges()); if (m_ranges.get()) @@ -1599,7 +1601,7 @@ void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() { dwo_module_spec.GetArchitecture() = m_obj_file->GetModule()->GetArchitecture(); // printf ("Loading dwo = '%s'\n", dwo_path); - Error error = ModuleList::GetSharedModule( + Status error = ModuleList::GetSharedModule( dwo_module_spec, module_sp, NULL, NULL, NULL); if (!module_sp) { GetObjectFile()->GetModule()->ReportWarning( @@ -1637,7 +1639,7 @@ SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() { if (var_sp && !var_sp->GetLocationIsConstantValueData()) { const DWARFExpression &location = var_sp->LocationExpression(); Value location_result; - Error error; + Status error; if (location.Evaluate(nullptr, nullptr, nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr, location_result, &error)) { @@ -1666,10 +1668,12 @@ SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() { uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "SymbolFileDWARF::" - "ResolveSymbolContext (so_addr = { " - "section = %p, offset = 0x%" PRIx64 - " }, resolve_scope = 0x%8.8x)", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, + "SymbolFileDWARF::" + "ResolveSymbolContext (so_addr = { " + "section = %p, offset = 0x%" PRIx64 + " }, resolve_scope = 0x%8.8x)", static_cast<void *>(so_addr.GetSection().get()), so_addr.GetOffset(), resolve_scope); uint32_t resolved = 0; @@ -1927,8 +1931,9 @@ void SymbolFileDWARF::Index() { if (m_indexed) return; m_indexed = true; + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, "SymbolFileDWARF::Index (%s)", + func_cat, "SymbolFileDWARF::Index (%s)", GetObjectFile()->GetFileSpec().GetFilename().AsCString("<Unknown>")); DWARFDebugInfo *debug_info = DebugInfo(); @@ -2390,8 +2395,8 @@ SymbolFileDWARF::FindFunctions(const ConstString &name, const CompilerDeclContext *parent_decl_ctx, uint32_t name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "SymbolFileDWARF::FindFunctions (name = '%s')", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')", name.AsCString()); // eFunctionNameTypeAuto should be pre-resolved by a call to @@ -2670,8 +2675,8 @@ SymbolFileDWARF::FindFunctions(const ConstString &name, uint32_t SymbolFileDWARF::FindFunctions(const RegularExpression ®ex, bool include_inlines, bool append, SymbolContextList &sc_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "SymbolFileDWARF::FindFunctions (regex = '%s')", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')", regex.GetText().str().c_str()); Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp index 45519663f71f..ad009a02a2aa 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp @@ -991,7 +991,8 @@ uint32_t SymbolFileDWARFDebugMap::FindFunctions( const ConstString &name, const CompilerDeclContext *parent_decl_ctx, uint32_t name_type_mask, bool include_inlines, bool append, SymbolContextList &sc_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolFileDWARFDebugMap::FindFunctions (name = %s)", name.GetCString()); @@ -1018,7 +1019,8 @@ uint32_t SymbolFileDWARFDebugMap::FindFunctions(const RegularExpression ®ex, bool include_inlines, bool append, SymbolContextList &sc_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolFileDWARFDebugMap::FindFunctions (regex = '%s')", regex.GetText().str().c_str()); @@ -1044,7 +1046,8 @@ uint32_t SymbolFileDWARFDebugMap::FindFunctions(const RegularExpression ®ex, size_t SymbolFileDWARFDebugMap::GetTypes(SymbolContextScope *sc_scope, uint32_t type_mask, TypeList &type_list) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolFileDWARFDebugMap::GetTypes (type_mask = 0x%8.8x)", type_mask); diff --git a/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp b/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp index 363fba2b0bba..5a377d7b04f7 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/SymbolVendor/ELF/SymbolVendorELF.cpp @@ -92,8 +92,8 @@ SymbolVendorELF::CreateInstance(const lldb::ModuleSP &module_sp, if (file_spec_list.IsEmpty()) return NULL; - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "SymbolVendorELF::CreateInstance (module = %s)", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "SymbolVendorELF::CreateInstance (module = %s)", module_sp->GetFileSpec().GetPath().c_str()); for (size_t idx = 0; idx < file_spec_list.GetSize(); ++idx) { diff --git a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp index 84e16991cce1..3976f40dd8d1 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp @@ -21,8 +21,8 @@ #include "lldb/Target/Thread.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" using namespace lldb; @@ -37,7 +37,7 @@ bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly( std::vector<uint8_t> function_text(range.GetByteSize()); ProcessSP process_sp(thread.GetProcess()); if (process_sp) { - Error error; + Status error; const bool prefer_file_cache = true; if (process_sp->GetTarget().ReadMemory( range.GetBaseAddress(), prefer_file_cache, function_text.data(), diff --git a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp index e72097474097..c171f0f4d2a0 100644 --- a/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp +++ b/contrib/llvm/tools/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp @@ -26,7 +26,7 @@ #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/UnwindAssembly.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -54,7 +54,7 @@ bool UnwindAssembly_x86::GetNonCallSiteUnwindPlanFromAssembly( return false; const bool prefer_file_cache = true; std::vector<uint8_t> function_text(func.GetByteSize()); - Error error; + Status error; if (process_sp->GetTarget().ReadMemory( func.GetBaseAddress(), prefer_file_cache, function_text.data(), func.GetByteSize(), error) == func.GetByteSize()) { @@ -161,7 +161,7 @@ bool UnwindAssembly_x86::AugmentUnwindPlanFromCallSite( return false; const bool prefer_file_cache = true; std::vector<uint8_t> function_text(func.GetByteSize()); - Error error; + Status error; if (process_sp->GetTarget().ReadMemory( func.GetBaseAddress(), prefer_file_cache, function_text.data(), func.GetByteSize(), error) == func.GetByteSize()) { @@ -192,7 +192,7 @@ bool UnwindAssembly_x86::GetFastUnwindPlan(AddressRange &func, Thread &thread, if (process_sp) { Target &target(process_sp->GetTarget()); const bool prefer_file_cache = true; - Error error; + Status error; if (target.ReadMemory(func.GetBaseAddress(), prefer_file_cache, opcode_data.data(), 4, error) == 4) { uint8_t i386_push_mov[] = {0x55, 0x89, 0xe5}; @@ -228,7 +228,7 @@ bool UnwindAssembly_x86::FirstNonPrologueInsn( const bool prefer_file_cache = true; std::vector<uint8_t> function_text(func.GetByteSize()); - Error error; + Status error; if (target->ReadMemory(func.GetBaseAddress(), prefer_file_cache, function_text.data(), func.GetByteSize(), error) == func.GetByteSize()) { diff --git a/contrib/llvm/tools/lldb/source/Symbol/ClangASTContext.cpp b/contrib/llvm/tools/lldb/source/Symbol/ClangASTContext.cpp index ac1bbb53cdf8..8b837b79bed8 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/ClangASTContext.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/ClangASTContext.cpp @@ -1394,6 +1394,12 @@ CompilerType ClangASTContext::CreateRecordType(DeclContext *decl_ctx, return CompilerType(); } +namespace { + bool IsValueParam(const clang::TemplateArgument &argument) { + return argument.getKind() == TemplateArgument::Integral; + } +} + static TemplateParameterList *CreateTemplateParameterList( ASTContext *ast, const ClangASTContext::TemplateParameterInfos &template_param_infos, @@ -1401,31 +1407,51 @@ static TemplateParameterList *CreateTemplateParameterList( const bool parameter_pack = false; const bool is_typename = false; const unsigned depth = 0; - const size_t num_template_params = template_param_infos.GetSize(); + const size_t num_template_params = template_param_infos.args.size(); + DeclContext *const decl_context = + ast->getTranslationUnitDecl(); // Is this the right decl context?, for (size_t i = 0; i < num_template_params; ++i) { const char *name = template_param_infos.names[i]; IdentifierInfo *identifier_info = nullptr; if (name && name[0]) identifier_info = &ast->Idents.get(name); - if (template_param_infos.args[i].getKind() == TemplateArgument::Integral) { + if (IsValueParam(template_param_infos.args[i])) { template_param_decls.push_back(NonTypeTemplateParmDecl::Create( - *ast, - ast->getTranslationUnitDecl(), // Is this the right decl context?, - // SourceLocation StartLoc, + *ast, decl_context, SourceLocation(), SourceLocation(), depth, i, identifier_info, template_param_infos.args[i].getIntegralType(), parameter_pack, nullptr)); } else { template_param_decls.push_back(TemplateTypeParmDecl::Create( - *ast, - ast->getTranslationUnitDecl(), // Is this the right decl context? + *ast, decl_context, SourceLocation(), SourceLocation(), depth, i, identifier_info, is_typename, parameter_pack)); } } - + + if (template_param_infos.packed_args && + template_param_infos.packed_args->args.size()) { + IdentifierInfo *identifier_info = nullptr; + if (template_param_infos.pack_name && template_param_infos.pack_name[0]) + identifier_info = &ast->Idents.get(template_param_infos.pack_name); + const bool parameter_pack_true = true; + if (IsValueParam(template_param_infos.packed_args->args[0])) { + template_param_decls.push_back(NonTypeTemplateParmDecl::Create( + *ast, decl_context, + SourceLocation(), SourceLocation(), depth, num_template_params, + identifier_info, + template_param_infos.packed_args->args[0].getIntegralType(), + parameter_pack_true, nullptr)); + } else { + template_param_decls.push_back(TemplateTypeParmDecl::Create( + *ast, decl_context, + SourceLocation(), SourceLocation(), depth, num_template_params, + identifier_info, + is_typename, parameter_pack_true)); + } + } clang::Expr *const requires_clause = nullptr; // TODO: Concepts TemplateParameterList *template_param_list = TemplateParameterList::Create( *ast, SourceLocation(), SourceLocation(), template_param_decls, @@ -1535,10 +1561,19 @@ ClangASTContext::CreateClassTemplateSpecializationDecl( DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind, const TemplateParameterInfos &template_param_infos) { ASTContext *ast = getASTContext(); + llvm::SmallVector<clang::TemplateArgument, 2> args( + template_param_infos.args.size() + + (template_param_infos.packed_args ? 1 : 0)); + std::copy(template_param_infos.args.begin(), template_param_infos.args.end(), + args.begin()); + if (template_param_infos.packed_args) { + args[args.size() - 1] = TemplateArgument::CreatePackCopy( + *ast, template_param_infos.packed_args->args); + } ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create( *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(), - SourceLocation(), class_template_decl, template_param_infos.args, + SourceLocation(), class_template_decl, args, nullptr); class_template_specialization_decl->setSpecializationKind( @@ -4458,7 +4493,7 @@ ClangASTContext::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) { case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = - qual_type->getAsObjCInterfacePointerType(); + qual_type->getAs<clang::ObjCObjectPointerType>(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && @@ -4567,7 +4602,7 @@ ClangASTContext::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type, case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = - qual_type->getAsObjCInterfacePointerType(); + qual_type->getAs<clang::ObjCObjectPointerType>(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && @@ -5636,7 +5671,7 @@ uint32_t ClangASTContext::GetNumFields(lldb::opaque_compiler_type_t type) { case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = - qual_type->getAsObjCInterfacePointerType(); + qual_type->getAs<clang::ObjCObjectPointerType>(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && @@ -5784,7 +5819,7 @@ CompilerType ClangASTContext::GetFieldAtIndex(lldb::opaque_compiler_type_t type, case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = - qual_type->getAsObjCInterfacePointerType(); + qual_type->getAs<clang::ObjCObjectPointerType>(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && @@ -6398,7 +6433,7 @@ CompilerType ClangASTContext::GetChildCompilerTypeAtIndex( if (base_class->isVirtual()) { bool handled = false; if (valobj) { - Error err; + Status err; AddressType addr_type = eAddressTypeInvalid; lldb::addr_t vtable_ptr_addr = valobj->GetCPPVTableAddress(addr_type); @@ -8792,7 +8827,7 @@ ClangASTContext::ConvertStringToFloatValue(lldb::opaque_compiler_type_t type, if (dst_size >= byte_size) { Scalar scalar = ap_float.bitcastToAPInt().zextOrTrunc( llvm::NextPowerOf2(byte_size) * 8); - lldb_private::Error get_data_error; + lldb_private::Status get_data_error; if (scalar.GetAsMemoryData(dst, byte_size, lldb_private::endian::InlHostByteOrder(), get_data_error)) @@ -9361,7 +9396,7 @@ void ClangASTContext::DumpSummary(lldb::opaque_compiler_type_t type, buf.back() = '\0'; size_t bytes_read; size_t total_cstr_len = 0; - Error error; + Status error; while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(), buf.size(), error)) > 0) { const size_t len = strlen((const char *)&buf.front()); diff --git a/contrib/llvm/tools/lldb/source/Symbol/CompactUnwindInfo.cpp b/contrib/llvm/tools/lldb/source/Symbol/CompactUnwindInfo.cpp index 77fcd33bbb3b..bc367496003e 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/CompactUnwindInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/CompactUnwindInfo.cpp @@ -272,7 +272,7 @@ void CompactUnwindInfo::ScanIndex(const ProcessSP &process_sp) { return; m_section_contents_if_encrypted.reset( new DataBufferHeap(m_section_sp->GetByteSize(), 0)); - Error error; + Status error; if (process_sp->ReadMemory( m_section_sp->GetLoadBaseAddress(&process_sp->GetTarget()), m_section_contents_if_encrypted->GetBytes(), @@ -836,7 +836,7 @@ bool CompactUnwindInfo::CreateUnwindPlan_x86_64(Target &target, if (process_sp) { Address subl_payload_addr(function_info.valid_range_offset_start, sl); subl_payload_addr.Slide(offset_to_subl_insn); - Error error; + Status error; uint64_t large_stack_size = process_sp->ReadUnsignedIntegerFromMemory( subl_payload_addr.GetLoadAddress(&target), 4, 0, error); if (large_stack_size != 0 && error.Success()) { @@ -1100,7 +1100,7 @@ bool CompactUnwindInfo::CreateUnwindPlan_i386(Target &target, if (process_sp) { Address subl_payload_addr(function_info.valid_range_offset_start, sl); subl_payload_addr.Slide(offset_to_subl_insn); - Error error; + Status error; uint64_t large_stack_size = process_sp->ReadUnsignedIntegerFromMemory( subl_payload_addr.GetLoadAddress(&target), 4, 0, error); if (large_stack_size != 0 && error.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Symbol/CompilerType.cpp b/contrib/llvm/tools/lldb/source/Symbol/CompilerType.cpp index cc33dc196226..e3880af27f22 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/CompilerType.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/CompilerType.cpp @@ -1004,7 +1004,7 @@ bool CompilerType::ReadFromMemory(lldb_private::ExecutionContext *exe_ctx, if (exe_ctx) process = exe_ctx->GetProcessPtr(); if (process) { - Error error; + Status error; return process->ReadMemory(addr, dst, byte_size, error) == byte_size; } } @@ -1039,7 +1039,7 @@ bool CompilerType::WriteToMemory(lldb_private::ExecutionContext *exe_ctx, if (exe_ctx) process = exe_ctx->GetProcessPtr(); if (process) { - Error error; + Status error; return process->WriteMemory(addr, new_value.GetData(), byte_size, error) == byte_size; } diff --git a/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp b/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp index d229e880d97d..015ecd856aa8 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/DWARFCallFrameInfo.cpp @@ -419,7 +419,8 @@ void DWARFCallFrameInfo::GetFDEIndex() { if (m_fde_index_initialized) // if two threads hit the locker return; - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s - %s", LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s - %s", LLVM_PRETTY_FUNCTION, m_objfile.GetFileSpec().GetFilename().AsCString("")); bool clear_address_zeroth_bit = false; diff --git a/contrib/llvm/tools/lldb/source/Symbol/JavaASTContext.cpp b/contrib/llvm/tools/lldb/source/Symbol/JavaASTContext.cpp index ac029dfe5dc8..ae4e9d5134b5 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/JavaASTContext.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/JavaASTContext.cpp @@ -137,7 +137,7 @@ public: if (m_dynamic_type_id.Evaluate(exe_ctx->GetBestExecutionContextScope(), nullptr, nullptr, 0, &obj_load_address, nullptr, result, nullptr)) { - Error error; + Status error; lldb::addr_t type_id_addr = result.GetScalar().UInt(); lldb::ProcessSP process_sp = exe_ctx->GetProcessSP(); @@ -303,7 +303,7 @@ public: if (!m_length_expression.IsValid()) return UINT32_MAX; - Error error; + Status error; ValueObjectSP address_obj = value_obj->AddressOf(error); if (error.Fail()) return UINT32_MAX; diff --git a/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp b/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp index 483a315defbd..c970de6fef06 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/ObjectFile.cpp @@ -37,8 +37,9 @@ ObjectFile::FindPlugin(const lldb::ModuleSP &module_sp, const FileSpec *file, ObjectFileSP object_file_sp; if (module_sp) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); Timer scoped_timer( - LLVM_PRETTY_FUNCTION, + func_cat, "ObjectFile::FindPlugin (module = %s, file = %p, file_offset = " "0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")", module_sp->GetFileSpec().GetPath().c_str(), @@ -176,9 +177,11 @@ ObjectFileSP ObjectFile::FindPlugin(const lldb::ModuleSP &module_sp, ObjectFileSP object_file_sp; if (module_sp) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "ObjectFile::FindPlugin (module = " - "%s, process = %p, header_addr = " - "0x%" PRIx64 ")", + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, + "ObjectFile::FindPlugin (module = " + "%s, process = %p, header_addr = " + "0x%" PRIx64 ")", module_sp->GetFileSpec().GetPath().c_str(), static_cast<void *>(process_sp.get()), header_addr); uint32_t idx; @@ -454,7 +457,7 @@ DataBufferSP ObjectFile::ReadMemory(const ProcessSP &process_sp, DataBufferSP data_sp; if (process_sp) { std::unique_ptr<DataBufferHeap> data_ap(new DataBufferHeap(byte_size, 0)); - Error error; + Status error; const size_t bytes_read = process_sp->ReadMemory( addr, data_ap->GetBytes(), data_ap->GetByteSize(), error); if (bytes_read == byte_size) @@ -493,7 +496,7 @@ size_t ObjectFile::ReadSectionData(const Section *section, if (IsInMemory()) { ProcessSP process_sp(m_process_wp.lock()); if (process_sp) { - Error error; + Status error; const addr_t base_load_addr = section->GetLoadBaseAddress(&process_sp->GetTarget()); if (base_load_addr != LLDB_INVALID_ADDRESS) @@ -654,17 +657,17 @@ ConstString ObjectFile::GetNextSyntheticSymbolName() { return ConstString(ss.GetString()); } -Error ObjectFile::LoadInMemory(Target &target, bool set_pc) { - Error error; +Status ObjectFile::LoadInMemory(Target &target, bool set_pc) { + Status error; ProcessSP process = target.CalculateProcess(); if (!process) - return Error("No Process"); + return Status("No Process"); if (set_pc && !GetEntryPointAddress().IsValid()) - return Error("No entry address in object file"); + return Status("No entry address in object file"); SectionList *section_list = GetSectionList(); if (!section_list) - return Error("No section in object file"); + return Status("No section in object file"); size_t section_count = section_list->GetNumSections(0); for (size_t i = 0; i < section_count; ++i) { SectionSP section_sp = section_list->GetSectionAtIndex(i); diff --git a/contrib/llvm/tools/lldb/source/Symbol/SymbolContext.cpp b/contrib/llvm/tools/lldb/source/Symbol/SymbolContext.cpp index d99bfc609261..5ea6f91200c1 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/SymbolContext.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/SymbolContext.cpp @@ -735,7 +735,7 @@ LineEntry SymbolContext::GetFunctionStartLineEntry() const { bool SymbolContext::GetAddressRangeFromHereToEndLine(uint32_t end_line, AddressRange &range, - Error &error) { + Status &error) { if (!line_entry.IsValid()) { error.SetErrorString("Symbol context has no line table."); return false; diff --git a/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp b/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp index e0710aa4e6b9..3eec3e706185 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/Symtab.cpp @@ -220,7 +220,8 @@ void Symtab::InitNameIndexes() { // Protected function, no need to lock mutex... if (!m_name_indexes_computed) { m_name_indexes_computed = true; - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); // Create the name index vector to be able to quickly search by name const size_t num_symbols = m_symbols.size(); #if 1 @@ -433,7 +434,8 @@ void Symtab::AppendSymbolNamesToMap(const IndexCollection &indexes, bool add_demangled, bool add_mangled, NameToIndexMap &name_to_index_map) const { if (add_demangled || add_mangled) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); std::lock_guard<std::recursive_mutex> guard(m_mutex); // Create the name index vector to be able to quickly search by name @@ -595,7 +597,8 @@ void Symtab::SortSymbolIndexesByValue(std::vector<uint32_t> &indexes, bool remove_duplicates) const { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); // No need to sort if we have zero or one items... if (indexes.size() <= 1) return; @@ -621,7 +624,8 @@ uint32_t Symtab::AppendSymbolIndexesWithName(const ConstString &symbol_name, std::vector<uint32_t> &indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); if (symbol_name) { if (!m_name_indexes_computed) InitNameIndexes(); @@ -637,7 +641,8 @@ uint32_t Symtab::AppendSymbolIndexesWithName(const ConstString &symbol_name, std::vector<uint32_t> &indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); if (symbol_name) { const size_t old_size = indexes.size(); if (!m_name_indexes_computed) @@ -766,7 +771,8 @@ Symtab::FindAllSymbolsWithNameAndType(const ConstString &name, std::vector<uint32_t> &symbol_indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); // Initialize all of the lookup by name indexes before converting NAME // to a uniqued string NAME_STR below. if (!m_name_indexes_computed) @@ -785,7 +791,8 @@ size_t Symtab::FindAllSymbolsWithNameAndType( Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); // Initialize all of the lookup by name indexes before converting NAME // to a uniqued string NAME_STR below. if (!m_name_indexes_computed) @@ -817,7 +824,8 @@ Symbol *Symtab::FindFirstSymbolWithNameAndType(const ConstString &name, Visibility symbol_visibility) { std::lock_guard<std::recursive_mutex> guard(m_mutex); - Timer scoped_timer(LLVM_PRETTY_FUNCTION, "%s", LLVM_PRETTY_FUNCTION); + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION); if (!m_name_indexes_computed) InitNameIndexes(); diff --git a/contrib/llvm/tools/lldb/source/Symbol/Type.cpp b/contrib/llvm/tools/lldb/source/Symbol/Type.cpp index 89fc9f974c67..53d9c5cc96a9 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/Type.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/Type.cpp @@ -410,7 +410,7 @@ bool Type::ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t addr, if (exe_ctx) { Process *process = exe_ctx->GetProcessPtr(); if (process) { - Error error; + Status error; return exe_ctx->GetProcessPtr()->ReadMemory(addr, dst, byte_size, error) == byte_size; } diff --git a/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp b/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp index 0d1db1cdeac0..fd19a0994966 100644 --- a/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp +++ b/contrib/llvm/tools/lldb/source/Symbol/Variable.cpp @@ -330,11 +330,11 @@ bool Variable::IsInScope(StackFrame *frame) { return false; } -Error Variable::GetValuesForVariableExpressionPath( +Status Variable::GetValuesForVariableExpressionPath( llvm::StringRef variable_expr_path, ExecutionContextScope *scope, GetVariableCallback callback, void *baton, VariableList &variable_list, ValueObjectList &valobj_list) { - Error error; + Status error; if (!callback || variable_expr_path.empty()) { error.SetErrorString("unknown error"); return error; @@ -350,7 +350,7 @@ Error Variable::GetValuesForVariableExpressionPath( return error; } for (uint32_t i = 0; i < valobj_list.GetSize();) { - Error tmp_error; + Status tmp_error; ValueObjectSP valobj_sp( valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error)); if (tmp_error.Fail()) { @@ -368,7 +368,7 @@ Error Variable::GetValuesForVariableExpressionPath( valobj_list); if (error.Success()) { for (uint32_t i = 0; i < valobj_list.GetSize();) { - Error tmp_error; + Status tmp_error; ValueObjectSP valobj_sp( valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error)); if (tmp_error.Fail()) { diff --git a/contrib/llvm/tools/lldb/source/Target/Language.cpp b/contrib/llvm/tools/lldb/source/Target/Language.cpp index 8fef32a3b186..cde6f8654aec 100644 --- a/contrib/llvm/tools/lldb/source/Target/Language.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Language.cpp @@ -387,7 +387,7 @@ DumpValueObjectOptions::DeclPrintingHelper Language::GetDeclPrintingHelper() { return nullptr; } -LazyBool Language::IsLogicalTrue(ValueObject &valobj, Error &error) { +LazyBool Language::IsLogicalTrue(ValueObject &valobj, Status &error) { return eLazyBoolCalculate; } diff --git a/contrib/llvm/tools/lldb/source/Target/LanguageRuntime.cpp b/contrib/llvm/tools/lldb/source/Target/LanguageRuntime.cpp index d0018b6df114..bd02121f6a4d 100644 --- a/contrib/llvm/tools/lldb/source/Target/LanguageRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Target/LanguageRuntime.cpp @@ -89,7 +89,8 @@ ExceptionSearchFilter::DoCopyForBreakpoint(Breakpoint &breakpoint) { } SearchFilter *ExceptionSearchFilter::CreateFromStructuredData( - Target &target, const StructuredData::Dictionary &data_dict, Error &error) { + Target &target, const StructuredData::Dictionary &data_dict, + Status &error) { SearchFilter *result = nullptr; return result; } diff --git a/contrib/llvm/tools/lldb/source/Target/Memory.cpp b/contrib/llvm/tools/lldb/source/Target/Memory.cpp index c78bd7ad7b34..ced359418682 100644 --- a/contrib/llvm/tools/lldb/source/Target/Memory.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Memory.cpp @@ -129,7 +129,8 @@ bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr, return false; } -size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len, Error &error) { +size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len, + Status &error) { size_t bytes_left = dst_len; // Check the L1 cache for a range that contain the entire memory read. @@ -344,7 +345,7 @@ void AllocatedMemoryCache::Clear() { AllocatedMemoryCache::AllocatedBlockSP AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions, - uint32_t chunk_size, Error &error) { + uint32_t chunk_size, Status &error) { AllocatedBlockSP block_sp; const size_t page_size = 4096; const size_t num_pages = (byte_size + page_size - 1) / page_size; @@ -370,7 +371,7 @@ AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions, lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size, uint32_t permissions, - Error &error) { + Status &error) { std::lock_guard<std::recursive_mutex> guard(m_mutex); addr_t addr = LLDB_INVALID_ADDRESS; diff --git a/contrib/llvm/tools/lldb/source/Target/ModuleCache.cpp b/contrib/llvm/tools/lldb/source/Target/ModuleCache.cpp index a4aa26a0e480..2b654772639a 100644 --- a/contrib/llvm/tools/lldb/source/Target/ModuleCache.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ModuleCache.cpp @@ -54,7 +54,7 @@ private: FileSpec m_file_spec; public: - ModuleLock(const FileSpec &root_dir_spec, const UUID &uuid, Error &error); + ModuleLock(const FileSpec &root_dir_spec, const UUID &uuid, Status &error); void Delete(); }; @@ -64,7 +64,7 @@ static FileSpec JoinPath(const FileSpec &path1, const char *path2) { return result_spec; } -static Error MakeDirectory(const FileSpec &dir_path) { +static Status MakeDirectory(const FileSpec &dir_path) { namespace fs = llvm::sys::fs; return fs::create_directories(dir_path.GetPath(), true, fs::perms::owner_all); @@ -92,7 +92,7 @@ void DeleteExistingModule(const FileSpec &root_dir_spec, if (!module_uuid.IsValid()) return; - Error error; + Status error; ModuleLock lock(root_dir_spec, module_uuid, error); if (error.Fail()) { if (log) @@ -125,17 +125,17 @@ void DecrementRefExistingModule(const FileSpec &root_dir_spec, llvm::sys::fs::remove(symfile_spec.GetPath()); } -Error CreateHostSysRootModuleLink(const FileSpec &root_dir_spec, - const char *hostname, - const FileSpec &platform_module_spec, - const FileSpec &local_module_spec, - bool delete_existing) { +Status CreateHostSysRootModuleLink(const FileSpec &root_dir_spec, + const char *hostname, + const FileSpec &platform_module_spec, + const FileSpec &local_module_spec, + bool delete_existing) { const auto sysroot_module_path_spec = JoinPath(JoinPath(root_dir_spec, hostname), platform_module_spec.GetPath().c_str()); if (sysroot_module_path_spec.Exists()) { if (!delete_existing) - return Error(); + return Status(); DecrementRefExistingModule(root_dir_spec, sysroot_module_path_spec); } @@ -152,7 +152,7 @@ Error CreateHostSysRootModuleLink(const FileSpec &root_dir_spec, } // namespace ModuleLock::ModuleLock(const FileSpec &root_dir_spec, const UUID &uuid, - Error &error) { + Status &error) { const auto lock_dir_spec = JoinPath(root_dir_spec, kLockDirName); error = MakeDirectory(lock_dir_spec); if (error.Fail()) @@ -184,9 +184,9 @@ void ModuleLock::Delete() { ///////////////////////////////////////////////////////////////////////// -Error ModuleCache::Put(const FileSpec &root_dir_spec, const char *hostname, - const ModuleSpec &module_spec, const FileSpec &tmp_file, - const FileSpec &target_file) { +Status ModuleCache::Put(const FileSpec &root_dir_spec, const char *hostname, + const ModuleSpec &module_spec, const FileSpec &tmp_file, + const FileSpec &target_file) { const auto module_spec_dir = GetModuleDirectory(root_dir_spec, module_spec.GetUUID()); const auto module_file_path = @@ -196,27 +196,27 @@ Error ModuleCache::Put(const FileSpec &root_dir_spec, const char *hostname, const auto err_code = llvm::sys::fs::rename(tmp_file_path, module_file_path.GetPath()); if (err_code) - return Error("Failed to rename file %s to %s: %s", tmp_file_path.c_str(), - module_file_path.GetPath().c_str(), - err_code.message().c_str()); + return Status("Failed to rename file %s to %s: %s", tmp_file_path.c_str(), + module_file_path.GetPath().c_str(), + err_code.message().c_str()); const auto error = CreateHostSysRootModuleLink( root_dir_spec, hostname, target_file, module_file_path, true); if (error.Fail()) - return Error("Failed to create link to %s: %s", - module_file_path.GetPath().c_str(), error.AsCString()); - return Error(); + return Status("Failed to create link to %s: %s", + module_file_path.GetPath().c_str(), error.AsCString()); + return Status(); } -Error ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname, - const ModuleSpec &module_spec, - ModuleSP &cached_module_sp, bool *did_create_ptr) { +Status ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname, + const ModuleSpec &module_spec, + ModuleSP &cached_module_sp, bool *did_create_ptr) { const auto find_it = m_loaded_modules.find(module_spec.GetUUID().GetAsString()); if (find_it != m_loaded_modules.end()) { cached_module_sp = (*find_it).second.lock(); if (cached_module_sp) - return Error(); + return Status(); m_loaded_modules.erase(find_it); } @@ -226,10 +226,10 @@ Error ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname, module_spec_dir, module_spec.GetFileSpec().GetFilename().AsCString()); if (!module_file_path.Exists()) - return Error("Module %s not found", module_file_path.GetPath().c_str()); + return Status("Module %s not found", module_file_path.GetPath().c_str()); if (module_file_path.GetByteSize() != module_spec.GetObjectSize()) - return Error("Module %s has invalid file size", - module_file_path.GetPath().c_str()); + return Status("Module %s has invalid file size", + module_file_path.GetPath().c_str()); // We may have already cached module but downloaded from an another host - in // this case let's create a link to it. @@ -237,8 +237,8 @@ Error ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname, module_spec.GetFileSpec(), module_file_path, false); if (error.Fail()) - return Error("Failed to create link to %s: %s", - module_file_path.GetPath().c_str(), error.AsCString()); + return Status("Failed to create link to %s: %s", + module_file_path.GetPath().c_str(), error.AsCString()); auto cached_module_spec(module_spec); cached_module_spec.GetUUID().Clear(); // Clear UUID since it may contain md5 @@ -258,16 +258,16 @@ Error ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname, m_loaded_modules.insert( std::make_pair(module_spec.GetUUID().GetAsString(), cached_module_sp)); - return Error(); + return Status(); } -Error ModuleCache::GetAndPut(const FileSpec &root_dir_spec, - const char *hostname, - const ModuleSpec &module_spec, - const ModuleDownloader &module_downloader, - const SymfileDownloader &symfile_downloader, - lldb::ModuleSP &cached_module_sp, - bool *did_create_ptr) { +Status ModuleCache::GetAndPut(const FileSpec &root_dir_spec, + const char *hostname, + const ModuleSpec &module_spec, + const ModuleDownloader &module_downloader, + const SymfileDownloader &symfile_downloader, + lldb::ModuleSP &cached_module_sp, + bool *did_create_ptr) { const auto module_spec_dir = GetModuleDirectory(root_dir_spec, module_spec.GetUUID()); auto error = MakeDirectory(module_spec_dir); @@ -276,9 +276,9 @@ Error ModuleCache::GetAndPut(const FileSpec &root_dir_spec, ModuleLock lock(root_dir_spec, module_spec.GetUUID(), error); if (error.Fail()) - return Error("Failed to lock module %s: %s", - module_spec.GetUUID().GetAsString().c_str(), - error.AsCString()); + return Status("Failed to lock module %s: %s", + module_spec.GetUUID().GetAsString().c_str(), + error.AsCString()); const auto escaped_hostname(GetEscapedHostname(hostname)); // Check local cache for a module. @@ -291,13 +291,13 @@ Error ModuleCache::GetAndPut(const FileSpec &root_dir_spec, error = module_downloader(module_spec, tmp_download_file_spec); llvm::FileRemover tmp_file_remover(tmp_download_file_spec.GetPath()); if (error.Fail()) - return Error("Failed to download module: %s", error.AsCString()); + return Status("Failed to download module: %s", error.AsCString()); // Put downloaded file into local module cache. error = Put(root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_file_spec, module_spec.GetFileSpec()); if (error.Fail()) - return Error("Failed to put module into cache: %s", error.AsCString()); + return Status("Failed to put module into cache: %s", error.AsCString()); tmp_file_remover.releaseFile(); error = Get(root_dir_spec, escaped_hostname.c_str(), module_spec, @@ -315,17 +315,18 @@ Error ModuleCache::GetAndPut(const FileSpec &root_dir_spec, // module might // contain the necessary symbols and the debugging is also possible without // a symfile. - return Error(); + return Status(); error = Put(root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_sym_file_spec, GetSymbolFileSpec(module_spec.GetFileSpec())); if (error.Fail()) - return Error("Failed to put symbol file into cache: %s", error.AsCString()); + return Status("Failed to put symbol file into cache: %s", + error.AsCString()); tmp_symfile_remover.releaseFile(); FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec()); cached_module_sp->SetSymbolFileFileSpec(symfile_spec); - return Error(); + return Status(); } diff --git a/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp b/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp index 6aeb4c46df48..165c75a0952b 100644 --- a/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ObjCLanguageRuntime.cpp @@ -250,7 +250,7 @@ ObjCLanguageRuntime::GetClassDescriptor(ValueObject &valobj) { Process *process = exe_ctx.GetProcessPtr(); if (process) { - Error error; + Status error; ObjCISA isa = process->ReadPointerFromMemory(isa_pointer, error); if (isa != LLDB_INVALID_ADDRESS) objc_class_sp = GetClassDescriptorFromISA(isa); @@ -377,9 +377,9 @@ bool ObjCLanguageRuntime::ObjCExceptionPrecondition::EvaluatePrecondition( void ObjCLanguageRuntime::ObjCExceptionPrecondition::GetDescription( Stream &stream, lldb::DescriptionLevel level) {} -Error ObjCLanguageRuntime::ObjCExceptionPrecondition::ConfigurePrecondition( +Status ObjCLanguageRuntime::ObjCExceptionPrecondition::ConfigurePrecondition( Args &args) { - Error error; + Status error; if (args.GetArgumentCount() > 0) error.SetErrorString( "The ObjC Exception breakpoint doesn't support extra options."); diff --git a/contrib/llvm/tools/lldb/source/Target/PathMappingList.cpp b/contrib/llvm/tools/lldb/source/Target/PathMappingList.cpp index 4fbaee98da61..b834a3600d0b 100644 --- a/contrib/llvm/tools/lldb/source/Target/PathMappingList.cpp +++ b/contrib/llvm/tools/lldb/source/Target/PathMappingList.cpp @@ -16,8 +16,8 @@ // Project includes #include "lldb/Host/PosixApi.h" #include "lldb/Target/PathMappingList.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" using namespace lldb; diff --git a/contrib/llvm/tools/lldb/source/Target/Platform.cpp b/contrib/llvm/tools/lldb/source/Target/Platform.cpp index fd909075a240..cfd971e9de62 100644 --- a/contrib/llvm/tools/lldb/source/Target/Platform.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Platform.cpp @@ -39,9 +39,9 @@ #include "lldb/Target/Target.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/DataBufferHeap.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" #include "llvm/Support/FileSystem.h" @@ -170,11 +170,11 @@ void Platform::SetHostPlatform(const lldb::PlatformSP &platform_sp) { } } -Error Platform::GetFileWithUUID(const FileSpec &platform_file, - const UUID *uuid_ptr, FileSpec &local_file) { +Status Platform::GetFileWithUUID(const FileSpec &platform_file, + const UUID *uuid_ptr, FileSpec &local_file) { // Default to the local case local_file = platform_file; - return Error(); + return Status(); } FileSpecList @@ -217,11 +217,11 @@ Platform::LocateExecutableScriptingResources(Target *target, Module &module, // return PlatformSP(); //} -Error Platform::GetSharedModule(const ModuleSpec &module_spec, Process *process, - ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - ModuleSP *old_module_sp_ptr, - bool *did_create_ptr) { +Status Platform::GetSharedModule(const ModuleSpec &module_spec, + Process *process, ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, + ModuleSP *old_module_sp_ptr, + bool *did_create_ptr) { if (IsHost()) return ModuleList::GetSharedModule( module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr, @@ -229,7 +229,7 @@ Error Platform::GetSharedModule(const ModuleSpec &module_spec, Process *process, return GetRemoteSharedModule(module_spec, process, module_sp, [&](const ModuleSpec &spec) { - Error error = ModuleList::GetSharedModule( + Status error = ModuleList::GetSharedModule( spec, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr, false); if (error.Success() && module_sp) @@ -267,7 +267,7 @@ PlatformSP Platform::Find(const ConstString &name) { return PlatformSP(); } -PlatformSP Platform::Create(const ConstString &name, Error &error) { +PlatformSP Platform::Create(const ConstString &name, Status &error) { PlatformCreateInstance create_callback = nullptr; lldb::PlatformSP platform_sp; if (name) { @@ -295,7 +295,7 @@ PlatformSP Platform::Create(const ConstString &name, Error &error) { } PlatformSP Platform::Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr, - Error &error) { + Status &error) { lldb::PlatformSP platform_sp; if (arch.IsValid()) { // Scope for locker @@ -540,7 +540,7 @@ FileSpec Platform::GetWorkingDirectory() { struct RecurseCopyBaton { const FileSpec &dst; Platform *platform_ptr; - Error error; + Status error; }; static FileSpec::EnumerateDirectoryResult @@ -560,7 +560,7 @@ RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, FileSpec dst_dir = rc_baton->dst; if (!dst_dir.GetFilename()) dst_dir.GetFilename() = src.GetLastPathComponent(); - Error error = rc_baton->platform_ptr->MakeDirectory( + Status error = rc_baton->platform_ptr->MakeDirectory( dst_dir, lldb::eFilePermissionsDirectoryDefault); if (error.Fail()) { rc_baton->error.SetErrorStringWithFormat( @@ -575,7 +575,8 @@ RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, // when we enumerate we can quickly fill in the filename for dst copies FileSpec recurse_dst; recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str()); - RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr, Error()}; + RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr, + Status()}; FileSpec::EnumerateDirectory(src_dir_path, true, true, true, RecurseCopy_Callback, &rc_baton2); if (rc_baton2.error.Fail()) { @@ -612,7 +613,7 @@ RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, FileSpec dst_file = rc_baton->dst; if (!dst_file.GetFilename()) dst_file.GetFilename() = src.GetFilename(); - Error err = rc_baton->platform_ptr->PutFile(src, dst_file); + Status err = rc_baton->platform_ptr->PutFile(src, dst_file); if (err.Fail()) { rc_baton->error.SetErrorString(err.AsCString()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out @@ -629,8 +630,8 @@ RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, llvm_unreachable("Unhandled file_type!"); } -Error Platform::Install(const FileSpec &src, const FileSpec &dst) { - Error error; +Status Platform::Install(const FileSpec &src, const FileSpec &dst) { + Status error; Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) @@ -708,7 +709,7 @@ Error Platform::Install(const FileSpec &src, const FileSpec &dst) { FileSpec recurse_dst; recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString()); std::string src_dir_path(src.GetPath()); - RecurseCopyBaton baton = {recurse_dst, this, Error()}; + RecurseCopyBaton baton = {recurse_dst, this, Status()}; FileSpec::EnumerateDirectory(src_dir_path, true, true, true, RecurseCopy_Callback, &baton); return baton.error; @@ -757,11 +758,12 @@ bool Platform::SetWorkingDirectory(const FileSpec &file_spec) { } } -Error Platform::MakeDirectory(const FileSpec &file_spec, uint32_t permissions) { +Status Platform::MakeDirectory(const FileSpec &file_spec, + uint32_t permissions) { if (IsHost()) return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions); else { - Error error; + Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); @@ -769,15 +771,15 @@ Error Platform::MakeDirectory(const FileSpec &file_spec, uint32_t permissions) { } } -Error Platform::GetFilePermissions(const FileSpec &file_spec, - uint32_t &file_permissions) { +Status Platform::GetFilePermissions(const FileSpec &file_spec, + uint32_t &file_permissions) { if (IsHost()) { auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath()); if (Value) file_permissions = Value.get(); - return Error(Value.getError()); + return Status(Value.getError()); } else { - Error error; + Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); @@ -785,13 +787,13 @@ Error Platform::GetFilePermissions(const FileSpec &file_spec, } } -Error Platform::SetFilePermissions(const FileSpec &file_spec, - uint32_t file_permissions) { +Status Platform::SetFilePermissions(const FileSpec &file_spec, + uint32_t file_permissions) { if (IsHost()) { auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions); return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms); } else { - Error error; + Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); @@ -877,10 +879,11 @@ bool Platform::SetOSVersion(uint32_t major, uint32_t minor, uint32_t update) { return false; } -Error Platform::ResolveExecutable(const ModuleSpec &module_spec, - lldb::ModuleSP &exe_module_sp, - const FileSpecList *module_search_paths_ptr) { - Error error; +Status +Platform::ResolveExecutable(const ModuleSpec &module_spec, + lldb::ModuleSP &exe_module_sp, + const FileSpecList *module_search_paths_ptr) { + Status error; if (module_spec.GetFileSpec().Exists()) { if (module_spec.GetArchitecture().IsValid()) { error = ModuleList::GetSharedModule(module_spec, exe_module_sp, @@ -909,9 +912,9 @@ Error Platform::ResolveExecutable(const ModuleSpec &module_spec, return error; } -Error Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, - FileSpec &sym_file) { - Error error; +Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, + FileSpec &sym_file) { + Status error; if (sym_spec.GetSymbolFileSpec().Exists()) sym_file = sym_spec.GetSymbolFileSpec(); else @@ -960,8 +963,8 @@ const ArchSpec &Platform::GetSystemArchitecture() { return m_system_arch; } -Error Platform::ConnectRemote(Args &args) { - Error error; +Status Platform::ConnectRemote(Args &args) { + Status error; if (IsHost()) error.SetErrorStringWithFormat("The currently selected platform (%s) is " "the host platform and is always connected.", @@ -973,8 +976,8 @@ Error Platform::ConnectRemote(Args &args) { return error; } -Error Platform::DisconnectRemote() { - Error error; +Status Platform::DisconnectRemote() { + Status error; if (IsHost()) error.SetErrorStringWithFormat("The currently selected platform (%s) is " "the host platform and is always connected.", @@ -1005,8 +1008,8 @@ uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info, return match_count; } -Error Platform::LaunchProcess(ProcessLaunchInfo &launch_info) { - Error error; +Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) { + Status error; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s()", __FUNCTION__); @@ -1057,13 +1060,13 @@ Error Platform::LaunchProcess(ProcessLaunchInfo &launch_info) { return error; } -Error Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) { +Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) { if (IsHost()) return Host::ShellExpandArguments(launch_info); - return Error("base lldb_private::Platform class can't expand arguments"); + return Status("base lldb_private::Platform class can't expand arguments"); } -Error Platform::KillProcess(const lldb::pid_t pid) { +Status Platform::KillProcess(const lldb::pid_t pid) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s, pid %" PRIu64, __FUNCTION__, pid); @@ -1083,19 +1086,19 @@ Error Platform::KillProcess(const lldb::pid_t pid) { } if (!IsHost()) { - return Error( + return Status( "base lldb_private::Platform class can't kill remote processes unless " "they are controlled by a process plugin"); } Host::Kill(pid, SIGTERM); - return Error(); + return Status(); } lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be nullptr, if nullptr create a // new target, else use existing one - Error &error) { + Status &error) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s entered (target %p)", __FUNCTION__, @@ -1186,7 +1189,7 @@ lldb::PlatformSP Platform::GetPlatformForArchitecture(const ArchSpec &arch, ArchSpec *platform_arch_ptr) { lldb::PlatformSP platform_sp; - Error error; + Status error; if (arch.IsValid()) platform_sp = Platform::Create(arch, platform_arch_ptr, error); return platform_sp; @@ -1230,8 +1233,8 @@ bool Platform::IsCompatibleArchitecture(const ArchSpec &arch, return false; } -Error Platform::PutFile(const FileSpec &source, const FileSpec &destination, - uint32_t uid, uint32_t gid) { +Status Platform::PutFile(const FileSpec &source, const FileSpec &destination, + uint32_t uid, uint32_t gid) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("[PutFile] Using block by block transfer....\n"); @@ -1243,13 +1246,13 @@ Error Platform::PutFile(const FileSpec &source, const FileSpec &destination, source_open_options |= File::eOpenOptionDontFollowSymlinks; File source_file(source, source_open_options, lldb::eFilePermissionsUserRW); - Error error; + Status error; uint32_t permissions = source_file.GetPermissions(error); if (permissions == 0) permissions = lldb::eFilePermissionsFileDefault; if (!source_file.IsValid()) - return Error("PutFile: unable to open source file"); + return Status("PutFile: unable to open source file"); lldb::user_id_t dest_file = OpenFile( destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite | File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec, @@ -1260,7 +1263,7 @@ Error Platform::PutFile(const FileSpec &source, const FileSpec &destination, if (error.Fail()) return error; if (dest_file == UINT64_MAX) - return Error("unable to open target file"); + return Status("unable to open target file"); lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0)); uint64_t offset = 0; for (;;) { @@ -1291,16 +1294,16 @@ Error Platform::PutFile(const FileSpec &source, const FileSpec &destination, return error; } -Error Platform::GetFile(const FileSpec &source, const FileSpec &destination) { - Error error("unimplemented"); +Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) { + Status error("unimplemented"); return error; } -Error Platform::CreateSymlink( - const FileSpec &src, // The name of the link is in src - const FileSpec &dst) // The symlink points to dst +Status +Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src + const FileSpec &dst) // The symlink points to dst { - Error error("unimplemented"); + Status error("unimplemented"); return error; } @@ -1308,8 +1311,8 @@ bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) { return false; } -Error Platform::Unlink(const FileSpec &path) { - Error error("unimplemented"); +Status Platform::Unlink(const FileSpec &path) { + Status error("unimplemented"); return error; } @@ -1323,7 +1326,7 @@ uint64_t Platform::ConvertMmapFlagsToPlatform(const ArchSpec &arch, return flags_platform; } -lldb_private::Error Platform::RunShellCommand( +lldb_private::Status Platform::RunShellCommand( const char *command, // Shouldn't be nullptr const FileSpec & working_dir, // Pass empty FileSpec to use the current working directory @@ -1339,7 +1342,7 @@ lldb_private::Error Platform::RunShellCommand( return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec); else - return Error("unimplemented"); + return Status("unimplemented"); } bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low, @@ -1402,11 +1405,11 @@ void OptionGroupPlatformRSync::OptionParsingStarting( m_ignores_remote_hostname = false; } -lldb_private::Error +lldb_private::Status OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 'r': @@ -1448,11 +1451,11 @@ void OptionGroupPlatformSSH::OptionParsingStarting( m_ssh_opts.clear(); } -lldb_private::Error +lldb_private::Status OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 's': @@ -1480,10 +1483,10 @@ void OptionGroupPlatformCaching::OptionParsingStarting( m_cache_dir.clear(); } -lldb_private::Error OptionGroupPlatformCaching::SetOptionValue( +lldb_private::Status OptionGroupPlatformCaching::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 'c': @@ -1514,10 +1517,9 @@ const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() { return m_trap_handlers; } -Error Platform::GetCachedExecutable(ModuleSpec &module_spec, - lldb::ModuleSP &module_sp, - const FileSpecList *module_search_paths_ptr, - Platform &remote_platform) { +Status Platform::GetCachedExecutable( + ModuleSpec &module_spec, lldb::ModuleSP &module_sp, + const FileSpecList *module_search_paths_ptr, Platform &remote_platform) { const auto platform_spec = module_spec.GetFileSpec(); const auto error = LoadCachedExecutable( module_spec, module_sp, module_search_paths_ptr, remote_platform); @@ -1529,7 +1531,7 @@ Error Platform::GetCachedExecutable(ModuleSpec &module_spec, return error; } -Error Platform::LoadCachedExecutable( +Status Platform::LoadCachedExecutable( const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform) { return GetRemoteSharedModule(module_spec, nullptr, module_sp, @@ -1540,11 +1542,11 @@ Error Platform::LoadCachedExecutable( nullptr); } -Error Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, - Process *process, - lldb::ModuleSP &module_sp, - const ModuleResolver &module_resolver, - bool *did_create_ptr) { +Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, + Process *process, + lldb::ModuleSP &module_sp, + const ModuleResolver &module_resolver, + bool *did_create_ptr) { // Get module information from a target. ModuleSpec resolved_module_spec; bool got_module_spec = false; @@ -1561,7 +1563,7 @@ Error Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, } if (module_spec.GetArchitecture().IsValid() == false) { - Error error; + Status error; // No valid architecture was specified, ask the platform for // the architectures that we should be using (in the correct order) // and see if we can find a match that way @@ -1600,7 +1602,7 @@ Error Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, const auto error = module_resolver(resolved_module_spec); if (error.Fail()) { if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr)) - return Error(); + return Status(); } return error; @@ -1640,11 +1642,11 @@ bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec, return false; } -Error Platform::DownloadModuleSlice(const FileSpec &src_file_spec, - const uint64_t src_offset, - const uint64_t src_size, - const FileSpec &dst_file_spec) { - Error error; +Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec, + const uint64_t src_offset, + const uint64_t src_size, + const FileSpec &dst_file_spec) { + Status error; std::error_code EC; llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::F_None); @@ -1682,15 +1684,15 @@ Error Platform::DownloadModuleSlice(const FileSpec &src_file_spec, dst.write(&buffer[0], n_read); } - Error close_error; + Status close_error; CloseFile(src_fd, close_error); // Ignoring close error. return error; } -Error Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp, - const FileSpec &dst_file_spec) { - return Error( +Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp, + const FileSpec &dst_file_spec) { + return Status( "Symbol file downloading not supported by the default platform."); } @@ -1716,7 +1718,7 @@ const UnixSignalsSP &Platform::GetUnixSignals() { uint32_t Platform::LoadImage(lldb_private::Process *process, const lldb_private::FileSpec &local_file, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error) { + lldb_private::Status &error) { if (local_file && remote_file) { // Both local and remote file was specified. Install the local file to the // given location. @@ -1752,21 +1754,21 @@ uint32_t Platform::LoadImage(lldb_private::Process *process, uint32_t Platform::DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, - lldb_private::Error &error) { + lldb_private::Status &error) { error.SetErrorString("LoadImage is not supported on the current platform"); return LLDB_INVALID_IMAGE_TOKEN; } -Error Platform::UnloadImage(lldb_private::Process *process, - uint32_t image_token) { - return Error("UnloadImage is not supported on the current platform"); +Status Platform::UnloadImage(lldb_private::Process *process, + uint32_t image_token) { + return Status("UnloadImage is not supported on the current platform"); } lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, - lldb_private::Error &error) { + lldb_private::Status &error) { error.Clear(); if (!target) { @@ -1795,7 +1797,7 @@ lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url, } size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger, - lldb_private::Error &error) { + lldb_private::Status &error) { error.Clear(); return 0; } diff --git a/contrib/llvm/tools/lldb/source/Target/Process.cpp b/contrib/llvm/tools/lldb/source/Target/Process.cpp index 0bc58f073bf1..ff86b0dbe051 100644 --- a/contrib/llvm/tools/lldb/source/Target/Process.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Process.cpp @@ -415,10 +415,10 @@ void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform, } } -Error ProcessLaunchCommandOptions::SetOptionValue( +Status ProcessLaunchCommandOptions::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { - Error error; + Status error; const int short_option = m_getopt_table[option_idx].val; switch (short_option) { @@ -1610,13 +1610,13 @@ void Process::SetPublicState(StateType new_state, bool restarted) { } } -Error Process::Resume() { +Status Process::Resume() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); if (log) log->Printf("Process::Resume -- locking run lock"); if (!m_public_run_lock.TrySetRunning()) { - Error error("Resume request failed - process still running."); + Status error("Resume request failed - process still running."); if (log) log->Printf("Process::Resume: -- TrySetRunning failed, not resuming."); return error; @@ -1624,13 +1624,13 @@ Error Process::Resume() { return PrivateResume(); } -Error Process::ResumeSynchronous(Stream *stream) { +Status Process::ResumeSynchronous(Stream *stream) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); if (log) log->Printf("Process::ResumeSynchronous -- locking run lock"); if (!m_public_run_lock.TrySetRunning()) { - Error error("Resume request failed - process still running."); + Status error("Resume request failed - process still running."); if (log) log->Printf("Process::Resume: -- TrySetRunning failed, not resuming."); return error; @@ -1640,7 +1640,7 @@ Error Process::ResumeSynchronous(Stream *stream) { Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack")); HijackProcessEvents(listener_sp); - Error error = PrivateResume(); + Status error = PrivateResume(); if (error.Success()) { StateType state = WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream); @@ -1813,8 +1813,8 @@ void Process::DisableAllBreakpointSites() { }); } -Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) { - Error error(DisableBreakpointSiteByID(break_id)); +Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) { + Status error(DisableBreakpointSiteByID(break_id)); if (error.Success()) m_breakpoint_site_list.Remove(break_id); @@ -1822,8 +1822,8 @@ Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) { return error; } -Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) { - Error error; +Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) { + Status error; BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); if (bp_site_sp) { if (bp_site_sp->IsEnabled()) @@ -1836,8 +1836,8 @@ Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) { return error; } -Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) { - Error error; +Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) { + Status error; BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); if (bp_site_sp) { if (!bp_site_sp->IsEnabled()) @@ -1882,7 +1882,7 @@ Process::CreateBreakpointSite(const BreakpointLocationSP &owner, if (owner->ShouldResolveIndirectFunctions()) { Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol(); if (symbol && symbol->IsIndirect()) { - Error error; + Status error; Address symbol_address = symbol->GetAddress(); load_addr = ResolveIndirectFunction(&symbol_address, error); if (!error.Success() && show_error) { @@ -1919,7 +1919,7 @@ Process::CreateBreakpointSite(const BreakpointLocationSP &owner, bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner, load_addr, use_hardware)); if (bp_site_sp) { - Error error = EnableBreakpointSite(bp_site_sp.get()); + Status error = EnableBreakpointSite(bp_site_sp.get()); if (error.Success()) { owner->SetBreakpointSite(bp_site_sp); return m_breakpoint_site_list.Add(bp_site_sp); @@ -1989,8 +1989,8 @@ size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) { return 0; } -Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) { - Error error; +Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) { + Status error; assert(bp_site != nullptr); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); const addr_t bp_addr = bp_site->GetLoadAddress(); @@ -2065,8 +2065,8 @@ Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) { return error; } -Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) { - Error error; +Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) { + Status error; assert(bp_site != nullptr); Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); addr_t bp_addr = bp_site->GetLoadAddress(); @@ -2158,7 +2158,7 @@ Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) { // Uncomment to verify memory caching works after making changes to caching code //#define VERIFY_MEMORY_READS -size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) { +size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) { error.Clear(); if (!GetDisableMemoryCache()) { #if defined(VERIFY_MEMORY_READS) @@ -2177,7 +2177,7 @@ size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) { assert(verify_buf.size() == size); const size_t cache_bytes_read = m_memory_cache.Read(this, addr, buf, size, error); - Error verify_error; + Status verify_error; const size_t verify_bytes_read = ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); @@ -2200,7 +2200,7 @@ size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) { } size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str, - Error &error) { + Status &error) { char buf[256]; out_str.clear(); addr_t curr_addr = addr; @@ -2220,7 +2220,7 @@ size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str, } size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes, - Error &error, size_t type_width) { + Status &error, size_t type_width) { size_t total_bytes_read = 0; if (dst && max_bytes && type_width && max_bytes >= type_width) { // Ensure a null terminator independent of the number of bytes that is read. @@ -2273,13 +2273,14 @@ size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes, // correct code to find // null terminators. size_t Process::ReadCStringFromMemory(addr_t addr, char *dst, - size_t dst_max_len, Error &result_error) { + size_t dst_max_len, + Status &result_error) { size_t total_cstr_len = 0; if (dst && dst_max_len) { result_error.Clear(); // NULL out everything just to be safe memset(dst, 0, dst_max_len); - Error error; + Status error; addr_t curr_addr = addr; const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); size_t bytes_left = dst_max_len - 1; @@ -2318,7 +2319,7 @@ size_t Process::ReadCStringFromMemory(addr_t addr, char *dst, } size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size, - Error &error) { + Status &error) { if (buf == nullptr || size == 0) return 0; @@ -2344,7 +2345,7 @@ size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size, uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, - Error &error) { + Status &error) { Scalar scalar; if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error)) @@ -2354,7 +2355,8 @@ uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr, int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr, size_t integer_byte_size, - int64_t fail_value, Error &error) { + int64_t fail_value, + Status &error) { Scalar scalar; if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar, error)) @@ -2362,7 +2364,7 @@ int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr, return fail_value; } -addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) { +addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) { Scalar scalar; if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error)) @@ -2371,7 +2373,7 @@ addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) { } bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, - Error &error) { + Status &error) { Scalar scalar; const uint32_t addr_byte_size = GetAddressByteSize(); if (addr_byte_size <= 4) @@ -2383,7 +2385,7 @@ bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, } size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size, - Error &error) { + Status &error) { size_t bytes_written = 0; const uint8_t *bytes = (const uint8_t *)buf; @@ -2399,7 +2401,7 @@ size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size, } size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size, - Error &error) { + Status &error) { #if defined(ENABLE_MEMORY_CACHING) m_memory_cache.Flush(addr, size); #endif @@ -2478,7 +2480,7 @@ size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size, } size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, - size_t byte_size, Error &error) { + size_t byte_size, Status &error) { if (byte_size == UINT32_MAX) byte_size = scalar.GetByteSize(); if (byte_size > 0) { @@ -2497,7 +2499,7 @@ size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, - Error &error) { + Status &error) { uint64_t uval = 0; if (byte_size == 0) { error.SetErrorString("byte size is zero"); @@ -2527,7 +2529,7 @@ size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size, #define USE_ALLOCATE_MEMORY_CACHE 1 addr_t Process::AllocateMemory(size_t size, uint32_t permissions, - Error &error) { + Status &error) { if (GetPrivateState() != eStateStopped) return LLDB_INVALID_ADDRESS; @@ -2548,7 +2550,7 @@ addr_t Process::AllocateMemory(size_t size, uint32_t permissions, } addr_t Process::CallocateMemory(size_t size, uint32_t permissions, - Error &error) { + Status &error) { addr_t return_addr = AllocateMemory(size, permissions, error); if (error.Success()) { std::string buffer(size, 0); @@ -2560,7 +2562,7 @@ addr_t Process::CallocateMemory(size_t size, uint32_t permissions, bool Process::CanJIT() { if (m_can_jit == eCanJITDontKnow) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); - Error err; + Status err; uint64_t allocated_memory = AllocateMemory( 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, @@ -2595,8 +2597,8 @@ void Process::SetCanRunCode(bool can_run_code) { m_can_interpret_function_calls = can_run_code; } -Error Process::DeallocateMemory(addr_t ptr) { - Error error; +Status Process::DeallocateMemory(addr_t ptr) { + Status error; #if defined(USE_ALLOCATE_MEMORY_CACHE) if (!m_allocated_memory_cache.DeallocateMemory(ptr)) { error.SetErrorStringWithFormat( @@ -2625,7 +2627,7 @@ ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec, } ModuleSP module_sp(new Module(file_spec, ArchSpec())); if (module_sp) { - Error error; + Status error; ObjectFile *objfile = module_sp->GetMemoryObjectFile( shared_from_this(), header_addr, error, size_to_read); if (objfile) @@ -2638,7 +2640,7 @@ bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr, uint32_t &permissions) { MemoryRegionInfo range_info; permissions = 0; - Error error(GetMemoryRegionInfo(load_addr, range_info)); + Status error(GetMemoryRegionInfo(load_addr, range_info)); if (!error.Success()) return false; if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow || @@ -2659,14 +2661,14 @@ bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr, return true; } -Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) { - Error error; +Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) { + Status error; error.SetErrorString("watchpoints are not supported"); return error; } -Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) { - Error error; +Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) { + Status error; error.SetErrorString("watchpoints are not supported"); return error; } @@ -2702,8 +2704,8 @@ void Process::LoadOperatingSystemPlugin(bool flush) { Flush(); } -Error Process::Launch(ProcessLaunchInfo &launch_info) { - Error error; +Status Process::Launch(ProcessLaunchInfo &launch_info) { + Status error; m_abi_sp.reset(); m_dyld_ap.reset(); m_jit_loaders_ap.reset(); @@ -2823,8 +2825,8 @@ Error Process::Launch(ProcessLaunchInfo &launch_info) { return error; } -Error Process::LoadCore() { - Error error = DoLoadCore(); +Status Process::LoadCore() { + Status error = DoLoadCore(); if (error.Success()) { ListenerSP listener_sp( Listener::MakeListener("lldb.process.load_core_listener")); @@ -2977,7 +2979,7 @@ ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) { return debugger.GetListener(); } -Error Process::Attach(ProcessAttachInfo &attach_info) { +Status Process::Attach(ProcessAttachInfo &attach_info) { m_abi_sp.reset(); m_process_input_reader.reset(); m_dyld_ap.reset(); @@ -2987,7 +2989,7 @@ Error Process::Attach(ProcessAttachInfo &attach_info) { m_stop_info_override_callback = nullptr; lldb::pid_t attach_pid = attach_info.GetProcessID(); - Error error; + Status error; if (attach_pid == LLDB_INVALID_PROCESS_ID) { char process_name[PATH_MAX]; @@ -3221,14 +3223,14 @@ void Process::CompleteAttach() { m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback(); } -Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) { +Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) { m_abi_sp.reset(); m_process_input_reader.reset(); // Find the process and its architecture. Make sure it matches the // architecture of the current Target, and if not adjust it. - Error error(DoConnectRemote(strm, remote_url)); + Status error(DoConnectRemote(strm, remote_url)); if (error.Success()) { if (GetID() != LLDB_INVALID_PROCESS_ID) { EventSP event_sp; @@ -3253,7 +3255,7 @@ Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) { return error; } -Error Process::PrivateResume() { +Status Process::PrivateResume() { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_STEP)); if (log) @@ -3266,7 +3268,7 @@ Error Process::PrivateResume() { // our signal filters before resuming. UpdateAutomaticSignalFiltering(); - Error error(WillResume()); + Status error(WillResume()); // Tell the process it is about to resume before the thread list if (error.Success()) { // Now let the thread list know we are about to resume so it @@ -3311,9 +3313,9 @@ Error Process::PrivateResume() { return error; } -Error Process::Halt(bool clear_thread_plans, bool use_run_lock) { +Status Process::Halt(bool clear_thread_plans, bool use_run_lock) { if (!StateIsRunningState(m_public_state.GetValue())) - return Error("Process is not running."); + return Status("Process is not running."); // Don't clear the m_clear_thread_plans_on_stop, only set it to true if // in case it was already set and some thread plan logic calls halt on its @@ -3334,7 +3336,7 @@ Error Process::Halt(bool clear_thread_plans, bool use_run_lock) { RestoreProcessEvents(); SetExitStatus(SIGKILL, "Cancelled async attach."); Destroy(false); - return Error(); + return Status(); } // Wait for 10 second for the process to stop. @@ -3344,16 +3346,16 @@ Error Process::Halt(bool clear_thread_plans, bool use_run_lock) { if (state == eStateInvalid || !event_sp) { // We timed out and didn't get a stop event... - return Error("Halt timed out. State = %s", StateAsCString(GetState())); + return Status("Halt timed out. State = %s", StateAsCString(GetState())); } BroadcastEvent(event_sp); - return Error(); + return Status(); } -Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { - Error error; +Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { + Status error; // Check both the public & private states here. If we're hung evaluating an // expression, for instance, then @@ -3400,18 +3402,19 @@ Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { // then continue on. StateType private_state = m_private_state.GetValue(); if (private_state != eStateStopped) { - return Error("Attempt to stop the target in order to detach timed out. " - "State = %s", - StateAsCString(GetState())); + return Status( + "Attempt to stop the target in order to detach timed out. " + "State = %s", + StateAsCString(GetState())); } } } return error; } -Error Process::Detach(bool keep_stopped) { +Status Process::Detach(bool keep_stopped) { EventSP exit_event_sp; - Error error; + Status error; m_destroy_in_process = true; error = WillDetach(); @@ -3463,7 +3466,7 @@ Error Process::Detach(bool keep_stopped) { return error; } -Error Process::Destroy(bool force_kill) { +Status Process::Destroy(bool force_kill) { // Tell ourselves we are in the process of destroying the process, so that we // don't do any unnecessary work @@ -3483,7 +3486,7 @@ Error Process::Destroy(bool force_kill) { m_destroy_in_process = true; - Error error(WillDestroy()); + Status error(WillDestroy()); if (error.Success()) { EventSP exit_event_sp; if (DestroyRequiresHalt()) { @@ -3538,8 +3541,8 @@ Error Process::Destroy(bool force_kill) { return error; } -Error Process::Signal(int signal) { - Error error(WillSignal()); +Status Process::Signal(int signal) { + Status error(WillSignal()); if (error.Success()) { error = DoSignal(signal); if (error.Success()) @@ -3967,9 +3970,9 @@ void Process::HandlePrivateEvent(EventSP &event_sp) { } } -Error Process::HaltPrivate() { +Status Process::HaltPrivate() { EventSP event_sp; - Error error(WillHalt()); + Status error(WillHalt()); if (error.Fail()) return error; @@ -4037,7 +4040,7 @@ thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) { log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, static_cast<void *>(this), GetID()); - Error error = HaltPrivate(); + Status error = HaltPrivate(); if (error.Fail() && log) log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") failed to halt the process: %s", @@ -4477,7 +4480,7 @@ Process::GetStructuredDataPlugin(const ConstString &type_name) const { return StructuredDataPluginSP(); } -size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) { +size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) { std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); if (m_profile_data.empty()) return 0; @@ -4505,7 +4508,7 @@ size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) { // Process STDIO //------------------------------------------------------------------ -size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) { +size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); size_t bytes_available = m_stdout_data.size(); if (bytes_available > 0) { @@ -4525,7 +4528,7 @@ size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) { return bytes_available; } -size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) { +size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) { std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex); size_t bytes_available = m_stderr_data.size(); if (bytes_available > 0) { @@ -4588,7 +4591,7 @@ public: SelectHelper select_helper; select_helper.FDSetRead(read_fd); select_helper.FDSetRead(pipe_read_fd); - Error error = select_helper.Select(); + Status error = select_helper.Select(); if (error.Fail()) { SetIsDone(true); @@ -4606,7 +4609,7 @@ public: if (select_helper.FDIsSetRead(pipe_read_fd)) { size_t bytes_read; // Consume the interrupt byte - Error error = m_pipe.Read(&ch, 1, bytes_read); + Status error = m_pipe.Read(&ch, 1, bytes_read); if (error.Success()) { switch (ch) { case 'q': @@ -4657,7 +4660,7 @@ public: if (m_active) { char ch = 'i'; // Send 'i' for interrupt size_t bytes_written = 0; - Error result = m_pipe.Write(&ch, 1, bytes_written); + Status result = m_pipe.Write(&ch, 1, bytes_written); return result.Success(); } else { // This IOHandler might be pushed on the stack, but not being run @@ -5082,7 +5085,7 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx, if (do_resume) { num_resumes++; - Error resume_error = PrivateResume(); + Status resume_error = PrivateResume(); if (!resume_error.Success()) { diagnostic_manager.Printf( eDiagnosticSeverityError, @@ -5361,7 +5364,7 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx, bool do_halt = true; const uint32_t num_retries = 5; while (try_halt_again < num_retries) { - Error halt_error; + Status halt_error; if (do_halt) { if (log) log->Printf("Process::RunThreadPlan(): Running Halt."); @@ -5473,7 +5476,7 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx, // plan, shut it down now. if (backup_private_state_thread.IsJoinable()) { StopPrivateStateThread(); - Error error; + Status error; m_private_state_thread = backup_private_state_thread; if (stopper_base_plan_sp) { thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); @@ -5862,7 +5865,7 @@ void Process::DidExec() { target.DidExec(); } -addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) { +addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) { if (address == nullptr) { error.SetErrorString("Invalid address argument"); return LLDB_INVALID_ADDRESS; @@ -6090,10 +6093,10 @@ Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr, return retval; } -Error Process::GetMemoryRegions( - std::vector<lldb::MemoryRegionInfoSP> ®ion_list) { +Status +Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list) { - Error error; + Status error; lldb::addr_t range_end = 0; @@ -6116,12 +6119,13 @@ Error Process::GetMemoryRegions( return error; } -Error Process::ConfigureStructuredData( - const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { +Status +Process::ConfigureStructuredData(const ConstString &type_name, + const StructuredData::ObjectSP &config_sp) { // If you get this, the Process-derived class needs to implement a method // to enable an already-reported asynchronous structured data feature. // See ProcessGDBRemote for an example implementation over gdb-remote. - return Error("unimplemented"); + return Status("unimplemented"); } void Process::MapSupportedStructuredDataPlugins( @@ -6158,8 +6162,7 @@ void Process::MapSupportedStructuredDataPlugins( } const_type_names.insert(ConstString(type_name->GetValue())); - if (log) - log->Printf("- %s", type_name->GetValue().c_str()); + LLDB_LOG(log, "- {0}", type_name->GetValue()); return true; }); @@ -6229,8 +6232,8 @@ bool Process::RouteAsyncStructuredData( return true; } -Error Process::UpdateAutomaticSignalFiltering() { +Status Process::UpdateAutomaticSignalFiltering() { // Default implementation does nothign. // No automatic signal filtering to speak of. - return Error(); + return Status(); } diff --git a/contrib/llvm/tools/lldb/source/Target/ProcessLaunchInfo.cpp b/contrib/llvm/tools/lldb/source/Target/ProcessLaunchInfo.cpp index 7de55f2fdcf9..3fa40dcc5cab 100644 --- a/contrib/llvm/tools/lldb/source/Target/ProcessLaunchInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ProcessLaunchInfo.cpp @@ -330,7 +330,7 @@ void ProcessLaunchInfo::FinalizeFileActions(Target *target, } bool ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell( - Error &error, bool localhost, bool will_debug, + Status &error, bool localhost, bool will_debug, bool first_arg_is_full_shell_command, int32_t num_resumes) { error.Clear(); diff --git a/contrib/llvm/tools/lldb/source/Target/RegisterContext.cpp b/contrib/llvm/tools/lldb/source/Target/RegisterContext.cpp index 6cbfb04a6e9a..66164c175e41 100644 --- a/contrib/llvm/tools/lldb/source/Target/RegisterContext.cpp +++ b/contrib/llvm/tools/lldb/source/Target/RegisterContext.cpp @@ -91,7 +91,7 @@ RegisterContext::UpdateDynamicRegisterSize(const lldb_private::ArchSpec &arch, DWARFExpression dwarf_expr(opcode_ctx, dwarf_data, nullptr, 0, dwarf_opcode_len); Value result; - Error error; + Status error; const lldb::offset_t offset = 0; if (dwarf_expr.Evaluate(&exe_ctx, nullptr, nullptr, this, opcode_ctx, dwarf_data, nullptr, offset, dwarf_opcode_len, @@ -299,11 +299,10 @@ bool RegisterContext::ClearHardwareWatchpoint(uint32_t hw_index) { bool RegisterContext::HardwareSingleStep(bool enable) { return false; } -Error RegisterContext::ReadRegisterValueFromMemory(const RegisterInfo *reg_info, - lldb::addr_t src_addr, - uint32_t src_len, - RegisterValue ®_value) { - Error error; +Status RegisterContext::ReadRegisterValueFromMemory( + const RegisterInfo *reg_info, lldb::addr_t src_addr, uint32_t src_len, + RegisterValue ®_value) { + Status error; if (reg_info == nullptr) { error.SetErrorString("invalid register info argument."); return error; @@ -318,7 +317,7 @@ Error RegisterContext::ReadRegisterValueFromMemory(const RegisterInfo *reg_info, // // Case 2: src_len > dst_len // - // Error! (The register should always be big enough to hold the data) + // Status! (The register should always be big enough to hold the data) // // Case 3: src_len < dst_len // @@ -371,12 +370,12 @@ Error RegisterContext::ReadRegisterValueFromMemory(const RegisterInfo *reg_info, return error; } -Error RegisterContext::WriteRegisterValueToMemory( +Status RegisterContext::WriteRegisterValueToMemory( const RegisterInfo *reg_info, lldb::addr_t dst_addr, uint32_t dst_len, const RegisterValue ®_value) { uint8_t dst[RegisterValue::kMaxRegisterByteSize]; - Error error; + Status error; ProcessSP process_sp(m_thread.GetProcess()); if (process_sp) { diff --git a/contrib/llvm/tools/lldb/source/Target/StackFrame.cpp b/contrib/llvm/tools/lldb/source/Target/StackFrame.cpp index 7b7b596c9773..9deebcaf9250 100644 --- a/contrib/llvm/tools/lldb/source/Target/StackFrame.cpp +++ b/contrib/llvm/tools/lldb/source/Target/StackFrame.cpp @@ -488,7 +488,7 @@ StackFrame::GetInScopeVariableList(bool get_file_globals, ValueObjectSP StackFrame::GetValueForVariableExpressionPath( llvm::StringRef var_expr, DynamicValueType use_dynamic, uint32_t options, - VariableSP &var_sp, Error &error) { + VariableSP &var_sp, Status &error) { llvm::StringRef original_var_expr = var_expr; // We can't fetch variable information for a history stack frame. if (m_is_history_frame) @@ -631,7 +631,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( // If we have a non pointer type with a sythetic value then lets check if // we have an sythetic dereference specified. if (!valobj_sp->IsPointerType() && valobj_sp->HasSyntheticValue()) { - Error deref_error; + Status deref_error; if (valobj_sp->GetCompilerType().IsReferenceType()) { valobj_sp = valobj_sp->GetSyntheticValue()->Dereference(deref_error); if (error.Fail()) { @@ -775,7 +775,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( // what we have is *ptr[low]. the most similar C++ syntax is to deref // ptr and extract bit low out of it. reading array item low would be // done by saying ptr[low], without a deref * sign - Error error; + Status error; ValueObjectSP temp(valobj_sp->Dereference(error)); if (error.Fail()) { valobj_sp->GetExpressionPath(var_expr_path_strm, false); @@ -794,7 +794,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( // (an operation that is equivalent to deref-ing arr) // and extract bit low out of it. reading array item low // would be done by saying arr[low], without a deref * sign - Error error; + Status error; ValueObjectSP temp(valobj_sp->GetChildAtIndex(0, true)); if (error.Fail()) { valobj_sp->GetExpressionPath(var_expr_path_strm, false); @@ -977,7 +977,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( // deref ptr and extract bits low thru high out of it. reading array // items low thru high would be done by saying ptr[low-high], without // a deref * sign - Error error; + Status error; ValueObjectSP temp(valobj_sp->Dereference(error)); if (error.Fail()) { valobj_sp->GetExpressionPath(var_expr_path_strm, false); @@ -994,7 +994,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( // arr[0] (an operation that is equivalent to deref-ing arr) and extract // bits low thru high out of it. reading array items low thru high would // be done by saying arr[low-high], without a deref * sign - Error error; + Status error; ValueObjectSP temp(valobj_sp->GetChildAtIndex(0, true)); if (error.Fail()) { valobj_sp->GetExpressionPath(var_expr_path_strm, false); @@ -1065,7 +1065,7 @@ ValueObjectSP StackFrame::GetValueForVariableExpressionPath( return valobj_sp; } -bool StackFrame::GetFrameBaseValue(Scalar &frame_base, Error *error_ptr) { +bool StackFrame::GetFrameBaseValue(Scalar &frame_base, Status *error_ptr) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (!m_cfa_is_valid) { m_frame_base_error.SetErrorString( @@ -1111,7 +1111,7 @@ bool StackFrame::GetFrameBaseValue(Scalar &frame_base, Error *error_ptr) { return m_frame_base_error.Success(); } -DWARFExpression *StackFrame::GetFrameBaseExpression(Error *error_ptr) { +DWARFExpression *StackFrame::GetFrameBaseExpression(Status *error_ptr) { if (!m_sc.function) { if (error_ptr) { error_ptr->SetErrorString("No function in symbol context."); @@ -1426,7 +1426,7 @@ ValueObjectSP GetValueForDereferincingOffset(StackFrame &frame, return ValueObjectSP(); } - Error error; + Status error; ValueObjectSP pointee = base->Dereference(error); if (!pointee) { diff --git a/contrib/llvm/tools/lldb/source/Target/StopInfo.cpp b/contrib/llvm/tools/lldb/source/Target/StopInfo.cpp index 8d40c7678b96..6af5ce1b2ebf 100644 --- a/contrib/llvm/tools/lldb/source/Target/StopInfo.cpp +++ b/contrib/llvm/tools/lldb/source/Target/StopInfo.cpp @@ -435,7 +435,7 @@ protected: // shouldn't stop that will win. if (bp_loc_sp->GetConditionText() != nullptr) { - Error condition_error; + Status condition_error; bool condition_says_stop = bp_loc_sp->ConditionSaysStop(exe_ctx, condition_error); @@ -796,7 +796,7 @@ protected: expr_options.SetUnwindOnError(true); expr_options.SetIgnoreBreakpoints(true); ValueObjectSP result_value_sp; - Error error; + Status error; result_code = UserExpression::Evaluate( exe_ctx, expr_options, wp_sp->GetConditionText(), llvm::StringRef(), result_value_sp, error); diff --git a/contrib/llvm/tools/lldb/source/Target/Target.cpp b/contrib/llvm/tools/lldb/source/Target/Target.cpp index 5c9e92aaaa27..5c46a024be60 100644 --- a/contrib/llvm/tools/lldb/source/Target/Target.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Target.cpp @@ -182,7 +182,7 @@ const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp, const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; } -lldb::REPLSP Target::GetREPL(Error &err, lldb::LanguageType language, +lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create) { if (language == eLanguageTypeUnknown) { std::set<LanguageType> repl_languages; @@ -547,7 +547,7 @@ BreakpointSP Target::CreateFuncRegexBreakpoint( lldb::BreakpointSP Target::CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal, - Args *additional_args, Error *error) { + Args *additional_args, Status *error) { BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint( *this, language, catch_bp, throw_bp, internal); if (exc_bkpt_sp && additional_args) { @@ -604,9 +604,9 @@ bool Target::ProcessIsValid() { return (m_process_sp && m_process_sp->IsAlive()); } -static bool CheckIfWatchpointsExhausted(Target *target, Error &error) { +static bool CheckIfWatchpointsExhausted(Target *target, Status &error) { uint32_t num_supported_hardware_watchpoints; - Error rc = target->GetProcessSP()->GetWatchpointSupportInfo( + Status rc = target->GetProcessSP()->GetWatchpointSupportInfo( num_supported_hardware_watchpoints); if (num_supported_hardware_watchpoints == 0) { error.SetErrorStringWithFormat( @@ -621,7 +621,7 @@ static bool CheckIfWatchpointsExhausted(Target *target, Error &error) { // the OptionGroupWatchpoint::WatchType enum type. WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, - Error &error) { + Status &error) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS)); if (log) log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 @@ -797,10 +797,10 @@ bool Target::EnableBreakpointByID(break_id_t break_id) { return false; } -Error Target::SerializeBreakpointsToFile(const FileSpec &file, - const BreakpointIDList &bp_ids, - bool append) { - Error error; +Status Target::SerializeBreakpointsToFile(const FileSpec &file, + const BreakpointIDList &bp_ids, + bool append) { + Status error; if (!file) { error.SetErrorString("Invalid FileSpec."); @@ -891,19 +891,19 @@ Error Target::SerializeBreakpointsToFile(const FileSpec &file, return error; } -Error Target::CreateBreakpointsFromFile(const FileSpec &file, - BreakpointIDList &new_bps) { +Status Target::CreateBreakpointsFromFile(const FileSpec &file, + BreakpointIDList &new_bps) { std::vector<std::string> no_names; return CreateBreakpointsFromFile(file, no_names, new_bps); } -Error Target::CreateBreakpointsFromFile(const FileSpec &file, - std::vector<std::string> &names, - BreakpointIDList &new_bps) { +Status Target::CreateBreakpointsFromFile(const FileSpec &file, + std::vector<std::string> &names, + BreakpointIDList &new_bps) { std::unique_lock<std::recursive_mutex> lock; GetBreakpointList().GetListMutex(lock); - Error error; + Status error; StructuredData::ObjectSP input_data_sp = StructuredData::ParseJSONFromFile(file, error); if (!error.Success()) { @@ -979,7 +979,7 @@ bool Target::RemoveAllWatchpoints(bool end_to_end) { if (!wp_sp) return false; - Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); + Status rc = m_process_sp->DisableWatchpoint(wp_sp.get()); if (rc.Fail()) return false; } @@ -1011,7 +1011,7 @@ bool Target::DisableAllWatchpoints(bool end_to_end) { if (!wp_sp) return false; - Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); + Status rc = m_process_sp->DisableWatchpoint(wp_sp.get()); if (rc.Fail()) return false; } @@ -1041,7 +1041,7 @@ bool Target::EnableAllWatchpoints(bool end_to_end) { if (!wp_sp) return false; - Error rc = m_process_sp->EnableWatchpoint(wp_sp.get()); + Status rc = m_process_sp->EnableWatchpoint(wp_sp.get()); if (rc.Fail()) return false; } @@ -1114,7 +1114,7 @@ bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) { WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id); if (wp_sp) { - Error rc = m_process_sp->DisableWatchpoint(wp_sp.get()); + Status rc = m_process_sp->DisableWatchpoint(wp_sp.get()); if (rc.Success()) return true; @@ -1134,7 +1134,7 @@ bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) { WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id); if (wp_sp) { - Error rc = m_process_sp->EnableWatchpoint(wp_sp.get()); + Status rc = m_process_sp->EnableWatchpoint(wp_sp.get()); if (rc.Success()) return true; @@ -1198,7 +1198,7 @@ Module *Target::GetExecutableModulePointer() { static void LoadScriptingResourceForModule(const ModuleSP &module_sp, Target *target) { - Error error; + Status error; StreamString feedback_stream; if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, @@ -1235,7 +1235,8 @@ void Target::SetExecutableModule(ModuleSP &executable_sp, ClearModules(false); if (executable_sp) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer(func_cat, "Target::SetExecutableModule (executable = '%s')", executable_sp->GetFileSpec().GetPath().c_str()); @@ -1335,9 +1336,9 @@ bool Target::SetArchitecture(const ArchSpec &arch_spec) { arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str()); ModuleSpec module_spec(executable_sp->GetFileSpec(), other); - Error error = ModuleList::GetSharedModule(module_spec, executable_sp, - &GetExecutableSearchPaths(), - nullptr, nullptr); + Status error = ModuleList::GetSharedModule(module_spec, executable_sp, + &GetExecutableSearchPaths(), + nullptr, nullptr); if (!error.Fail() && executable_sp) { SetExecutableModule(executable_sp, true); @@ -1474,7 +1475,7 @@ bool Target::ModuleIsExcludedForUnconstrainedSearches( } size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst, - size_t dst_len, Error &error) { + size_t dst_len, Status &error) { SectionSP section_sp(addr.GetSection()); if (section_sp) { // If the contents of this section are encrypted, the on-disk file is @@ -1506,7 +1507,7 @@ size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst, } size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache, - void *dst, size_t dst_len, Error &error, + void *dst, size_t dst_len, Status &error, lldb::addr_t *load_addr_ptr) { error.Clear(); @@ -1598,7 +1599,7 @@ size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache, } size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str, - Error &error) { + Status &error) { char buf[256]; out_str.clear(); addr_t curr_addr = addr.GetLoadAddress(this); @@ -1620,13 +1621,13 @@ size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str, } size_t Target::ReadCStringFromMemory(const Address &addr, char *dst, - size_t dst_max_len, Error &result_error) { + size_t dst_max_len, Status &result_error) { size_t total_cstr_len = 0; if (dst && dst_max_len) { result_error.Clear(); // NULL out everything just to be safe memset(dst, 0, dst_max_len); - Error error; + Status error; addr_t curr_addr = addr.GetLoadAddress(this); Address address(addr); @@ -1675,7 +1676,7 @@ size_t Target::ReadCStringFromMemory(const Address &addr, char *dst, size_t Target::ReadScalarIntegerFromMemory(const Address &addr, bool prefer_file_cache, uint32_t byte_size, bool is_signed, - Scalar &scalar, Error &error) { + Scalar &scalar, Status &error) { uint64_t uval; if (byte_size <= sizeof(uval)) { @@ -1705,7 +1706,7 @@ uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr, bool prefer_file_cache, size_t integer_byte_size, uint64_t fail_value, - Error &error) { + Status &error) { Scalar scalar; if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size, false, scalar, error)) @@ -1714,7 +1715,7 @@ uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr, } bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache, - Error &error, Address &pointer_addr) { + Status &error, Address &pointer_addr) { Scalar scalar; if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, m_arch.GetAddressByteSize(), false, scalar, @@ -1744,10 +1745,10 @@ bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache, } ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec, - Error *error_ptr) { + Status *error_ptr) { ModuleSP module_sp; - Error error; + Status error; // First see if we already have this module in our module list. If we do, // then we're done, we don't need @@ -1918,7 +1919,7 @@ void Target::ImageSearchPathsChanged(const PathMappingList &path_list, target->SetExecutableModule(exe_module_sp, true); } -TypeSystem *Target::GetScratchTypeSystemForLanguage(Error *error, +TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error, lldb::LanguageType language, bool create_on_demand) { if (!m_valid) @@ -1968,8 +1969,8 @@ Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) { UserExpression *Target::GetUserExpressionForLanguage( llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, - const EvaluateExpressionOptions &options, Error &error) { - Error type_system_error; + const EvaluateExpressionOptions &options, Status &error) { + Status type_system_error; TypeSystem *type_system = GetScratchTypeSystemForLanguage(&type_system_error, language); @@ -1996,8 +1997,8 @@ UserExpression *Target::GetUserExpressionForLanguage( FunctionCaller *Target::GetFunctionCallerForLanguage( lldb::LanguageType language, const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, - const char *name, Error &error) { - Error type_system_error; + const char *name, Status &error) { + Status type_system_error; TypeSystem *type_system = GetScratchTypeSystemForLanguage(&type_system_error, language); FunctionCaller *persistent_fn = nullptr; @@ -2023,8 +2024,8 @@ FunctionCaller *Target::GetFunctionCallerForLanguage( UtilityFunction * Target::GetUtilityFunctionForLanguage(const char *text, lldb::LanguageType language, - const char *name, Error &error) { - Error type_system_error; + const char *name, Status &error) { + Status type_system_error; TypeSystem *type_system = GetScratchTypeSystemForLanguage(&type_system_error, language); UtilityFunction *utility_fn = nullptr; @@ -2162,7 +2163,7 @@ ExpressionResults Target::EvaluateExpression( execution_results = eExpressionCompleted; } else { const char *prefix = GetExpressionPrefixContentsAsCString(); - Error error; + Status error; execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix, result_valobj_sp, error, 0, // Line Number @@ -2653,8 +2654,8 @@ const TargetPropertiesSP &Target::GetGlobalProperties() { return *g_settings_sp_ptr; } -Error Target::Install(ProcessLaunchInfo *launch_info) { - Error error; +Status Target::Install(ProcessLaunchInfo *launch_info) { + Status error; PlatformSP platform_sp(GetPlatform()); if (platform_sp) { if (platform_sp->IsRemote()) { @@ -2784,8 +2785,8 @@ bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp, void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); } -Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { - Error error; +Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { + Status error; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET)); if (log) @@ -2933,7 +2934,7 @@ Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { error = m_process_sp->PrivateResume(); } if (!error.Success()) { - Error error2; + Status error2; error2.SetErrorStringWithFormat( "process resume at entry point failed: %s", error.AsCString()); error = error2; @@ -2971,7 +2972,7 @@ Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { } m_process_sp->RestoreProcessEvents(); } else { - Error error2; + Status error2; error2.SetErrorStringWithFormat("process launch failed: %s", error.AsCString()); error = error2; @@ -2979,15 +2980,15 @@ Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) { return error; } -Error Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { +Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { auto state = eStateInvalid; auto process_sp = GetProcessSP(); if (process_sp) { state = process_sp->GetState(); if (process_sp->IsAlive() && state != eStateConnected) { if (state == eStateAttaching) - return Error("process attach is in progress"); - return Error("a process is already being debugged"); + return Status("process attach is in progress"); + return Status("a process is already being debugged"); } } @@ -3001,8 +3002,8 @@ Error Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { old_exec_module_sp->GetPlatformFileSpec().GetFilename(); if (!attach_info.ProcessInfoSpecified()) { - return Error("no process specified, create a target with a file, or " - "specify the --pid or --name"); + return Status("no process specified, create a target with a file, or " + "specify the --pid or --name"); } } @@ -3016,7 +3017,7 @@ Error Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) { attach_info.SetHijackListener(hijack_listener_sp); } - Error error; + Status error; if (state != eStateConnected && platform_sp != nullptr && platform_sp->CanDebugProcess()) { SetPlatform(platform_sp); diff --git a/contrib/llvm/tools/lldb/source/Target/TargetList.cpp b/contrib/llvm/tools/lldb/source/Target/TargetList.cpp index 0849c18b89e0..43e1227ba205 100644 --- a/contrib/llvm/tools/lldb/source/Target/TargetList.cpp +++ b/contrib/llvm/tools/lldb/source/Target/TargetList.cpp @@ -55,33 +55,33 @@ TargetList::~TargetList() { m_target_list.clear(); } -Error TargetList::CreateTarget(Debugger &debugger, - llvm::StringRef user_exe_path, - llvm::StringRef triple_str, - bool get_dependent_files, - const OptionGroupPlatform *platform_options, - TargetSP &target_sp) { +Status TargetList::CreateTarget(Debugger &debugger, + llvm::StringRef user_exe_path, + llvm::StringRef triple_str, + bool get_dependent_files, + const OptionGroupPlatform *platform_options, + TargetSP &target_sp) { return CreateTargetInternal(debugger, user_exe_path, triple_str, get_dependent_files, platform_options, target_sp, false); } -Error TargetList::CreateTarget(Debugger &debugger, - llvm::StringRef user_exe_path, - const ArchSpec &specified_arch, - bool get_dependent_files, - PlatformSP &platform_sp, TargetSP &target_sp) { +Status TargetList::CreateTarget(Debugger &debugger, + llvm::StringRef user_exe_path, + const ArchSpec &specified_arch, + bool get_dependent_files, + PlatformSP &platform_sp, TargetSP &target_sp) { return CreateTargetInternal(debugger, user_exe_path, specified_arch, get_dependent_files, platform_sp, target_sp, false); } -Error TargetList::CreateTargetInternal( +Status TargetList::CreateTargetInternal( Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, bool get_dependent_files, const OptionGroupPlatform *platform_options, TargetSP &target_sp, bool is_dummy_target) { - Error error; + Status error; PlatformSP platform_sp; // This is purposely left empty unless it is specified by triple_cstr. @@ -302,34 +302,34 @@ lldb::TargetSP TargetList::GetDummyTarget(lldb_private::Debugger &debugger) { ArchSpec arch(Target::GetDefaultArchitecture()); if (!arch.IsValid()) arch = HostInfo::GetArchitecture(); - Error err = CreateDummyTarget( + Status err = CreateDummyTarget( debugger, arch.GetTriple().getTriple().c_str(), m_dummy_target_sp); } return m_dummy_target_sp; } -Error TargetList::CreateDummyTarget(Debugger &debugger, - llvm::StringRef specified_arch_name, - lldb::TargetSP &target_sp) { +Status TargetList::CreateDummyTarget(Debugger &debugger, + llvm::StringRef specified_arch_name, + lldb::TargetSP &target_sp) { PlatformSP host_platform_sp(Platform::GetHostPlatform()); return CreateTargetInternal( debugger, (const char *)nullptr, specified_arch_name, false, (const OptionGroupPlatform *)nullptr, target_sp, true); } -Error TargetList::CreateTargetInternal(Debugger &debugger, - llvm::StringRef user_exe_path, - const ArchSpec &specified_arch, - bool get_dependent_files, - lldb::PlatformSP &platform_sp, - lldb::TargetSP &target_sp, - bool is_dummy_target) { - Timer scoped_timer(LLVM_PRETTY_FUNCTION, - "TargetList::CreateTarget (file = '%s', arch = '%s')", - user_exe_path.str().c_str(), - specified_arch.GetArchitectureName()); - Error error; +Status TargetList::CreateTargetInternal(Debugger &debugger, + llvm::StringRef user_exe_path, + const ArchSpec &specified_arch, + bool get_dependent_files, + lldb::PlatformSP &platform_sp, + lldb::TargetSP &target_sp, + bool is_dummy_target) { + static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); + Timer scoped_timer( + func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')", + user_exe_path.str().c_str(), specified_arch.GetArchitectureName()); + Status error; ArchSpec arch(specified_arch); diff --git a/contrib/llvm/tools/lldb/source/Target/Thread.cpp b/contrib/llvm/tools/lldb/source/Target/Thread.cpp index 4b21382ff86f..43ae7b5413be 100644 --- a/contrib/llvm/tools/lldb/source/Target/Thread.cpp +++ b/contrib/llvm/tools/lldb/source/Target/Thread.cpp @@ -1335,8 +1335,8 @@ bool Thread::PlanIsBasePlan(ThreadPlan *plan_ptr) { return m_plan_stack[0].get() == plan_ptr; } -Error Thread::UnwindInnermostExpression() { - Error error; +Status Thread::UnwindInnermostExpression() { + Status error; int stack_size = m_plan_stack.size(); // If the input plan is nullptr, discard all plans. Otherwise make sure this @@ -1635,11 +1635,11 @@ lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) { return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx); } -Error Thread::ReturnFromFrameWithIndex(uint32_t frame_idx, - lldb::ValueObjectSP return_value_sp, - bool broadcast) { +Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx, + lldb::ValueObjectSP return_value_sp, + bool broadcast) { StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx); - Error return_error; + Status return_error; if (!frame_sp) { return_error.SetErrorStringWithFormat( @@ -1650,10 +1650,10 @@ Error Thread::ReturnFromFrameWithIndex(uint32_t frame_idx, return ReturnFromFrame(frame_sp, return_value_sp, broadcast); } -Error Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp, - lldb::ValueObjectSP return_value_sp, - bool broadcast) { - Error return_error; +Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp, + lldb::ValueObjectSP return_value_sp, + bool broadcast) { + Status return_error; if (!frame_sp) { return_error.SetErrorString("Can't return to a null frame."); @@ -1740,8 +1740,8 @@ static void DumpAddressList(Stream &s, const std::vector<Address> &list, } } -Error Thread::JumpToLine(const FileSpec &file, uint32_t line, - bool can_leave_function, std::string *warnings) { +Status Thread::JumpToLine(const FileSpec &file, uint32_t line, + bool can_leave_function, std::string *warnings) { ExecutionContext exe_ctx(GetStackFrameAtIndex(0)); Target *target = exe_ctx.GetTargetPtr(); TargetSP target_sp = exe_ctx.GetTargetSP(); @@ -1769,16 +1769,16 @@ Error Thread::JumpToLine(const FileSpec &file, uint32_t line, // Check if we got anything. if (candidates.empty()) { if (outside_function.empty()) { - return Error("Cannot locate an address for %s:%i.", - file.GetFilename().AsCString(), line); + return Status("Cannot locate an address for %s:%i.", + file.GetFilename().AsCString(), line); } else if (outside_function.size() == 1) { - return Error("%s:%i is outside the current function.", - file.GetFilename().AsCString(), line); + return Status("%s:%i is outside the current function.", + file.GetFilename().AsCString(), line); } else { StreamString sstr; DumpAddressList(sstr, outside_function, target); - return Error("%s:%i has multiple candidate locations:\n%s", - file.GetFilename().AsCString(), line, sstr.GetData()); + return Status("%s:%i has multiple candidate locations:\n%s", + file.GetFilename().AsCString(), line, sstr.GetData()); } } @@ -1794,9 +1794,9 @@ Error Thread::JumpToLine(const FileSpec &file, uint32_t line, } if (!reg_ctx->SetPC(dest)) - return Error("Cannot change PC to target address."); + return Status("Cannot change PC to target address."); - return Error(); + return Status(); } void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, @@ -2001,8 +2001,8 @@ bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level, StructuredData::ObjectSP name = activity_dict->GetValueForKey("name"); if (name && name->GetType() == StructuredData::Type::eTypeString && id && id->GetType() == StructuredData::Type::eTypeInteger) { - strm.Printf(" Activity '%s', 0x%" PRIx64 "\n", - name->GetAsString()->GetValue().c_str(), + strm.Format(" Activity '{0}', {1:x}\n", + name->GetAsString()->GetValue(), id->GetAsInteger()->GetValue()); } printed_activity = true; @@ -2018,8 +2018,8 @@ bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level, breadcrumb_dict->GetValueForKey("name"); if (breadcrumb_text && breadcrumb_text->GetType() == StructuredData::Type::eTypeString) { - strm.Printf(" Current Breadcrumb: %s\n", - breadcrumb_text->GetAsString()->GetValue().c_str()); + strm.Format(" Current Breadcrumb: {0}\n", + breadcrumb_text->GetAsString()->GetValue()); } printed_breadcrumb = true; } @@ -2040,8 +2040,7 @@ bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level, message_dict->GetValueForKey("message"); if (message_text && message_text->GetType() == StructuredData::Type::eTypeString) { - strm.Printf(" %s\n", - message_text->GetAsString()->GetValue().c_str()); + strm.Format(" {0}\n", message_text->GetAsString()->GetValue()); } } } @@ -2117,12 +2116,12 @@ bool Thread::IsStillAtLastBreakpointHit() { return false; } -Error Thread::StepIn(bool source_step, - LazyBool step_in_avoids_code_without_debug_info, - LazyBool step_out_avoids_code_without_debug_info) +Status Thread::StepIn(bool source_step, + LazyBool step_in_avoids_code_without_debug_info, + LazyBool step_out_avoids_code_without_debug_info) { - Error error; + Status error; Process *process = GetProcess().get(); if (StateIsStoppedState(process->GetState(), true)) { StackFrameSP frame_sp = GetStackFrameAtIndex(0); @@ -2153,9 +2152,9 @@ Error Thread::StepIn(bool source_step, return error; } -Error Thread::StepOver(bool source_step, - LazyBool step_out_avoids_code_without_debug_info) { - Error error; +Status Thread::StepOver(bool source_step, + LazyBool step_out_avoids_code_without_debug_info) { + Status error; Process *process = GetProcess().get(); if (StateIsStoppedState(process->GetState(), true)) { StackFrameSP frame_sp = GetStackFrameAtIndex(0); @@ -2186,8 +2185,8 @@ Error Thread::StepOver(bool source_step, return error; } -Error Thread::StepOut() { - Error error; +Status Thread::StepOut() { + Status error; Process *process = GetProcess().get(); if (StateIsStoppedState(process->GetState(), true)) { const bool first_instruction = false; diff --git a/contrib/llvm/tools/lldb/source/Target/ThreadPlanCallFunction.cpp b/contrib/llvm/tools/lldb/source/Target/ThreadPlanCallFunction.cpp index 2c630d59e84c..e3b9ae15dc95 100644 --- a/contrib/llvm/tools/lldb/source/Target/ThreadPlanCallFunction.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ThreadPlanCallFunction.cpp @@ -58,7 +58,7 @@ bool ThreadPlanCallFunction::ConstructorSetup( // If we can't read memory at the point of the process where we are planning // to put our function, we're // not going to get any further... - Error error; + Status error; process_sp->ReadUnsignedIntegerFromMemory(m_function_sp, 4, 0, error); if (!error.Success()) { m_constructor_errors.Printf( diff --git a/contrib/llvm/tools/lldb/source/Target/ThreadPlanTracer.cpp b/contrib/llvm/tools/lldb/source/Target/ThreadPlanTracer.cpp index f8368123a0c7..014c7fd27975 100644 --- a/contrib/llvm/tools/lldb/source/Target/ThreadPlanTracer.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ThreadPlanTracer.cpp @@ -145,7 +145,7 @@ void ThreadPlanAssemblyTracer::Log() { Disassembler *disassembler = GetDisassembler(); if (disassembler) { - Error err; + Status err; process_sp->ReadMemory(pc, buffer, sizeof(buffer), err); if (err.Success()) { diff --git a/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp b/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp index c7eec078612a..f769d1a775af 100644 --- a/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp +++ b/contrib/llvm/tools/lldb/source/Target/ThreadSpec.cpp @@ -39,11 +39,11 @@ const ThreadSpec &ThreadSpec::operator=(const ThreadSpec &rhs) { } std::unique_ptr<ThreadSpec> ThreadSpec::CreateFromStructuredData( - const StructuredData::Dictionary &spec_dict, Error &error) { + const StructuredData::Dictionary &spec_dict, Status &error) { uint32_t index = UINT32_MAX; lldb::tid_t tid = LLDB_INVALID_THREAD_ID; - std::string name; - std::string queue_name; + llvm::StringRef name; + llvm::StringRef queue_name; std::unique_ptr<ThreadSpec> thread_spec_up(new ThreadSpec()); bool success = spec_dict.GetValueForKeyAsInteger( @@ -59,12 +59,12 @@ std::unique_ptr<ThreadSpec> ThreadSpec::CreateFromStructuredData( success = spec_dict.GetValueForKeyAsString(GetKey(OptionNames::ThreadName), name); if (success) - thread_spec_up->SetName(name.c_str()); + thread_spec_up->SetName(name); success = spec_dict.GetValueForKeyAsString(GetKey(OptionNames::ThreadName), queue_name); if (success) - thread_spec_up->SetQueueName(queue_name.c_str()); + thread_spec_up->SetQueueName(queue_name); return thread_spec_up; } diff --git a/contrib/llvm/tools/lldb/source/Utility/JSON.cpp b/contrib/llvm/tools/lldb/source/Utility/JSON.cpp index d20d9e46fefd..cb23f140cbfe 100644 --- a/contrib/llvm/tools/lldb/source/Utility/JSON.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/JSON.cpp @@ -246,7 +246,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { "error: an error occurred getting a character from offset %" PRIu64, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } else { const bool is_end_quote = escaped_ch == '"'; @@ -259,13 +259,13 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { "character 0x%4.4x at offset %" PRIu64, escaped_ch, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } } else if (is_end_quote) { return Token::String; } else if (is_null) { value = "error: missing end quote for string"; - return Token::Error; + return Token::Status; } } } @@ -316,7 +316,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { error.Printf("error: extra decimal point found at offset %" PRIu64, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } else { got_decimal_point = true; ++m_index; // Skip this character @@ -330,7 +330,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { "error: extra exponent character found at offset %" PRIu64, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } else { exp_index = m_index; ++m_index; // Skip this character @@ -346,7 +346,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { error.Printf("error: unexpected %c character at offset %" PRIu64, next_ch, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } break; @@ -368,7 +368,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { "at offset in float value \"%s\"", value.c_str()); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } } else { // No exponent, but we need at least one decimal after the decimal @@ -379,7 +379,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { error.Printf("error: no digits after decimal point \"%s\"", value.c_str()); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } } } else { @@ -390,14 +390,14 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { } else { error.Printf("error: no digits negate sign \"%s\"", value.c_str()); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } } } else { error.Printf("error: invalid number found at offset %" PRIu64, start_index); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } } break; default: @@ -407,7 +407,7 @@ JSONParser::Token JSONParser::GetToken(std::string &value) { " (around character '%c')", start_index, ch); value = std::move(error.GetString()); - return Token::Error; + return Token::Status; } int JSONParser::GetEscapedChar(bool &was_escaped) { diff --git a/contrib/llvm/tools/lldb/source/Utility/SelectHelper.cpp b/contrib/llvm/tools/lldb/source/Utility/SelectHelper.cpp index 7b0557ea192c..a46213f8bfcb 100644 --- a/contrib/llvm/tools/lldb/source/Utility/SelectHelper.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/SelectHelper.cpp @@ -15,8 +15,8 @@ #endif #include "lldb/Utility/SelectHelper.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/LLDBAssert.h" +#include "lldb/Utility/Status.h" #include "lldb/lldb-enumerations.h" // for ErrorType::eErrorTypePOSIX #include "lldb/lldb-types.h" // for socket_t @@ -90,14 +90,14 @@ static void updateMaxFd(llvm::Optional<lldb::socket_t> &vold, vold = std::max(*vold, vnew); } -lldb_private::Error SelectHelper::Select() { - lldb_private::Error error; +lldb_private::Status SelectHelper::Select() { + lldb_private::Status error; #ifdef _MSC_VER // On windows FD_SETSIZE limits the number of file descriptors, not their // numeric value. lldbassert(m_fd_map.size() <= FD_SETSIZE); if (m_fd_map.size() > FD_SETSIZE) - return lldb_private::Error("Too many file descriptors for select()"); + return lldb_private::Status("Too many file descriptors for select()"); #endif llvm::Optional<lldb::socket_t> max_read_fd; diff --git a/contrib/llvm/tools/lldb/source/Utility/Error.cpp b/contrib/llvm/tools/lldb/source/Utility/Status.cpp index b21ee57b61af..5996be1e4e05 100644 --- a/contrib/llvm/tools/lldb/source/Utility/Error.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/Status.cpp @@ -1,4 +1,5 @@ -//===-- Error.cpp -----------------------------------------------*- C++ -*-===// +//===-- Status.cpp -----------------------------------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -7,7 +8,7 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include "lldb/Utility/VASPrintf.h" #include "lldb/lldb-defines.h" // for LLDB_GENERIC_ERROR @@ -35,18 +36,18 @@ class raw_ostream; using namespace lldb; using namespace lldb_private; -Error::Error() : m_code(0), m_type(eErrorTypeInvalid), m_string() {} +Status::Status() : m_code(0), m_type(eErrorTypeInvalid), m_string() {} -Error::Error(ValueType err, ErrorType type) +Status::Status(ValueType err, ErrorType type) : m_code(err), m_type(type), m_string() {} -Error::Error(std::error_code EC) +Status::Status(std::error_code EC) : m_code(EC.value()), m_type(ErrorType::eErrorTypeGeneric), m_string(EC.message()) {} -Error::Error(const Error &rhs) = default; +Status::Status(const Status &rhs) = default; -Error::Error(const char *format, ...) +Status::Status(const char *format, ...) : m_code(0), m_type(eErrorTypeInvalid), m_string() { va_list args; va_start(args, format); @@ -58,7 +59,7 @@ Error::Error(const char *format, ...) //---------------------------------------------------------------------- // Assignment operator //---------------------------------------------------------------------- -const Error &Error::operator=(const Error &rhs) { +const Status &Status::operator=(const Status &rhs) { if (this != &rhs) { m_code = rhs.m_code; m_type = rhs.m_type; @@ -70,21 +71,21 @@ const Error &Error::operator=(const Error &rhs) { //---------------------------------------------------------------------- // Assignment operator //---------------------------------------------------------------------- -const Error &Error::operator=(uint32_t err) { +const Status &Status::operator=(uint32_t err) { m_code = err; m_type = eErrorTypeMachKernel; m_string.clear(); return *this; } -Error::~Error() = default; +Status::~Status() = default; //---------------------------------------------------------------------- // Get the error value as a NULL C string. The error string will be // fetched and cached on demand. The cached error string value will // remain until the error value is changed or cleared. //---------------------------------------------------------------------- -const char *Error::AsCString(const char *default_error_str) const { +const char *Status::AsCString(const char *default_error_str) const { if (Success()) return nullptr; @@ -119,7 +120,7 @@ const char *Error::AsCString(const char *default_error_str) const { //---------------------------------------------------------------------- // Clear the error and any cached error string that it might contain. //---------------------------------------------------------------------- -void Error::Clear() { +void Status::Clear() { m_code = 0; m_type = eErrorTypeInvalid; m_string.clear(); @@ -128,38 +129,38 @@ void Error::Clear() { //---------------------------------------------------------------------- // Access the error value. //---------------------------------------------------------------------- -Error::ValueType Error::GetError() const { return m_code; } +Status::ValueType Status::GetError() const { return m_code; } //---------------------------------------------------------------------- // Access the error type. //---------------------------------------------------------------------- -ErrorType Error::GetType() const { return m_type; } +ErrorType Status::GetType() const { return m_type; } //---------------------------------------------------------------------- // Returns true if this object contains a value that describes an // error or otherwise non-success result. //---------------------------------------------------------------------- -bool Error::Fail() const { return m_code != 0; } +bool Status::Fail() const { return m_code != 0; } //---------------------------------------------------------------------- // Set accesssor for the error value to "err" and the type to // "eErrorTypeMachKernel" //---------------------------------------------------------------------- -void Error::SetMachError(uint32_t err) { +void Status::SetMachError(uint32_t err) { m_code = err; m_type = eErrorTypeMachKernel; m_string.clear(); } -void Error::SetExpressionError(lldb::ExpressionResults result, - const char *mssg) { +void Status::SetExpressionError(lldb::ExpressionResults result, + const char *mssg) { m_code = result; m_type = eErrorTypeExpression; m_string = mssg; } -int Error::SetExpressionErrorWithFormat(lldb::ExpressionResults result, - const char *format, ...) { +int Status::SetExpressionErrorWithFormat(lldb::ExpressionResults result, + const char *format, ...) { int length = 0; if (format != nullptr && format[0]) { @@ -178,7 +179,7 @@ int Error::SetExpressionErrorWithFormat(lldb::ExpressionResults result, //---------------------------------------------------------------------- // Set accesssor for the error value and type. //---------------------------------------------------------------------- -void Error::SetError(ValueType err, ErrorType type) { +void Status::SetError(ValueType err, ErrorType type) { m_code = err; m_type = type; m_string.clear(); @@ -188,7 +189,7 @@ void Error::SetError(ValueType err, ErrorType type) { // Update the error value to be "errno" and update the type to // be "POSIX". //---------------------------------------------------------------------- -void Error::SetErrorToErrno() { +void Status::SetErrorToErrno() { m_code = errno; m_type = eErrorTypePOSIX; m_string.clear(); @@ -198,7 +199,7 @@ void Error::SetErrorToErrno() { // Update the error value to be LLDB_GENERIC_ERROR and update the type // to be "Generic". //---------------------------------------------------------------------- -void Error::SetErrorToGenericError() { +void Status::SetErrorToGenericError() { m_code = LLDB_GENERIC_ERROR; m_type = eErrorTypeGeneric; m_string.clear(); @@ -210,7 +211,7 @@ void Error::SetErrorToGenericError() { // The error string value will remain until the error value is // cleared or a new error value/type is assigned. //---------------------------------------------------------------------- -void Error::SetErrorString(llvm::StringRef err_str) { +void Status::SetErrorString(llvm::StringRef err_str) { if (!err_str.empty()) { // If we have an error string, we should always at least have an error // set to a generic value. @@ -226,7 +227,7 @@ void Error::SetErrorString(llvm::StringRef err_str) { /// @param format /// A printf style format string //------------------------------------------------------------------ -int Error::SetErrorStringWithFormat(const char *format, ...) { +int Status::SetErrorStringWithFormat(const char *format, ...) { if (format != nullptr && format[0]) { va_list args; va_start(args, format); @@ -239,7 +240,7 @@ int Error::SetErrorStringWithFormat(const char *format, ...) { return 0; } -int Error::SetErrorStringWithVarArg(const char *format, va_list args) { +int Status::SetErrorStringWithVarArg(const char *format, va_list args) { if (format != nullptr && format[0]) { // If we have an error string, we should always at least have // an error set to a generic value. @@ -260,14 +261,14 @@ int Error::SetErrorStringWithVarArg(const char *format, va_list args) { // Returns true if the error code in this object is considered a // successful return value. //---------------------------------------------------------------------- -bool Error::Success() const { return m_code == 0; } +bool Status::Success() const { return m_code == 0; } -bool Error::WasInterrupted() const { +bool Status::WasInterrupted() const { return (m_type == eErrorTypePOSIX && m_code == EINTR); } -void llvm::format_provider<lldb_private::Error>::format( - const lldb_private::Error &error, llvm::raw_ostream &OS, +void llvm::format_provider<lldb_private::Status>::format( + const lldb_private::Status &error, llvm::raw_ostream &OS, llvm::StringRef Options) { llvm::format_provider<llvm::StringRef>::format(error.AsCString(), OS, Options); diff --git a/contrib/llvm/tools/lldb/source/Utility/UUID.cpp b/contrib/llvm/tools/lldb/source/Utility/UUID.cpp index d82f4d41215e..b47f8b52f1c2 100644 --- a/contrib/llvm/tools/lldb/source/Utility/UUID.cpp +++ b/contrib/llvm/tools/lldb/source/Utility/UUID.cpp @@ -160,12 +160,9 @@ llvm::StringRef UUID::DecodeUUIDBytesFromString(llvm::StringRef p, bytes_decoded = uuid_byte_idx; return p; } -size_t UUID::SetFromCString(const char *cstr, uint32_t num_uuid_bytes) { - if (cstr == NULL) - return 0; - llvm::StringRef orig(cstr); - llvm::StringRef p = orig; +size_t UUID::SetFromStringRef(llvm::StringRef str, uint32_t num_uuid_bytes) { + llvm::StringRef p = str; // Skip leading whitespace characters p = p.ltrim(); @@ -178,12 +175,19 @@ size_t UUID::SetFromCString(const char *cstr, uint32_t num_uuid_bytes) { // were consumed if (bytes_decoded == num_uuid_bytes) { m_num_uuid_bytes = num_uuid_bytes; - return orig.size() - rest.size(); + return str.size() - rest.size(); } // Else return zero to indicate we were not able to parse a UUID value return 0; } + +size_t UUID::SetFromCString(const char *cstr, uint32_t num_uuid_bytes) { + if (cstr == NULL) + return 0; + + return SetFromStringRef(cstr, num_uuid_bytes); +} } bool lldb_private::operator==(const lldb_private::UUID &lhs, diff --git a/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdBase.cpp b/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdBase.cpp index c645d84c1e99..cd5bf27c73fe 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdBase.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdBase.cpp @@ -195,7 +195,7 @@ bool CMICmdBase::HasMIResultRecordExtra() const { // metadata // object and set the command's error status. // Type: Method. -// Args: rErrMsg - (R) Error description. +// Args: rErrMsg - (R) Status description. // Return: None. // Throws: None. //-- diff --git a/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdCmdData.h b/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdCmdData.h index 683e41022af5..ab8d6ba5cd19 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdCmdData.h +++ b/contrib/llvm/tools/lldb/tools/lldb-mi/MICmdCmdData.h @@ -77,7 +77,7 @@ private: bool m_bExpressionValid; // True = yes is valid, false = not valid bool m_bEvaluatedExpression; // True = yes is expression evaluated, false = // failed - lldb::SBError m_Error; // Error object, which is examined when + lldb::SBError m_Error; // Status object, which is examined when // m_bEvaluatedExpression is false CMIUtilString m_strValue; CMICmnMIValueTuple m_miValueTuple; diff --git a/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriver.cpp b/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriver.cpp index ea8b57297dda..49e8588bf732 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriver.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriver.cpp @@ -710,7 +710,7 @@ const CMIUtilString &CMIDriver::GetDriverId() const { return GetId(); } // Check the error message if the function returns a failure. // Type: Overridden. // Args: vCmd - (R) Command instruction to interpret. -// vwErrMsg - (W) Error description on command failing. +// vwErrMsg - (W) Status description on command failing. // Return: MIstatus::success - Command succeeded. // MIstatus::failure - Command failed. // Throws: None. diff --git a/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriverBase.cpp b/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriverBase.cpp index 0620b6154b1a..f70da6ea08e1 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriverBase.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-mi/MIDriverBase.cpp @@ -44,7 +44,7 @@ CMIDriverBase::~CMIDriverBase() { m_pDriverFallThru = NULL; } // Check the error message if the function returns a failure. // Type: Overridden. // Args: vCmd - (R) Command instruction to interpret. -// vwErrMsg - (W) Error description on command failing. +// vwErrMsg - (W) Status description on command failing. // Return: MIstatus::success - Command succeeded. // MIstatus::failure - Command failed. // Throws: None. diff --git a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.cpp b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.cpp index 48a364886dc3..16db9e9d30df 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.cpp @@ -56,11 +56,11 @@ const char *FindSchemeByProtocol(const Socket::SocketProtocol protocol) { } } -Error Acceptor::Listen(int backlog) { +Status Acceptor::Listen(int backlog) { return m_listener_socket_up->Listen(StringRef(m_name), backlog); } -Error Acceptor::Accept(const bool child_processes_inherit, Connection *&conn) { +Status Acceptor::Accept(const bool child_processes_inherit, Connection *&conn) { Socket *conn_socket = nullptr; auto error = m_listener_socket_up->Accept(conn_socket); if (error.Success()) @@ -81,7 +81,7 @@ std::string Acceptor::GetLocalSocketId() const { return m_local_socket_id(); } std::unique_ptr<Acceptor> Acceptor::Create(StringRef name, const bool child_processes_inherit, - Error &error) { + Status &error) { error.Clear(); Socket::SocketProtocol socket_protocol = Socket::ProtocolUnixDomain; diff --git a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h index 410970915f1f..207bb4d973a5 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h +++ b/contrib/llvm/tools/lldb/tools/lldb-server/Acceptor.h @@ -11,7 +11,7 @@ #include "lldb/Core/Connection.h" #include "lldb/Host/Socket.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #include <functional> #include <memory> @@ -28,13 +28,13 @@ class Acceptor { public: virtual ~Acceptor() = default; - Error Listen(int backlog); + Status Listen(int backlog); - Error Accept(const bool child_processes_inherit, Connection *&conn); + Status Accept(const bool child_processes_inherit, Connection *&conn); static std::unique_ptr<Acceptor> Create(llvm::StringRef name, const bool child_processes_inherit, - Error &error); + Status &error); Socket::SocketProtocol GetSocketProtocol() const; diff --git a/contrib/llvm/tools/lldb/tools/lldb-server/lldb-gdbserver.cpp b/contrib/llvm/tools/lldb/tools/lldb-server/lldb-gdbserver.cpp index 59f5a44ce4e3..6139bfabee3d 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-server/lldb-gdbserver.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-server/lldb-gdbserver.cpp @@ -35,7 +35,7 @@ #include "lldb/Host/Pipe.h" #include "lldb/Host/Socket.h" #include "lldb/Host/StringConvert.h" -#include "lldb/Utility/Error.h" +#include "lldb/Utility/Status.h" #ifndef LLGS_PROGRAM_NAME #define LLGS_PROGRAM_NAME "lldb-server" @@ -112,7 +112,7 @@ static void display_usage(const char *progname, const char *subcommand) { void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid) { - Error error = gdb_server.AttachToProcess(pid); + Status error = gdb_server.AttachToProcess(pid); if (error.Fail()) { fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString()); @@ -145,7 +145,7 @@ void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server, void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[]) { - Error error; + Status error; error = gdb_server.SetLaunchArguments(argv, argc); if (error.Fail()) { fprintf(stderr, "error: failed to set launch args for '%s': %s\n", argv[0], @@ -170,15 +170,15 @@ void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc, } } -Error writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) { +Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) { size_t bytes_written = 0; // Write the port number as a C string with the NULL terminator. return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1, bytes_written); } -Error writeSocketIdToPipe(const char *const named_pipe_path, - const std::string &socket_id) { +Status writeSocketIdToPipe(const char *const named_pipe_path, + const std::string &socket_id) { Pipe port_name_pipe; // Wait for 10 seconds for pipe to be opened. auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false, @@ -188,9 +188,9 @@ Error writeSocketIdToPipe(const char *const named_pipe_path, return writeSocketIdToPipe(port_name_pipe, socket_id); } -Error writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id) { +Status writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id) { #if defined(_WIN32) - return Error("Unnamed pipes are not supported on Windows."); + return Status("Unnamed pipes are not supported on Windows."); #else Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd}; return writeSocketIdToPipe(port_pipe, socket_id); @@ -202,7 +202,7 @@ void ConnectToRemote(MainLoop &mainloop, bool reverse_connect, const char *const host_and_port, const char *const progname, const char *const subcommand, const char *const named_pipe_path, int unnamed_pipe_fd) { - Error error; + Status error; if (host_and_port && host_and_port[0]) { // Parse out host and port. @@ -311,7 +311,7 @@ void ConnectToRemote(MainLoop &mainloop, // main //---------------------------------------------------------------------- int main_gdbserver(int argc, char *argv[]) { - Error error; + Status error; MainLoop mainloop; #ifndef _WIN32 // Setup signal handlers first thing. diff --git a/contrib/llvm/tools/lldb/tools/lldb-server/lldb-platform.cpp b/contrib/llvm/tools/lldb/tools/lldb-server/lldb-platform.cpp index d9790cdf43a0..8d45682566b9 100644 --- a/contrib/llvm/tools/lldb/tools/lldb-server/lldb-platform.cpp +++ b/contrib/llvm/tools/lldb/tools/lldb-server/lldb-platform.cpp @@ -34,8 +34,8 @@ #include "lldb/Host/HostGetOpt.h" #include "lldb/Host/OptionParser.h" #include "lldb/Host/common/TCPSocket.h" -#include "lldb/Utility/Error.h" #include "lldb/Utility/FileSpec.h" +#include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; @@ -98,13 +98,13 @@ static void display_usage(const char *progname, const char *subcommand) { exit(0); } -static Error save_socket_id_to_file(const std::string &socket_id, - const FileSpec &file_spec) { +static Status save_socket_id_to_file(const std::string &socket_id, + const FileSpec &file_spec) { FileSpec temp_file_spec(file_spec.GetDirectory().AsCString(), false); - Error error(llvm::sys::fs::create_directory(temp_file_spec.GetPath())); + Status error(llvm::sys::fs::create_directory(temp_file_spec.GetPath())); if (error.Fail()) - return Error("Failed to create directory %s: %s", - temp_file_spec.GetCString(), error.AsCString()); + return Status("Failed to create directory %s: %s", + temp_file_spec.GetCString(), error.AsCString()); llvm::SmallString<64> temp_file_path; temp_file_spec.AppendPathComponent("port-file.%%%%%%"); @@ -112,7 +112,7 @@ static Error save_socket_id_to_file(const std::string &socket_id, auto err_code = llvm::sys::fs::createUniqueFile(temp_file_spec.GetPath(), FD, temp_file_path); if (err_code) - return Error("Failed to create temp file: %s", err_code.message().c_str()); + return Status("Failed to create temp file: %s", err_code.message().c_str()); llvm::FileRemover tmp_file_remover(temp_file_path); @@ -121,16 +121,16 @@ static Error save_socket_id_to_file(const std::string &socket_id, temp_file << socket_id; temp_file.close(); if (temp_file.has_error()) - return Error("Failed to write to port file."); + return Status("Failed to write to port file."); } err_code = llvm::sys::fs::rename(temp_file_path, file_spec.GetPath()); if (err_code) - return Error("Failed to rename file %s to %s: %s", temp_file_path.c_str(), - file_spec.GetPath().c_str(), err_code.message().c_str()); + return Status("Failed to rename file %s to %s: %s", temp_file_path.c_str(), + file_spec.GetPath().c_str(), err_code.message().c_str()); tmp_file_remover.releaseFile(); - return Error(); + return Status(); } //---------------------------------------------------------------------- @@ -144,7 +144,7 @@ int main_platform(int argc, char *argv[]) { signal(SIGPIPE, SIG_IGN); signal(SIGHUP, signal_handler); int long_option_index = 0; - Error error; + Status error; std::string listen_host_port; int ch; @@ -350,9 +350,9 @@ int main_platform(int argc, char *argv[]) { lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; uint16_t port = 0; std::string socket_name; - Error error = platform.LaunchGDBServer(inferior_arguments, - "", // hostname - pid, port, socket_name); + Status error = platform.LaunchGDBServer(inferior_arguments, + "", // hostname + pid, port, socket_name); if (error.Success()) platform.SetPendingGdbServer(pid, port, socket_name); else diff --git a/contrib/llvm/tools/lli/RemoteJITUtils.h b/contrib/llvm/tools/lli/RemoteJITUtils.h index 89a514202567..3c82f73ff072 100644 --- a/contrib/llvm/tools/lli/RemoteJITUtils.h +++ b/contrib/llvm/tools/lli/RemoteJITUtils.h @@ -118,9 +118,8 @@ public: MemMgr->registerEHFrames(Addr, LoadAddr, Size); } - void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, - size_t Size) override { - MemMgr->deregisterEHFrames(Addr, LoadAddr, Size); + void deregisterEHFrames() override { + MemMgr->deregisterEHFrames(); } bool finalizeMemory(std::string *ErrMsg = nullptr) override { diff --git a/contrib/llvm/tools/llvm-ar/llvm-ar.cpp b/contrib/llvm/tools/llvm-ar/llvm-ar.cpp index 1519464521dd..3de260410bd9 100644 --- a/contrib/llvm/tools/llvm-ar/llvm-ar.cpp +++ b/contrib/llvm/tools/llvm-ar/llvm-ar.cpp @@ -16,7 +16,7 @@ #include "llvm/ADT/Triple.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" -#include "llvm/LibDriver/LibDriver.h" +#include "llvm/ToolDrivers/llvm-lib/LibDriver.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ArchiveWriter.h" #include "llvm/Object/MachO.h" diff --git a/contrib/llvm/tools/llvm-pdbdump/LLVMOutputStyle.cpp b/contrib/llvm/tools/llvm-pdbdump/LLVMOutputStyle.cpp index 2dd4ef0fb30d..e975a5220af6 100644 --- a/contrib/llvm/tools/llvm-pdbdump/LLVMOutputStyle.cpp +++ b/contrib/llvm/tools/llvm-pdbdump/LLVMOutputStyle.cpp @@ -180,7 +180,7 @@ private: CompactTypeDumpVisitor CTDV(DB, Index, &P); CVTypeVisitor Visitor(CTDV); DictScope D(P, Label); - if (DB.containsTypeIndex(Index)) { + if (DB.contains(Index)) { CVType &Type = DB.getTypeRecord(Index); if (auto EC = Visitor.visitTypeRecord(Type)) return EC; diff --git a/contrib/llvm/tools/llvm-pdbdump/PrettyCompilandDumper.cpp b/contrib/llvm/tools/llvm-pdbdump/PrettyCompilandDumper.cpp index 6257313e3e1a..9cf7bf82a164 100644 --- a/contrib/llvm/tools/llvm-pdbdump/PrettyCompilandDumper.cpp +++ b/contrib/llvm/tools/llvm-pdbdump/PrettyCompilandDumper.cpp @@ -115,6 +115,8 @@ void CompilandDumper::start(const PDBSymbolCompiland &Symbol, } void CompilandDumper::dump(const PDBSymbolData &Symbol) { + if (!shouldDumpSymLevel(opts::pretty::SymLevel::Data)) + return; if (Printer.IsSymbolExcluded(Symbol.getName())) return; @@ -125,11 +127,17 @@ void CompilandDumper::dump(const PDBSymbolData &Symbol) { Printer << "data: "; WithColor(Printer, PDB_ColorItem::Address).get() << "[" << format_hex(Symbol.getVirtualAddress(), 10) << "]"; + + WithColor(Printer, PDB_ColorItem::Comment).get() + << " [sizeof = " << getTypeLength(Symbol) << "]"; + break; case PDB_LocType::Constant: Printer << "constant: "; WithColor(Printer, PDB_ColorItem::LiteralValue).get() << "[" << Symbol.getValue() << "]"; + WithColor(Printer, PDB_ColorItem::Comment).get() + << " [sizeof = " << getTypeLength(Symbol) << "]"; break; default: Printer << "data(unexpected type=" << LocType << ")"; @@ -140,6 +148,8 @@ void CompilandDumper::dump(const PDBSymbolData &Symbol) { } void CompilandDumper::dump(const PDBSymbolFunc &Symbol) { + if (!shouldDumpSymLevel(opts::pretty::SymLevel::Functions)) + return; if (Symbol.getLength() == 0) return; if (Printer.IsSymbolExcluded(Symbol.getName())) @@ -162,6 +172,8 @@ void CompilandDumper::dump(const PDBSymbolLabel &Symbol) { } void CompilandDumper::dump(const PDBSymbolThunk &Symbol) { + if (!shouldDumpSymLevel(opts::pretty::SymLevel::Thunks)) + return; if (Printer.IsSymbolExcluded(Symbol.getName())) return; diff --git a/contrib/llvm/tools/llvm-pdbdump/PrettyFunctionDumper.cpp b/contrib/llvm/tools/llvm-pdbdump/PrettyFunctionDumper.cpp index b0be33c157ce..8b2043989b81 100644 --- a/contrib/llvm/tools/llvm-pdbdump/PrettyFunctionDumper.cpp +++ b/contrib/llvm/tools/llvm-pdbdump/PrettyFunctionDumper.cpp @@ -26,6 +26,7 @@ #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/Support/Format.h" +#include "llvm/Support/FormatVariadic.h" using namespace llvm; using namespace llvm::codeview; @@ -119,14 +120,19 @@ void FunctionDumper::start(const PDBSymbolFunc &Symbol, PointerType Pointer) { WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(FuncStart, 10); if (auto DebugStart = Symbol.findOneChild<PDBSymbolFuncDebugStart>()) { uint64_t Prologue = DebugStart->getVirtualAddress() - FuncStart; - WithColor(Printer, PDB_ColorItem::Offset).get() << "+" << Prologue; + WithColor(Printer, PDB_ColorItem::Offset).get() + << formatv("+{0,2}", Prologue); } Printer << " - "; WithColor(Printer, PDB_ColorItem::Address).get() << format_hex(FuncEnd, 10); if (auto DebugEnd = Symbol.findOneChild<PDBSymbolFuncDebugEnd>()) { uint64_t Epilogue = FuncEnd - DebugEnd->getVirtualAddress(); - WithColor(Printer, PDB_ColorItem::Offset).get() << "-" << Epilogue; + WithColor(Printer, PDB_ColorItem::Offset).get() + << formatv("-{0,2}", Epilogue); } + + WithColor(Printer, PDB_ColorItem::Comment).get() + << formatv(" | sizeof={0,3}", Symbol.getLength()); Printer << "] ("; if (Symbol.hasFramePointer()) { diff --git a/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp b/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp index 4cdd87620c86..0e5913fa3c93 100644 --- a/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp +++ b/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp @@ -110,12 +110,22 @@ cl::list<std::string> InputFilenames(cl::Positional, cl::opt<bool> Compilands("compilands", cl::desc("Display compilands"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); -cl::opt<bool> Symbols("symbols", cl::desc("Display symbols for each compiland"), +cl::opt<bool> Symbols("module-syms", + cl::desc("Display symbols for each compiland"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); cl::opt<bool> Globals("globals", cl::desc("Dump global symbols"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); cl::opt<bool> Externals("externals", cl::desc("Dump external symbols"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); +cl::list<SymLevel> SymTypes( + "sym-types", cl::desc("Type of symbols to dump (default all)"), + cl::cat(TypeCategory), cl::sub(PrettySubcommand), cl::ZeroOrMore, + cl::values( + clEnumValN(SymLevel::Thunks, "thunks", "Display thunk symbols"), + clEnumValN(SymLevel::Data, "data", "Display data symbols"), + clEnumValN(SymLevel::Functions, "funcs", "Display function symbols"), + clEnumValN(SymLevel::All, "all", "Display all symbols (default)"))); + cl::opt<bool> Types("types", cl::desc("Display all types (implies -classes, -enums, -typedefs)"), @@ -126,6 +136,16 @@ cl::opt<bool> Enums("enums", cl::desc("Display enum types"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); cl::opt<bool> Typedefs("typedefs", cl::desc("Display typedef types"), cl::cat(TypeCategory), cl::sub(PrettySubcommand)); +cl::opt<SymbolSortMode> SymbolOrder( + "symbol-order", cl::desc("symbol sort order"), + cl::init(SymbolSortMode::None), + cl::values(clEnumValN(SymbolSortMode::None, "none", + "Undefined / no particular sort order"), + clEnumValN(SymbolSortMode::Name, "name", "Sort symbols by name"), + clEnumValN(SymbolSortMode::Size, "size", + "Sort symbols by size")), + cl::cat(TypeCategory), cl::sub(PrettySubcommand)); + cl::opt<ClassSortMode> ClassOrder( "class-order", cl::desc("Class sort order"), cl::init(ClassSortMode::None), cl::values( @@ -620,6 +640,49 @@ static void diff(StringRef Path1, StringRef Path2) { ExitOnErr(O->dump()); } +bool opts::pretty::shouldDumpSymLevel(SymLevel Search) { + if (SymTypes.empty()) + return true; + if (llvm::find(SymTypes, Search) != SymTypes.end()) + return true; + if (llvm::find(SymTypes, SymLevel::All) != SymTypes.end()) + return true; + return false; +} + +uint32_t llvm::pdb::getTypeLength(const PDBSymbolData &Symbol) { + auto SymbolType = Symbol.getType(); + const IPDBRawSymbol &RawType = SymbolType->getRawSymbol(); + + return RawType.getLength(); +} + +bool opts::pretty::compareFunctionSymbols( + const std::unique_ptr<PDBSymbolFunc> &F1, + const std::unique_ptr<PDBSymbolFunc> &F2) { + assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None); + + if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name) + return F1->getName() < F2->getName(); + + // Note that we intentionally sort in descending order on length, since + // long functions are more interesting than short functions. + return F1->getLength() > F2->getLength(); +} + +bool opts::pretty::compareDataSymbols( + const std::unique_ptr<PDBSymbolData> &F1, + const std::unique_ptr<PDBSymbolData> &F2) { + assert(opts::pretty::SymbolOrder != opts::pretty::SymbolSortMode::None); + + if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::Name) + return F1->getName() < F2->getName(); + + // Note that we intentionally sort in descending order on length, since + // large types are more interesting than short ones. + return getTypeLength(*F1) > getTypeLength(*F2); +} + static void dumpPretty(StringRef Path) { std::unique_ptr<IPDBSession> Session; @@ -708,21 +771,42 @@ static void dumpPretty(StringRef Path) { Printer.NewLine(); WithColor(Printer, PDB_ColorItem::SectionHeader).get() << "---GLOBALS---"; Printer.Indent(); - { + if (shouldDumpSymLevel(opts::pretty::SymLevel::Functions)) { FunctionDumper Dumper(Printer); auto Functions = GlobalScope->findAllChildren<PDBSymbolFunc>(); - while (auto Function = Functions->getNext()) { - Printer.NewLine(); - Dumper.start(*Function, FunctionDumper::PointerType::None); + if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) { + while (auto Function = Functions->getNext()) { + Printer.NewLine(); + Dumper.start(*Function, FunctionDumper::PointerType::None); + } + } else { + std::vector<std::unique_ptr<PDBSymbolFunc>> Funcs; + while (auto Func = Functions->getNext()) + Funcs.push_back(std::move(Func)); + std::sort(Funcs.begin(), Funcs.end(), + opts::pretty::compareFunctionSymbols); + for (const auto &Func : Funcs) { + Printer.NewLine(); + Dumper.start(*Func, FunctionDumper::PointerType::None); + } } } - { + if (shouldDumpSymLevel(opts::pretty::SymLevel::Data)) { auto Vars = GlobalScope->findAllChildren<PDBSymbolData>(); VariableDumper Dumper(Printer); - while (auto Var = Vars->getNext()) - Dumper.start(*Var); + if (opts::pretty::SymbolOrder == opts::pretty::SymbolSortMode::None) { + while (auto Var = Vars->getNext()) + Dumper.start(*Var); + } else { + std::vector<std::unique_ptr<PDBSymbolData>> Datas; + while (auto Var = Vars->getNext()) + Datas.push_back(std::move(Var)); + std::sort(Datas.begin(), Datas.end(), opts::pretty::compareDataSymbols); + for (const auto &Var : Datas) + Dumper.start(*Var); + } } - { + if (shouldDumpSymLevel(opts::pretty::SymLevel::Thunks)) { auto Thunks = GlobalScope->findAllChildren<PDBSymbolThunk>(); CompilandDumper Dumper(Printer); while (auto Thunk = Thunks->getNext()) diff --git a/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.h b/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.h index 8b1dde9399bf..e38b32c6a345 100644 --- a/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.h +++ b/contrib/llvm/tools/llvm-pdbdump/llvm-pdbdump.h @@ -14,6 +14,17 @@ #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" +#include <memory> +#include <stdint.h> + +namespace llvm { +namespace pdb { +class PDBSymbolData; +class PDBSymbolFunc; +uint32_t getTypeLength(const PDBSymbolData &Symbol); +} +} + namespace opts { namespace pretty { @@ -29,6 +40,17 @@ enum class ClassSortMode { PaddingPctImmediate }; +enum class SymbolSortMode { None, Name, Size }; + +enum class SymLevel { Functions, Data, Thunks, All }; + +bool shouldDumpSymLevel(SymLevel Level); +bool compareFunctionSymbols( + const std::unique_ptr<llvm::pdb::PDBSymbolFunc> &F1, + const std::unique_ptr<llvm::pdb::PDBSymbolFunc> &F2); +bool compareDataSymbols(const std::unique_ptr<llvm::pdb::PDBSymbolData> &F1, + const std::unique_ptr<llvm::pdb::PDBSymbolData> &F2); + extern llvm::cl::opt<bool> Compilands; extern llvm::cl::opt<bool> Symbols; extern llvm::cl::opt<bool> Globals; @@ -45,6 +67,7 @@ extern llvm::cl::list<std::string> ExcludeCompilands; extern llvm::cl::list<std::string> IncludeTypes; extern llvm::cl::list<std::string> IncludeSymbols; extern llvm::cl::list<std::string> IncludeCompilands; +extern llvm::cl::opt<SymbolSortMode> SymbolOrder; extern llvm::cl::opt<ClassSortMode> ClassOrder; extern llvm::cl::opt<uint32_t> SizeThreshold; extern llvm::cl::opt<uint32_t> PaddingThreshold; diff --git a/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp b/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp index 049af2c4f076..aca7de840d80 100644 --- a/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp +++ b/contrib/llvm/tools/llvm-readobj/COFFDumper.cpp @@ -1562,6 +1562,14 @@ void COFFDumper::printResourceDirectoryTable( raw_svector_ostream OS(IDStr); if (i < Table.NumberOfNameEntries) { ArrayRef<UTF16> RawEntryNameString = unwrapOrError(RSF.getEntryNameString(Entry)); + std::vector<UTF16> EndianCorrectedNameString; + if (llvm::sys::IsBigEndianHost) { + EndianCorrectedNameString.resize(RawEntryNameString.size() + 1); + std::copy(RawEntryNameString.begin(), RawEntryNameString.end(), + EndianCorrectedNameString.begin() + 1); + EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED; + RawEntryNameString = makeArrayRef(EndianCorrectedNameString); + } std::string EntryNameString; if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString)) error(object_error::parse_failed); diff --git a/contrib/llvm/tools/llvm-readobj/llvm-readobj.cpp b/contrib/llvm/tools/llvm-readobj/llvm-readobj.cpp index 8a9d7bc720c3..cd7244a8f970 100644 --- a/contrib/llvm/tools/llvm-readobj/llvm-readobj.cpp +++ b/contrib/llvm/tools/llvm-readobj/llvm-readobj.cpp @@ -311,13 +311,6 @@ static void reportError(StringRef Input, std::error_code EC) { reportError(Twine(Input) + ": " + EC.message()); } -static void reportError(StringRef Input, StringRef Message) { - if (Input == "-") - Input = "<stdin>"; - - reportError(Twine(Input) + ": " + Message); -} - static void reportError(StringRef Input, Error Err) { if (Input == "-") Input = "<stdin>"; @@ -481,11 +474,7 @@ static void dumpArchive(const Archive *Arc) { Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); if (!ChildOrErr) { if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) { - std::string Buf; - raw_string_ostream OS(Buf); - logAllUnhandledErrors(ChildOrErr.takeError(), OS, ""); - OS.flush(); - reportError(Arc->getFileName(), Buf); + reportError(Arc->getFileName(), ChildOrErr.takeError()); } continue; } @@ -507,11 +496,7 @@ static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) { if (ObjOrErr) dumpObject(&*ObjOrErr.get()); else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { - std::string Buf; - raw_string_ostream OS(Buf); - logAllUnhandledErrors(ObjOrErr.takeError(), OS, ""); - OS.flush(); - reportError(UBinary->getFileName(), Buf); + reportError(UBinary->getFileName(), ObjOrErr.takeError()); } else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) dumpArchive(&*AOrErr.get()); @@ -524,7 +509,7 @@ static void dumpInput(StringRef File) { // Attempt to open the binary. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File); if (!BinaryOrErr) - reportError(File, errorToErrorCode(BinaryOrErr.takeError())); + reportError(File, BinaryOrErr.takeError()); Binary &Binary = *BinaryOrErr.get().getBinary(); if (Archive *Arc = dyn_cast<Archive>(&Binary)) diff --git a/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp b/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp index 75345de50280..ba130ce80be8 100644 --- a/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp +++ b/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp @@ -175,8 +175,7 @@ public: void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override {} - void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, - size_t Size) override {} + void deregisterEHFrames() override {} void preallocateSlab(uint64_t Size) { std::string Err; diff --git a/contrib/llvm/tools/opt/opt.cpp b/contrib/llvm/tools/opt/opt.cpp index 40459e559986..c362dff3a3e0 100644 --- a/contrib/llvm/tools/opt/opt.cpp +++ b/contrib/llvm/tools/opt/opt.cpp @@ -385,18 +385,20 @@ int main(int argc, char **argv) { initializeTarget(Registry); // For codegen passes, only passes that do IR to IR transformation are // supported. + initializeScalarizeMaskedMemIntrinPass(Registry); initializeCodeGenPreparePass(Registry); initializeAtomicExpandPass(Registry); initializeRewriteSymbolsLegacyPassPass(Registry); initializeWinEHPreparePass(Registry); initializeDwarfEHPreparePass(Registry); - initializeSafeStackPass(Registry); + initializeSafeStackLegacyPassPass(Registry); initializeSjLjEHPreparePass(Registry); initializePreISelIntrinsicLoweringLegacyPassPass(Registry); initializeGlobalMergePass(Registry); initializeInterleavedAccessPass(Registry); initializeCountingFunctionInserterPass(Registry); initializeUnreachableBlockElimLegacyPassPass(Registry); + initializeExpandReductionsPass(Registry); #ifdef LINK_POLLY_INTO_TOOLS polly::initializePollyPasses(Registry); diff --git a/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp b/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp index bb2ec2a64e49..f4a760990999 100644 --- a/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp +++ b/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp @@ -77,6 +77,7 @@ CGIOperandList::CGIOperandList(Record *R) : TheDef(R) { PrintMethod = Rec->getValueAsString("PrintMethod"); OperandType = Rec->getValueAsString("OperandType"); OperandNamespace = Rec->getValueAsString("OperandNamespace"); + EncoderMethod = Rec->getValueAsString("EncoderMethod"); } else if (Rec->isSubClassOf("Operand")) { PrintMethod = Rec->getValueAsString("PrintMethod"); OperandType = Rec->getValueAsString("OperandType"); diff --git a/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp b/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp index 30516ef5d10d..1903f405d859 100644 --- a/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp +++ b/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp @@ -415,7 +415,7 @@ EmitStageAndOperandCycleData(raw_ostream &OS, BypassTable += " 0, // No itinerary\n"; // For each Itinerary across all processors, add a unique entry to the stages, - // operand cycles, and pipepine bypess tables. Then add the new Itinerary + // operand cycles, and pipeline bypass tables. Then add the new Itinerary // object with computed offsets to the ProcItinLists result. unsigned StageCount = 1, OperandCycleCount = 1; std::map<std::string, unsigned> ItinStageMap, ItinOperandMap; diff --git a/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp b/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp index 4298bc5763b6..55e75763ad69 100644 --- a/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp +++ b/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp @@ -21,129 +21,6 @@ #include <string> using namespace llvm; - -#define MRM_MAPPING \ - MAP(C0, 64) \ - MAP(C1, 65) \ - MAP(C2, 66) \ - MAP(C3, 67) \ - MAP(C4, 68) \ - MAP(C5, 69) \ - MAP(C6, 70) \ - MAP(C7, 71) \ - MAP(C8, 72) \ - MAP(C9, 73) \ - MAP(CA, 74) \ - MAP(CB, 75) \ - MAP(CC, 76) \ - MAP(CD, 77) \ - MAP(CE, 78) \ - MAP(CF, 79) \ - MAP(D0, 80) \ - MAP(D1, 81) \ - MAP(D2, 82) \ - MAP(D3, 83) \ - MAP(D4, 84) \ - MAP(D5, 85) \ - MAP(D6, 86) \ - MAP(D7, 87) \ - MAP(D8, 88) \ - MAP(D9, 89) \ - MAP(DA, 90) \ - MAP(DB, 91) \ - MAP(DC, 92) \ - MAP(DD, 93) \ - MAP(DE, 94) \ - MAP(DF, 95) \ - MAP(E0, 96) \ - MAP(E1, 97) \ - MAP(E2, 98) \ - MAP(E3, 99) \ - MAP(E4, 100) \ - MAP(E5, 101) \ - MAP(E6, 102) \ - MAP(E7, 103) \ - MAP(E8, 104) \ - MAP(E9, 105) \ - MAP(EA, 106) \ - MAP(EB, 107) \ - MAP(EC, 108) \ - MAP(ED, 109) \ - MAP(EE, 110) \ - MAP(EF, 111) \ - MAP(F0, 112) \ - MAP(F1, 113) \ - MAP(F2, 114) \ - MAP(F3, 115) \ - MAP(F4, 116) \ - MAP(F5, 117) \ - MAP(F6, 118) \ - MAP(F7, 119) \ - MAP(F8, 120) \ - MAP(F9, 121) \ - MAP(FA, 122) \ - MAP(FB, 123) \ - MAP(FC, 124) \ - MAP(FD, 125) \ - MAP(FE, 126) \ - MAP(FF, 127) - -// A clone of X86 since we can't depend on something that is generated. -namespace X86Local { - enum { - Pseudo = 0, - RawFrm = 1, - AddRegFrm = 2, - RawFrmMemOffs = 3, - RawFrmSrc = 4, - RawFrmDst = 5, - RawFrmDstSrc = 6, - RawFrmImm8 = 7, - RawFrmImm16 = 8, - MRMDestMem = 32, - MRMSrcMem = 33, - MRMSrcMem4VOp3 = 34, - MRMSrcMemOp4 = 35, - MRMXm = 39, - MRM0m = 40, MRM1m = 41, MRM2m = 42, MRM3m = 43, - MRM4m = 44, MRM5m = 45, MRM6m = 46, MRM7m = 47, - MRMDestReg = 48, - MRMSrcReg = 49, - MRMSrcReg4VOp3 = 50, - MRMSrcRegOp4 = 51, - MRMXr = 55, - MRM0r = 56, MRM1r = 57, MRM2r = 58, MRM3r = 59, - MRM4r = 60, MRM5r = 61, MRM6r = 62, MRM7r = 63, -#define MAP(from, to) MRM_##from = to, - MRM_MAPPING -#undef MAP - }; - - enum { - OB = 0, TB = 1, T8 = 2, TA = 3, XOP8 = 4, XOP9 = 5, XOPA = 6 - }; - - enum { - PS = 1, PD = 2, XS = 3, XD = 4 - }; - - enum { - VEX = 1, XOP = 2, EVEX = 3 - }; - - enum { - OpSize16 = 1, OpSize32 = 2 - }; - - enum { - AdSize16 = 1, AdSize32 = 2, AdSize64 = 3 - }; - - enum { - VEX_W0 = 0, VEX_W1 = 1, VEX_WIG = 2 - }; -} - using namespace X86Disassembler; /// byteFromBitsInit - Extracts a value at most 8 bits in width from a BitsInit. @@ -890,7 +767,7 @@ void RecognizableInstr::emitDecodePath(DisassemblerTables &tables) const { case X86Local::MRM6m: case X86Local::MRM7m: filter = new ExtendedFilter(false, Form - X86Local::MRM0m); break; - MRM_MAPPING + X86_INSTR_MRM_MAPPING filter = new ExactFilter(0xC0 + Form - X86Local::MRM_C0); \ break; } // switch (Form) diff --git a/contrib/llvm/utils/TableGen/X86RecognizableInstr.h b/contrib/llvm/utils/TableGen/X86RecognizableInstr.h index 91ed928540c3..7fe731ec8b1c 100644 --- a/contrib/llvm/utils/TableGen/X86RecognizableInstr.h +++ b/contrib/llvm/utils/TableGen/X86RecognizableInstr.h @@ -24,6 +24,128 @@ namespace llvm { +#define X86_INSTR_MRM_MAPPING \ + MAP(C0, 64) \ + MAP(C1, 65) \ + MAP(C2, 66) \ + MAP(C3, 67) \ + MAP(C4, 68) \ + MAP(C5, 69) \ + MAP(C6, 70) \ + MAP(C7, 71) \ + MAP(C8, 72) \ + MAP(C9, 73) \ + MAP(CA, 74) \ + MAP(CB, 75) \ + MAP(CC, 76) \ + MAP(CD, 77) \ + MAP(CE, 78) \ + MAP(CF, 79) \ + MAP(D0, 80) \ + MAP(D1, 81) \ + MAP(D2, 82) \ + MAP(D3, 83) \ + MAP(D4, 84) \ + MAP(D5, 85) \ + MAP(D6, 86) \ + MAP(D7, 87) \ + MAP(D8, 88) \ + MAP(D9, 89) \ + MAP(DA, 90) \ + MAP(DB, 91) \ + MAP(DC, 92) \ + MAP(DD, 93) \ + MAP(DE, 94) \ + MAP(DF, 95) \ + MAP(E0, 96) \ + MAP(E1, 97) \ + MAP(E2, 98) \ + MAP(E3, 99) \ + MAP(E4, 100) \ + MAP(E5, 101) \ + MAP(E6, 102) \ + MAP(E7, 103) \ + MAP(E8, 104) \ + MAP(E9, 105) \ + MAP(EA, 106) \ + MAP(EB, 107) \ + MAP(EC, 108) \ + MAP(ED, 109) \ + MAP(EE, 110) \ + MAP(EF, 111) \ + MAP(F0, 112) \ + MAP(F1, 113) \ + MAP(F2, 114) \ + MAP(F3, 115) \ + MAP(F4, 116) \ + MAP(F5, 117) \ + MAP(F6, 118) \ + MAP(F7, 119) \ + MAP(F8, 120) \ + MAP(F9, 121) \ + MAP(FA, 122) \ + MAP(FB, 123) \ + MAP(FC, 124) \ + MAP(FD, 125) \ + MAP(FE, 126) \ + MAP(FF, 127) + +// A clone of X86 since we can't depend on something that is generated. +namespace X86Local { + enum { + Pseudo = 0, + RawFrm = 1, + AddRegFrm = 2, + RawFrmMemOffs = 3, + RawFrmSrc = 4, + RawFrmDst = 5, + RawFrmDstSrc = 6, + RawFrmImm8 = 7, + RawFrmImm16 = 8, + MRMDestMem = 32, + MRMSrcMem = 33, + MRMSrcMem4VOp3 = 34, + MRMSrcMemOp4 = 35, + MRMXm = 39, + MRM0m = 40, MRM1m = 41, MRM2m = 42, MRM3m = 43, + MRM4m = 44, MRM5m = 45, MRM6m = 46, MRM7m = 47, + MRMDestReg = 48, + MRMSrcReg = 49, + MRMSrcReg4VOp3 = 50, + MRMSrcRegOp4 = 51, + MRMXr = 55, + MRM0r = 56, MRM1r = 57, MRM2r = 58, MRM3r = 59, + MRM4r = 60, MRM5r = 61, MRM6r = 62, MRM7r = 63, +#define MAP(from, to) MRM_##from = to, + X86_INSTR_MRM_MAPPING +#undef MAP + }; + + enum { + OB = 0, TB = 1, T8 = 2, TA = 3, XOP8 = 4, XOP9 = 5, XOPA = 6 + }; + + enum { + PS = 1, PD = 2, XS = 3, XD = 4 + }; + + enum { + VEX = 1, XOP = 2, EVEX = 3 + }; + + enum { + OpSize16 = 1, OpSize32 = 2 + }; + + enum { + AdSize16 = 1, AdSize32 = 2, AdSize64 = 3 + }; + + enum { + VEX_W0 = 0, VEX_W1 = 1, VEX_WIG = 2 + }; +} + namespace X86Disassembler { /// RecognizableInstr - Encapsulates all information required to decode a single diff --git a/lib/clang/include/clang/Basic/Version.inc b/lib/clang/include/clang/Basic/Version.inc index 3231f0865f8b..420bf474be44 100644 --- a/lib/clang/include/clang/Basic/Version.inc +++ b/lib/clang/include/clang/Basic/Version.inc @@ -8,4 +8,4 @@ #define CLANG_VENDOR "FreeBSD " -#define SVN_REVISION "302418" +#define SVN_REVISION "303197" diff --git a/lib/clang/include/lld/Config/Version.inc b/lib/clang/include/lld/Config/Version.inc index bc855198f1bf..6e6c097ad8e1 100644 --- a/lib/clang/include/lld/Config/Version.inc +++ b/lib/clang/include/lld/Config/Version.inc @@ -4,5 +4,5 @@ #define LLD_VERSION_STRING "5.0.0" #define LLD_VERSION_MAJOR 5 #define LLD_VERSION_MINOR 0 -#define LLD_REVISION_STRING "302418" +#define LLD_REVISION_STRING "303197" #define LLD_REPOSITORY_STRING "FreeBSD" diff --git a/lib/clang/include/llvm/Support/VCSRevision.h b/lib/clang/include/llvm/Support/VCSRevision.h index e0782eaddcf2..bd8abc23c17a 100644 --- a/lib/clang/include/llvm/Support/VCSRevision.h +++ b/lib/clang/include/llvm/Support/VCSRevision.h @@ -1,2 +1,2 @@ /* $FreeBSD$ */ -#define LLVM_REVISION "svn-r302418" +#define LLVM_REVISION "svn-r303197" diff --git a/lib/clang/liblldb/Makefile b/lib/clang/liblldb/Makefile index f2771498e355..273333c4d3fb 100644 --- a/lib/clang/liblldb/Makefile +++ b/lib/clang/liblldb/Makefile @@ -555,7 +555,6 @@ SRCS+= Utility/DataBufferHeap.cpp SRCS+= Utility/DataBufferLLVM.cpp SRCS+= Utility/DataEncoder.cpp SRCS+= Utility/DataExtractor.cpp -SRCS+= Utility/Error.cpp SRCS+= Utility/FastDemangle.cpp SRCS+= Utility/FileSpec.cpp SRCS+= Utility/JSON.cpp @@ -566,6 +565,7 @@ SRCS+= Utility/NameMatches.cpp SRCS+= Utility/RegularExpression.cpp SRCS+= Utility/SelectHelper.cpp SRCS+= Utility/SharingPtr.cpp +SRCS+= Utility/Status.cpp SRCS+= Utility/Stream.cpp SRCS+= Utility/StreamCallback.cpp SRCS+= Utility/StreamGDBRemote.cpp diff --git a/lib/clang/libllvm/Makefile b/lib/clang/libllvm/Makefile index e806c0b402bd..ad7307a1b628 100644 --- a/lib/clang/libllvm/Makefile +++ b/lib/clang/libllvm/Makefile @@ -155,6 +155,7 @@ SRCS_MIN+= CodeGen/EdgeBundles.cpp SRCS_MIN+= CodeGen/ExecutionDepsFix.cpp SRCS_MIN+= CodeGen/ExpandISelPseudos.cpp SRCS_MIN+= CodeGen/ExpandPostRAPseudos.cpp +SRCS_MIN+= CodeGen/ExpandReductions.cpp SRCS_MIN+= CodeGen/FEntryInserter.cpp SRCS_MIN+= CodeGen/FaultMaps.cpp SRCS_MIN+= CodeGen/FuncletLayout.cpp @@ -182,6 +183,7 @@ SRCS_MIN+= CodeGen/LiveIntervalUnion.cpp SRCS_MIN+= CodeGen/LivePhysRegs.cpp SRCS_MIN+= CodeGen/LiveRangeCalc.cpp SRCS_MIN+= CodeGen/LiveRangeEdit.cpp +SRCS_MIN+= CodeGen/LiveRangeShrink.cpp SRCS_MIN+= CodeGen/LiveRegMatrix.cpp SRCS_MIN+= CodeGen/LiveRegUnits.cpp SRCS_MIN+= CodeGen/LiveStackAnalysis.cpp @@ -254,6 +256,7 @@ SRCS_MIN+= CodeGen/ResetMachineFunctionPass.cpp SRCS_MIN+= CodeGen/SafeStack.cpp SRCS_MIN+= CodeGen/SafeStackColoring.cpp SRCS_MIN+= CodeGen/SafeStackLayout.cpp +SRCS_MIN+= CodeGen/ScalarizeMaskedMemIntrin.cpp SRCS_MIN+= CodeGen/ScheduleDAG.cpp SRCS_MIN+= CodeGen/ScheduleDAGInstrs.cpp SRCS_MIN+= CodeGen/ScheduleDAGPrinter.cpp @@ -516,7 +519,6 @@ SRCS_EXL+= LTO/LTOCodeGenerator.cpp SRCS_EXL+= LTO/LTOModule.cpp SRCS_EXL+= LTO/ThinLTOCodeGenerator.cpp SRCS_MIN+= LTO/UpdateCompilerUsed.cpp -SRCS_EXL+= LibDriver/LibDriver.cpp SRCS_MIN+= LineEditor/LineEditor.cpp SRCS_MIN+= Linker/IRMover.cpp SRCS_MIN+= Linker/LinkModules.cpp @@ -676,6 +678,7 @@ SRCS_MIN+= Support/MemoryBuffer.cpp SRCS_MIN+= Support/Mutex.cpp SRCS_MIN+= Support/NativeFormatting.cpp SRCS_MIN+= Support/Options.cpp +SRCS_LLD+= Support/Parallel.cpp SRCS_MIN+= Support/Path.cpp SRCS_MIN+= Support/PluginLoader.cpp SRCS_MIN+= Support/PrettyStackTrace.cpp @@ -989,6 +992,7 @@ SRCS_MIN+= Target/X86/X86TargetTransformInfo.cpp SRCS_MIN+= Target/X86/X86VZeroUpper.cpp SRCS_MIN+= Target/X86/X86WinAllocaExpander.cpp SRCS_MIN+= Target/X86/X86WinEHState.cpp +SRCS_EXL+= ToolDrivers/llvm-lib/LibDriver.cpp SRCS_MIN+= Transforms/Coroutines/CoroCleanup.cpp SRCS_MIN+= Transforms/Coroutines/CoroEarly.cpp SRCS_MIN+= Transforms/Coroutines/CoroElide.cpp @@ -1228,10 +1232,10 @@ AttributesCompatFunc.inc: ${LLVM_SRCS}/lib/IR/AttributesCompatFunc.td ${LLVM_SRCS}/lib/IR/AttributesCompatFunc.td TGHDRS+= AttributesCompatFunc.inc -Options.inc: ${LLVM_SRCS}/lib/LibDriver/Options.td +Options.inc: ${LLVM_SRCS}/lib/ToolDrivers/llvm-lib/Options.td ${LLVM_TBLGEN} -gen-opt-parser-defs \ -I ${LLVM_SRCS}/include -d ${.TARGET}.d -o ${.TARGET} \ - ${LLVM_SRCS}/lib/LibDriver/Options.td + ${LLVM_SRCS}/lib/ToolDrivers/llvm-lib/Options.td TGHDRS+= Options.inc # Note: some rules are superfluous, not every combination is valid. diff --git a/usr.bin/clang/lld/Makefile b/usr.bin/clang/lld/Makefile index 901992381437..2f4ea3d6a80b 100644 --- a/usr.bin/clang/lld/Makefile +++ b/usr.bin/clang/lld/Makefile @@ -51,7 +51,6 @@ SRCS+= lib/Core/Reproduce.cpp SRCS+= lib/Core/Resolver.cpp SRCS+= lib/Core/SymbolTable.cpp SRCS+= lib/Core/TargetOptionsCommandFlags.cpp -SRCS+= lib/Core/TaskGroup.cpp SRCS+= tools/lld/lld.cpp .include "${SRCTOP}/lib/clang/llvm.build.mk" |