diff --git a/.gitignore b/.gitignore index 4e9178e3499681cef0bdc824ca1f7ce53fe9eb5b..e39b0f79aec0740f877a4b2e647d445f0b825799 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -android +android/* third_party/d8* third_party/icu* third_party/libdex* diff --git a/Makefile b/Makefile index 3887020450dd087c3f7e03c30c22e4f2f0896d1a..b07eddd8672afdc41bee428660c34219031a6fa8 100644 --- a/Makefile +++ b/Makefile @@ -19,6 +19,7 @@ OPS_ANDROID := 0 INSTALL_DIR := $(MAPLE_BUILD_OUTPUT) MAPLE_BIN_DIR := $(MAPLE_ROOT)/src/mapleall/bin MRT_ROOT := $(MAPLE_ROOT)/src/mrt +ANDROID_ROOT := $(MAPLE_ROOT)/android ifeq ($(DEBUG),0) BUILD_TYPE := RELEASE else @@ -38,10 +39,18 @@ GN_OPTIONS := \ OPS_ANDROID=$(OPS_ANDROID) .PHONY: default -default: install mplfe +default: install + +.PHONY: install_patch +install_patch: + @bash build/third_party/patch.sh patch + +.PHONY: uninstall_patch +uninstall_patch: + @bash build/third_party/patch.sh unpatch .PHONY: maplegen -maplegen: +maplegen:install_patch $(call build_gn, $(GN_OPTIONS), maplegen) .PHONY: maplegendef @@ -61,7 +70,7 @@ ast2mpl: $(call build_gn, $(GN_OPTIONS), ast2mpl) .PHONY: mplfe -mplfe: +mplfe: install_patch $(call build_gn, $(GN_OPTIONS), mplfe) .PHONY: mplfeUT @@ -122,11 +131,12 @@ test_ourboros: libcore testall: test_irbuild test_ourboros .PHONY: cleanrsd -cleanrsd: +cleanrsd:uninstall_patch @rm -rf libjava-core/libcore-all.* libjava-core/m* libjava-core/comb.* .PHONY: clean clean: cleanrsd + @rm -rf $(MAPLE_BUILD_OUTPUT)/ @rm -rf $(MAPLE_BUILD_OUTPUT) .PHONY: clobber diff --git a/build/build.sh b/build/build.sh old mode 100644 new mode 100755 index 17a9e51b4270ed3207e57dc3962b070ff9570458..c88052b81a918ee150c5fe13d447f6d9964b1553 --- a/build/build.sh +++ b/build/build.sh @@ -14,7 +14,7 @@ # See the Mulan PSL v2 for more details. # set -e -source build/envsetup.sh +source build/envsetup.sh arm release make clean option=$@ model=$1 diff --git a/build/config.gni b/build/config.gni index 5ed59b245ff197686a0327e0446b8a350d6527c9..83b682e89e8ac837e2ec6f1d0067329e18cd4dc7 100644 --- a/build/config.gni +++ b/build/config.gni @@ -1,5 +1,5 @@ # -# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. +# Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. # # OpenArkCompiler is licensed under Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -19,7 +19,6 @@ if (OLD_OS == "1") { } else { CLANG_PATH = "/usr" } - ANDROID_GCC_PATH = "${MAPLE_ROOT}/tools/gcc" ANDROID_CLANG_PATH = "${MAPLE_ROOT}/tools/clang-r353983c" GCC_LINARO_PATH = "${MAPLE_ROOT}/tools/gcc-linaro-7.5.0" diff --git a/build/config/BUILDCONFIG.gn b/build/config/BUILDCONFIG.gn old mode 100644 new mode 100755 index 84af356ab1c76de937758fe9e414de9fd090babf..adfa3a5ced63ada461707f2127c96e1699d35286 --- a/build/config/BUILDCONFIG.gn +++ b/build/config/BUILDCONFIG.gn @@ -29,6 +29,7 @@ declare_args() { # Define global args MAPLE_ROOT = getenv("MAPLE_ROOT") ANDROID_ROOT = "${MAPLE_ROOT}/android" +AOSP_ROOT = "${MAPLE_ROOT}/third_party/aosp_10.0.0_r35" MAPLE_BUILD_TYPE = getenv("MAPLE_BUILD_TYPE") MAPLE_BUILD_OUTPUT = getenv("MAPLE_BUILD_OUTPUT") OLD_OS = getenv("OLD_OS") diff --git a/build/core/libcore.mk b/build/core/libcore.mk index 32f0ac069b4d2edf5c23a828c8380cc00f7731d8..a1c2f939dee0becedc8a9b2bff5499515c285ddf 100644 --- a/build/core/libcore.mk +++ b/build/core/libcore.mk @@ -81,7 +81,7 @@ install: libcore_so deplibs rsync -a -L $(MAPLE_OUT)/lib/$(OPT)/libcore-all.so $(MAPLE_OUT)/ops/host-x86_64-$(OPT); \ rsync -a -L $(MAPLE_OUT)/libjava-core/mrt_module_init.o $(MAPLE_OUT)/ops/; \ rsync -a -L $(MAPLE_OUT)/libjava-core/libcore-all.mplt $(MAPLE_OUT)/ops/; \ - rsync -a -L $(MAPLE_ROOT)/third_party/libnativehelper $(MAPLE_OUT)/ops/; \ + rsync -a -L $(MAPLE_ROOT)/third_party/aosp_10.0.0_r35/libnativehelper $(MAPLE_OUT)/ops/; \ rsync -a -L $(MAPLE_ROOT)/android/out/target/common/obj/JAVA_LIBRARIES $(MAPLE_OUT)/ops/third_party; \ rsync -a -L $(MAPLE_ROOT)/third_party/libdex/prebuilts/aarch64-linux-gnu/libz.so.1.2.8 $(MAPLE_OUT)/ops/third_party/libz.so.1; \ rsync -a -L $(MAPLE_ROOT)/third_party/icu/lib/aarch64-linux-gnu/* $(MAPLE_OUT)/ops/third_party/; \ diff --git a/build/core/maple_variables.mk b/build/core/maple_variables.mk index a529a6f6aa75684acfb44f26070c49dcf30ee226..c64a65e1ffe2f3289de80d7475551c8c31724929 100644 --- a/build/core/maple_variables.mk +++ b/build/core/maple_variables.mk @@ -18,12 +18,7 @@ LIB_CORE_PATH := $(MAPLE_BUILD_OUTPUT)/libjava-core LIB_CORE_JAR := $(LIB_CORE_PATH)/java-core.jar LIB_CORE_MPLT := $(LIB_CORE_PATH)/java-core.mplt -ifeq ($(OLD_OS), 1) - CLANG_PATH = "${MAPLE_ROOT}/tools/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-16.04" -else - CLANG_PATH = "/usr" -endif - +CLANG_PATH := $(MAPLE_ROOT)/tools/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-16.04 ANDROID_GCC_PATH := $(MAPLE_ROOT)/tools/gcc ANDROID_CLANG_PATH := $(MAPLE_ROOT)/tools/clang-r353983c GCC_LINARO_PATH := $(MAPLE_ROOT)/tools/gcc-linaro-7.5.0 diff --git a/build/envsetup.sh b/build/envsetup.sh index f61521763c8ce34bbf0e3597cdb8b09521b03046..c70616c9eb0815fbc2d6f5bcebe5d7b4f2a266ef 100644 --- a/build/envsetup.sh +++ b/build/envsetup.sh @@ -120,4 +120,3 @@ unset MAPLE_EXECUTE_BIN export MAPLE_EXECUTE_BIN=${MAPLE_ROOT}/output/${MAPLE_BUILD_TYPE}/bin export PATH=$PATH:${MAPLE_EXECUTE_BIN} - diff --git a/build/maplelld.so.lds b/build/maplelld.so.lds deleted file mode 100644 index 76480328f67d8b6fa0545cf7e83f13c8c41c33c0..0000000000000000000000000000000000000000 --- a/build/maplelld.so.lds +++ /dev/null @@ -1,426 +0,0 @@ -/* Script for -pie -z combreloc: position independent executable, combine & sort relocs */ -/* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. - * - * OpenArkCompiler is licensed under the Mulan PSL v1. - * You can use this software according to the terms and conditions of the Mulan PSL v1. - * You may obtain a copy of Mulan PSL v1 at: - * - * http://license.coscl.org.cn/MulanPSL - * - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR - * FIT FOR A PARTICULAR PURPOSE. - * See the Mulan PSL v1 for more details. - */ -OUTPUT_FORMAT("elf64-littleaarch64", "elf64-bigaarch64", - "elf64-littleaarch64") -OUTPUT_ARCH(aarch64) -SEARCH_DIR("=/usr/local/lib/aarch64-linux-gnu"); SEARCH_DIR("=/lib/aarch64-linux-gnu"); SEARCH_DIR("=/usr/lib/aarch64-linux-gnu"); SEARCH_DIR("=/usr/local/lib"); SEARCH_DIR("=/lib"); SEARCH_DIR("=/usr/lib"); SEARCH_DIR("=/usr/aarch64-linux-gnu/lib"); -PHDRS -{ - text PT_LOAD FILEHDR PHDRS; - data PT_LOAD; - dynamic PT_DYNAMIC; - note PT_NOTE; - gnu_eh_frame PT_GNU_EH_FRAME; - gnu_stack PT_GNU_STACK; - gnu_relro PT_GNU_RELRO; - /* headers PT_PHDR PHDRS; */ /* Reserve segment for lld */ - /* interp PT_INTERP; */ /* Reserve segment for lld */ - thread_local PT_TLS; /* Reserve segment for lld */ -} - -SECTIONS -{ - PROVIDE_HIDDEN(__maple_start__ = .); - /* Read-only sections, merged into text segment: */ - PROVIDE (__executable_start = SEGMENT_START("text-segment", 0)); . = SEGMENT_START("text-segment", 0) + SIZEOF_HEADERS; - .interp : { *(.interp) } - .note.gnu.build-id : - { - PROVIDE_HIDDEN (__linkerHashSo_begin = .); - KEEP (*(.note.gnu.build-id)) - PROVIDE_HIDDEN (__linkerHashSo_end = .); - } :text :note - .hash : { *(.hash) } :text - .gnu.hash : { *(.gnu.hash) } - .dynsym : { *(.dynsym) } - .dynstr : { *(.dynstr) } - .gnu.version : { *(.gnu.version) } - .gnu.version_d : { *(.gnu.version_d) } - .gnu.version_r : { *(.gnu.version_r) } - .rela.dyn : - { - *(.rela.init) - *(.rela.text .rela.text.* .rela.gnu.linkonce.t.*) - *(.rela.fini) - *(.rela.rodata .rela.rodata.* .rela.gnu.linkonce.r.*) - *(.rela.data .rela.data.* .rela.gnu.linkonce.d.*) - *(.rela.tdata .rela.tdata.* .rela.gnu.linkonce.td.*) - *(.rela.tbss .rela.tbss.* .rela.gnu.linkonce.tb.*) - *(.rela.ctors) - *(.rela.dtors) - *(.rela.got) - *(.rela.bss .rela.bss.* .rela.gnu.linkonce.b.*) - *(.rela.ifunc) - } - .rela.plt : - { - *(.rela.plt) - PROVIDE_HIDDEN (__rela_iplt_start = .); - *(.rela.iplt) - PROVIDE_HIDDEN (__rela_iplt_end = .); - } - .init : - { - KEEP (*(.init)) - } =0 - .plt : ALIGN(16) { *(.plt) *(.iplt) } - .text : - { - *(.text.unlikely .text.*_unlikely .text.unlikely.*) - *(.text.exit .text.exit.*) - *(.text.startup .text.startup.*) - *(.text.hot .text.hot.*) - *(.text .stub .text.* .gnu.linkonce.t.*) - /* .gnu.warning sections are handled specially by elf32.em. */ - *(.gnu.warning) - } =0 - .java_text : - { - PROVIDE_HIDDEN (java_text_begin = .); - KEEP (*(.java_text)) - PROVIDE_HIDDEN (java_text_end = .); - } - .fini : - { - KEEP (*(.fini)) - } =0 - PROVIDE (__etext = .); - PROVIDE (_etext = .); - PROVIDE (etext = .); - .rodata : - { - *(.rodata .rodata.* .gnu.linkonce.r.*) - } - .rometadata : - { - mfile_rometadata_method_start = .; - KEEP (*(.rometadata.method)) - mfile_rometadata_method_end = .; - - mfile_rometadata_field_start = .; - KEEP (*(.rometadata.field)) - mfile_rometadata_field_end = .; - } - .romuidtab : - { - mfile_romuidtab_start = .; - KEEP (*(.__muid_ro_func_def_orig_tab)) - KEEP (*(.__muid_ro_data_def_orig_tab)) - /* madvised */ - KEEP (*(.__muid_ro_func_inf_tab)) - /* madvised */ - KEEP (*(.__muid_ro_func_def_muid_tab)) - /* madvised */ - KEEP (*(.__muid_ro_data_def_muid_tab)) - KEEP (*(.__muid_ro_func_undef_muid_tab)) - KEEP (*(.__muid_ro_data_undef_muid_tab)) - /* madvised */ - KEEP (*(.__muid_ro_func_muid_idx_tab)) - mfile_romuidtab_end = .; - } - .rodata1 : { *(.rodata1) } - .eh_frame_hdr : { *(.eh_frame_hdr) *(.eh_frame_entry .eh_frame_entry.*) } :text :gnu_eh_frame - .eh_frame : ONLY_IF_RO - { - PROVIDE_HIDDEN ( __eh_frame_start = .); - KEEP (*(.eh_frame)) *(.eh_frame.*) - PROVIDE_HIDDEN ( __eh_frame_end = .); - } :text - .gcc_except_table : ONLY_IF_RO { *(.gcc_except_table - .gcc_except_table.*) } - .gnu_extab : ONLY_IF_RO { *(.gnu_extab*) } - /* These sections are generated by the Sun/Oracle C++ compiler. */ - .exception_ranges : ONLY_IF_RO { *(.exception_ranges - .exception_ranges*) } - - /* Adjust the address for the data segment. We want to adjust up to - the same address within the page on the next page up. */ - . = DATA_SEGMENT_ALIGN (CONSTANT (MAXPAGESIZE), CONSTANT (COMMONPAGESIZE)); - /* Exception handling */ - .eh_frame : ONLY_IF_RW { KEEP (*(.eh_frame)) *(.eh_frame.*) } - .gnu_extab : ONLY_IF_RW { *(.gnu_extab) } - .gcc_except_table : ONLY_IF_RW { *(.gcc_except_table .gcc_except_table.*) } - .exception_ranges : ONLY_IF_RW { *(.exception_ranges .exception_ranges*) } - /* Thread Local Storage sections */ - .tdata : { *(.tdata .tdata.* .gnu.linkonce.td.*) } :thread_local - .tbss : { *(.tbss .tbss.* .gnu.linkonce.tb.*) *(.tcommon) } :thread_local - .dynamic : { *(.dynamic) } :data :gnu_relro :dynamic - .preinit_array : - { - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP (*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - } - .init_array : - { - PROVIDE_HIDDEN (__init_array_start = .); - KEEP (*(.init_array.* .ctors.*)) - KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) - PROVIDE_HIDDEN (__init_array_end = .); - } :data :gnu_relro - .fini_array : - { - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP (*(.fini_array.* .dtors.*)) - KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) - PROVIDE_HIDDEN (__fini_array_end = .); - } :data :gnu_relro - .ctors : - { - /* gcc uses crtbegin.o to find the start of - the constructors, so we make sure it is - first. Because this is a wildcard, it - doesn't matter if the user does not - actually link against crtbegin.o; the - linker won't look for a file to match a - wildcard. The wildcard also means that it - doesn't matter which directory crtbegin.o - is in. */ - KEEP (*crtbegin.o(.ctors)) - KEEP (*crtbegin?.o(.ctors)) - /* We don't want to include the .ctor section from - the crtend.o file until after the sorted ctors. - The .ctor section from the crtend file contains the - end of ctors marker and it must be last */ - KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors)) - KEEP (*(SORT(.ctors.*))) - KEEP (*(.ctors)) - } - .dtors : - { - KEEP (*crtbegin.o(.dtors)) - KEEP (*crtbegin?.o(.dtors)) - KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors)) - KEEP (*(SORT(.dtors.*))) - KEEP (*(.dtors)) - } - .jcr : { KEEP (*(.jcr)) } - .data.rel.ro : { *(.data.rel.ro.local* .gnu.linkonce.d.rel.ro.local.*) *(.data.rel.ro .data.rel.ro.* .gnu.linkonce.d.rel.ro.*) } - .got : { *(.got) *(.igot) } :data :gnu_relro - . = DATA_SEGMENT_RELRO_END (24, .); - .got.plt : { *(.got.plt) *(.igot.plt) } :data - .data : - { - PROVIDE_HIDDEN (__data_section_begin = .); - *(.data .data.* .gnu.linkonce.d.*) - SORT(CONSTRUCTORS) - PROVIDE_HIDDEN (__data_section_end = .); - } - .data1 : { *(.data1) } - _edata = .; PROVIDE (edata = .); - /* maple specific sections */ - . = ALIGN( 8 ); - .maple.gcrootsmap : - { - KEEP (*(.maple.gcrootsmap)) - } - - . = ALIGN( 8 ); - .reg_jni_tab : - { - PROVIDE_HIDDEN (__reg_jni_tab_begin = .); - KEEP (*(.reg_jni_tab)) - PROVIDE_HIDDEN (__reg_jni_tab_end = .); - } - - . = ALIGN( 8 ); - .reg_jni_func_tab : - { - PROVIDE_HIDDEN (__reg_jni_func_tab_begin = .); - KEEP (*(.reg_jni_func_tab)) - PROVIDE_HIDDEN (__reg_jni_func_tab_end = .); - } - - . = ALIGN( 8 ); - .bb_profile_strtab : - { - PROVIDE_HIDDEN (__bb_profile_strtab_begin = .); - KEEP (*(.__bb_profile_strtab)) - PROVIDE_HIDDEN (__bb_profile_strtab_end = .); - } - - . = ALIGN( 8 ); - .bb_profile_tab : - { - PROVIDE_HIDDEN (__bb_profile_tab_begin = .); - KEEP (*(.__bb_profile_tab)) - PROVIDE_HIDDEN (__bb_profile_tab_end = .); - } - - . = ALIGN( 8 ); - .muid_tab : - { - PROVIDE_HIDDEN (__muid_tab_start = .); - - PROVIDE_HIDDEN (__decouple_start__ = .); - KEEP (*(.__decouple)) - PROVIDE_HIDDEN (__decouple_end__ = .); - - PROVIDE_HIDDEN (__muid_range_tab_begin__ = .); - KEEP (*(.__muid_range_tab)) - PROVIDE_HIDDEN (__muid_range_tab_end__ = .); - - PROVIDE_HIDDEN (__muid_conststr_start__ = .); - KEEP (*(.__muid_conststr)) - PROVIDE_HIDDEN (__muid_conststr_end__ = .); - - KEEP (*(.__muid_func_def_tab)) - KEEP (*(.__muid_func_undef_tab)) - KEEP (*(.__muid_data_def_tab)) - KEEP (*(.__muid_data_undef_tab)) - KEEP (*(.__muid_itab)) - KEEP (*(.__muid_vtab)) - KEEP (*(.__muid_vtab_offset_tab)) - KEEP (*(.__muid_field_offset_tab)) - KEEP (*(.__muid_superclass)) - KEEP (*(.__muid_offset_value_table)) - KEEP (*(.__muid_local_classinfo_tab)) - - PROVIDE_HIDDEN (__muid_tab_end = .); - } - - . = ALIGN( 8 ); - .mpl_version : - { - PROVIDE_HIDDEN (__compilerVersionNumTab_begin__ = .); - KEEP (*(.__compilerVersionNumTab)) - PROVIDE_HIDDEN (__compilerVersionNumTab_end__ = .); - - KEEP (*(.__sourceMuidTab)) - - PROVIDE_HIDDEN (__compiler_mfile_status_begin__ = .); - KEEP (*(.__compiler_mfile_status)) - PROVIDE_HIDDEN (__compiler_mfile_status_end__ = .); - } - - . = ALIGN( 8 ); - .profile_tab : - { - KEEP (*(.__profile_func_tab)) - } - - . = ALIGN( 8 ); - .classmetadata : - { - KEEP (*(.__muid_classmetadata)) - } - - . = ALIGN( 8 ); - .classmetadata_bucket : - { - PROVIDE_HIDDEN (__muid_classmetadata_bucket_begin = .); - *(.__muid_classmetadata_bucket) - PROVIDE_HIDDEN (__muid_classmetadata_bucket_end = .); - } - - .refl_strtab : - { - . = ALIGN( 8 ); - PROVIDE_HIDDEN(__reflection_strtab_start__ = .); - KEEP (*(.reflection_strtab)) - PROVIDE_HIDDEN(__reflection_strtab_end__ = .); - } - - .refl_strtab.hot : - { - . = ALIGN( 8 ); - PROVIDE_HIDDEN(__reflection_start_hot_strtab_start__ = .); - KEEP (*(.reflection_start_hot_strtab)) - PROVIDE_HIDDEN(__reflection_start_hot_strtab_end__ = .); - - . = ALIGN( 8 ); - PROVIDE_HIDDEN(__reflection_both_hot_strtab_start__ = .); - KEEP (*(.reflection_both_hot_strtab)) - PROVIDE_HIDDEN(__reflection_both_hot_strtab_end__ = .); - - . = ALIGN( 8 ); - PROVIDE_HIDDEN(__reflection_run_hot_strtab_start__ = .); - KEEP (*(.reflection_run_hot_strtab)) - PROVIDE_HIDDEN(__reflection_run_hot_strtab_end__ = .); - } - - . = ALIGN( 4096 ); - __bss_start = . ; __bss_start__ = . ; - .bss : - { - PROVIDE_HIDDEN(__bss_section_begin = .); - *(.dynbss) - *(.bss .bss.* .gnu.linkonce.b.*) - *(COMMON) - /* Align here to ensure that the .bss section occupies space up to - _end. Align after .bss to ensure correct alignment even if the - .bss section disappears because there are no input sections. - FIXME: Why do we need it? When there is no .bss section, we don't - pad the .data section. */ - . = ALIGN(. != 0 ? 64 / 8 : 1); - PROVIDE_HIDDEN(__bss_section_end = .); - } - _bss_end__ = . ; __bss_end__ = . ; - - . = ALIGN(64 / 8); - . = SEGMENT_START("ldata-segment", .); - . = ALIGN(64 / 8); - __end__ = .; - PROVIDE_HIDDEN(__maple_end__ = .); - _end = .; PROVIDE (end = .); - . = DATA_SEGMENT_END (.); - /* Stabs debugging sections. */ - .stab 0 : { *(.stab) } - .stabstr 0 : { *(.stabstr) } - .stab.excl 0 : { *(.stab.excl) } - .stab.exclstr 0 : { *(.stab.exclstr) } - .stab.index 0 : { *(.stab.index) } - .stab.indexstr 0 : { *(.stab.indexstr) } - .comment 0 : { *(.comment) } - /* DWARF debug sections. - Symbols in the DWARF debugging sections are relative to the beginning - of the section so we begin them at 0. */ - /* DWARF 1 */ - .debug 0 : { *(.debug) } - .line 0 : { *(.line) } - /* GNU DWARF 1 extensions */ - .debug_srcinfo 0 : { *(.debug_srcinfo) } - .debug_sfnames 0 : { *(.debug_sfnames) } - /* DWARF 1.1 and DWARF 2 */ - .debug_aranges 0 : { *(.debug_aranges) } - .maple_java_debug_aranges 0 : { KEEP(*(.maple_java_debug_aranges)) } - .debug_pubnames 0 : { *(.debug_pubnames) } - /* DWARF 2 */ - .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } - .maple_java_debug_info 0 : { KEEP(*(.maple_java_debug_info)) } - .debug_abbrev 0 : { *(.debug_abbrev) } - .maple_java_debug_abbrev 0 : { KEEP(*(.maple_java_debug_abbrev)) } - .debug_line 0 : { *(.debug_line .debug_line.* .debug_line_end ) } - .maple_java_debug_line 0 : { KEEP(*(.maple_java_debug_line)) } - .debug_frame 0 : { *(.debug_frame) } - .debug_str 0 : { *(.debug_str) } - .debug_loc 0 : { *(.debug_loc) } - .debug_macinfo 0 : { *(.debug_macinfo) } - /* SGI/MIPS DWARF 2 extensions */ - .debug_weaknames 0 : { *(.debug_weaknames) } - .debug_funcnames 0 : { *(.debug_funcnames) } - .debug_typenames 0 : { *(.debug_typenames) } - .debug_varnames 0 : { *(.debug_varnames) } - /* DWARF 3 */ - .debug_pubtypes 0 : { *(.debug_pubtypes) } - .debug_ranges 0 : { *(.debug_ranges) } - .maple_java_debug_ranges 0 : { KEEP(*(.maple_java_debug_ranges)) } - /* DWARF Extension. */ - .debug_macro 0 : { *(.debug_macro) } - .ARM.attributes 0 : { KEEP (*(.ARM.attributes)) KEEP (*(.gnu.attributes)) } - .note.gnu.arm.ident 0 : { KEEP (*(.note.gnu.arm.ident)) } - /DISCARD/ : { *(.note.GNU-stack) *(.gnu_debuglink) *(.gnu.lto_*) } -} diff --git a/build/third_party/aosp_gn/art/libdexfile/BUILD.gn b/build/third_party/aosp_gn/art/libdexfile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2c9a3e2a4d93840040ca84f6273f94727c7e8c95 --- /dev/null +++ b/build/third_party/aosp_gn/art/libdexfile/BUILD.gn @@ -0,0 +1,45 @@ +include_directories = [ + "${AOSP_ROOT}/system/core/base/include", + "${AOSP_ROOT}/system/core/libziparchive/include", + "${AOSP_ROOT}/system/core/liblog/include", + "${AOSP_ROOT}/system/core/libutils/include", + "${AOSP_ROOT}/art/libartpalette/include", + "${AOSP_ROOT}/art/libartbase", + "${AOSP_ROOT}/art/libdexfile", + "${AOSP_ROOT}/include", + "${AOSP_ROOT}/libnativehelper/include_jni", +] + +sources_files = [ + "dex/art_dex_file_loader.cc", + "dex/compact_dex_file.cc", + "dex/compact_offset_table.cc", + "dex/descriptors_names.cc", + "dex/dex_file.cc", + "dex/dex_file_exception_helpers.cc", + "dex/dex_file_layout.cc", + "dex/dex_file_loader.cc", + "dex/dex_file_tracking_registrar.cc", + "dex/dex_file_verifier.cc", + "dex/dex_instruction.cc", + "dex/modifiers.cc", + "dex/primitive.cc", + "dex/signature.cc", + "dex/standard_dex_file.cc", + "dex/type_lookup_table.cc", + "dex/utf.cc", +] + +static_library("libdexfile") { + sources = sources_files + + include_dirs = include_directories + + cflags_cc += [ + "-Wno-defaulted-function-deleted", + "-std=gnu++17", + "-fPIC", + ] + + output_dir = "${root_out_dir}/lib" +} diff --git a/build/third_party/aosp_gn/system/core/base/BUILD.gn b/build/third_party/aosp_gn/system/core/base/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cdc7374fcf2e9172eedb2535aba9a38e3d6dbf4c --- /dev/null +++ b/build/third_party/aosp_gn/system/core/base/BUILD.gn @@ -0,0 +1,32 @@ +include_directories = [ + "${AOSP_ROOT}/system/core/base/include", + "${AOSP_ROOT}/include", +] + +source_files = [ + "chrono_utils.cpp", + "cmsg.cpp", + "file.cpp", + "logging.cpp", + "mapped_file.cpp", + "parsenetaddress.cpp", + "properties.cpp", + "quick_exit.cpp", + "stringprintf.cpp", + "strings.cpp", + "test_utils.cpp", + "threads.cpp", +] + +static_library("libbase") { + sources = source_files + + include_dirs = include_directories + + cflags_cc += [ + "-std=gnu++17", + "-fPIC", + ] + + output_dir = "${root_out_dir}/lib" +} diff --git a/build/third_party/aosp_gn/system/core/libziparchive/BUILD.gn b/build/third_party/aosp_gn/system/core/libziparchive/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..442ae3460d8eca3525b574ab52fa7fa402928cf7 --- /dev/null +++ b/build/third_party/aosp_gn/system/core/libziparchive/BUILD.gn @@ -0,0 +1,24 @@ +include_directories = [ + "${AOSP_ROOT}/system/core/include", + "${AOSP_ROOT}/system/core/base/include", + "${AOSP_ROOT}/system/core/libziparchive/include", + "${AOSP_ROOT}/system/core/libziparchive", + "${AOSP_ROOT}/system/core/liblog/include", + "${AOSP_ROOT}/system/core/libutils/include", + "${AOSP_ROOT}/include", +] + +static_library("libziparchive") { + sources = [ + "zip_archive.cc", + "zip_archive_stream_entry.cc", + "zip_writer.cc", + ] + + include_dirs = include_directories + cflags_cc += [ + "-std=gnu++17", + "-fPIC", + ] + output_dir = "${root_out_dir}/lib" +} diff --git a/build/third_party/art_001.patch b/build/third_party/art_001.patch new file mode 100644 index 0000000000000000000000000000000000000000..3b9938f48afbadbf5bb73f243c55febd395f5cde --- /dev/null +++ b/build/third_party/art_001.patch @@ -0,0 +1,703 @@ +diff -ur art_aosp/libartbase/arch/instruction_set.cc art/libartbase/arch/instruction_set.cc +--- art_aosp/libartbase/arch/instruction_set.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/arch/instruction_set.cc 2021-01-29 10:34:50.012986865 +0800 +@@ -19,6 +19,7 @@ + #include "android-base/logging.h" + #include "base/bit_utils.h" + #include "base/globals.h" ++#include + + namespace art { + +@@ -115,11 +116,23 @@ + static_assert(IsAligned(kX86StackOverflowReservedBytes), "X86 gap not page aligned"); + static_assert(IsAligned(kX86_64StackOverflowReservedBytes), + "X86_64 gap not page aligned"); +- ++/* ++cflags += [ ++ "-DART_STACK_OVERFLOW_GAP_arm=8192", ++ "-DART_STACK_OVERFLOW_GAP_arm64=8192", ++ "-DART_STACK_OVERFLOW_GAP_mips=16384", ++ "-DART_STACK_OVERFLOW_GAP_mips64=16384", ++ "-DART_STACK_OVERFLOW_GAP_x86=16384", ++ "-DART_STACK_OVERFLOW_GAP_x86_64=20480", ++ "-DART_FRAME_SIZE_LIMIT=7400", ++ ] ++ */ ++/* + #if !defined(ART_FRAME_SIZE_LIMIT) + #error "ART frame size limit missing" + #endif +- ++*/ ++const uint32_t ART_FRAME_SIZE_LIMIT = 7400; + // TODO: Should we require an extra page (RoundUp(SIZE) + kPageSize)? + static_assert(ART_FRAME_SIZE_LIMIT < kArmStackOverflowReservedBytes, "Frame size limit too large"); + static_assert(ART_FRAME_SIZE_LIMIT < kArm64StackOverflowReservedBytes, +diff -ur art_aosp/libartbase/arch/instruction_set.h art/libartbase/arch/instruction_set.h +--- art_aosp/libartbase/arch/instruction_set.h 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/arch/instruction_set.h 2021-01-29 10:34:50.012986865 +0800 +@@ -227,19 +227,30 @@ + } + + namespace instruction_set_details { +- ++/* ++cflags += [ ++ "-DART_STACK_OVERFLOW_GAP_arm=8192", ++ "-DART_STACK_OVERFLOW_GAP_arm64=8192", ++ "-DART_STACK_OVERFLOW_GAP_mips=16384", ++ "-DART_STACK_OVERFLOW_GAP_mips64=16384", ++ "-DART_STACK_OVERFLOW_GAP_x86=16384", ++ "-DART_STACK_OVERFLOW_GAP_x86_64=20480", ++ "-DART_FRAME_SIZE_LIMIT=7400", ++ ] ++ */ ++ /* + #if !defined(ART_STACK_OVERFLOW_GAP_arm) || !defined(ART_STACK_OVERFLOW_GAP_arm64) || \ + !defined(ART_STACK_OVERFLOW_GAP_mips) || !defined(ART_STACK_OVERFLOW_GAP_mips64) || \ + !defined(ART_STACK_OVERFLOW_GAP_x86) || !defined(ART_STACK_OVERFLOW_GAP_x86_64) + #error "Missing defines for stack overflow gap" + #endif +- +-static constexpr size_t kArmStackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_arm; +-static constexpr size_t kArm64StackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_arm64; +-static constexpr size_t kMipsStackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_mips; +-static constexpr size_t kMips64StackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_mips64; +-static constexpr size_t kX86StackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_x86; +-static constexpr size_t kX86_64StackOverflowReservedBytes = ART_STACK_OVERFLOW_GAP_x86_64; ++*/ ++static constexpr size_t kArmStackOverflowReservedBytes = 8192; ++static constexpr size_t kArm64StackOverflowReservedBytes = 8192; ++static constexpr size_t kMipsStackOverflowReservedBytes = 16384; ++static constexpr size_t kMips64StackOverflowReservedBytes = 16384; ++static constexpr size_t kX86StackOverflowReservedBytes = 16384; ++static constexpr size_t kX86_64StackOverflowReservedBytes = 20480; + + NO_RETURN void GetStackOverflowReservedBytesFailure(const char* error_msg); + +diff -ur art_aosp/libartbase/base/arena_allocator.h art/libartbase/base/arena_allocator.h +--- art_aosp/libartbase/base/arena_allocator.h 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/arena_allocator.h 2021-01-29 10:34:50.012986865 +0800 +@@ -25,6 +25,7 @@ + #include "dchecked_vector.h" + #include "macros.h" + #include "memory_tool.h" ++#include + + namespace art { + +diff -ur art_aosp/libartbase/base/bit_vector.h art/libartbase/base/bit_vector.h +--- art_aosp/libartbase/base/bit_vector.h 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/bit_vector.h 2021-01-29 10:34:50.012986865 +0800 +@@ -19,7 +19,7 @@ + + #include + #include +- ++#include + #include "bit_utils.h" + #include "globals.h" + +diff -ur art_aosp/libartbase/base/file_magic.cc art/libartbase/base/file_magic.cc +--- art_aosp/libartbase/base/file_magic.cc 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/file_magic.cc 2021-01-29 10:34:50.012986865 +0800 +@@ -19,7 +19,7 @@ + #include + #include + #include +- ++#include + #include + #include + +diff -ur art_aosp/libartbase/base/file_utils.cc art/libartbase/base/file_utils.cc +--- art_aosp/libartbase/base/file_utils.cc 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/file_utils.cc 2021-01-29 10:34:50.012986865 +0800 +@@ -40,7 +40,7 @@ + + + #include +- ++#include + #include "android-base/stringprintf.h" + #include "android-base/strings.h" + +@@ -401,7 +401,7 @@ + &error_msg); + return (android_root != nullptr) + && (runtime_root != nullptr) +- && (std::string_view(android_root) != std::string_view(runtime_root)); ++ && (StringView(android_root) != StringView(runtime_root)); + } + + int DupCloexec(int fd) { +diff -ur art_aosp/libartbase/base/hiddenapi_stubs.h art/libartbase/base/hiddenapi_stubs.h +--- art_aosp/libartbase/base/hiddenapi_stubs.h 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/hiddenapi_stubs.h 2021-01-29 10:34:50.012986865 +0800 +@@ -18,11 +18,16 @@ + #define ART_LIBARTBASE_BASE_HIDDENAPI_STUBS_H_ + + #include +-#include ++#include "string_view_format.h" + + namespace art { + namespace hiddenapi { + ++const std::string kPublicApiStr = "public-api"; ++const std::string kSystemApiStr = "system-api"; ++const std::string kTestApiStr = "test-api"; ++const std::string kCorePlatformApiStr = "core-platform-api"; ++ + class ApiStubs { + public: + enum class Kind { +@@ -32,7 +37,7 @@ + kCorePlatformApi, + }; + +- static const std::string_view ToString(Kind api) { ++ static std::string ToString(Kind api) { + switch (api) { + case Kind::kPublicApi: + return kPublicApiStr; +@@ -45,16 +50,10 @@ + } + } + +- static bool IsStubsFlag(const std::string_view& api_flag_name) { ++ static bool IsStubsFlag(const std::string& api_flag_name) { + return api_flag_name == kPublicApiStr || api_flag_name == kSystemApiStr || + api_flag_name == kTestApiStr || api_flag_name == kCorePlatformApiStr; + } +- +- private: +- static constexpr std::string_view kPublicApiStr{"public-api"}; +- static constexpr std::string_view kSystemApiStr{"system-api"}; +- static constexpr std::string_view kTestApiStr{"test-api"}; +- static constexpr std::string_view kCorePlatformApiStr{"core-platform-api"}; + }; + + } // namespace hiddenapi +diff -ur art_aosp/libartbase/base/logging.cc art/libartbase/base/logging.cc +--- art_aosp/libartbase/base/logging.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/logging.cc 2021-01-29 10:34:50.012986865 +0800 +@@ -23,6 +23,7 @@ + #include "aborting.h" + #include "os.h" + #include "unix_file/fd_file.h" ++#include + + // Headers for LogMessage::LogLine. + #ifdef ART_TARGET_ANDROID +diff -ur art_aosp/libartbase/base/memfd.cc art/libartbase/base/memfd.cc +--- art_aosp/libartbase/base/memfd.cc 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/memfd.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -25,6 +25,7 @@ + #endif + + #include "macros.h" ++#include + + // When building for linux host, glibc in prebuilts does not include memfd_create system call + // number. As a temporary testing measure, we add the definition here. +diff -ur art_aosp/libartbase/base/os_linux.cc art/libartbase/base/os_linux.cc +--- art_aosp/libartbase/base/os_linux.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/os_linux.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -62,8 +62,7 @@ + CHECK(name != nullptr); + bool read_only = ((flags & O_ACCMODE) == O_RDONLY); + bool check_usage = !read_only && auto_flush; +- std::unique_ptr file( +- new File(name, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH, check_usage)); ++ std::unique_ptr file(new File(name, flags, 0666, check_usage)); + if (!file->IsOpened()) { + return nullptr; + } +diff -ur art_aosp/libartbase/base/safe_copy.cc art/libartbase/base/safe_copy.cc +--- art_aosp/libartbase/base/safe_copy.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/safe_copy.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -56,10 +56,10 @@ + } + + src_iovs[iovecs_used].iov_base = const_cast(cur); +- if (!IsAlignedParam(cur, PAGE_SIZE)) { +- src_iovs[iovecs_used].iov_len = AlignUp(cur, PAGE_SIZE) - cur; ++ if (!IsAlignedParam(cur, sysconf(_SC_PAGE_SIZE))) { ++ src_iovs[iovecs_used].iov_len = AlignUp(cur, sysconf(_SC_PAGE_SIZE)) - cur; + } else { +- src_iovs[iovecs_used].iov_len = PAGE_SIZE; ++ src_iovs[iovecs_used].iov_len = sysconf(_SC_PAGE_SIZE); + } + + src_iovs[iovecs_used].iov_len = std::min(src_iovs[iovecs_used].iov_len, len); +diff -ur art_aosp/libartbase/base/scoped_flock.cc art/libartbase/base/scoped_flock.cc +--- art_aosp/libartbase/base/scoped_flock.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/scoped_flock.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -24,6 +24,7 @@ + + #include "file_utils.h" + #include "unix_file/fd_file.h" ++#include + + namespace art { + +diff -ur art_aosp/libartbase/base/string_view_cpp20.h art/libartbase/base/string_view_cpp20.h +--- art_aosp/libartbase/base/string_view_cpp20.h 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/string_view_cpp20.h 2021-01-29 10:34:50.016986900 +0800 +@@ -17,21 +17,21 @@ + #ifndef ART_LIBARTBASE_BASE_STRING_VIEW_CPP20_H_ + #define ART_LIBARTBASE_BASE_STRING_VIEW_CPP20_H_ + +-#include ++#include "string_view_format.h" + + namespace art { + +-// Replacement functions for std::string_view::starts_with(), ends_with() ++// Replacement functions for StringView::starts_with(), ends_with() + // which shall be available in C++20. + #if __cplusplus >= 202000L + #error "When upgrading to C++20, remove this error and file a bug to remove this workaround." + #endif + +-inline bool StartsWith(std::string_view sv, std::string_view prefix) { ++inline bool StartsWith(StringView sv, StringView prefix) { + return sv.substr(0u, prefix.size()) == prefix; + } + +-inline bool EndsWith(std::string_view sv, std::string_view suffix) { ++inline bool EndsWith(StringView sv, StringView suffix) { + return sv.size() >= suffix.size() && sv.substr(sv.size() - suffix.size()) == suffix; + } + +diff -ur art_aosp/libartbase/base/unix_file/fd_file.cc art/libartbase/base/unix_file/fd_file.cc +--- art_aosp/libartbase/base/unix_file/fd_file.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/unix_file/fd_file.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -20,6 +20,7 @@ + #include + #include + #include ++#include + + #if defined(__BIONIC__) + #include +diff -ur art_aosp/libartbase/base/utils.cc art/libartbase/base/utils.cc +--- art_aosp/libartbase/base/utils.cc 2021-01-29 11:00:02.202266487 +0800 ++++ art/libartbase/base/utils.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -29,7 +29,6 @@ + #include "android-base/stringprintf.h" + #include "android-base/strings.h" + +-#include "bit_utils.h" + #include "os.h" + + #if defined(__APPLE__) +@@ -63,98 +62,6 @@ + using android::base::ReadFileToString; + using android::base::StringPrintf; + +-#if defined(__arm__) +- +-namespace { +- +-// Bitmap of caches to flush for cacheflush(2). Must be zero for ARM. +-static constexpr int kCacheFlushFlags = 0x0; +- +-// Number of retry attempts when flushing cache ranges. +-static constexpr size_t kMaxFlushAttempts = 4; +- +-int CacheFlush(uintptr_t start, uintptr_t limit) { +- // The signature of cacheflush(2) seems to vary by source. On ARM the system call wrapper +- // (bionic/SYSCALLS.TXT) has the form: int cacheflush(long start, long end, long flags); +- int r = cacheflush(start, limit, kCacheFlushFlags); +- if (r == -1) { +- CHECK_NE(errno, EINVAL); +- } +- return r; +-} +- +-bool TouchAndFlushCacheLinesWithinPage(uintptr_t start, uintptr_t limit, size_t attempts) { +- CHECK_LT(start, limit); +- CHECK_EQ(RoundDown(start, kPageSize), RoundDown(limit - 1, kPageSize)) << "range spans pages"; +- // Declare a volatile variable so the compiler does not elide reads from the page being touched. +- volatile uint8_t v = 0; +- for (size_t i = 0; i < attempts; ++i) { +- // Touch page to maximize chance page is resident. +- v = *reinterpret_cast(start); +- +- if (LIKELY(CacheFlush(start, limit) == 0)) { +- return true; +- } +- } +- return false; +-} +- +-} // namespace +- +-bool FlushCpuCaches(void* begin, void* end) { +- // This method is specialized for ARM as the generic implementation below uses the +- // __builtin___clear_cache() intrinsic which is declared as void. On ARMv7 flushing the CPU +- // caches is a privileged operation. The Linux kernel allows these operations to fail when they +- // trigger a fault (e.g. page not resident). We use a wrapper for the ARM specific cacheflush() +- // system call to detect the failure and potential erroneous state of the data and instruction +- // caches. +- // +- // The Android bug for this is b/132205399 and there's a similar discussion on +- // https://reviews.llvm.org/D37788. This is primarily an issue for the dual view JIT where the +- // pages where code is executed are only ever RX and never RWX. When attempting to invalidate +- // instruction cache lines in the RX mapping after writing fresh code in the RW mapping, the +- // page may not be resident (due to memory pressure), and this means that a fault is raised in +- // the midst of a cacheflush() call and the instruction cache lines are not invalidated and so +- // have stale code. +- // +- // Other architectures fair better for reasons such as: +- // +- // (1) stronger coherence between the data and instruction caches. +- // +- // (2) fault handling that allows flushing/invalidation to continue after +- // a missing page has been faulted in. +- +- // In the common case, this flush of the complete range succeeds. +- uintptr_t start = reinterpret_cast(begin); +- const uintptr_t limit = reinterpret_cast(end); +- if (LIKELY(CacheFlush(start, limit) == 0)) { +- return true; +- } +- +- // A rare failure has occurred implying that part of the range (begin, end] has been swapped +- // out. Retry flushing but this time grouping cache-line flushes on individual pages and +- // touching each page before flushing. +- uintptr_t next_page = RoundUp(start + 1, kPageSize); +- while (start < limit) { +- uintptr_t boundary = std::min(next_page, limit); +- if (!TouchAndFlushCacheLinesWithinPage(start, boundary, kMaxFlushAttempts)) { +- return false; +- } +- start = boundary; +- next_page += kPageSize; +- } +- return true; +-} +- +-#else +- +-bool FlushCpuCaches(void* begin, void* end) { +- __builtin___clear_cache(reinterpret_cast(begin), reinterpret_cast(end)); +- return true; +-} +- +-#endif +- + pid_t GetTid() { + #if defined(__APPLE__) + uint64_t owner; +diff -ur art_aosp/libartbase/base/utils.h art/libartbase/base/utils.h +--- art_aosp/libartbase/base/utils.h 2021-01-29 11:00:02.198266452 +0800 ++++ art/libartbase/base/utils.h 2021-01-29 10:34:50.016986900 +0800 +@@ -113,8 +113,15 @@ + // Sleep forever and never come back. + NO_RETURN void SleepForever(); + +-// Flush CPU caches. Returns true on success, false if flush failed. +-WARN_UNUSED bool FlushCpuCaches(void* begin, void* end); ++inline void FlushDataCache(void* begin, void* end) { ++ __builtin___clear_cache(reinterpret_cast(begin), reinterpret_cast(end)); ++} ++ ++inline void FlushInstructionCache(void* begin, void* end) { ++ // Same as FlushInstructionCache for lack of other builtin. __builtin___clear_cache ++ // flushes both caches. ++ __builtin___clear_cache(reinterpret_cast(begin), reinterpret_cast(end)); ++} + + template + constexpr PointerSize ConvertToPointerSize(T any) { +diff -ur art_aosp/libartpalette/system/palette_fake.cc art/libartpalette/system/palette_fake.cc +--- art_aosp/libartpalette/system/palette_fake.cc 2021-01-29 11:01:59.615297526 +0800 ++++ art/libartpalette/system/palette_fake.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -21,7 +21,7 @@ + + #include + #include // For ATTRIBUTE_UNUSED +- ++#include "string_view_format.h" + #include "palette_system.h" + + enum PaletteStatus PaletteGetVersion(int32_t* version) { +@@ -54,7 +54,7 @@ + } + + enum PaletteStatus PaletteWriteCrashThreadStacks(/*in*/ const char* stacks, size_t stacks_len) { +- LOG(INFO) << std::string_view(stacks, stacks_len); ++ LOG(INFO) << StringView(stacks, stacks_len); + return PaletteStatus::kOkay; + } + +diff -ur art_aosp/libdexfile/dex/compact_dex_file.cc art/libdexfile/dex/compact_dex_file.cc +--- art_aosp/libdexfile/dex/compact_dex_file.cc 2021-01-29 11:02:31.435577410 +0800 ++++ art/libdexfile/dex/compact_dex_file.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -19,6 +19,8 @@ + #include "base/leb128.h" + #include "code_item_accessors-inl.h" + #include "dex_file-inl.h" ++#include ++#include + + namespace art { + +diff -ur art_aosp/libdexfile/dex/compact_offset_table.h art/libdexfile/dex/compact_offset_table.h +--- art_aosp/libdexfile/dex/compact_offset_table.h 2021-01-29 11:02:32.119583426 +0800 ++++ art/libdexfile/dex/compact_offset_table.h 2021-01-29 10:34:50.016986900 +0800 +@@ -28,7 +28,7 @@ + public: + // This value is coupled with the leb chunk bitmask. That logic must also be adjusted when the + // integer is modified. +- static constexpr size_t kElementsPerIndex = 16; ++ static constexpr std::size_t kElementsPerIndex = 16; + + // Leb block format: + // [uint16_t] 16 bit mask for what indexes actually have a non zero offset for the chunk. +@@ -61,7 +61,7 @@ + uint32_t* out_table_offset); + + // 32 bit aligned for the offset table. +- static constexpr size_t kAlignment = sizeof(uint32_t); ++ static constexpr std::size_t kAlignment = sizeof(uint32_t); + }; + + } // namespace art +diff -ur art_aosp/libdexfile/dex/descriptors_names.cc art/libdexfile/dex/descriptors_names.cc +--- art_aosp/libdexfile/dex/descriptors_names.cc 2021-01-29 11:02:30.463568859 +0800 ++++ art/libdexfile/dex/descriptors_names.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -21,6 +21,8 @@ + + #include "base/macros.h" + #include "dex/utf-inl.h" ++#include ++#include + + namespace art { + +diff -ur art_aosp/libdexfile/dex/dex_file.cc art/libdexfile/dex/dex_file.cc +--- art_aosp/libdexfile/dex/dex_file.cc 2021-01-29 11:02:29.831563300 +0800 ++++ art/libdexfile/dex/dex_file.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -400,7 +400,7 @@ + } + + // Given a signature place the type ids into the given vector +-bool DexFile::CreateTypeList(std::string_view signature, ++bool DexFile::CreateTypeList(StringView signature, + dex::TypeIndex* return_type_idx, + std::vector* param_type_idxs) const { + if (signature[0] != '(') { +diff -ur art_aosp/libdexfile/dex/dex_file.h art/libdexfile/dex/dex_file.h +--- art_aosp/libdexfile/dex/dex_file.h 2021-01-29 11:02:29.947564321 +0800 ++++ art/libdexfile/dex/dex_file.h 2021-01-29 10:34:50.016986900 +0800 +@@ -19,7 +19,7 @@ + + #include + #include +-#include ++#include "string_view_format.h" + #include + + #include +@@ -262,7 +262,7 @@ + const char* StringDataAndUtf16LengthByIdx(dex::StringIndex idx, uint32_t* utf16_length) const; + + const char* StringDataByIdx(dex::StringIndex idx) const; +- std::string_view StringViewByIdx(dex::StringIndex idx) const; ++ StringView StringViewByIdx(dex::StringIndex idx) const; + + // Looks up a string id for a given modified utf8 string. + const dex::StringId* FindStringId(const char* string) const; +@@ -480,7 +480,7 @@ + } + + // Given a signature place the type ids into the given vector, returns true on success +- bool CreateTypeList(std::string_view signature, ++ bool CreateTypeList(StringView signature, + dex::TypeIndex* return_type_idx, + std::vector* param_type_idxs) const; + +diff -ur art_aosp/libdexfile/dex/dex_file-inl.h art/libdexfile/dex/dex_file-inl.h +--- art_aosp/libdexfile/dex/dex_file-inl.h 2021-01-29 11:02:30.975573364 +0800 ++++ art/libdexfile/dex/dex_file-inl.h 2021-01-29 10:34:50.016986900 +0800 +@@ -28,14 +28,15 @@ + #include "dex_instruction_iterator.h" + #include "invoke_type.h" + #include "standard_dex_file.h" ++#include "string_view_format.h" + + namespace art { + +-inline std::string_view StringViewFromUtf16Length(const char* utf8_data, size_t utf16_length) { ++inline StringView StringViewFromUtf16Length(const char* utf8_data, size_t utf16_length) { + size_t utf8_length = LIKELY(utf8_data[utf16_length] == 0) // Is ASCII? + ? utf16_length + : utf16_length + strlen(utf8_data + utf16_length); +- return std::string_view(utf8_data, utf8_length); ++ return StringView(utf8_data, utf8_length); + } + + inline int32_t DexFile::GetStringLength(const dex::StringId& string_id) const { +@@ -71,10 +72,10 @@ + return StringDataAndUtf16LengthByIdx(idx, &unicode_length); + } + +-inline std::string_view DexFile::StringViewByIdx(dex::StringIndex idx) const { ++inline StringView DexFile::StringViewByIdx(dex::StringIndex idx) const { + uint32_t unicode_length; + const char* data = StringDataAndUtf16LengthByIdx(idx, &unicode_length); +- return data != nullptr ? StringViewFromUtf16Length(data, unicode_length) : std::string_view(""); ++ return data != nullptr ? StringViewFromUtf16Length(data, unicode_length) : StringView(""); + } + + inline const char* DexFile::StringByTypeIdx(dex::TypeIndex idx, uint32_t* unicode_length) const { +diff -ur art_aosp/libdexfile/dex/dex_file_loader.h art/libdexfile/dex/dex_file_loader.h +--- art_aosp/libdexfile/dex/dex_file_loader.h 2021-01-29 11:02:31.547578394 +0800 ++++ art/libdexfile/dex/dex_file_loader.h 2021-01-29 10:34:50.016986900 +0800 +@@ -19,6 +19,7 @@ + + #include + #include ++#include + #include + #include + +diff -ur art_aosp/libdexfile/dex/dex_file_verifier.cc art/libdexfile/dex/dex_file_verifier.cc +--- art_aosp/libdexfile/dex/dex_file_verifier.cc 2021-01-29 11:02:29.603561296 +0800 ++++ art/libdexfile/dex/dex_file_verifier.cc 2021-01-29 10:34:50.016986900 +0800 +@@ -17,7 +17,7 @@ + #include "dex_file_verifier.h" + + #include +- ++#include + #include + + #include "android-base/stringprintf.h" +diff -ur art_aosp/libdexfile/dex/signature.cc art/libdexfile/dex/signature.cc +--- art_aosp/libdexfile/dex/signature.cc 2021-01-29 11:02:32.579587471 +0800 ++++ art/libdexfile/dex/signature.cc 2021-01-29 10:34:50.020986935 +0800 +@@ -57,11 +57,11 @@ + return strcmp(return_type, "V") == 0; + } + +-bool Signature::operator==(std::string_view rhs) const { ++bool Signature::operator==(StringView rhs) const { + if (dex_file_ == nullptr) { + return false; + } +- std::string_view tail(rhs); ++ StringView tail(rhs); + if (!StartsWith(tail, "(")) { + return false; // Invalid signature + } +@@ -69,7 +69,7 @@ + const TypeList* params = dex_file_->GetProtoParameters(*proto_id_); + if (params != nullptr) { + for (uint32_t i = 0; i < params->Size(); ++i) { +- std::string_view param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_)); ++ StringView param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_)); + if (!StartsWith(tail, param)) { + return false; + } +diff -ur art_aosp/libdexfile/dex/signature.h art/libdexfile/dex/signature.h +--- art_aosp/libdexfile/dex/signature.h 2021-01-29 11:02:30.347567837 +0800 ++++ art/libdexfile/dex/signature.h 2021-01-29 10:34:50.020986935 +0800 +@@ -19,7 +19,7 @@ + + #include + #include +-#include ++#include "string_view_format.h" + + #include + +@@ -49,7 +49,7 @@ + return !(*this == rhs); + } + +- bool operator==(std::string_view rhs) const; ++ bool operator==(StringView rhs) const; + + private: + Signature(const DexFile* dex, const dex::ProtoId& proto) : dex_file_(dex), proto_id_(&proto) { +diff -ur art_aosp/libdexfile/dex/signature-inl.h art/libdexfile/dex/signature-inl.h +--- art_aosp/libdexfile/dex/signature-inl.h 2021-01-29 11:02:32.063582932 +0800 ++++ art/libdexfile/dex/signature-inl.h 2021-01-29 10:34:50.020986935 +0800 +@@ -36,13 +36,13 @@ + uint32_t lhs_shorty_len; // For a shorty utf16 length == mutf8 length. + const char* lhs_shorty_data = dex_file_->StringDataAndUtf16LengthByIdx(proto_id_->shorty_idx_, + &lhs_shorty_len); +- std::string_view lhs_shorty(lhs_shorty_data, lhs_shorty_len); ++ StringView lhs_shorty(lhs_shorty_data, lhs_shorty_len); + { + uint32_t rhs_shorty_len; + const char* rhs_shorty_data = + rhs.dex_file_->StringDataAndUtf16LengthByIdx(rhs.proto_id_->shorty_idx_, + &rhs_shorty_len); +- std::string_view rhs_shorty(rhs_shorty_data, rhs_shorty_len); ++ StringView rhs_shorty(rhs_shorty_data, rhs_shorty_len); + if (lhs_shorty != rhs_shorty) { + return false; // Shorty mismatch. + } +@@ -56,7 +56,7 @@ + return false; // Return type mismatch. + } + } +- if (lhs_shorty.find('L', 1) != std::string_view::npos) { ++ if (lhs_shorty.find('L', 1) != StringView::npos) { + const dex::TypeList* params = dex_file_->GetProtoParameters(*proto_id_); + const dex::TypeList* rhs_params = rhs.dex_file_->GetProtoParameters(*rhs.proto_id_); + // We found a reference parameter in the matching shorty, so both lists must be non-empty. +diff -ur art_aosp/libdexfile/dex/standard_dex_file.cc art/libdexfile/dex/standard_dex_file.cc +--- art_aosp/libdexfile/dex/standard_dex_file.cc 2021-01-29 11:02:31.491577900 +0800 ++++ art/libdexfile/dex/standard_dex_file.cc 2021-01-29 10:34:50.020986935 +0800 +@@ -20,6 +20,8 @@ + #include "base/leb128.h" + #include "code_item_accessors-inl.h" + #include "dex_file-inl.h" ++#include ++#include + + namespace art { + +diff -ur art_aosp/libdexfile/external/include/art_api/dex_file_support.h art/libdexfile/external/include/art_api/dex_file_support.h +--- art_aosp/libdexfile/external/include/art_api/dex_file_support.h 2021-01-29 11:02:33.379594509 +0800 ++++ art/libdexfile/external/include/art_api/dex_file_support.h 2021-01-29 10:34:50.020986935 +0800 +@@ -22,7 +22,7 @@ + #include + #include + #include +-#include ++#include "string_view_format.h" + #include + #include + +@@ -46,7 +46,7 @@ + } + explicit DexString(const char* str = "") + : ext_string_(MakeExtDexFileString(str, std::strlen(str))) {} +- explicit DexString(std::string_view str) ++ explicit DexString(StringView str) + : ext_string_(MakeExtDexFileString(str.data(), str.size())) {} + ~DexString() { g_ExtDexFileFreeString(ext_string_); } + +@@ -68,10 +68,10 @@ + } + size_t length() const { return size(); } + +- operator std::string_view() const { ++ operator StringView() const { + size_t len; + const char* chars = g_ExtDexFileGetString(ext_string_, &len); +- return std::string_view(chars, len); ++ return StringView(chars, len); + } + + private: diff --git a/build/third_party/patch.sh b/build/third_party/patch.sh new file mode 100644 index 0000000000000000000000000000000000000000..39cd85dd632c70e219da4adad46188a83f99e368 --- /dev/null +++ b/build/third_party/patch.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# +# Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved. +# +# OpenArkCompiler is licensed under Mulan PSL v2. +# You can use this software according to the terms and conditions of the Mulan PSL v2. +# You may obtain a copy of Mulan PSL v2 at: +# +# http://license.coscl.org.cn/MulanPSL2 +# +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR +# FIT FOR A PARTICULAR PURPOSE. +# See the Mulan PSL v2 for more details. +# + +THIRD_PARTY_PATH=$MAPLE_ROOT/third_party +TOOLS_PATH=$MAPLE_ROOT/build/third_party +AOSP_PATH=$THIRD_PARTY_PATH/aosp_10.0.0_r35 +TEMP_PATH=$THIRD_PARTY_PATH/temp +AOSP_GN_PATH=$TOOLS_PATH/aosp_gn + +function install_patch { + if [ -d $TEMP_PATH ];then + echo "Already Patched." + exit 0 + fi + + echo "Preparing the build environment..." + + #backup source code + cd $THIRD_PARTY_PATH + mkdir -p $TEMP_PATH + tar -zcf aosp_10.0.0_r35.tar.gz aosp_10.0.0_r35/ + mv aosp_10.0.0_r35.tar.gz $TEMP_PATH/ + + #patch + cd $AOSP_PATH + patch -p0 < $TOOLS_PATH/system_001.patch + patch -p0 < $TOOLS_PATH/art_001.patch + mkdir -p include/ + cp -r ${MAPLE_ROOT}/src/mplfe/dex_input/include/string_view_format.h include/ + + #add third_party gn + cp $AOSP_GN_PATH/art/libdexfile/BUILD.gn $AOSP_PATH/art/libdexfile/ + cp $AOSP_GN_PATH/system/core/libziparchive/BUILD.gn $AOSP_PATH/system/core/libziparchive/ + cp $AOSP_GN_PATH/system/core/base/BUILD.gn $AOSP_PATH/system/core/base/ + +} + + +function uninstall_patch { + if [ ! -d $TEMP_PATH ];then + exit 0 + fi + + cd $THIRD_PARTY_PATH + rm -rf $AOSP_PATH + mv $TEMP_PATH/aosp_10.0.0_r35.tar.gz . + tar -zxvf aosp_10.0.0_r35.tar.gz > 0 + rm -rf $TEMP_PATH + rm -rf aosp_10.0.0_r35.tar.gz +} + +function main { + if [ "x$1" == "xpatch" ]; then + install_patch + fi + + if [ "x$1" == "xunpatch" ]; then + uninstall_patch + fi + cd $MAPLE_ROOT +} + + +main $@ diff --git a/build/third_party/system_001.patch b/build/third_party/system_001.patch new file mode 100644 index 0000000000000000000000000000000000000000..a9c5aa77f2859f45158071c39b3f98980dcaa0ce --- /dev/null +++ b/build/third_party/system_001.patch @@ -0,0 +1,476 @@ +diff -ur system_aosp/core/base/cmsg.cpp system/core/base/cmsg.cpp +--- system_aosp/core/base/cmsg.cpp 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/cmsg.cpp 2021-01-29 10:36:40.905961768 +0800 +@@ -21,7 +21,7 @@ + #include + #include + #include +- ++#include + #include + + #include +@@ -33,7 +33,7 @@ + const std::vector& fds) { + size_t cmsg_space = CMSG_SPACE(sizeof(int) * fds.size()); + size_t cmsg_len = CMSG_LEN(sizeof(int) * fds.size()); +- if (cmsg_space >= PAGE_SIZE) { ++ if (cmsg_space >= sysconf(_SC_PAGE_SIZE)) { + errno = ENOMEM; + return -1; + } +@@ -75,7 +75,7 @@ + fds->clear(); + + size_t cmsg_space = CMSG_SPACE(sizeof(int) * max_fds); +- if (cmsg_space >= PAGE_SIZE) { ++ if (cmsg_space >= sysconf(_SC_PAGE_SIZE)) { + errno = ENOMEM; + return -1; + } +diff -ur system_aosp/core/base/include/android-base/logging.h system/core/base/include/android-base/logging.h +--- system_aosp/core/base/include/android-base/logging.h 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/include/android-base/logging.h 2021-01-29 10:36:40.905961768 +0800 +@@ -81,7 +81,7 @@ + + enum LogSeverity { + VERBOSE, +- DEBUG, ++ DEBUG_S, + INFO, + WARNING, + ERROR, +@@ -181,7 +181,7 @@ + // Note: DO NOT USE DIRECTLY. This is an implementation detail. + #define SEVERITY_LAMBDA(severity) ([&]() { \ + using ::android::base::VERBOSE; \ +- using ::android::base::DEBUG; \ ++ using ::android::base::DEBUG_S; \ + using ::android::base::INFO; \ + using ::android::base::WARNING; \ + using ::android::base::ERROR; \ +@@ -248,7 +248,7 @@ + // Logs a message to logcat with the specified log ID on Android otherwise to + // stderr. If the severity is FATAL it also causes an abort. + // Use an expression here so we can support the << operator following the macro, +-// like "LOG(DEBUG) << xxx;". ++// like "LOG(DEBUG_S) << xxx;". + #define LOG_TO(dest, severity) LOGGING_PREAMBLE(severity) && LOG_STREAM_TO(dest, severity) + + // A variant of LOG that also logs the current errno value. To be used when +diff -ur system_aosp/core/base/include/android-base/strings.h system/core/base/include/android-base/strings.h +--- system_aosp/core/base/include/android-base/strings.h 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/include/android-base/strings.h 2021-01-29 10:36:40.905961768 +0800 +@@ -19,6 +19,7 @@ + #include + #include + #include ++#include "string_view_format.h" + + namespace android { + namespace base { +@@ -56,17 +57,17 @@ + extern template std::string Join(const std::vector&, const std::string&); + + // Tests whether 's' starts with 'prefix'. +-bool StartsWith(std::string_view s, std::string_view prefix); +-bool StartsWith(std::string_view s, char prefix); +-bool StartsWithIgnoreCase(std::string_view s, std::string_view prefix); ++bool StartsWith(StringView s, StringView prefix); ++bool StartsWith(StringView s, char prefix); ++bool StartsWithIgnoreCase(StringView s, StringView prefix); + + // Tests whether 's' ends with 'suffix'. +-bool EndsWith(std::string_view s, std::string_view suffix); +-bool EndsWith(std::string_view s, char suffix); +-bool EndsWithIgnoreCase(std::string_view s, std::string_view suffix); ++bool EndsWith(StringView s, StringView suffix); ++bool EndsWith(StringView s, char suffix); ++bool EndsWithIgnoreCase(StringView s, StringView suffix); + + // Tests whether 'lhs' equals 'rhs', ignoring case. +-bool EqualsIgnoreCase(std::string_view lhs, std::string_view rhs); ++bool EqualsIgnoreCase(StringView lhs, StringView rhs); + + } // namespace base + } // namespace android +diff -ur system_aosp/core/base/logging.cpp system/core/base/logging.cpp +--- system_aosp/core/base/logging.cpp 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/logging.cpp 2021-01-29 10:36:40.905961768 +0800 +@@ -16,10 +16,11 @@ + + #if defined(_WIN32) + #include ++#include "android-base/threads.h" + #endif + + #include "android-base/logging.h" +- ++#include + #include + #include + #include +@@ -167,7 +168,7 @@ + static constexpr int kLogSeverityToKernelLogLevel[] = { + [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log + // level) +- [android::base::DEBUG] = 7, // KERN_DEBUG ++ [android::base::DEBUG_S] = 7, // KERN_DEBUG_S + [android::base::INFO] = 6, // KERN_INFO + [android::base::WARNING] = 4, // KERN_WARNING + [android::base::ERROR] = 3, // KERN_ERROR +@@ -310,7 +311,7 @@ + gMinimumLogSeverity = VERBOSE; + continue; + case 'd': +- gMinimumLogSeverity = DEBUG; ++ gMinimumLogSeverity = DEBUG_S; + continue; + case 'i': + gMinimumLogSeverity = INFO; +diff -ur system_aosp/core/base/mapped_file.cpp system/core/base/mapped_file.cpp +--- system_aosp/core/base/mapped_file.cpp 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/mapped_file.cpp 2021-01-29 10:36:40.905961768 +0800 +@@ -76,7 +76,7 @@ + if (base_ != nullptr) UnmapViewOfFile(base_); + if (handle_ != nullptr) CloseHandle(handle_); + #else +- if (base_ != nullptr) munmap(base_, size_ + offset_); ++ if (base_ != nullptr) munmap(base_, size_); + #endif + + base_ = nullptr; +diff -ur system_aosp/core/base/strings.cpp system/core/base/strings.cpp +--- system_aosp/core/base/strings.cpp 2021-01-29 10:43:34.145594722 +0800 ++++ system/core/base/strings.cpp 2021-01-29 10:36:40.905961768 +0800 +@@ -87,32 +87,32 @@ + template std::string Join(const std::vector&, const std::string&); + template std::string Join(const std::vector&, const std::string&); + +-bool StartsWith(std::string_view s, std::string_view prefix) { ++bool StartsWith(StringView s, StringView prefix) { + return s.substr(0, prefix.size()) == prefix; + } + +-bool StartsWith(std::string_view s, char prefix) { ++bool StartsWith(StringView s, char prefix) { + return !s.empty() && s.front() == prefix; + } + +-bool StartsWithIgnoreCase(std::string_view s, std::string_view prefix) { ++bool StartsWithIgnoreCase(StringView s, StringView prefix) { + return s.size() >= prefix.size() && strncasecmp(s.data(), prefix.data(), prefix.size()) == 0; + } + +-bool EndsWith(std::string_view s, std::string_view suffix) { ++bool EndsWith(StringView s, StringView suffix) { + return s.size() >= suffix.size() && s.substr(s.size() - suffix.size(), suffix.size()) == suffix; + } + +-bool EndsWith(std::string_view s, char suffix) { ++bool EndsWith(StringView s, char suffix) { + return !s.empty() && s.back() == suffix; + } + +-bool EndsWithIgnoreCase(std::string_view s, std::string_view suffix) { ++bool EndsWithIgnoreCase(StringView s, StringView suffix) { + return s.size() >= suffix.size() && + strncasecmp(s.data() + (s.size() - suffix.size()), suffix.data(), suffix.size()) == 0; + } + +-bool EqualsIgnoreCase(std::string_view lhs, std::string_view rhs) { ++bool EqualsIgnoreCase(StringView lhs, StringView rhs) { + return lhs.size() == rhs.size() && strncasecmp(lhs.data(), rhs.data(), lhs.size()) == 0; + } + +diff -ur system_aosp/core/include/cutils/android_filesystem_config.h system/core/include/cutils/android_filesystem_config.h +--- system_aosp/core/include/cutils/android_filesystem_config.h 2021-01-29 10:43:42.185665405 +0800 ++++ system/core/include/cutils/android_filesystem_config.h 2021-01-29 10:36:40.909961804 +0800 +@@ -144,6 +144,7 @@ + /* The range 2900-2999 is reserved for OEM, and must never be + * used here */ + #define AID_OEM_RESERVED_START 2900 ++#define AID_HDB 2901 /* access hdbservice */ + #define AID_OEM_RESERVED_END 2999 + + /* The 3000 series are intended for use as supplemental group id's only. +@@ -161,6 +162,38 @@ + + /* The range 5000-5999 is also reserved for OEM, and must never be used here. */ + #define AID_OEM_RESERVED_2_START 5000 ++ ++/* Huawei Extend AID */ ++/* ++ * 1. ALL huawei extend AID should add VENDOR prefix,e.g. AID_VENDOR_XXXX ++ * 2. If the added AID was used in vendor partition only, Add it to config.fs ++ * vendor/huawei/chipset_common/config/common/config.fs ++ * 3. Huawei AID range: ++ * AID used in system partition: 5501-5900 ++ * AID used in vendor partiton only: 5900-5999 ++ * 4. wiki: http://3ms.huawei.com/hi/group/2844405/wiki_5160709.html?for_statistic_from=creation_group_wiki ++*/ ++ ++#define AID_VENDOR_HDB 5501 /* access hdbservice*/ ++ ++#define AID_VENDOR_DSM 5502 /* dsm access */ ++ ++#define AID_VENDOR_HWHFD 5503 /* Huawei kernel hot fix daemon */ ++ ++#define AID_VENDOR_SKYTONE 5504 /* access skytone */ ++ ++#define AID_VENDOR_ACT_RCS 5505 /* access device actr */ ++ ++#define AID_VENDOR_ODMF 5506 /* access AI model files */ ++ ++#define AID_VENDOR_INSTALLER 5507 /* access installer files */ ++ ++#define AID_VENDOR_HBS 5508 /* access hbs data */ ++ ++#define AID_DSM 5509 /* dsm access */ ++ ++#define AID_VENDOR_FACEID 5510 /* acess faceid */ ++ + #define AID_OEM_RESERVED_2_END 5999 + + #define AID_EVERYBODY 9997 /* shared between all apps in the same profile */ +diff -ur system_aosp/core/include/cutils/fs.h system/core/include/cutils/fs.h +--- system_aosp/core/include/cutils/fs.h 2021-01-29 10:43:42.185665405 +0800 ++++ system/core/include/cutils/fs.h 2021-01-29 10:36:40.909961804 +0800 +@@ -45,6 +45,14 @@ + */ + extern int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid); + ++/* DTS2016051401335 AR000485VM FixUid l00214442 20160514 begin */ ++/* ++ * Ensure that directory exists with given mode and owners. If it exists ++ * with a different mode or owners, they are fixed to match the given values recursively. ++ */ ++extern int fs_prepare_dir_fixup_recursive(const char* path, mode_t mode, uid_t uid, gid_t gid, int allow_fixup); ++/* DTS2016051401335 AR000485VM FixUid l00214442 20160514 end */ ++ + /* + * Ensure that directory exists with given mode and owners. If it exists + * with different owners, they are not fixed and -1 is returned. +diff -ur system_aosp/core/include/cutils/trace.h system/core/include/cutils/trace.h +--- system_aosp/core/include/cutils/trace.h 2021-01-29 10:43:42.185665405 +0800 ++++ system/core/include/cutils/trace.h 2021-01-29 10:36:40.909961804 +0800 +@@ -18,7 +18,6 @@ + #define _LIBS_CUTILS_TRACE_H + + #include +-#include + #include + #include + #include +@@ -88,7 +87,7 @@ + #elif ATRACE_TAG > ATRACE_TAG_VALID_MASK + #error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h + #endif +- ++using namespace std; + /** + * Opens the trace file for writing and reads the property for initial tags. + * The atrace.tags.enableflags property sets the tags to trace. +diff -ur system_aosp/core/include/log/log_id.h system/core/include/log/log_id.h +--- system_aosp/core/include/log/log_id.h 2021-01-29 10:43:42.185665405 +0800 ++++ system/core/include/log/log_id.h 2021-01-29 10:36:40.909961804 +0800 +@@ -58,6 +58,8 @@ + log_id_t android_name_to_log_id(const char* logName); + const char* android_log_id_to_name(log_id_t log_id); + ++int __hwlog_setparam(int paramid, const char *val); ++ + #ifdef __cplusplus + } + #endif +diff -ur system_aosp/core/include/private/android_filesystem_config.h system/core/include/private/android_filesystem_config.h +--- system_aosp/core/include/private/android_filesystem_config.h 2021-01-29 10:43:42.185665405 +0800 ++++ system/core/include/private/android_filesystem_config.h 2021-01-29 10:36:40.909961804 +0800 +@@ -144,6 +144,7 @@ + /* The range 2900-2999 is reserved for OEM, and must never be + * used here */ + #define AID_OEM_RESERVED_START 2900 ++#define AID_HDB 2901 /* access hdbservice */ + #define AID_OEM_RESERVED_END 2999 + + /* The 3000 series are intended for use as supplemental group id's only. +@@ -161,6 +162,38 @@ + + /* The range 5000-5999 is also reserved for OEM, and must never be used here. */ + #define AID_OEM_RESERVED_2_START 5000 ++ ++/* Huawei Extend AID */ ++/* ++ * 1. ALL huawei extend AID should add VENDOR prefix,e.g. AID_VENDOR_XXXX ++ * 2. If the added AID was used in vendor partition only, Add it to config.fs ++ * vendor/huawei/chipset_common/config/common/config.fs ++ * 3. Huawei AID range: ++ * AID used in system partition: 5501-5900 ++ * AID used in vendor partiton only: 5900-5999 ++ * 4. wiki: http://3ms.huawei.com/hi/group/2844405/wiki_5160709.html?for_statistic_from=creation_group_wiki ++*/ ++ ++#define AID_VENDOR_HDB 5501 /* access hdbservice*/ ++ ++#define AID_VENDOR_DSM 5502 /* dsm access */ ++ ++#define AID_VENDOR_HWHFD 5503 /* Huawei kernel hot fix daemon */ ++ ++#define AID_VENDOR_SKYTONE 5504 /* access skytone */ ++ ++#define AID_VENDOR_ACT_RCS 5505 /* access device actr */ ++ ++#define AID_VENDOR_ODMF 5506 /* access AI model files */ ++ ++#define AID_VENDOR_INSTALLER 5507 /* access installer files */ ++ ++#define AID_VENDOR_HBS 5508 /* access hbs data */ ++ ++#define AID_DSM 5509 /* dsm access */ ++ ++#define AID_VENDOR_FACEID 5510 /* acess faceid */ ++ + #define AID_OEM_RESERVED_2_END 5999 + + #define AID_EVERYBODY 9997 /* shared between all apps in the same profile */ +diff -ur system_aosp/core/include/utils/Flattenable.h system/core/include/utils/Flattenable.h +--- system_aosp/core/include/utils/Flattenable.h 2021-01-29 10:43:42.189665440 +0800 ++++ system/core/include/utils/Flattenable.h 2021-01-29 10:36:40.909961804 +0800 +@@ -47,12 +47,7 @@ + + template + static size_t align(void*& buffer) { +- static_assert(!(N & (N - 1)), "Can only align to a power of 2."); +- void* b = buffer; +- buffer = reinterpret_cast((uintptr_t(buffer) + (N-1)) & ~(N-1)); +- size_t delta = size_t(uintptr_t(buffer) - uintptr_t(b)); +- memset(b, 0, delta); +- return delta; ++ return align( const_cast(buffer) ); + } + + static void advance(void*& buffer, size_t& size, size_t offset) { +diff -ur system_aosp/core/include/utils/String8.h system/core/include/utils/String8.h +--- system_aosp/core/include/utils/String8.h 2021-01-29 10:43:42.189665440 +0800 ++++ system/core/include/utils/String8.h 2021-01-29 10:36:40.909961804 +0800 +@@ -58,6 +58,9 @@ + explicit String8(const char16_t* o, size_t numChars); + explicit String8(const char32_t* o); + explicit String8(const char32_t* o, size_t numChars); ++ //fix bug of sogou input method ++ explicit String8(unsigned short const* o); ++ //fix bug of sogou input method + ~String8(); + + static inline const String8 empty(); +diff -ur system_aosp/core/liblog/include/log/log_id.h system/core/liblog/include/log/log_id.h +--- system_aosp/core/liblog/include/log/log_id.h 2021-01-29 10:43:56.097787709 +0800 ++++ system/core/liblog/include/log/log_id.h 2021-01-29 10:36:40.909961804 +0800 +@@ -58,6 +58,8 @@ + log_id_t android_name_to_log_id(const char* logName); + const char* android_log_id_to_name(log_id_t log_id); + ++int __hwlog_setparam(int paramid, const char *val); ++ + #ifdef __cplusplus + } + #endif +diff -ur system_aosp/core/liblog/include_vndk/log/log_id.h system/core/liblog/include_vndk/log/log_id.h +--- system_aosp/core/liblog/include_vndk/log/log_id.h 2021-01-29 10:43:56.097787709 +0800 ++++ system/core/liblog/include_vndk/log/log_id.h 2021-01-29 10:36:40.909961804 +0800 +@@ -58,6 +58,8 @@ + log_id_t android_name_to_log_id(const char* logName); + const char* android_log_id_to_name(log_id_t log_id); + ++int __hwlog_setparam(int paramid, const char *val); ++ + #ifdef __cplusplus + } + #endif +diff -ur system_aosp/core/liblog/liblog.map.txt system/core/liblog/liblog.map.txt +--- system_aosp/core/liblog/liblog.map.txt 2021-01-29 10:43:56.097787709 +0800 ++++ system/core/liblog/liblog.map.txt 2021-01-29 10:36:40.909961804 +0800 +@@ -63,6 +63,7 @@ + __android_log_security; # apex + android_log_reset; #vndk + android_log_parser_reset; #vndk ++ __hwlog_setparam; + }; + + LIBLOG_PRIVATE { +diff -ur system_aosp/core/libutils/include/utils/Flattenable.h system/core/libutils/include/utils/Flattenable.h +--- system_aosp/core/libutils/include/utils/Flattenable.h 2021-01-29 10:44:02.421843310 +0800 ++++ system/core/libutils/include/utils/Flattenable.h 2021-01-29 10:36:40.909961804 +0800 +@@ -47,12 +47,7 @@ + + template + static size_t align(void*& buffer) { +- static_assert(!(N & (N - 1)), "Can only align to a power of 2."); +- void* b = buffer; +- buffer = reinterpret_cast((uintptr_t(buffer) + (N-1)) & ~(N-1)); +- size_t delta = size_t(uintptr_t(buffer) - uintptr_t(b)); +- memset(b, 0, delta); +- return delta; ++ return align( const_cast(buffer) ); + } + + static void advance(void*& buffer, size_t& size, size_t offset) { +diff -ur system_aosp/core/libutils/include/utils/String8.h system/core/libutils/include/utils/String8.h +--- system_aosp/core/libutils/include/utils/String8.h 2021-01-29 10:44:02.421843310 +0800 ++++ system/core/libutils/include/utils/String8.h 2021-01-29 10:36:40.909961804 +0800 +@@ -58,6 +58,9 @@ + explicit String8(const char16_t* o, size_t numChars); + explicit String8(const char32_t* o); + explicit String8(const char32_t* o, size_t numChars); ++ //fix bug of sogou input method ++ explicit String8(unsigned short const* o); ++ //fix bug of sogou input method + ~String8(); + + static inline const String8 empty(); +diff -ur system_aosp/core/libziparchive/zip_archive.cc system/core/libziparchive/zip_archive.cc +--- system_aosp/core/libziparchive/zip_archive.cc 2021-01-29 10:44:10.001909933 +0800 ++++ system/core/libziparchive/zip_archive.cc 2021-01-29 10:36:40.913961839 +0800 +@@ -33,6 +33,7 @@ + + #include + #include ++#include "string_view_format.h" + + #if defined(__APPLE__) + #define lseek64 lseek +@@ -103,8 +104,8 @@ + + static uint32_t ComputeHash(const ZipString& name) { + #if !defined(_WIN32) +- return std::hash{}( +- std::string_view(reinterpret_cast(name.name), name.name_length)); ++ return std::hash{}( ++ StringView(reinterpret_cast(name.name), name.name_length)); + #else + // Remove this code path once the windows compiler knows how to compile the above statement. + uint32_t hash = 0; +diff -ur system_aosp/core/libziparchive/zip_archive_private.h system/core/libziparchive/zip_archive_private.h +--- system_aosp/core/libziparchive/zip_archive_private.h 2021-01-29 10:44:10.001909933 +0800 ++++ system/core/libziparchive/zip_archive_private.h 2021-01-29 10:36:40.913961839 +0800 +@@ -138,7 +138,7 @@ + + /** + * More space efficient string representation of strings in an mmaped zipped file than +- * std::string_view or ZipString. Using ZipString as an entry in the ZipArchive hashtable wastes ++ * StringView or ZipString. Using ZipString as an entry in the ZipArchive hashtable wastes + * space. ZipString stores a pointer to a string (on 64 bit, 8 bytes) and the length to read from + * that pointer, 2 bytes. Because of alignment, the structure consumes 16 bytes, wasting 6 bytes. + * ZipStringOffset stores a 4 byte offset from a fixed location in the memory mapped file instead +diff -ur system_aosp/core/libziparchive/zip_writer.cc system/core/libziparchive/zip_writer.cc +--- system_aosp/core/libziparchive/zip_writer.cc 2021-01-29 10:44:10.001909933 +0800 ++++ system/core/libziparchive/zip_writer.cc 2021-01-29 10:36:40.913961839 +0800 +@@ -358,7 +358,7 @@ + CHECK(z_stream_->avail_out != 0); + + // Prepare the input. +- z_stream_->next_in = reinterpret_cast(data); ++ z_stream_->next_in = (unsigned char *)(data); + z_stream_->avail_in = len; + + while (z_stream_->avail_in > 0) { diff --git a/build/toolchain/BUILD.gn b/build/toolchain/BUILD.gn old mode 100644 new mode 100755 diff --git a/src/mapleall/BUILD.gn b/src/mapleall/BUILD.gn index 34e983a3a1bb7481ef347af0e18a1165211d2cd3..1e6969ef370471ecb33bc665bbcb0b7f6974d32d 100644 --- a/src/mapleall/BUILD.gn +++ b/src/mapleall/BUILD.gn @@ -15,7 +15,7 @@ config("mapleallcompilecfg") { cflags_cc = [] cflags_cc += [ - "-std=c++14", + "-std=c++17", "-fno-common", "-DTARGAARCH64", ] diff --git a/src/mapleall/bin/dex2mpl b/src/mapleall/bin/dex2mpl index 6e040c68fcfb4861dd36182bfc875ad202cd75de..b56b21ce93d518823371d99b4f1b0d2b8a0118db 100755 Binary files a/src/mapleall/bin/dex2mpl and b/src/mapleall/bin/dex2mpl differ diff --git a/src/mapleall/bin/dex2mpl_android b/src/mapleall/bin/dex2mpl_android index 856422861ffa925617793ba0fbf48fe94fc63418..15066bad3f3b99fec652bbdd47147b6806d14504 100755 Binary files a/src/mapleall/bin/dex2mpl_android and b/src/mapleall/bin/dex2mpl_android differ diff --git a/src/mapleall/bin/jbc2mpl b/src/mapleall/bin/jbc2mpl index de92b2c81fb448c66b8dd1a24fbb3576ba3e0cc6..1c3c44417047e3d4a7c26c766a86fc8aa654caf1 100755 Binary files a/src/mapleall/bin/jbc2mpl and b/src/mapleall/bin/jbc2mpl differ diff --git a/src/mapleall/bin/maple b/src/mapleall/bin/maple deleted file mode 100755 index 8b04981fb50aa87a60d4649c8206baccd12b19a4..0000000000000000000000000000000000000000 Binary files a/src/mapleall/bin/maple and /dev/null differ diff --git a/src/mapleall/maple_be/include/ad/target/mplad_arch_define.def b/src/mapleall/maple_be/include/ad/target/mplad_arch_define.def deleted file mode 100644 index d0893ea3ad59c966a4842dcb2a94cdc9da5cf51d..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_arch_define.def +++ /dev/null @@ -1,2 +0,0 @@ -/* cortex_a55 Architecture definition : */ -SetMaxParallelism(2); diff --git a/src/mapleall/maple_be/include/ad/target/mplad_bypass_define.def b/src/mapleall/maple_be/include/ad/target/mplad_bypass_define.def deleted file mode 100644 index 94082c9b0534c25c1c76c62757fb2b09a4db5d8f..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_bypass_define.def +++ /dev/null @@ -1,143 +0,0 @@ -ADDBYPASS(kLtShift, kLtAlu, 0); -ADDBYPASS(kLtShiftReg, kLtAlu, 0); -ADDBYPASS(kLtShift, kLtShift, 1); -ADDBYPASS(kLtShift, kLtShiftReg, 1); -ADDBYPASS(kLtShift, kLtAluShift, 1); -ADDBYPASS(kLtShift, kLtAluShiftReg, 1); -ADDBYPASS(kLtShiftReg, kLtShift, 1); -ADDBYPASS(kLtShiftReg, kLtShiftReg, 1); -ADDBYPASS(kLtShiftReg, kLtAluShift, 1); -ADDBYPASS(kLtShiftReg, kLtAluShiftReg, 1); -ADDBYPASS(kLtAlu, kLtAlu, 1); -ADDBYPASS(kLtAluShift, kLtAlu, 1); -ADDBYPASS(kLtAluShiftReg, kLtAlu, 1); -ADDALUSHIFTBYPASS(kLtAlu, kLtAluShift, 1); -ADDALUSHIFTBYPASS(kLtAluShift, kLtAluShift, 1); -ADDALUSHIFTBYPASS(kLtAluShiftReg, kLtAluShift, 1); -ADDALUSHIFTBYPASS(kLtAluExtr, kLtAluShift, 1); -ADDALUSHIFTBYPASS(kLtAlu, kLtAluShiftReg, 1); -ADDALUSHIFTBYPASS(kLtAluShift, kLtAluShiftReg, 1); -ADDALUSHIFTBYPASS(kLtAluShiftReg, kLtAluShiftReg, 1); -ADDALUSHIFTBYPASS(kLtAluExtr, kLtAluShiftReg, 1); -ADDBYPASS(kLtAlu, kLtAluShift, 2); -ADDBYPASS(kLtAluShift, kLtAluShift, 2); -ADDBYPASS(kLtAluShiftReg, kLtAluShift, 2); -ADDBYPASS(kLtAluExtr, kLtAluShift, 2); -ADDBYPASS(kLtAlu, kLtAluShiftReg, 2); -ADDBYPASS(kLtAluShift, kLtAluShiftReg, 2); -ADDBYPASS(kLtAluShiftReg, kLtAluShiftReg, 2); -ADDBYPASS(kLtAluExtr, kLtAluShiftReg, 2); -ADDBYPASS(kLtAlu, kLtAluExtr, 2); -ADDBYPASS(kLtAluShift, kLtAluExtr, 2); -ADDBYPASS(kLtAluShiftReg, kLtAluExtr, 2); -ADDBYPASS(kLtAluExtr, kLtAluExtr, 2); -ADDBYPASS(kLtAlu, kLtShift, 2); -ADDBYPASS(kLtAluShift, kLtShift, 2); -ADDBYPASS(kLtAluShiftReg, kLtShift, 2); -ADDBYPASS(kLtAluExtr, kLtShift, 2); -ADDBYPASS(kLtAlu, kLtShiftReg, 2); -ADDBYPASS(kLtAluShift, kLtShiftReg, 2); -ADDBYPASS(kLtAluShiftReg, kLtShiftReg, 2); -ADDBYPASS(kLtAluExtr, kLtShiftReg, 2); -ADDACCUMULATORBYPASS(kLtMul, kLtMul, 2); -ADDBYPASS(kLtMul, kLtAlu, 2); -ADDBYPASS(kLtMul, kLtAluShift, 3); -ADDBYPASS(kLtMul, kLtAluShiftReg, 3); -ADDBYPASS(kLtMul, kLtAluExtr, 3); -ADDBYPASS(kLtMul, kLtShift, 3); -ADDBYPASS(kLtMul, kLtShiftReg, 3); -ADDBYPASS(kLtLoad1, kLtAlu, 2); -ADDBYPASS(kLtLoad1, kLtAluShift, 3); -ADDBYPASS(kLtLoad1, kLtAluShiftReg, 3); -ADDBYPASS(kLtLoad1, kLtAluExtr, 3); -ADDBYPASS(kLtLoad1, kLtShift, 3); -ADDBYPASS(kLtLoad1, kLtShiftReg, 3); -ADDBYPASS(kLtLoad2, kLtAlu, 3); -ADDSTOREBYPASS(kLtAlu, kLtStore1, 0); -ADDSTOREBYPASS(kLtAlu, kLtStore2, 0); -ADDSTOREBYPASS(kLtAlu, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtAluShift, kLtStore1, 0); -ADDSTOREBYPASS(kLtAluShift, kLtStore2, 0); -ADDSTOREBYPASS(kLtAluShift, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtAluShiftReg, kLtStore1, 0); -ADDSTOREBYPASS(kLtAluShiftReg, kLtStore2, 0); -ADDSTOREBYPASS(kLtAluShiftReg, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtAluExtr, kLtStore1, 0); -ADDSTOREBYPASS(kLtAluExtr, kLtStore2, 0); -ADDSTOREBYPASS(kLtAluExtr, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtShift, kLtStore1, 0); -ADDSTOREBYPASS(kLtShift, kLtStore2, 0); -ADDSTOREBYPASS(kLtShift, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtShiftReg, kLtStore1, 0); -ADDSTOREBYPASS(kLtShiftReg, kLtStore2, 0); -ADDSTOREBYPASS(kLtShiftReg, kLtStore3plus, 0); -ADDSTOREBYPASS(kLtMul, kLtStore1, 1); -ADDSTOREBYPASS(kLtMul, kLtStore2, 1); -ADDSTOREBYPASS(kLtMul, kLtStore3plus, 1); -ADDSTOREBYPASS(kLtLoad1, kLtStore1, 1); -ADDSTOREBYPASS(kLtLoad1, kLtStore2, 1); -ADDSTOREBYPASS(kLtLoad1, kLtStore3plus, 1); -ADDSTOREBYPASS(kLtLoad2, kLtStore1, 1); -ADDSTOREBYPASS(kLtLoad2, kLtStore2, 1); -ADDSTOREBYPASS(kLtLoad2, kLtStore3plus, 1); -ADDSTOREBYPASS(kLtLoad3plus, kLtStore1, 1); -ADDSTOREBYPASS(kLtLoad3plus, kLtStore2, 1); -ADDSTOREBYPASS(kLtLoad3plus, kLtStore3plus, 1); -ADDBYPASS(kLtAlu, kLtR2f, 0); -ADDBYPASS(kLtAluShift, kLtR2f, 0); -ADDBYPASS(kLtAluShiftReg, kLtR2f, 0); -ADDBYPASS(kLtAluExtr, kLtR2f, 0); -ADDBYPASS(kLtShift, kLtR2f, 0); -ADDBYPASS(kLtShiftReg, kLtR2f, 0); -ADDBYPASS(kLtMul, kLtR2f, 1); -ADDBYPASS(kLtLoad1, kLtR2f, 1); -ADDBYPASS(kLtLoad2, kLtR2f, 1); -ADDBYPASS(kLtAlu, kLtR2fCvt, 2); -ADDBYPASS(kLtAluShift, kLtR2fCvt, 2); -ADDBYPASS(kLtAluShiftReg, kLtR2fCvt, 2); -ADDBYPASS(kLtAluExtr, kLtR2fCvt, 2); -ADDBYPASS(kLtMul, kLtR2fCvt, 3); -ADDBYPASS(kLtLoad1, kLtR2fCvt, 3); -ADDBYPASS(kLtLoad2, kLtR2fCvt, 3); -ADDBYPASS(kLtAlu, kLtBranch, 0); -ADDBYPASS(kLtAluShift, kLtBranch, 0); -ADDBYPASS(kLtAluShiftReg, kLtBranch, 0); -ADDBYPASS(kLtAluExtr, kLtBranch, 0); -ADDBYPASS(kLtShift, kLtBranch, 0); -ADDBYPASS(kLtShiftReg, kLtBranch, 0); -ADDACCUMULATORBYPASS(kLtFpalu, kLtFpmac, 1); -ADDACCUMULATORBYPASS(kLtFpmul, kLtFpmac, 1); -ADDACCUMULATORBYPASS(kLtR2f, kLtFpmac, 1); -ADDACCUMULATORBYPASS(kLtR2fCvt, kLtFpmac, 1); -ADDACCUMULATORBYPASS(kLtFconst, kLtFpmac, 1); -ADDBYPASS(kLtFLoad64, kLtFpmac, 1); -ADDBYPASS(kLtFLoadMany, kLtFpmac, 1); -ADDACCUMULATORBYPASS(kLtFpmac, kLtFpmac, 4); -ADDBYPASS(kLtCryptoAese, kLtCryptoAesmc, 0); -ADDBYPASS(kLtShiftReg, kLtClinit, 1); -ADDBYPASS(kLtAlu, kLtClinit, 2); -ADDBYPASS(kLtAluShift, kLtClinit, 2); -ADDBYPASS(kLtAluExtr, kLtClinit, 2); -ADDBYPASS(kLtMul, kLtClinit, 3); -ADDBYPASS(kLtLoad1, kLtClinit, 3); -ADDBYPASS(kLtAlu, kLtClinit, 13); -ADDSTOREBYPASS(kLtClinit, kLtStore1, 11); -ADDSTOREBYPASS(kLtClinit, kLtStore3plus, 11); -ADDBYPASS(kLtClinit, kLtR2f, 11); -ADDBYPASS(kLtClinit, kLtR2fCvt, 13); -ADDBYPASS(kLtShiftReg, kLtAdrpLdr, 1); -ADDBYPASS(kLtAlu, kLtAdrpLdr, 2); -ADDBYPASS(kLtAluShift, kLtAdrpLdr, 2); -ADDBYPASS(kLtAluExtr, kLtAdrpLdr, 2); -ADDBYPASS(kLtMul, kLtAdrpLdr, 3); -ADDBYPASS(kLtLoad1, kLtAdrpLdr, 3); -ADDBYPASS(kLtAdrpLdr, kLtAlu, 5); -ADDSTOREBYPASS(kLtAdrpLdr, kLtStore1, 3); -ADDSTOREBYPASS(kLtAdrpLdr, kLtStore3plus, 3); -ADDBYPASS(kLtAdrpLdr, kLtR2f, 3); -ADDBYPASS(kLtAdrpLdr, kLtR2fCvt, 5); -ADDBYPASS(kLtClinitTail, kLtAlu, 7); -ADDSTOREBYPASS(kLtClinitTail, kLtStore1, 5); -ADDSTOREBYPASS(kLtClinitTail, kLtStore3plus, 5); -ADDBYPASS(kLtClinitTail, kLtR2f, 5); -ADDBYPASS(kLtClinitTail, kLtR2fCvt, 7); diff --git a/src/mapleall/maple_be/include/ad/target/mplad_latency_type.def b/src/mapleall/maple_be/include/ad/target/mplad_latency_type.def deleted file mode 100644 index baf1b2d36c6cd5eeb12123d282fef72764c5e373..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_latency_type.def +++ /dev/null @@ -1,43 +0,0 @@ -/* cortex_a55 latency type definition definition : */ - kLtUndef, - kLtShift, - kLtShiftReg, - kLtAlu, - kLtAluShift, - kLtAluShiftReg, - kLtAluExtr, - kLtMul, - kLtDiv, - kLtLoad1, - kLtStore1, - kLtLoad2, - kLtStore2, - kLtLoad3plus, - kLtStore3plus, - kLtBranch, - kLtFpalu, - kLtFconst, - kLtFpmul, - kLtFpmac, - kLtR2f, - kLtF2r, - kLtR2fCvt, - kLtF2rCvt, - kLtFFlags, - kLtFLoad64, - kLtFLoadMany, - kLtFStore64, - kLtFStoreMany, - kLtAdvsimdAlu, - kLtAdvsimdAluQ, - kLtAdvsimdMul, - kLtAdvsimdMulQ, - kLtAdvsimdDivS, - kLtAdvsimdDivD, - kLtAdvsimdDivSQ, - kLtAdvsimdDivdQ, - kLtCryptoAese, - kLtCryptoAesmc, - kLtClinit, - kLtAdrpLdr, - kLtClinitTail, diff --git a/src/mapleall/maple_be/include/ad/target/mplad_reservation_define.def b/src/mapleall/maple_be/include/ad/target/mplad_reservation_define.def deleted file mode 100644 index a327e79c13bfa9545ac9139e2467efa2ffbc347f..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_reservation_define.def +++ /dev/null @@ -1,360 +0,0 @@ -/* cortex_a55 reservations definition : */ -Reservation *resvInstkLtUndef = new Reservation(kLtUndef, 0, 0); -if(resvInstkLtUndef == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtUndef failed." << std::endl; -} -ASSERT(resvInstkLtUndef, "Reservation allocation for kLtUndef failed."); - -Reservation *resvInstkLtShift = new Reservation(kLtShift, 2, 1, - GetUnitByUnitId(kUnitIdSlotS)); -if(resvInstkLtShift == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtShift failed." << std::endl; -} -ASSERT(resvInstkLtShift, "Reservation allocation for kLtShift failed."); - -Reservation *resvInstkLtShiftReg = new Reservation(kLtShiftReg, 2, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdHazard)); -if(resvInstkLtShiftReg == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtShiftReg failed." << std::endl; -} -ASSERT(resvInstkLtShiftReg, "Reservation allocation for kLtShiftReg failed."); - -Reservation *resvInstkLtAlu = new Reservation(kLtAlu, 3, 1, - GetUnitByUnitId(kUnitIdSlotS)); -if(resvInstkLtAlu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAlu failed." << std::endl; -} -ASSERT(resvInstkLtAlu, "Reservation allocation for kLtAlu failed."); - -Reservation *resvInstkLtAluShift = new Reservation(kLtAluShift, 3, 1, - GetUnitByUnitId(kUnitIdSlotS)); -if(resvInstkLtAluShift == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAluShift failed." << std::endl; -} -ASSERT(resvInstkLtAluShift, "Reservation allocation for kLtAluShift failed."); - -Reservation *resvInstkLtAluShiftReg = new Reservation(kLtAluShiftReg, 3, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdHazard)); -if(resvInstkLtAluShiftReg == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAluShiftReg failed." << std::endl; -} -ASSERT(resvInstkLtAluShiftReg, "Reservation allocation for kLtAluShiftReg failed."); - -Reservation *resvInstkLtAluExtr = new Reservation(kLtAluExtr, 3, 1, - GetUnitByUnitId(kUnitIdSlot1)); -if(resvInstkLtAluExtr == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAluExtr failed." << std::endl; -} -ASSERT(resvInstkLtAluExtr, "Reservation allocation for kLtAluExtr failed."); - -Reservation *resvInstkLtMul = new Reservation(kLtMul, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdMul)); -if(resvInstkLtMul == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtMul failed." << std::endl; -} -ASSERT(resvInstkLtMul, "Reservation allocation for kLtMul failed."); - -Reservation *resvInstkLtDiv = new Reservation(kLtDiv, 4, 3, - GetUnitByUnitId(kUnitIdSlot0), - GetUnitByUnitId(kUnitIdDiv), - GetUnitByUnitId(kUnitIdDiv)); -if(resvInstkLtDiv == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtDiv failed." << std::endl; -} -ASSERT(resvInstkLtDiv, "Reservation allocation for kLtDiv failed."); - -Reservation *resvInstkLtLoad1 = new Reservation(kLtLoad1, 4, 2, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtLoad1 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtLoad1 failed." << std::endl; -} -ASSERT(resvInstkLtLoad1, "Reservation allocation for kLtLoad1 failed."); - -Reservation *resvInstkLtStore1 = new Reservation(kLtStore1, 2, 2, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdStAgu)); -if(resvInstkLtStore1 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtStore1 failed." << std::endl; -} -ASSERT(resvInstkLtStore1, "Reservation allocation for kLtStore1 failed."); - -Reservation *resvInstkLtLoad2 = new Reservation(kLtLoad2, 4, 3, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtLoad2 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtLoad2 failed." << std::endl; -} -ASSERT(resvInstkLtLoad2, "Reservation allocation for kLtLoad2 failed."); - -Reservation *resvInstkLtStore2 = new Reservation(kLtStore2, 2, 2, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdStAgu)); -if(resvInstkLtStore2 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtStore2 failed." << std::endl; -} -ASSERT(resvInstkLtStore2, "Reservation allocation for kLtStore2 failed."); - -Reservation *resvInstkLtLoad3plus = new Reservation(kLtLoad3plus, 6, 3, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtLoad3plus == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtLoad3plus failed." << std::endl; -} -ASSERT(resvInstkLtLoad3plus, "Reservation allocation for kLtLoad3plus failed."); - -Reservation *resvInstkLtStore3plus = new Reservation(kLtStore3plus, 2, 3, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0StAgu), - GetUnitByUnitId(kUnitIdStAgu)); -if(resvInstkLtStore3plus == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtStore3plus failed." << std::endl; -} -ASSERT(resvInstkLtStore3plus, "Reservation allocation for kLtStore3plus failed."); - -Reservation *resvInstkLtBranch = new Reservation(kLtBranch, 0, 1, - GetUnitByUnitId(kUnitIdSlotSBranch)); -if(resvInstkLtBranch == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtBranch failed." << std::endl; -} -ASSERT(resvInstkLtBranch, "Reservation allocation for kLtBranch failed."); - -Reservation *resvInstkLtFpalu = new Reservation(kLtFpalu, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtFpalu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFpalu failed." << std::endl; -} -ASSERT(resvInstkLtFpalu, "Reservation allocation for kLtFpalu failed."); - -Reservation *resvInstkLtFconst = new Reservation(kLtFconst, 2, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtFconst == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFconst failed." << std::endl; -} -ASSERT(resvInstkLtFconst, "Reservation allocation for kLtFconst failed."); - -Reservation *resvInstkLtFpmul = new Reservation(kLtFpmul, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpMulS)); -if(resvInstkLtFpmul == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFpmul failed." << std::endl; -} -ASSERT(resvInstkLtFpmul, "Reservation allocation for kLtFpmul failed."); - -Reservation *resvInstkLtFpmac = new Reservation(kLtFpmac, 8, 6, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpMulS), - nullptr, - nullptr, - nullptr, - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtFpmac == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFpmac failed." << std::endl; -} -ASSERT(resvInstkLtFpmac, "Reservation allocation for kLtFpmac failed."); - -Reservation *resvInstkLtR2f = new Reservation(kLtR2f, 2, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtR2f == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtR2f failed." << std::endl; -} -ASSERT(resvInstkLtR2f, "Reservation allocation for kLtR2f failed."); - -Reservation *resvInstkLtF2r = new Reservation(kLtF2r, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtF2r == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtF2r failed." << std::endl; -} -ASSERT(resvInstkLtF2r, "Reservation allocation for kLtF2r failed."); - -Reservation *resvInstkLtR2fCvt = new Reservation(kLtR2fCvt, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtR2fCvt == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtR2fCvt failed." << std::endl; -} -ASSERT(resvInstkLtR2fCvt, "Reservation allocation for kLtR2fCvt failed."); - -Reservation *resvInstkLtF2rCvt = new Reservation(kLtF2rCvt, 5, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtF2rCvt == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtF2rCvt failed." << std::endl; -} -ASSERT(resvInstkLtF2rCvt, "Reservation allocation for kLtF2rCvt failed."); - -Reservation *resvInstkLtFFlags = new Reservation(kLtFFlags, 5, 1, - GetUnitByUnitId(kUnitIdSlotS)); -if(resvInstkLtFFlags == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFFlags failed." << std::endl; -} -ASSERT(resvInstkLtFFlags, "Reservation allocation for kLtFFlags failed."); - -Reservation *resvInstkLtFLoad64 = new Reservation(kLtFLoad64, 3, 2, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtFLoad64 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFLoad64 failed." << std::endl; -} -ASSERT(resvInstkLtFLoad64, "Reservation allocation for kLtFLoad64 failed."); - -Reservation *resvInstkLtFLoadMany = new Reservation(kLtFLoadMany, 4, 3, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtFLoadMany == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFLoadMany failed." << std::endl; -} -ASSERT(resvInstkLtFLoadMany, "Reservation allocation for kLtFLoadMany failed."); - -Reservation *resvInstkLtFStore64 = new Reservation(kLtFStore64, 0, 2, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdStAgu)); -if(resvInstkLtFStore64 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFStore64 failed." << std::endl; -} -ASSERT(resvInstkLtFStore64, "Reservation allocation for kLtFStore64 failed."); - -Reservation *resvInstkLtFStoreMany = new Reservation(kLtFStoreMany, 0, 3, - GetUnitByUnitId(kUnitIdSlotSAgen), - GetUnitByUnitId(kUnitIdSlot0StAgu), - GetUnitByUnitId(kUnitIdStAgu)); -if(resvInstkLtFStoreMany == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtFStoreMany failed." << std::endl; -} -ASSERT(resvInstkLtFStoreMany, "Reservation allocation for kLtFStoreMany failed."); - -Reservation *resvInstkLtAdvsimdAlu = new Reservation(kLtAdvsimdAlu, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpAluS)); -if(resvInstkLtAdvsimdAlu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdAlu failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdAlu, "Reservation allocation for kLtAdvsimdAlu failed."); - -Reservation *resvInstkLtAdvsimdAluQ = new Reservation(kLtAdvsimdAluQ, 4, 2, - GetUnitByUnitId(kUnitIdSlot0), - GetUnitByUnitId(kUnitIdFpAluD)); -if(resvInstkLtAdvsimdAluQ == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdAluQ failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdAluQ, "Reservation allocation for kLtAdvsimdAluQ failed."); - -Reservation *resvInstkLtAdvsimdMul = new Reservation(kLtAdvsimdMul, 4, 2, - GetUnitByUnitId(kUnitIdSlotS), - GetUnitByUnitId(kUnitIdFpMulS)); -if(resvInstkLtAdvsimdMul == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdMul failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdMul, "Reservation allocation for kLtAdvsimdMul failed."); - -Reservation *resvInstkLtAdvsimdMulQ = new Reservation(kLtAdvsimdMulQ, 4, 2, - GetUnitByUnitId(kUnitIdSlot0), - GetUnitByUnitId(kUnitIdFpMulD)); -if(resvInstkLtAdvsimdMulQ == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdMulQ failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdMulQ, "Reservation allocation for kLtAdvsimdMulQ failed."); - -Reservation *resvInstkLtAdvsimdDivS = new Reservation(kLtAdvsimdDivS, 14, 3, - GetUnitByUnitId(kUnitIdSlot0), - GetUnitByUnitId(kUnitIdFpMulS), - GetUnitByUnitId(kUnitIdFpDivS)); -if(resvInstkLtAdvsimdDivS == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdDivS failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdDivS, "Reservation allocation for kLtAdvsimdDivS failed."); - -Reservation *resvInstkLtAdvsimdDivD = new Reservation(kLtAdvsimdDivD, 29, 3, - GetUnitByUnitId(kUnitIdSlot0), - GetUnitByUnitId(kUnitIdFpMulS), - GetUnitByUnitId(kUnitIdFpDivS)); -if(resvInstkLtAdvsimdDivD == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdDivD failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdDivD, "Reservation allocation for kLtAdvsimdDivD failed."); - -Reservation *resvInstkLtAdvsimdDivSQ = new Reservation(kLtAdvsimdDivSQ, 14, 3, - GetUnitByUnitId(kUnitIdSlotD), - GetUnitByUnitId(kUnitIdFpMulD), - GetUnitByUnitId(kUnitIdFpDivD)); -if(resvInstkLtAdvsimdDivSQ == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdDivSQ failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdDivSQ, "Reservation allocation for kLtAdvsimdDivSQ failed."); - -Reservation *resvInstkLtAdvsimdDivdQ = new Reservation(kLtAdvsimdDivdQ, 29, 3, - GetUnitByUnitId(kUnitIdSlotD), - GetUnitByUnitId(kUnitIdFpMulD), - GetUnitByUnitId(kUnitIdFpDivD)); -if(resvInstkLtAdvsimdDivdQ == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdvsimdDivdQ failed." << std::endl; -} -ASSERT(resvInstkLtAdvsimdDivdQ, "Reservation allocation for kLtAdvsimdDivdQ failed."); - -Reservation *resvInstkLtCryptoAese = new Reservation(kLtCryptoAese, 3, 1, - GetUnitByUnitId(kUnitIdSlot0)); -if(resvInstkLtCryptoAese == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtCryptoAese failed." << std::endl; -} -ASSERT(resvInstkLtCryptoAese, "Reservation allocation for kLtCryptoAese failed."); - -Reservation *resvInstkLtCryptoAesmc = new Reservation(kLtCryptoAesmc, 3, 1, - GetUnitByUnitId(kUnitIdSlotS)); -if(resvInstkLtCryptoAesmc == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtCryptoAesmc failed." << std::endl; -} -ASSERT(resvInstkLtCryptoAesmc, "Reservation allocation for kLtCryptoAesmc failed."); - -Reservation *resvInstkLtClinit = new Reservation(kLtClinit, 14, 13, - GetUnitByUnitId(kUnitIdSlotS), - nullptr, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu), - nullptr, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu), - nullptr, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtClinit == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtClinit failed." << std::endl; -} -ASSERT(resvInstkLtClinit, "Reservation allocation for kLtClinit failed."); - -Reservation *resvInstkLtAdrpLdr = new Reservation(kLtAdrpLdr, 6, 5, - GetUnitByUnitId(kUnitIdSlotS), - nullptr, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtAdrpLdr == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtAdrpLdr failed." << std::endl; -} -ASSERT(resvInstkLtAdrpLdr, "Reservation allocation for kLtAdrpLdr failed."); - -Reservation *resvInstkLtClinitTail = new Reservation(kLtClinitTail, 8, 7, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu), - nullptr, - GetUnitByUnitId(kUnitIdSlotDAgen), - GetUnitByUnitId(kUnitIdSlot0LdAgu), - GetUnitByUnitId(kUnitIdLdAgu)); -if(resvInstkLtClinitTail == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Reservation allocation for kLtClinitTail failed." << std::endl; -} -ASSERT(resvInstkLtClinitTail, "Reservation allocation for kLtClinitTail failed."); - diff --git a/src/mapleall/maple_be/include/ad/target/mplad_unit_define.def b/src/mapleall/maple_be/include/ad/target/mplad_unit_define.def deleted file mode 100644 index 62233a365dbda980ad1d6e6ee2377a58931e61b3..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_unit_define.def +++ /dev/null @@ -1,204 +0,0 @@ -/* cortex_a55 function units definition : */ - -const unsigned int kunitNum = 2; -Unit *instancekUnitIdSlot0 = new Unit(kUnitIdSlot0); -if(instancekUnitIdSlot0 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlot0 failed." << std::endl; -} -ASSERT(instancekUnitIdSlot0, "Unit allocation for kUnitIdSlot0 failed."); - -Unit *instancekUnitIdSlot1 = new Unit(kUnitIdSlot1); -if(instancekUnitIdSlot1 == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlot1 failed." << std::endl; -} -ASSERT(instancekUnitIdSlot1, "Unit allocation for kUnitIdSlot1 failed."); - -Unit *instancekUnitIdAgen = new Unit(kUnitIdAgen); -if(instancekUnitIdAgen == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdAgen failed." << std::endl; -} -ASSERT(instancekUnitIdAgen, "Unit allocation for kUnitIdAgen failed."); - -Unit *instancekUnitIdHazard = new Unit(kUnitIdHazard); -if(instancekUnitIdHazard == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdHazard failed." << std::endl; -} -ASSERT(instancekUnitIdHazard, "Unit allocation for kUnitIdHazard failed."); - -Unit *instancekUnitIdCrypto = new Unit(kUnitIdCrypto); -if(instancekUnitIdCrypto == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdCrypto failed." << std::endl; -} -ASSERT(instancekUnitIdCrypto, "Unit allocation for kUnitIdCrypto failed."); - -Unit *instancekUnitIdMul = new Unit(kUnitIdMul); -if(instancekUnitIdMul == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdMul failed." << std::endl; -} -ASSERT(instancekUnitIdMul, "Unit allocation for kUnitIdMul failed."); - -Unit *instancekUnitIdDiv = new Unit(kUnitIdDiv); -if(instancekUnitIdDiv == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdDiv failed." << std::endl; -} -ASSERT(instancekUnitIdDiv, "Unit allocation for kUnitIdDiv failed."); - -Unit *instancekUnitIdBranch = new Unit(kUnitIdBranch); -if(instancekUnitIdBranch == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdBranch failed." << std::endl; -} -ASSERT(instancekUnitIdBranch, "Unit allocation for kUnitIdBranch failed."); - -Unit *instancekUnitIdStAgu = new Unit(kUnitIdStAgu); -if(instancekUnitIdStAgu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdStAgu failed." << std::endl; -} -ASSERT(instancekUnitIdStAgu, "Unit allocation for kUnitIdStAgu failed."); - -Unit *instancekUnitIdLdAgu = new Unit(kUnitIdLdAgu); -if(instancekUnitIdLdAgu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdLdAgu failed." << std::endl; -} -ASSERT(instancekUnitIdLdAgu, "Unit allocation for kUnitIdLdAgu failed."); - -Unit *instancekUnitIdFpAluLo = new Unit(kUnitIdFpAluLo); -if(instancekUnitIdFpAluLo == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpAluLo failed." << std::endl; -} -ASSERT(instancekUnitIdFpAluLo, "Unit allocation for kUnitIdFpAluLo failed."); - -Unit *instancekUnitIdFpAluHi = new Unit(kUnitIdFpAluHi); -if(instancekUnitIdFpAluHi == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpAluHi failed." << std::endl; -} -ASSERT(instancekUnitIdFpAluHi, "Unit allocation for kUnitIdFpAluHi failed."); - -Unit *instancekUnitIdFpMulLo = new Unit(kUnitIdFpMulLo); -if(instancekUnitIdFpMulLo == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpMulLo failed." << std::endl; -} -ASSERT(instancekUnitIdFpMulLo, "Unit allocation for kUnitIdFpMulLo failed."); - -Unit *instancekUnitIdFpMulHi = new Unit(kUnitIdFpMulHi); -if(instancekUnitIdFpMulHi == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpMulHi failed." << std::endl; -} -ASSERT(instancekUnitIdFpMulHi, "Unit allocation for kUnitIdFpMulHi failed."); - -Unit *instancekUnitIdFpDivLo = new Unit(kUnitIdFpDivLo); -if(instancekUnitIdFpDivLo == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpDivLo failed." << std::endl; -} -ASSERT(instancekUnitIdFpDivLo, "Unit allocation for kUnitIdFpDivLo failed."); - -Unit *instancekUnitIdFpDivHi = new Unit(kUnitIdFpDivHi); -if(instancekUnitIdFpDivHi == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpDivHi failed." << std::endl; -} -ASSERT(instancekUnitIdFpDivHi, "Unit allocation for kUnitIdFpDivHi failed."); - -Unit *instancekUnitIdSlotS = new Unit(kUnitTypeOr, kUnitIdSlotS, kunitNum, - instancekUnitIdSlot0, instancekUnitIdSlot1); -if(instancekUnitIdSlotS == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotS failed." << std::endl; -} -ASSERT(instancekUnitIdSlotS, "Unit allocation for kUnitIdSlotS failed."); - -Unit *instancekUnitIdFpAluS = new Unit(kUnitTypeOr, kUnitIdFpAluS, kunitNum, - instancekUnitIdFpAluLo, instancekUnitIdFpAluHi); -if(instancekUnitIdFpAluS == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpAluS failed." << std::endl; -} -ASSERT(instancekUnitIdFpAluS, "Unit allocation for kUnitIdFpAluS failed."); - -Unit *instancekUnitIdFpMulS = new Unit(kUnitTypeOr, kUnitIdFpMulS, kunitNum, - instancekUnitIdFpMulLo, instancekUnitIdFpMulHi); -if(instancekUnitIdFpMulS == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpMulS failed." << std::endl; -} -ASSERT(instancekUnitIdFpMulS, "Unit allocation for kUnitIdFpMulS failed."); - -Unit *instancekUnitIdFpDivS = new Unit(kUnitTypeOr, kUnitIdFpDivS, kunitNum, - instancekUnitIdFpDivLo, instancekUnitIdFpDivHi); -if(instancekUnitIdFpDivS == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpDivS failed." << std::endl; -} -ASSERT(instancekUnitIdFpDivS, "Unit allocation for kUnitIdFpDivS failed."); - -Unit *instancekUnitIdSlotD = new Unit(kUnitTypeAnd, kUnitIdSlotD, kunitNum, - instancekUnitIdSlot0, instancekUnitIdSlot1); -if(instancekUnitIdSlotD == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotD failed." << std::endl; -} -ASSERT(instancekUnitIdSlotD, "Unit allocation for kUnitIdSlotD failed."); - -Unit *instancekUnitIdFpAluD = new Unit(kUnitTypeAnd, kUnitIdFpAluD, kunitNum, - instancekUnitIdFpAluLo, instancekUnitIdFpAluHi); -if(instancekUnitIdFpAluD == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpAluD failed." << std::endl; -} -ASSERT(instancekUnitIdFpAluD, "Unit allocation for kUnitIdFpAluD failed."); - -Unit *instancekUnitIdFpMulD = new Unit(kUnitTypeAnd, kUnitIdFpMulD, kunitNum, - instancekUnitIdFpMulLo, instancekUnitIdFpMulHi); -if(instancekUnitIdFpMulD == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpMulD failed." << std::endl; -} -ASSERT(instancekUnitIdFpMulD, "Unit allocation for kUnitIdFpMulD failed."); - -Unit *instancekUnitIdFpDivD = new Unit(kUnitTypeAnd, kUnitIdFpDivD, kunitNum, - instancekUnitIdFpDivLo, instancekUnitIdFpDivHi); -if(instancekUnitIdFpDivD == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdFpDivD failed." << std::endl; -} -ASSERT(instancekUnitIdFpDivD, "Unit allocation for kUnitIdFpDivD failed."); - -Unit *instancekUnitIdSlotSHazard = new Unit(kUnitTypeAnd, kUnitIdSlotSHazard, kunitNum, - instancekUnitIdSlotS, instancekUnitIdHazard); -if(instancekUnitIdSlotSHazard == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotSHazard failed." << std::endl; -} -ASSERT(instancekUnitIdSlotSHazard, "Unit allocation for kUnitIdSlotSHazard failed."); - -Unit *instancekUnitIdSlotSMul = new Unit(kUnitTypeAnd, kUnitIdSlotSMul, kunitNum, - instancekUnitIdSlotS, instancekUnitIdMul); -if(instancekUnitIdSlotSMul == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotSMul failed." << std::endl; -} -ASSERT(instancekUnitIdSlotSMul, "Unit allocation for kUnitIdSlotSMul failed."); - -Unit *instancekUnitIdSlotSBranch = new Unit(kUnitTypeAnd, kUnitIdSlotSBranch, kunitNum, - instancekUnitIdSlotS, instancekUnitIdBranch); -if(instancekUnitIdSlotSBranch == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotSBranch failed." << std::endl; -} -ASSERT(instancekUnitIdSlotSBranch, "Unit allocation for kUnitIdSlotSBranch failed."); - -Unit *instancekUnitIdSlotSAgen = new Unit(kUnitTypeAnd, kUnitIdSlotSAgen, kunitNum, - instancekUnitIdSlotS, instancekUnitIdAgen); -if(instancekUnitIdSlotSAgen == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotSAgen failed." << std::endl; -} -ASSERT(instancekUnitIdSlotSAgen, "Unit allocation for kUnitIdSlotSAgen failed."); - -Unit *instancekUnitIdSlotDAgen = new Unit(kUnitTypeAnd, kUnitIdSlotDAgen, kunitNum, - instancekUnitIdSlot0, instancekUnitIdSlot1, instancekUnitIdAgen); -if(instancekUnitIdSlotDAgen == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlotDAgen failed." << std::endl; -} -ASSERT(instancekUnitIdSlotDAgen, "Unit allocation for kUnitIdSlotDAgen failed."); - -Unit *instancekUnitIdSlot0LdAgu = new Unit(kUnitTypeAnd, kUnitIdSlot0LdAgu, kunitNum, - instancekUnitIdSlot0, instancekUnitIdLdAgu); -if(instancekUnitIdSlot0LdAgu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlot0LdAgu failed." << std::endl; -} -ASSERT(instancekUnitIdSlot0LdAgu, "Unit allocation for kUnitIdSlot0LdAgu failed."); - -Unit *instancekUnitIdSlot0StAgu = new Unit(kUnitTypeAnd, kUnitIdSlot0StAgu, kunitNum, - instancekUnitIdSlot0, instancekUnitIdStAgu); -if(instancekUnitIdSlot0StAgu == nullptr) { - maple::LogInfo::MapleLogger(maple::kLlErr) << "Unit allocation for kUnitIdSlot0StAgu failed." << std::endl; -} -ASSERT(instancekUnitIdSlot0StAgu, "Unit allocation for kUnitIdSlot0StAgu failed."); - diff --git a/src/mapleall/maple_be/include/ad/target/mplad_unit_id.def b/src/mapleall/maple_be/include/ad/target/mplad_unit_id.def deleted file mode 100644 index 66396da32c9e833def7346109afb4329b51e1bc6..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_unit_id.def +++ /dev/null @@ -1,33 +0,0 @@ -/* cortex_a55 function unit ID definition : */ - kUnitIdSlot0, - kUnitIdSlot1, - kUnitIdAgen, - kUnitIdHazard, - kUnitIdCrypto, - kUnitIdMul, - kUnitIdDiv, - kUnitIdBranch, - kUnitIdStAgu, - kUnitIdLdAgu, - kUnitIdFpAluLo, - kUnitIdFpAluHi, - kUnitIdFpMulLo, - kUnitIdFpMulHi, - kUnitIdFpDivLo, - kUnitIdFpDivHi, - kUnitIdSlotS, - kUnitIdFpAluS, - kUnitIdFpMulS, - kUnitIdFpDivS, - kUnitIdSlotD, - kUnitIdFpAluD, - kUnitIdFpMulD, - kUnitIdFpDivD, - kUnitIdSlotSHazard, - kUnitIdSlotSMul, - kUnitIdSlotSBranch, - kUnitIdSlotSAgen, - kUnitIdSlotDAgen, - kUnitIdSlot0LdAgu, - kUnitIdSlot0StAgu, - nothing, diff --git a/src/mapleall/maple_be/include/ad/target/mplad_unit_name.def b/src/mapleall/maple_be/include/ad/target/mplad_unit_name.def deleted file mode 100644 index 2586d10668c3462550cc3daf5277752ba454ac38..0000000000000000000000000000000000000000 --- a/src/mapleall/maple_be/include/ad/target/mplad_unit_name.def +++ /dev/null @@ -1,32 +0,0 @@ -/* cortex_a55 function unit name definition : */ -"Slot0", -"Slot1", -"Agen", -"Hazard", -"Crypto", -"Mul", -"Div", -"Branch", -"StAgu", -"LdAgu", -"FpAluLo", -"FpAluHi", -"FpMulLo", -"FpMulHi", -"FpDivLo", -"FpDivHi", -"SlotS", -"FpAluS", -"FpMulS", -"FpDivS", -"SlotD", -"FpAluD", -"FpMulD", -"FpDivD", -"SlotSHazard", -"SlotSMul", -"SlotSBranch", -"SlotSAgen", -"SlotDAgen", -"Slot0LdAgu", -"Slot0StAgu", diff --git a/src/mapleall/maple_be/include/be/lower.h b/src/mapleall/maple_be/include/be/lower.h index 6b3a54edad67726d120836ec42a1dc853c05392c..07393dde48987b9236958216d48ff7e4177deb52 100644 --- a/src/mapleall/maple_be/include/be/lower.h +++ b/src/mapleall/maple_be/include/be/lower.h @@ -156,7 +156,7 @@ class CGLowerer { virtual BlockNode *LowerReturn(NaryStmtNode &retNode); void LowerEntry(MIRFunction &func); - StmtNode *LowerCall(CallNode &call, StmtNode *&stmt, BlockNode &block, MIRType *reTty = nullptr); + StmtNode *LowerCall(CallNode &call, StmtNode *&stmt, BlockNode &block, MIRType *retTy = nullptr); void SplitCallArg(CallNode &callNode, BaseNode *newOpnd, size_t i, BlockNode &newBlk); void CleanupBranches(MIRFunction &func) const; diff --git a/src/mapleall/maple_be/include/cg/aarch64/aarch64_cgfunc.h b/src/mapleall/maple_be/include/cg/aarch64/aarch64_cgfunc.h index 7a1b03be6db9d79811f926c8f6b073b0ce35117f..84aca10943e6b83d3c61622976c98e65ddae1809 100644 --- a/src/mapleall/maple_be/include/cg/aarch64/aarch64_cgfunc.h +++ b/src/mapleall/maple_be/include/cg/aarch64/aarch64_cgfunc.h @@ -562,8 +562,8 @@ class AArch64CGFunc : public CGFunc { void CreateCallStructParamPassByStack(int32 symSize, MIRSymbol *sym, RegOperand *addrOpnd, int32 baseOffset); void CreateCallStructParamPassByReg(AArch64reg reg, MemOperand &memOpnd, AArch64ListOperand &srcOpnds); - void CreateCallStructParamMemcpy(MIRSymbol *sym, RegOperand *addropnd, uint32 structSize, int32 copyOffset, - int32 fromOffset); + void CreateCallStructParamMemcpy(const MIRSymbol *sym, RegOperand *addropnd, + uint32 structSize, int32 copyOffset, int32 fromOffset); AArch64RegOperand *CreateCallStructParamCopyToStack(uint32 numMemOp, MIRSymbol *sym, RegOperand *addropnd, int32 copyOffset, AArch64reg reg); void SelectParmListDreadSmallAggregate(MIRSymbol &sym, MIRType &structType, AArch64ListOperand &srcOpnds, diff --git a/src/mapleall/maple_be/include/cg/aarch64/aarch64_insn.h b/src/mapleall/maple_be/include/cg/aarch64/aarch64_insn.h index 8f85878bdec3b911167f3449413b6186a359fca1..9f0634f55143f5b79f75f783bd195f2bcba99709 100644 --- a/src/mapleall/maple_be/include/cg/aarch64/aarch64_insn.h +++ b/src/mapleall/maple_be/include/cg/aarch64/aarch64_insn.h @@ -163,7 +163,7 @@ class AArch64Insn : public Insn { void EmitAdrpLdr(const CG&, Emitter&) const; void EmitLazyBindingRoutine(Emitter&) const; void EmitClinitTail(Emitter&) const; - void EmitAdrpLabel(Emitter &) const; + void EmitAdrpLabel(Emitter&) const; void EmitLazyLoad(Emitter&) const; void EmitLazyLoadStatic(Emitter&) const; void EmitArrayClassCacheLoad(Emitter&) const; diff --git a/src/mapleall/maple_be/src/be/lower.cpp b/src/mapleall/maple_be/src/be/lower.cpp index df2fc77381f17f6197047f28e9f61c34fbe8579c..b9db6393d4243a58481176d4715171c0f3180f23 100644 --- a/src/mapleall/maple_be/src/be/lower.cpp +++ b/src/mapleall/maple_be/src/be/lower.cpp @@ -818,14 +818,14 @@ BlockNode *CGLowerer::GenBlockNode(StmtNode &newCall, const CallReturnVector &p2 StmtNode *dStmt = nullptr; MIRType *retType = nullptr; if (p2nRets.size() == 1) { - MIRSymbol *sym; + MIRSymbol *sym = nullptr; StIdx stIdx = p2nRets[0].first; if (stIdx.IsGlobal()) { sym = GlobalTables::GetGsymTable().GetSymbolFromStidx(stIdx.Idx()); } else { sym = GetCurrentFunc()->GetSymbolTabItem(stIdx.Idx()); } - if (sym) { + if (sym != nullptr) { retType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(sym->GetTyIdx()); } RegFieldPair regFieldPair = p2nRets[0].second; @@ -1187,7 +1187,7 @@ StmtNode *CGLowerer::LowerCall(CallNode &callNode, StmtNode *&nextStmt, BlockNod } if (retTy && beCommon.GetTypeSize(retTy->GetTypeIndex().GetIdx()) <= k16ByteSize) { - // return structure fitting in one or two regs. + /* return structure fitting in one or two regs. */ return &callNode; } @@ -1235,6 +1235,7 @@ StmtNode *CGLowerer::LowerCall(CallNode &callNode, StmtNode *&nextStmt, BlockNod addrofNode->SetPrimType(LOWERED_PTR_TYPE); addrofNode->SetStIdx(dsgnSt->GetStIdx()); addrofNode->SetFieldID(0); + if (callNode.op == OP_icall) { auto ond = callNode.GetNopnd().begin(); newNopnd.emplace_back(*ond); @@ -1248,6 +1249,7 @@ StmtNode *CGLowerer::LowerCall(CallNode &callNode, StmtNode *&nextStmt, BlockNod newNopnd.emplace_back(opnd); } } + callNode.SetNOpnd(newNopnd); callNode.SetNumOpnds(static_cast(newNopnd.size())); CHECK_FATAL(nextStmt != nullptr, "nullptr is not expected"); diff --git a/src/mapleall/maple_be/src/cg/aarch64/aarch64_cgfunc.cpp b/src/mapleall/maple_be/src/cg/aarch64/aarch64_cgfunc.cpp index 906b97872a6cc407c18cdc0e83b99371b8f6450b..438542527109d09ef4a4b28334c1e0827d6fe916 100644 --- a/src/mapleall/maple_be/src/cg/aarch64/aarch64_cgfunc.cpp +++ b/src/mapleall/maple_be/src/cg/aarch64/aarch64_cgfunc.cpp @@ -1526,7 +1526,7 @@ PrimType AArch64CGFunc::GetDestTypeFromAggSize(uint32 bitSize) const { } Operand &AArch64CGFunc::SelectAddrofLabel(AddroflabelNode &expr) { - // adrp reg, label-id + /* adrp reg, label-id */ Operand &dst = CreateVirtualRegisterOperand(NewVReg(kRegTyInt, expr.SizeOfInstr())); Operand &immOpnd = CreateImmOperand(expr.GetOffset(), k64BitSize, false); GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_adrp_label, dst, immOpnd)); @@ -4731,7 +4731,7 @@ void AArch64CGFunc::SelectParmListDreadSmallAggregate(MIRSymbol &sym, MIRType &s void AArch64CGFunc::SelectParmListIreadSmallAggregate(const IreadNode &iread, MIRType &structType, AArch64ListOperand &srcOpnds, ParmLocator &parmLocator) { int32 symSize = GetBecommon().GetTypeSize(structType.GetTypeIndex().GetIdx()); - RegOperand *addrOpnd0 = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); + RegOperand *addrOpnd0 = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); RegOperand *addrOpnd1 = &LoadIntoRegister(*addrOpnd0, iread.Opnd(0)->GetPrimType()); PLocInfo ploc; parmLocator.LocateNextParm(structType, ploc); @@ -4741,8 +4741,8 @@ void AArch64CGFunc::SelectParmListIreadSmallAggregate(const IreadNode &iread, MI } else { /* pass by param regs. */ AArch64OfstOperand *offOpnd0 = &GetOrCreateOfstOpnd(0, k32BitSize); - MemOperand *mopnd; - mopnd = &GetOrCreateMemOpnd(AArch64MemOperand::kAddrModeBOi, k64BitSize, addrOpnd1, nullptr, offOpnd0, nullptr); + MemOperand *mopnd = + &GetOrCreateMemOpnd(AArch64MemOperand::kAddrModeBOi, k64BitSize, addrOpnd1, nullptr, offOpnd0, nullptr); CreateCallStructParamPassByReg(ploc.reg0, *mopnd, srcOpnds); if (ploc.reg1) { AArch64OfstOperand *offOpnd1 = &GetOrCreateOfstOpnd(kSizeOfPtr, k32BitSize); @@ -4787,20 +4787,21 @@ void AArch64CGFunc::SelectParmListIreadLargeAggregate(const IreadNode &iread, MI AArch64ListOperand &srcOpnds, ParmLocator &parmLocator, int32 &structCopyOffset) { int32 symSize = GetBecommon().GetTypeSize(structType.GetTypeIndex().GetIdx()); - RegOperand *addrOpnd0 = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); + RegOperand *addrOpnd0 = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); RegOperand *addrOpnd1 = &LoadIntoRegister(*addrOpnd0, iread.Opnd(0)->GetPrimType()); PLocInfo ploc; parmLocator.LocateNextParm(structType, ploc); uint32 numMemOp = static_cast(RoundUp(symSize, kSizeOfPtr) / kSizeOfPtr); /* round up */ - AArch64RegOperand *parmOpnd; - parmOpnd = CreateCallStructParamCopyToStack(numMemOp, nullptr, addrOpnd1, structCopyOffset, ploc.reg0); + AArch64RegOperand *parmOpnd = + CreateCallStructParamCopyToStack(numMemOp, nullptr, addrOpnd1, structCopyOffset, ploc.reg0); structCopyOffset += (numMemOp * kSizeOfPtr); srcOpnds.PushOpnd(*parmOpnd); } void AArch64CGFunc::CreateCallStructParamPassByStack(int32 symSize, MIRSymbol *sym, RegOperand *addrOpnd, int32 baseOffset) { - MemOperand *ldMopnd, *stMopnd; + MemOperand *ldMopnd = nullptr; + MemOperand *stMopnd = nullptr; int numRegNeeded = (symSize <= k8ByteSize) ? kOneRegister : kTwoRegister; for (int j = 0; j < numRegNeeded; j++) { if (sym) { @@ -4822,61 +4823,63 @@ void AArch64CGFunc::CreateCallStructParamPassByReg(AArch64reg reg, MemOperand &m srcOpnds.PushOpnd(parmOpnd); } -void AArch64CGFunc::CreateCallStructParamMemcpy(MIRSymbol *sym, RegOperand *addropnd, uint32 structSize, - int32 copyOffset, int32 fromOffset) { - std::vector opndVec; +void AArch64CGFunc::CreateCallStructParamMemcpy(const MIRSymbol *sym, RegOperand *addropnd, + uint32 structSize, int32 copyOffset, int32 fromOffset) { + std::vector opndVec; - RegOperand *vreg1 = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, 8)); - opndVec.push_back(vreg1); // result + RegOperand *vreg1 = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8BitSize)); + opndVec.push_back(vreg1); /* result */ - RegOperand *parmOpnd = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, 8)); + RegOperand *parmOpnd = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8BitSize)); RegOperand *spReg = &GetOrCreatePhysicalRegisterOperand(RSP, k64BitSize, kRegTyInt); - AArch64ImmOperand *offsetOpnd = &CreateImmOperand(copyOffset, k64BitSize, false); - SelectAdd(*parmOpnd, *spReg, *offsetOpnd, PTY_a64); - opndVec.push_back(parmOpnd); // param 0 + AArch64ImmOperand *offsetOpnd0 = &CreateImmOperand(copyOffset, k64BitSize, false); + SelectAdd(*parmOpnd, *spReg, *offsetOpnd0, PTY_a64); + opndVec.push_back(parmOpnd); /* param 0 */ - if (sym) { + if (sym != nullptr) { if (sym->GetStorageClass() == kScGlobal || sym->GetStorageClass() == kScExtern) { StImmOperand &stopnd = CreateStImmOperand(*sym, 0, 0); AArch64RegOperand &staddropnd = static_cast(CreateRegisterOperandOfType(PTY_u64)); SelectAddrof(staddropnd, stopnd); - opndVec.push_back(&staddropnd); // param 1 + opndVec.push_back(&staddropnd); /* param 1 */ } else if (sym->GetStorageClass() == kScAuto || sym->GetStorageClass() == kScFormal) { RegOperand *parm1Reg = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8ByteSize)); AArch64SymbolAlloc *symloc = static_cast(GetMemlayout()->GetSymAllocInfo(sym->GetStIndex())); AArch64RegOperand *baseOpnd = static_cast(GetBaseReg(*symloc)); int32 stoffset = GetBaseOffset(*symloc); - AArch64ImmOperand *offsetOpnd = &CreateImmOperand(stoffset, k64BitSize, false); - GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xaddrri12, *parm1Reg, *baseOpnd, *offsetOpnd)); + AArch64ImmOperand *offsetOpnd1 = &CreateImmOperand(stoffset, k64BitSize, false); + GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xaddrri12, *parm1Reg, *baseOpnd, *offsetOpnd1)); if (sym->GetStorageClass() == kScFormal) { - MemOperand *ldmopnd = &GetOrCreateMemOpnd(AArch64MemOperand::kAddrModeBOi, k64BitSize, parm1Reg, nullptr, - &GetOrCreateOfstOpnd(0, k32BitSize), static_cast(nullptr)); + MemOperand *ldmopnd = + &GetOrCreateMemOpnd(AArch64MemOperand::kAddrModeBOi, k64BitSize, parm1Reg, nullptr, + &GetOrCreateOfstOpnd(0, k32BitSize), static_cast(nullptr)); RegOperand *tmpreg = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8ByteSize)); RegOperand *vreg2 = &CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8ByteSize)); - GetCurBB()->AppendInsn(GetCG()->BuildInstruction(PickLdInsn(k64BitSize, PTY_a64), *tmpreg, *ldmopnd)); + GetCurBB()->AppendInsn(GetCG()->BuildInstruction(PickLdInsn(k64BitSize, PTY_a64), + *tmpreg, *ldmopnd)); GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xaddrri12, *vreg2, *tmpreg, CreateImmOperand(fromOffset, k64BitSize, false))); parm1Reg = vreg2; } - opndVec.push_back(parm1Reg); // param 1 + opndVec.push_back(parm1Reg); /* param 1 */ } else if (sym->GetStorageClass() == kScPstatic || sym->GetStorageClass() == kScFstatic) { - CHECK_FATAL(sym->GetSKind() != kStConst,"Unsupported sym const for struct param"); + CHECK_FATAL(sym->GetSKind() != kStConst, "Unsupported sym const for struct param"); StImmOperand *stopnd = &CreateStImmOperand(*sym, 0, 0); AArch64RegOperand &staddropnd = static_cast(CreateRegisterOperandOfType(PTY_u64)); GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xadrp, staddropnd, *stopnd)); GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xadrpl12, staddropnd, staddropnd, *stopnd)); - opndVec.push_back(&staddropnd); // param 1 + opndVec.push_back(&staddropnd); /* param 1 */ } else { - CHECK_FATAL(0,"Unsupported sym for struct param"); + CHECK_FATAL(0, "Unsupported sym for struct param"); } } else { - opndVec.push_back(addropnd); // param 1 + opndVec.push_back(addropnd); /* param 1 */ } - RegOperand &vreg3 = CreateVirtualRegisterOperand(NewVReg(kRegTyInt, 8)); + RegOperand &vreg3 = CreateVirtualRegisterOperand(NewVReg(kRegTyInt, k8BitSize)); AArch64ImmOperand &sizeOpnd = CreateImmOperand(structSize, k64BitSize, false); GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xmovri32, vreg3, sizeOpnd)); - opndVec.push_back(&vreg3); // param 2 + opndVec.push_back(&vreg3); /* param 2 */ SelectLibCall("memcpy", opndVec, PTY_a64, PTY_a64); } @@ -4884,9 +4887,10 @@ void AArch64CGFunc::CreateCallStructParamMemcpy(MIRSymbol *sym, RegOperand *addr AArch64RegOperand *AArch64CGFunc::CreateCallStructParamCopyToStack(uint32 numMemOp, MIRSymbol *sym, RegOperand *addrOpd, int32 copyOffset, AArch64reg reg) { /* Create the struct copies. */ - MemOperand *ldMopnd, *stMopnd; + MemOperand *ldMopnd = nullptr; + MemOperand *stMopnd = nullptr; for (int j = 0; j < numMemOp; j++) { - if (sym) { + if (sym != nullptr) { ldMopnd = &GetOrCreateMemOpnd(*sym, (j * static_cast(kSizeOfPtr)), k64BitSize); } else { ldMopnd = &GetOrCreateMemOpnd(AArch64MemOperand::kAddrModeBOi, k64BitSize, addrOpd, nullptr, @@ -4914,7 +4918,7 @@ void AArch64CGFunc::CreateCallStructMemcpyToParamReg(MIRType &structType, int32 PLocInfo ploc; parmLocator.LocateNextParm(structType, ploc); - if (ploc.reg0) { + if (ploc.reg0 != 0) { RegOperand &res = GetOrCreatePhysicalRegisterOperand(ploc.reg0, k64BitSize, kRegTyInt); SelectAdd(res, spReg, offsetOpnd, PTY_a64); srcOpnds.PushOpnd(res); @@ -4962,7 +4966,7 @@ void AArch64CGFunc::SelectParmListForAggregate(BaseNode &argExpr, AArch64ListOpe if (symSize <= k16ByteSize) { SelectParmListIreadSmallAggregate(iread, *ty, srcOpnds, parmLocator); } else if (symSize > kParmMemcpySize) { - RegOperand *ireadOpnd = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); + RegOperand *ireadOpnd = static_cast(HandleExpr(iread, *(iread.Opnd(0)))); RegOperand *addrOpnd = &LoadIntoRegister(*ireadOpnd, iread.Opnd(0)->GetPrimType()); if (rhsOffset > 0) { GetCurBB()->AppendInsn(GetCG()->BuildInstruction(MOP_xaddrri12, *addrOpnd, *addrOpnd, diff --git a/src/mapleall/maple_be/src/cg/aarch64/aarch64_insn.cpp b/src/mapleall/maple_be/src/cg/aarch64/aarch64_insn.cpp index c7fdae35fc7307b5d01174584090d48bdd42f326..c4bf2b166979c142a0d5569352a7567fe492b203 100644 --- a/src/mapleall/maple_be/src/cg/aarch64/aarch64_insn.cpp +++ b/src/mapleall/maple_be/src/cg/aarch64/aarch64_insn.cpp @@ -725,8 +725,9 @@ void AArch64Insn::EmitAdrpLdr(const CG &cg, Emitter &emitter) const { } void AArch64Insn::EmitAdrpLabel(Emitter &emitter) const { - // adrp xd, label - // add xd, xd, #lo12:label + /* adrp xd, label + * add xd, xd, #lo12:label + */ const AArch64MD *md = &AArch64CG::kMd[MOP_adrp_label]; Operand *opnd0 = opnds[0]; @@ -734,7 +735,7 @@ void AArch64Insn::EmitAdrpLabel(Emitter &emitter) const { OpndProp *prop0 = static_cast(md->operand[0]); LabelIdx lidx = static_cast(opnd1)->GetValue(); - // adrp xd, label + /* adrp xd, label */ emitter.Emit("\t").Emit("adrp").Emit("\t"); opnd0->Emit(emitter, prop0); emitter.Emit(", "); @@ -742,7 +743,7 @@ void AArch64Insn::EmitAdrpLabel(Emitter &emitter) const { idx = strdup(std::to_string(Globals::GetInstance()->GetBECommon()->GetMIRModule().CurFunction()->GetPuidx()).c_str()); emitter.Emit(".label.").Emit(idx).Emit("__").Emit(lidx).Emit("\n"); - // add xd, xd, #lo12:label + /* add xd, xd, #lo12:label */ emitter.Emit("\tadd\t"); opnd0->Emit(emitter, prop0); emitter.Emit(", "); diff --git a/src/mapleall/maple_ipa/BUILD.gn b/src/mapleall/maple_ipa/BUILD.gn old mode 100644 new mode 100755 diff --git a/src/mapleall/maple_ir/BUILD.gn b/src/mapleall/maple_ir/BUILD.gn old mode 100644 new mode 100755 diff --git a/src/mapleall/maple_ir/include/mir_type.h b/src/mapleall/maple_ir/include/mir_type.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_ir/include/opcodes.h b/src/mapleall/maple_ir/include/opcodes.h index 17f3e3e533e0c34b94c6b9e8f9e281ccc3ab2618..e3ea91037c21a814a6ef7027955ef4d257d7b39e 100644 --- a/src/mapleall/maple_ir/include/opcodes.h +++ b/src/mapleall/maple_ir/include/opcodes.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -39,7 +39,8 @@ inline constexpr bool IsCallAssigned(Opcode code) { } inline constexpr bool IsBranch(Opcode opcode) { - return (opcode == OP_goto || opcode == OP_brtrue || opcode == OP_brfalse || opcode == OP_switch || opcode == OP_igoto); + return (opcode == OP_goto || opcode == OP_brtrue || opcode == OP_brfalse || opcode == OP_switch || + opcode == OP_igoto); } constexpr bool IsCommutative(Opcode opcode) { diff --git a/src/mapleall/maple_ir/src/bin_mpl_export.cpp b/src/mapleall/maple_ir/src/bin_mpl_export.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_ir/src/bin_mpl_import.cpp b/src/mapleall/maple_ir/src/bin_mpl_import.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_ir/src/global_tables.cpp b/src/mapleall/maple_ir/src/global_tables.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_ir/src/mir_parser.cpp b/src/mapleall/maple_ir/src/mir_parser.cpp index 6db91aa6d7b4377bd5630cbd9db7319eb6956a21..7c6fcf2dfa4c04565ecb25dd22924c463dc1dcb4 100644 --- a/src/mapleall/maple_ir/src/mir_parser.cpp +++ b/src/mapleall/maple_ir/src/mir_parser.cpp @@ -2271,7 +2271,7 @@ bool MIRParser::ParseExprAddroflabel(BaseNodePtr &expr) { } LabelIdx lblIdx = mod.CurFunction()->GetOrCreateLableIdxFromName(lexer.GetName()); addrOfLabelNode->SetOffset(lblIdx); - mod.CurFunction()->GetLabelTab()->GetAddrTakenLabels().insert(lblIdx); + (void)mod.CurFunction()->GetLabelTab()->GetAddrTakenLabels().insert(lblIdx); lexer.NextToken(); return true; } @@ -2648,14 +2648,14 @@ bool MIRParser::ParseConstAddrLeafExpr(MIRConstPtr &cexpr) { MIRPtrType ptrType(ptyIdx, (mod.IsJavaModule() ? PTY_ref : PTY_ptr)); ptyIdx = GlobalTables::GetTypeTable().GetOrCreateMIRType(&ptrType); MIRType *exprTy = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptyIdx); - int32 ofst = 0; + uint32 ofst = 0; if (lexer.GetTokenKind() == TK_lparen) { lexer.NextToken(); if (lexer.GetTokenKind() != TK_intconst) { Error("ParseConstAddrLeafExpr: wrong offset specification for addrof"); return false; } else { - ofst = lexer.GetTheIntVal(); + ofst = static_cast(lexer.GetTheIntVal()); } lexer.NextToken(); if (lexer.GetTokenKind() != TK_rparen) { diff --git a/src/mapleall/maple_ir/src/mir_type.cpp b/src/mapleall/maple_ir/src/mir_type.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_ir/src/parser.cpp b/src/mapleall/maple_ir/src/parser.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/BUILD.gn b/src/mapleall/maple_me/BUILD.gn old mode 100644 new mode 100755 diff --git a/src/mapleall/maple_me/include/bb.h b/src/mapleall/maple_me/include/bb.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/hdse.h b/src/mapleall/maple_me/include/hdse.h index 7d222204580239e6e0e2c55078e133e5a5c74d73..1bee47b10ec3aa24983ba436a3658c478acf254b 100644 --- a/src/mapleall/maple_me/include/hdse.h +++ b/src/mapleall/maple_me/include/hdse.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/irmap_build.h b/src/mapleall/maple_me/include/irmap_build.h index 1db0ebaaac432c2f0b13b3f39704ba594cd13324..78469d58193b9c50e0ec76d7ca48f6cfa87e5228 100644 --- a/src/mapleall/maple_me/include/irmap_build.h +++ b/src/mapleall/maple_me/include/irmap_build.h @@ -46,30 +46,31 @@ class IRMapBuild { void BuildPhiMeNode(BB&); void SetMeExprOpnds(MeExpr &meExpr, BaseNode &mirNode); - OpMeExpr *BuildOpMeExpr(BaseNode &mirNode) const { - OpMeExpr *meExpr = new OpMeExpr(kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds()); + OpMeExpr *BuildOpMeExpr(const BaseNode &mirNode) const { + auto meExpr = new OpMeExpr(kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds()); return meExpr; } - MeExpr *BuildAddrofMeExpr(BaseNode &mirNode) const; - MeExpr *BuildAddroffuncMeExpr(BaseNode &mirNode) const; - MeExpr *BuildAddroflabelMeExpr(BaseNode &mirNode) const; - MeExpr *BuildGCMallocMeExpr(BaseNode &mirNode) const; - MeExpr *BuildSizeoftypeMeExpr(BaseNode &mirNode) const; - MeExpr *BuildFieldsDistMeExpr(BaseNode &mirNode) const; - MeExpr *BuildIvarMeExpr(BaseNode &mirNode) const; + + MeExpr *BuildAddrofMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildAddroffuncMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildAddroflabelMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildGCMallocMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildSizeoftypeMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildFieldsDistMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildIvarMeExpr(const BaseNode &mirNode) const; MeExpr *BuildConstMeExpr(BaseNode &mirNode) const; - MeExpr *BuildConststrMeExpr(BaseNode &mirNode) const; - MeExpr *BuildConststr16MeExpr(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForCompare(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForTypeCvt(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForRetype(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForIread(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForExtractbits(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForJarrayMalloc(BaseNode &mirNode) const; - MeExpr *BuildOpMeExprForResolveFunc(BaseNode &mirNode) const; - MeExpr *BuildNaryMeExprForArray(BaseNode &mirNode) const; - MeExpr *BuildNaryMeExprForIntrinsicop(BaseNode &mirNode) const; - MeExpr *BuildNaryMeExprForIntrinsicWithType(BaseNode &mirNode) const; + MeExpr *BuildConststrMeExpr(const BaseNode &mirNode) const; + MeExpr *BuildConststr16MeExpr(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForCompare(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForTypeCvt(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForRetype(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForIread(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForExtractbits(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForJarrayMalloc(const BaseNode &mirNode) const; + MeExpr *BuildOpMeExprForResolveFunc(const BaseNode &mirNode) const; + MeExpr *BuildNaryMeExprForArray(const BaseNode &mirNode) const; + MeExpr *BuildNaryMeExprForIntrinsicop(const BaseNode &mirNode) const; + MeExpr *BuildNaryMeExprForIntrinsicWithType(const BaseNode &mirNode) const; MeExpr *BuildExpr(BaseNode&); static void InitMeExprBuildFactory(); diff --git a/src/mapleall/maple_me/include/me_abco.h b/src/mapleall/maple_me/include/me_abco.h old mode 100755 new mode 100644 index f5636a51175d5822f50a00c6e0b2c9aba434bc45..d931b220ef2d9e5cb56c1418b0e5873a0272036c --- a/src/mapleall/maple_me/include/me_abco.h +++ b/src/mapleall/maple_me/include/me_abco.h @@ -100,7 +100,7 @@ class MeABC { bool CollectABC(); void ABCCollectArrayExpr(MeStmt &meStmt, MeExpr &meExpr, bool isUpdate = false); void CollectCareInsns(); - bool IsVirtualVar(const VarMeExpr &var, const SSATab &ssaTab) const; + bool IsVirtualVar(const VarMeExpr &var) const; ESSABaseNode *GetOrCreateRHSNode(MeExpr &expr); void BuildPhiInGraph(MePhiNode &phi); void BuildSoloPiInGraph(const PiassignMeStmt &piMeStmt); diff --git a/src/mapleall/maple_me/include/me_analyze_rc.h b/src/mapleall/maple_me/include/me_analyze_rc.h index 307d744e2ac6fdac072aae77f0f08119740902c5..b289a75ea4eebe9607a1a05247dc1c7c3d3176b6 100644 --- a/src/mapleall/maple_me/include/me_analyze_rc.h +++ b/src/mapleall/maple_me/include/me_analyze_rc.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/me_cfg.h b/src/mapleall/maple_me/include/me_cfg.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/me_delegate_rc.h b/src/mapleall/maple_me/include/me_delegate_rc.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/me_hdse.h b/src/mapleall/maple_me/include/me_hdse.h index bef86c82bb25bbac53f3358dc572cba65e2ff9df..078f38b9379336446f3903787f18f31c87fc41a9 100644 --- a/src/mapleall/maple_me/include/me_hdse.h +++ b/src/mapleall/maple_me/include/me_hdse.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/me_inequality_graph.h b/src/mapleall/maple_me/include/me_inequality_graph.h old mode 100755 new mode 100644 index 6554c48a850f0726ad1885d5b4415c2b4771020d..4376f666d0513feda443637181d3341aac65d9a3 --- a/src/mapleall/maple_me/include/me_inequality_graph.h +++ b/src/mapleall/maple_me/include/me_inequality_graph.h @@ -320,7 +320,7 @@ class InequalityGraph { void AddPhiEdge(ESSABaseNode &from, ESSABaseNode &to, EdgeType type); void AddEdge(ESSABaseNode &from, ESSABaseNode &to, MeExpr &value, bool positive, EdgeType type); void ConnectTrivalEdge(); - void DumpDotFile(IRMap &irMap, DumpType dumpType) const; + void DumpDotFile(DumpType dumpType) const; ESSABaseNode &GetNode(const MeExpr &meExpr); ESSABaseNode &GetNode(int64 value); bool HasNode(const MeExpr &meExpr) const; @@ -333,11 +333,11 @@ class InequalityGraph { std::string GetColor(EdgeType type) const; bool HasNode(int64 value) const; InequalEdge *HasEdge(ESSABaseNode &from, ESSABaseNode &to, InequalEdge &type) const; - std::string GetName(ESSABaseNode &node, IRMap &irMap) const; - std::string GetName(const MeExpr &meExpr, IRMap &irMap) const; - void DumpDotNodes(IRMap &irMap, std::ostream &out, DumpType dumpType, + std::string GetName(ESSABaseNode &node) const; + std::string GetName(const MeExpr &meExpr) const; + void DumpDotNodes(std::ostream &out, DumpType dumpType, const std::map> &nodes) const; - void DumpDotEdges(IRMap &irMap, const std::pair &map, + void DumpDotEdges(const std::pair &map, std::ostream &out, std::string &from) const; MeFunction *meFunction; diff --git a/src/mapleall/maple_me/include/me_ir.h b/src/mapleall/maple_me/include/me_ir.h index d09a3b8afe1f36930850f9b69da290abe2bcc6d4..c9c4ec48504a37e09e22dc8c5c9db665a4cd30c5 100644 --- a/src/mapleall/maple_me/include/me_ir.h +++ b/src/mapleall/maple_me/include/me_ir.h @@ -158,7 +158,7 @@ class MeExpr { MeExpr *ResolveMeExprValue(); bool CouldThrowException() const; bool IsAllOpndsIdentical(const MeExpr &meExpr) const; - bool PointsToSomethingThatNeedsIncRef(SSATab &ssaTab); + bool PointsToSomethingThatNeedsIncRef(); virtual uint32 GetHashIndex() const { return 0; } @@ -232,6 +232,10 @@ class ScalarMeExpr : public MeExpr { return ost; } + OStIdx GetOstIdx() const { + return ost->GetIndex(); + } + size_t GetVstIdx() const { return vstIdx; } @@ -319,12 +323,16 @@ class VarMeExpr final : public ScalarMeExpr { bool IsVolatile() const override; // indicate if the variable is local variable but not a function formal variable - bool IsPureLocal(const SSATab&, const MIRFunction&) const; + bool IsPureLocal(const MIRFunction&) const; bool IsZeroVersion() const; bool IsSameVariableValue(const VarMeExpr&) const override; VarMeExpr &ResolveVarMeValue(); bool PointsToStringLiteral(); + FieldID GetFieldID() const { + return GetOst()->GetFieldID(); + } + TyIdx GetInferredTyIdx() const { return inferredTyIdx; } @@ -1090,7 +1098,7 @@ class MeStmt { return nullptr; } - void EmitCallReturnVector(SSATab &ssaTab, CallReturnVector &nRets); + void EmitCallReturnVector(CallReturnVector &nRets); virtual MapleVector *GetMustDefList() { return nullptr; } @@ -1158,7 +1166,7 @@ class MeStmt { return nullptr; } - virtual MeExpr *GetLHSRef(SSATab&, bool) { + virtual MeExpr *GetLHSRef(bool) { return nullptr; } @@ -1544,7 +1552,7 @@ class DassignMeStmt : public MeStmt { return lhs; } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar); void UpdateLHS(VarMeExpr &var) { lhs = &var; var.SetDefBy(kDefByStmt); @@ -1727,7 +1735,7 @@ class MaydassignMeStmt : public MeStmt { return chiList.begin()->second->GetLHS(); } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar); StmtNode &EmitStmt(SSATab &ssaTab); private: @@ -1797,7 +1805,7 @@ class IassignMeStmt : public MeStmt { chiList = value; } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar); bool NeedDecref() const { return needDecref; } @@ -1951,7 +1959,7 @@ class AssignedPart { virtual ~AssignedPart() = default; void DumpAssignedPart(const IRMap *irMap) const; - VarMeExpr *GetAssignedPartLHSRef(SSATab &ssaTab, bool excludeLocalRefVar); + VarMeExpr *GetAssignedPartLHSRef(bool excludeLocalRefVar); protected: MapleVector mustDefList; @@ -2031,8 +2039,8 @@ class CallMeStmt : public NaryMeStmt, public MuChiMePart, public AssignedPart { return mustDefList.empty() ? nullptr : mustDefList.front().GetLHS(); } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { - return GetAssignedPartLHSRef(ssaTab, excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar) { + return GetAssignedPartLHSRef(excludeLocalRefVar); } VarMeExpr *GetVarLHS() { @@ -2126,8 +2134,8 @@ class IcallMeStmt : public NaryMeStmt, public MuChiMePart, public AssignedPart { return mustDefList.empty() ? nullptr : mustDefList.front().GetLHS(); } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { - return GetAssignedPartLHSRef(ssaTab, excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar) { + return GetAssignedPartLHSRef(excludeLocalRefVar); } bool NeedDecref() const { @@ -2246,8 +2254,8 @@ class IntrinsiccallMeStmt : public NaryMeStmt, public MuChiMePart, public Assign return mustDefList.empty() ? nullptr : mustDefList.front().GetLHS(); } - MeExpr *GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { - return GetAssignedPartLHSRef(ssaTab, excludeLocalRefVar); + MeExpr *GetLHSRef(bool excludeLocalRefVar) { + return GetAssignedPartLHSRef(excludeLocalRefVar); } bool NeedDecref() const { diff --git a/src/mapleall/maple_me/include/me_loop_canon.h b/src/mapleall/maple_me/include/me_loop_canon.h index 5623e6e46cb27f63a5fb3ee4ff2906e473ab7566..0a7742c7f3715c0cc28d6f9e425e6f1a1e0edbba 100644 --- a/src/mapleall/maple_me/include/me_loop_canon.h +++ b/src/mapleall/maple_me/include/me_loop_canon.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/me_may2dassign.h b/src/mapleall/maple_me/include/me_may2dassign.h index 724b676402b95042534c04304a6ccbb3ea5d1d04..b6168085cdaf17936dbe80e5bd831ba685d776ee 100644 --- a/src/mapleall/maple_me/include/me_may2dassign.h +++ b/src/mapleall/maple_me/include/me_may2dassign.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/me_ssa_update.h b/src/mapleall/maple_me/include/me_ssa_update.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/me_ssi.h b/src/mapleall/maple_me/include/me_ssi.h index c40226ee8a4ec5672b09088cbb177d7310661162..6cbd8d54cfd0446e8223e1691e8210d47017c5a9 100644 --- a/src/mapleall/maple_me/include/me_ssi.h +++ b/src/mapleall/maple_me/include/me_ssi.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -90,9 +90,9 @@ class DefPoint { const OStIdx GetOStIdx() const { if (defKind == kDefByPi) { - return value.pi->GetRHS()->GetOst()->GetIndex(); + return value.pi->GetRHS()->GetOstIdx(); } else { - return value.phi->GetOpnd(0)->GetOst()->GetIndex(); + return value.phi->GetOpnd(0)->GetOstIdx(); } } diff --git a/src/mapleall/maple_me/include/me_ssu_pre.h b/src/mapleall/maple_me/include/me_ssu_pre.h old mode 100755 new mode 100644 index b3bd0fa35ae36ce74350953bbb5f9cfeaafec6b0..000cdb4f4be3166f7f00a86d64358cc7a91b4177 --- a/src/mapleall/maple_me/include/me_ssu_pre.h +++ b/src/mapleall/maple_me/include/me_ssu_pre.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -282,7 +282,7 @@ class SPhiOcc : public SOcc { class SpreWorkCand { public: - SpreWorkCand(MapleAllocator &alloc, const OriginalSt &ost) + SpreWorkCand(MapleAllocator &alloc, OriginalSt &ost) : next(nullptr), theOst(&ost), theVar(nullptr), @@ -296,7 +296,7 @@ class SpreWorkCand { return next; } - const OriginalSt *GetOst() const { + OriginalSt *GetOst() const { return theOst; } @@ -330,7 +330,7 @@ class SpreWorkCand { private: SpreWorkCand *next; - const OriginalSt *theOst; // the stored symbol of this workcand + OriginalSt *theOst; // the stored symbol of this workcand VarMeExpr *theVar; // any existing node of the lhs var MapleVector realOccs; // maintained in order of pdt_preorder bool hasStoreOcc; // true if there is any store occurrence diff --git a/src/mapleall/maple_me/include/me_stmt_pre.h b/src/mapleall/maple_me/include/me_stmt_pre.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/occur.h b/src/mapleall/maple_me/include/occur.h old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/include/orig_symbol.h b/src/mapleall/maple_me/include/orig_symbol.h index 5e19ae3e98357cf76abc0f54950105a0d0d89ea0..612e18fdeb294aadf4ea19c2f53959b9274f0c73 100644 --- a/src/mapleall/maple_me/include/orig_symbol.h +++ b/src/mapleall/maple_me/include/orig_symbol.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/ssa_pre.h b/src/mapleall/maple_me/include/ssa_pre.h index e461a4d7aaa2c7c8e52e31e015e0c923ce146aff..c77891b2a4f1de18c26d886a3a425c84e22a3441 100644 --- a/src/mapleall/maple_me/include/ssa_pre.h +++ b/src/mapleall/maple_me/include/ssa_pre.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/ssa_tab.h b/src/mapleall/maple_me/include/ssa_tab.h index 510fea2df8d8a039ca1fe27111e2555f93d5557e..7ba125bcda96cc1e9f0defe0bfb5dfa409c50856 100644 --- a/src/mapleall/maple_me/include/ssa_tab.h +++ b/src/mapleall/maple_me/include/ssa_tab.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/include/ver_symbol.h b/src/mapleall/maple_me/include/ver_symbol.h index 81e0c00568603149e8140acac3e3bcd88ed9f9cb..e6de1f79c96e8429644abf9d8469af8c0269fff1 100644 --- a/src/mapleall/maple_me/include/ver_symbol.h +++ b/src/mapleall/maple_me/include/ver_symbol.h @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/alias_class.cpp b/src/mapleall/maple_me/src/alias_class.cpp index 776cef880069bc943066433a770e6dfe671bdabf..2364c8ed3a92fd908c6c449535ec41eeb5d49e39 100644 --- a/src/mapleall/maple_me/src/alias_class.cpp +++ b/src/mapleall/maple_me/src/alias_class.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/bb.cpp b/src/mapleall/maple_me/src/bb.cpp old mode 100755 new mode 100644 index 71125e00869f13925a75e43dbe7fd270ccdf09f3..134428a03973b42cabad65e84828dca322dcec73 --- a/src/mapleall/maple_me/src/bb.cpp +++ b/src/mapleall/maple_me/src/bb.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/hdse.cpp b/src/mapleall/maple_me/src/hdse.cpp old mode 100755 new mode 100644 index c616b3da649a5133e5cbafca20f0fc35fbc30849..8bc38e1f5095fd4a27dee3670db285b7271c278b --- a/src/mapleall/maple_me/src/hdse.cpp +++ b/src/mapleall/maple_me/src/hdse.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -43,7 +43,8 @@ void HDSE::RemoveNotRequiredStmtsInBB(BB &bb) { mirModule.GetOut() << "========== HSSA DSE is deleting this stmt: "; meStmt.Dump(&irMap); } - if (meStmt.GetOp() != OP_dassign && (meStmt.IsCondBr() || meStmt.GetOp() == OP_switch || meStmt.GetOp() == OP_igoto)) { + if (meStmt.GetOp() != OP_dassign && + (meStmt.IsCondBr() || meStmt.GetOp() == OP_switch || meStmt.GetOp() == OP_igoto)) { // update CFG while (bb.GetSucc().size() != 1) { BB *succ = bb.GetSucc().back(); diff --git a/src/mapleall/maple_me/src/irmap.cpp b/src/mapleall/maple_me/src/irmap.cpp index 2a51610987e61b46a459a320f3135c7bf6a2a9cf..216ea48f43b8e46945a76671b5f70cf41eaf5782 100644 --- a/src/mapleall/maple_me/src/irmap.cpp +++ b/src/mapleall/maple_me/src/irmap.cpp @@ -36,7 +36,7 @@ MeExpr *IRMap::CreateAddrofMeExpr(OStIdx ostIdx) { MeExpr *IRMap::CreateAddrofMeExpr(MeExpr &expr) { if (expr.GetMeOp() == kMeOpVar) { auto &varMeExpr = static_cast(expr); - return CreateAddrofMeExpr(varMeExpr.GetOst()->GetIndex()); + return CreateAddrofMeExpr(varMeExpr.GetOstIdx()); } else { ASSERT(expr.GetMeOp() == kMeOpIvar, "expecting IVarMeExpr"); auto &ivarExpr = static_cast(expr); @@ -198,7 +198,7 @@ VarMeExpr *IRMap::GetOrCreateZeroVersionVarMeExpr(OriginalSt &ost) { } if (vst2MeExprTable[ost.GetZeroVersionIndex()] == nullptr) { auto *varMeExpr = New(exprID++, &ost, ost.GetZeroVersionIndex(), - GlobalTables::GetTypeTable().GetTypeFromTyIdx(ost.GetTyIdx())->GetPrimType()); + GlobalTables::GetTypeTable().GetTypeFromTyIdx(ost.GetTyIdx())->GetPrimType()); ASSERT(!GlobalTables::GetTypeTable().GetTypeTable().empty(), "container check"); vst2MeExprTable[ost.GetZeroVersionIndex()] = varMeExpr; return varMeExpr; @@ -253,17 +253,21 @@ MeExpr *IRMap::HashMeExpr(MeExpr &meExpr) { resultExpr = New(exprID, static_cast(meExpr).GetConstVal(), meExpr.GetPrimType()); break; case kMeOpConststr: - resultExpr = New(exprID, static_cast(meExpr).GetStrIdx(), meExpr.GetPrimType()); + resultExpr = + New(exprID, static_cast(meExpr).GetStrIdx(), meExpr.GetPrimType()); break; case kMeOpConststr16: - resultExpr = New(exprID, static_cast(meExpr).GetStrIdx(), meExpr.GetPrimType()); + resultExpr = + New(exprID, static_cast(meExpr).GetStrIdx(), meExpr.GetPrimType()); break; case kMeOpSizeoftype: - resultExpr = New(exprID, meExpr.GetPrimType(), static_cast(meExpr).GetTyIdx()); + resultExpr = + New(exprID, meExpr.GetPrimType(), static_cast(meExpr).GetTyIdx()); break; case kMeOpFieldsDist: { auto &expr = static_cast(meExpr); - resultExpr = New(exprID, meExpr.GetPrimType(), expr.GetTyIdx(), expr.GetFieldID1(), expr.GetFieldID2()); + resultExpr = New(exprID, meExpr.GetPrimType(), expr.GetTyIdx(), + expr.GetFieldID1(), expr.GetFieldID2()); break; } case kMeOpAddrof: @@ -280,12 +284,13 @@ MeExpr *IRMap::HashMeExpr(MeExpr &meExpr) { resultExpr = New(exprID, static_cast(meExpr).labelIdx); break; case kMeOpGcmalloc: - resultExpr = New(exprID, meExpr.GetOp(), meExpr.GetPrimType(), static_cast(meExpr).GetTyIdx()); + resultExpr = New(exprID, meExpr.GetOp(), meExpr.GetPrimType(), + static_cast(meExpr).GetTyIdx()); break; default: CHECK_FATAL(false, "not yet implement"); } - exprID++; + ++exprID; if (meExpr.GetMeOp() == kMeOpOp || meExpr.GetMeOp() == kMeOpNary) { resultExpr->UpdateDepth(); } diff --git a/src/mapleall/maple_me/src/irmap_build.cpp b/src/mapleall/maple_me/src/irmap_build.cpp index b74a9e8adc3f9c13bf694981eb521dd8da864deb..5575a21b8b2116b519f79409b60292185ea15e47 100644 --- a/src/mapleall/maple_me/src/irmap_build.cpp +++ b/src/mapleall/maple_me/src/irmap_build.cpp @@ -47,8 +47,7 @@ RegMeExpr *IRMapBuild::GetOrCreateRegFromVerSt(VersionSt &vst) { } OriginalSt *ost = vst.GetOst(); ASSERT(ost->IsPregOst(), "GetOrCreateRegFromVerSt: PregOST expected"); - auto *regx = irMap->New(irMap->exprID++, - ost, vindex, ost->GetMIRPreg()->GetPrimType()); + auto *regx = irMap->New(irMap->exprID++, ost, vindex, ost->GetMIRPreg()->GetPrimType()); irMap->vst2MeExprTable[vindex] = regx; return regx; } @@ -82,7 +81,7 @@ void IRMapBuild::BuildChiList(MeStmt &meStmt, TypeOfMayDefList &mayDefNodes, lhs->SetDefBy(kDefByChi); lhs->SetDefChi(*chiMeStmt); chiMeStmt->SetLHS(lhs); - (void)outList.insert(std::make_pair(lhs->GetOst()->GetIndex(), chiMeStmt)); + (void)outList.insert(std::make_pair(lhs->GetOstIdx(), chiMeStmt)); } } @@ -126,7 +125,7 @@ void IRMapBuild::BuildMuList(TypeOfMayUseList &mayUseList, MapleMapGetOst()->GetIndex(), varMeExpr)); + (void)muList.insert(std::make_pair(varMeExpr->GetOstIdx(), varMeExpr)); } } @@ -156,127 +155,136 @@ void IRMapBuild::SetMeExprOpnds(MeExpr &meExpr, BaseNode &mirNode) { } } -MeExpr *IRMapBuild::BuildAddrofMeExpr(BaseNode &mirNode) const { - auto &addrofNode = static_cast(mirNode); - AddrofMeExpr *meExpr = new AddrofMeExpr(kInvalidExprID, addrofNode.GetPrimType(), addrofNode.GetSSAVar()->GetOrigSt()->GetIndex()); +MeExpr *IRMapBuild::BuildAddrofMeExpr(const BaseNode &mirNode) const { + auto &addrofNode = static_cast(mirNode); + auto meExpr = new AddrofMeExpr(kInvalidExprID, addrofNode.GetPrimType(), + addrofNode.GetSSAVar()->GetOrigSt()->GetIndex()); meExpr->SetFieldID(addrofNode.GetFieldID()); return meExpr; } -MeExpr *IRMapBuild::BuildAddroffuncMeExpr(BaseNode &mirNode) const { - AddroffuncMeExpr *meExpr = new AddroffuncMeExpr(kInvalidExprID, static_cast(mirNode).GetPUIdx()); +MeExpr *IRMapBuild::BuildAddroffuncMeExpr(const BaseNode &mirNode) const { + auto meExpr = new AddroffuncMeExpr(kInvalidExprID, static_cast(mirNode).GetPUIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildAddroflabelMeExpr(BaseNode &mirNode) const { - AddroflabelMeExpr *meExpr = new AddroflabelMeExpr(kInvalidExprID, static_cast(mirNode).GetOffset()); +MeExpr *IRMapBuild::BuildAddroflabelMeExpr(const BaseNode &mirNode) const { + auto meExpr = new AddroflabelMeExpr(kInvalidExprID, static_cast(mirNode).GetOffset()); return meExpr; } -MeExpr *IRMapBuild::BuildGCMallocMeExpr(BaseNode &mirNode) const { - GcmallocMeExpr *meExpr = new GcmallocMeExpr(kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), static_cast(mirNode).GetTyIdx()); +MeExpr *IRMapBuild::BuildGCMallocMeExpr(const BaseNode &mirNode) const { + auto meExpr = new GcmallocMeExpr(kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), + static_cast(mirNode).GetTyIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildSizeoftypeMeExpr(BaseNode &mirNode) const { - SizeoftypeMeExpr *meExpr = new SizeoftypeMeExpr(kInvalidExprID, mirNode.GetPrimType(), static_cast(mirNode).GetTyIdx()); +MeExpr *IRMapBuild::BuildSizeoftypeMeExpr(const BaseNode &mirNode) const { + auto meExpr = new SizeoftypeMeExpr(kInvalidExprID, mirNode.GetPrimType(), + static_cast(mirNode).GetTyIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildFieldsDistMeExpr(BaseNode &mirNode) const { - auto &fieldsDistNode = static_cast(mirNode); - FieldsDistMeExpr *meExpr = new FieldsDistMeExpr(kInvalidExprID, mirNode.GetPrimType(), fieldsDistNode.GetTyIdx(), - fieldsDistNode.GetFiledID1(), fieldsDistNode.GetFiledID2()); +MeExpr *IRMapBuild::BuildFieldsDistMeExpr(const BaseNode &mirNode) const { + auto &fieldsDistNode = static_cast(mirNode); + auto meExpr = new FieldsDistMeExpr(kInvalidExprID, mirNode.GetPrimType(), fieldsDistNode.GetTyIdx(), + fieldsDistNode.GetFiledID1(), fieldsDistNode.GetFiledID2()); return meExpr; } -MeExpr *IRMapBuild::BuildIvarMeExpr(BaseNode &mirNode) const { - auto &ireadSSANode = static_cast(mirNode); - IvarMeExpr *meExpr = new IvarMeExpr(kInvalidExprID, mirNode.GetPrimType(), ireadSSANode.GetTyIdx(), ireadSSANode.GetFieldID()); +MeExpr *IRMapBuild::BuildIvarMeExpr(const BaseNode &mirNode) const { + auto &ireadSSANode = static_cast(mirNode); + auto meExpr = new IvarMeExpr(kInvalidExprID, mirNode.GetPrimType(), ireadSSANode.GetTyIdx(), + ireadSSANode.GetFieldID()); return meExpr; } MeExpr *IRMapBuild::BuildConstMeExpr(BaseNode &mirNode) const { - auto &constvalNode = static_cast(mirNode); - ConstMeExpr *meExpr = new ConstMeExpr(kInvalidExprID, constvalNode.GetConstVal(), mirNode.GetPrimType()); + auto &constvalNode = static_cast(mirNode); + auto meExpr = new ConstMeExpr(kInvalidExprID, constvalNode.GetConstVal(), mirNode.GetPrimType()); meExpr->SetOp(OP_constval); return meExpr; } -MeExpr *IRMapBuild::BuildConststrMeExpr(BaseNode &mirNode) const { - ConststrMeExpr *meExpr = new ConststrMeExpr(kInvalidExprID, static_cast(mirNode).GetStrIdx(), mirNode.GetPrimType()); +MeExpr *IRMapBuild::BuildConststrMeExpr(const BaseNode &mirNode) const { + auto meExpr = new ConststrMeExpr(kInvalidExprID, static_cast(mirNode).GetStrIdx(), + mirNode.GetPrimType()); return meExpr; } -MeExpr *IRMapBuild::BuildConststr16MeExpr(BaseNode &mirNode) const { - Conststr16MeExpr *meExpr = new Conststr16MeExpr(kInvalidExprID, static_cast(mirNode).GetStrIdx(), mirNode.GetPrimType()); +MeExpr *IRMapBuild::BuildConststr16MeExpr(const BaseNode &mirNode) const { + auto meExpr = new Conststr16MeExpr(kInvalidExprID, static_cast(mirNode).GetStrIdx(), + mirNode.GetPrimType()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForCompare(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForCompare(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - meExpr->SetOpndType(static_cast(mirNode).GetOpndType()); + meExpr->SetOpndType(static_cast(mirNode).GetOpndType()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForTypeCvt(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForTypeCvt(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - meExpr->SetOpndType(static_cast(mirNode).FromType()); + meExpr->SetOpndType(static_cast(mirNode).FromType()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForRetype(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForRetype(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - auto &retypeNode = static_cast(mirNode); + auto &retypeNode = static_cast(mirNode); meExpr->SetOpndType(retypeNode.FromType()); meExpr->SetTyIdx(retypeNode.GetTyIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForIread(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForIread(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - auto &ireadNode = static_cast(mirNode); + auto &ireadNode = static_cast(mirNode); meExpr->SetTyIdx(ireadNode.GetTyIdx()); meExpr->SetFieldID(ireadNode.GetFieldID()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForExtractbits(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForExtractbits(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - auto &extractbitsNode = static_cast(mirNode); + auto &extractbitsNode = static_cast(mirNode); meExpr->SetBitsOffSet(extractbitsNode.GetBitsOffset()); meExpr->SetBitsSize(extractbitsNode.GetBitsSize()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForJarrayMalloc(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForJarrayMalloc(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - meExpr->SetTyIdx(static_cast(mirNode).GetTyIdx()); + meExpr->SetTyIdx(static_cast(mirNode).GetTyIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildOpMeExprForResolveFunc(BaseNode &mirNode) const { +MeExpr *IRMapBuild::BuildOpMeExprForResolveFunc(const BaseNode &mirNode) const { OpMeExpr *meExpr = BuildOpMeExpr(mirNode); - meExpr->SetFieldID(static_cast(mirNode).GetPuIdx()); + meExpr->SetFieldID(static_cast(mirNode).GetPuIdx()); return meExpr; } -MeExpr *IRMapBuild::BuildNaryMeExprForArray(BaseNode &mirNode) const { - auto &arrayNode = static_cast(mirNode); - NaryMeExpr *meExpr = - new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds(), arrayNode.GetTyIdx(), INTRN_UNDEFINED, arrayNode.GetBoundsCheck()); +MeExpr *IRMapBuild::BuildNaryMeExprForArray(const BaseNode &mirNode) const { + auto &arrayNode = static_cast(mirNode); + auto meExpr = new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), + mirNode.GetNumOpnds(), arrayNode.GetTyIdx(), INTRN_UNDEFINED, + arrayNode.GetBoundsCheck()); return meExpr; } -MeExpr *IRMapBuild::BuildNaryMeExprForIntrinsicop(BaseNode &mirNode) const { - NaryMeExpr *meExpr = - new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds(), TyIdx(0), static_cast(mirNode).GetIntrinsic(), false); +MeExpr *IRMapBuild::BuildNaryMeExprForIntrinsicop(const BaseNode &mirNode) const { + auto meExpr = new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), + mirNode.GetNumOpnds(), TyIdx(0), + static_cast(mirNode).GetIntrinsic(), false); return meExpr; } -MeExpr *IRMapBuild::BuildNaryMeExprForIntrinsicWithType(BaseNode &mirNode) const { - auto &intrinNode = static_cast(mirNode); - NaryMeExpr *meExpr = new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds(), intrinNode.GetTyIdx(), intrinNode.GetIntrinsic(), false); +MeExpr *IRMapBuild::BuildNaryMeExprForIntrinsicWithType(const BaseNode &mirNode) const { + auto &intrinNode = static_cast(mirNode); + NaryMeExpr *meExpr = new NaryMeExpr(&irMap->irMapAlloc, kInvalidExprID, mirNode.GetOpCode(), mirNode.GetPrimType(), + mirNode.GetNumOpnds(), intrinNode.GetTyIdx(), intrinNode.GetIntrinsic(), false); return meExpr; } diff --git a/src/mapleall/maple_me/src/irmap_emit.cpp b/src/mapleall/maple_me/src/irmap_emit.cpp old mode 100755 new mode 100644 index 301a7acd0760de4c1bb26fa69739069ec97618af..9dba09cddee63bf4dd6166e02787fc573d1aaba5 --- a/src/mapleall/maple_me/src/irmap_emit.cpp +++ b/src/mapleall/maple_me/src/irmap_emit.cpp @@ -316,7 +316,7 @@ StmtNode &MaydassignMeStmt::EmitStmt(SSATab &ssaTab) { return *dassignStmt; } -void MeStmt::EmitCallReturnVector(SSATab &ssaTab, CallReturnVector &nRets) { +void MeStmt::EmitCallReturnVector(CallReturnVector &nRets) { MapleVector *mustDefs = GetMustDefList(); if (mustDefs == nullptr || mustDefs->empty()) { return; @@ -364,7 +364,7 @@ StmtNode &CallMeStmt::EmitStmt(SSATab &ssaTab) { callNode->SetNumOpnds(callNode->GetNopndSize()); callNode->SetSrcPos(GetSrcPosition()); if (kOpcodeInfo.IsCallAssigned(GetOp())) { - EmitCallReturnVector(ssaTab, callNode->GetReturnVec()); + EmitCallReturnVector(callNode->GetReturnVec()); for (size_t j = 0; j < callNode->GetReturnVec().size(); ++j) { CallReturnPair retPair = callNode->GetReturnVec()[j]; if (!retPair.second.IsReg()) { @@ -388,7 +388,7 @@ StmtNode &CallMeStmt::EmitStmt(SSATab &ssaTab) { icallNode->SetNumOpnds(icallNode->GetNopndSize()); icallNode->SetSrcPos(GetSrcPosition()); if (kOpcodeInfo.IsCallAssigned(GetOp())) { - EmitCallReturnVector(ssaTab, icallNode->GetReturnVec()); + EmitCallReturnVector(icallNode->GetReturnVec()); icallNode->SetRetTyIdx(TyIdx(PTY_void)); for (size_t j = 0; j < icallNode->GetReturnVec().size(); ++j) { CallReturnPair retPair = icallNode->GetReturnVec()[j]; @@ -420,7 +420,7 @@ StmtNode &IcallMeStmt::EmitStmt(SSATab &ssaTab) { icallNode->SetNumOpnds(icallNode->GetNopndSize()); icallNode->SetSrcPos(GetSrcPosition()); if (kOpcodeInfo.IsCallAssigned(GetOp())) { - EmitCallReturnVector(ssaTab, icallNode->GetReturnVec()); + EmitCallReturnVector(icallNode->GetReturnVec()); icallNode->SetRetTyIdx(TyIdx(PTY_void)); for (size_t j = 0; j < icallNode->GetReturnVec().size(); ++j) { CallReturnPair retPair = icallNode->GetReturnVec()[j]; @@ -455,7 +455,7 @@ StmtNode &IntrinsiccallMeStmt::EmitStmt(SSATab &ssaTab) { callNode->SetNumOpnds(callNode->GetNopndSize()); callNode->SetSrcPos(GetSrcPosition()); if (kOpcodeInfo.IsCallAssigned(GetOp())) { - EmitCallReturnVector(ssaTab, callNode->GetReturnVec()); + EmitCallReturnVector(callNode->GetReturnVec()); for (size_t j = 0; j < callNode->GetReturnVec().size(); ++j) { CallReturnPair retPair = callNode->GetReturnVec()[j]; if (!retPair.second.IsReg()) { diff --git a/src/mapleall/maple_me/src/me_abco.cpp b/src/mapleall/maple_me/src/me_abco.cpp old mode 100755 new mode 100644 index d353ece2d86c3d64f1ee5308882ea40563e8a2af..de1f9865de14ec8e4fa61d629eb03bdc48f7114e --- a/src/mapleall/maple_me/src/me_abco.cpp +++ b/src/mapleall/maple_me/src/me_abco.cpp @@ -66,7 +66,7 @@ bool MeABC::CollectABC() { return !arrayChecks.empty(); } -bool MeABC::IsVirtualVar(const VarMeExpr &var, const SSATab &ssaTab) const { +bool MeABC::IsVirtualVar(const VarMeExpr &var) const { const OriginalSt *ost = var.GetOst(); return ost->GetIndirectLev() > 0; } @@ -95,7 +95,7 @@ void MeABC::BuildPhiInGraph(MePhiNode &phi) { return; } VarMeExpr *lhsExpr = static_cast(phi.GetLHS()); - if (lhsExpr != nullptr && IsVirtualVar(*lhsExpr, irMap->GetSSATab())) { + if (lhsExpr != nullptr && IsVirtualVar(*lhsExpr)) { return; } for (auto *phiRHS : phi.GetOpnds()) { @@ -1053,8 +1053,8 @@ void MeABC::ExecuteABCO() { BuildInequalityGraph(); if (MeABC::isDebug) { meFunc->GetTheCfg()->DumpToFile(meFunc->GetName()); - inequalityGraph->DumpDotFile(*irMap, DumpType::kDumpUpperAndNone); - inequalityGraph->DumpDotFile(*irMap, DumpType::kDumpLowerAndNone); + inequalityGraph->DumpDotFile(DumpType::kDumpUpperAndNone); + inequalityGraph->DumpDotFile(DumpType::kDumpLowerAndNone); } FindRedundantABC(*(pair.first), *(static_cast(pair.second))); } diff --git a/src/mapleall/maple_me/src/me_analyze_rc.cpp b/src/mapleall/maple_me/src/me_analyze_rc.cpp index 4ff8dc57a0f27ff8e0634b9fbe8f25b495902cd8..88cb63aeac8ffaa474c55cf645e611948d422535 100644 --- a/src/mapleall/maple_me/src/me_analyze_rc.cpp +++ b/src/mapleall/maple_me/src/me_analyze_rc.cpp @@ -135,7 +135,7 @@ bool AnalyzeRC::NeedIncref(const MeStmt &stmt) const { } MeExpr *rhs = stmt.GetRHS(); CHECK_NULL_FATAL(rhs); - return rhs->PointsToSomethingThatNeedsIncRef(ssaTab); + return rhs->PointsToSomethingThatNeedsIncRef(); } // identify assignments to ref pointers and insert decref before it and incref @@ -145,7 +145,7 @@ void AnalyzeRC::IdentifyRCStmts() { for (auto bIt = func.valid_begin(); bIt != eIt; ++bIt) { auto &bb = **bIt; for (auto &stmt : bb.GetMeStmts()) { - MeExpr *lhsRef = stmt.GetLHSRef(ssaTab, skipLocalRefVars); + MeExpr *lhsRef = stmt.GetLHSRef(skipLocalRefVars); if (lhsRef != nullptr) { OriginalSt *ost = GetOriginalSt(*lhsRef); ASSERT(ost != nullptr, "IdentifyRCStmts: cannot get SymbolOriginalSt"); @@ -220,7 +220,7 @@ void AnalyzeRC::TraverseStmt(BB &bb) { static_cast(meStmt).GetIntrinsic() == INTRN_MPL_CLEANUP_LOCALREFVARS)) { RenameUses(meStmt); } else { - MeExpr *lhsRef = meStmt.GetLHSRef(ssaTab, skipLocalRefVars); + MeExpr *lhsRef = meStmt.GetLHSRef(skipLocalRefVars); if (lhsRef == nullptr) { continue; } diff --git a/src/mapleall/maple_me/src/me_cfg.cpp b/src/mapleall/maple_me/src/me_cfg.cpp old mode 100755 new mode 100644 index c4332475217bf7543bb4ed1745415d83b147aa97..be2da677bea6005e864354147c8b26e4e9bfe7bf --- a/src/mapleall/maple_me/src/me_cfg.cpp +++ b/src/mapleall/maple_me/src/me_cfg.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_cond_based_opt.cpp b/src/mapleall/maple_me/src/me_cond_based_opt.cpp old mode 100755 new mode 100644 index 17ed3ce2ad7b2d019ba3ca1fb9d8ad8fa1a88b12..e40417a6d23530eaef7128e07f0203e817fe4ad1 --- a/src/mapleall/maple_me/src/me_cond_based_opt.cpp +++ b/src/mapleall/maple_me/src/me_cond_based_opt.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_critical_edge.cpp b/src/mapleall/maple_me/src/me_critical_edge.cpp index 7aa2a81882849557d1ab837c5596376137aa43db..20f11e559cc5f95c88865864ad37ebdec8497ad9 100644 --- a/src/mapleall/maple_me/src/me_critical_edge.cpp +++ b/src/mapleall/maple_me/src/me_critical_edge.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_delegate_rc.cpp b/src/mapleall/maple_me/src/me_delegate_rc.cpp old mode 100755 new mode 100644 index 53bd5f7bcce6d63e04637ee087563197c1f20851..5664c68da5b9a1b9ca2843f4b27b78e27c8d0378 --- a/src/mapleall/maple_me/src/me_delegate_rc.cpp +++ b/src/mapleall/maple_me/src/me_delegate_rc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -714,7 +714,7 @@ std::set DelegateRC::RenameAndGetLiveLocalRefVar() { CHECK_FATAL(lhs != nullptr, "null ptr check"); const OriginalSt *ost = lhs->GetOst(); if (ost->IsLocal() && !ost->IsFormal() && !ost->IsIgnoreRC() && lhs->GetPrimType() == PTY_ref) { - (void)liveLocalrefvars.insert(lhs->GetOst()->GetIndex()); + (void)liveLocalrefvars.insert(lhs->GetOstIdx()); } } else if (kOpcodeInfo.IsCallAssigned(stmt.GetOp())) { MapleVector *mustdefList = stmt.GetMustDefList(); @@ -727,7 +727,7 @@ std::set DelegateRC::RenameAndGetLiveLocalRefVar() { auto *varLhs = static_cast(theLhs); const OriginalSt *ost = varLhs->GetOst(); if (ost->IsLocal() && !ost->IsFormal() && !ost->IsIgnoreRC()) { - (void)liveLocalrefvars.insert(varLhs->GetOst()->GetIndex()); + (void)liveLocalrefvars.insert(ost->GetIndex()); } } } @@ -757,7 +757,7 @@ void DelegateRC::CleanUpDeadLocalRefVar(const std::set &liveLocalrefvars IntrinsiccallMeStmt *intrin = static_cast(stmt); for (size_t i = 0; i < intrin->NumMeStmtOpnds(); ++i) { auto *varMeExpr = static_cast(intrin->GetOpnd(i)); - if (liveLocalrefvars.find(varMeExpr->GetOst()->GetIndex()) == liveLocalrefvars.end()) { + if (liveLocalrefvars.find(varMeExpr->GetOstIdx()) == liveLocalrefvars.end()) { continue; } if (nextPos != i) { diff --git a/src/mapleall/maple_me/src/me_function.cpp b/src/mapleall/maple_me/src/me_function.cpp old mode 100755 new mode 100644 index 1fabc1ae63eea5250b054a61f11566fa8d4f42c6..e7be8d52817451f2ae332d7a904ecaf1827ebfd0 --- a/src/mapleall/maple_me/src/me_function.cpp +++ b/src/mapleall/maple_me/src/me_function.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_hdse.cpp b/src/mapleall/maple_me/src/me_hdse.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/src/me_inequality_graph.cpp b/src/mapleall/maple_me/src/me_inequality_graph.cpp old mode 100755 new mode 100644 index 90291ec57932cf6b9ecc37cfb7fbbff4b0dbb423..cf5c4ee17170812e3b600e14272456ef90674129 --- a/src/mapleall/maple_me/src/me_inequality_graph.cpp +++ b/src/mapleall/maple_me/src/me_inequality_graph.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -180,7 +180,7 @@ InequalEdge *InequalityGraph::HasEdge(ESSABaseNode &from, ESSABaseNode &to, Ineq return nullptr; } -std::string InequalityGraph::GetName(const MeExpr &meExpr, IRMap &irMap) const { +std::string InequalityGraph::GetName(const MeExpr &meExpr) const { std::string name; MeExprOp meOp = meExpr.GetMeOp(); CHECK_FATAL(meOp == kMeOpVar, "must be VarMeExpr"); @@ -190,7 +190,7 @@ std::string InequalityGraph::GetName(const MeExpr &meExpr, IRMap &irMap) const { return name; } -std::string InequalityGraph::GetName(ESSABaseNode &node, IRMap &irMap) const { +std::string InequalityGraph::GetName(ESSABaseNode &node) const { std::string name; if (node.GetKind() == kConstNode) { return std::to_string((*static_cast(&node)).GetValue()); @@ -243,40 +243,40 @@ std::string InequalityGraph::GetColor(EdgeType type) const { } } -void InequalityGraph::DumpDotEdges(IRMap &irMap, const std::pair &map, +void InequalityGraph::DumpDotEdges(const std::pair &map, std::ostream &out, std::string &from) const { ASSERT_NOT_NULL(map.second); if (map.second->IsVarValue()) { - std::string to = GetName(*(map.first), irMap); + std::string to = GetName(*(map.first)); std::string positive = map.second->GetVarValue().IsPositive() ? "" : "-"; std::string color = GetColor(map.second->GetEdgeType()); out << "\"" << from << "\" -> \"" << to << "\" "; - out << "[label=\"" << positive << GetName(map.second->GetVarValue().GetVarMeExpr(), irMap) + out << "[label=\"" << positive << GetName(map.second->GetVarValue().GetVarMeExpr()) << "\" " << color << "];\n"; } else { - std::string to = GetName(*(map.first), irMap); + std::string to = GetName(*(map.first)); std::string color = GetColor(map.second->GetEdgeType()); out << "\"" << from << "\" -> \"" << to << "\" "; out << "[label=\"" << map.second->GetConstValue() << "\" " << color << "];\n"; } } -void InequalityGraph::DumpDotNodes(IRMap &irMap, std::ostream &out, DumpType dumpType, +void InequalityGraph::DumpDotNodes(std::ostream &out, DumpType dumpType, const std::map> &nodes) const { for (auto iter = nodes.begin(); iter != nodes.end(); ++iter) { - std::string from = GetName(*(iter->second), irMap); + std::string from = GetName(*(iter->second)); out << "\"" << from << "\";\n"; for (auto iterConstEdges = iter->second.get()->GetOutWithConstEdgeMap().begin(); iterConstEdges != iter->second.get()->GetOutWithConstEdgeMap().end(); ++iterConstEdges) { EdgeType edgeType = iterConstEdges->second->GetEdgeType(); if (dumpType == kDumpNone) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } else if ((dumpType == kDumpUpperAndNone) && (edgeType == kUpper || edgeType == kNone || edgeType == kUpperInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } else if ((dumpType == kDumpLowerAndNone) && (edgeType == kLower || edgeType == kNone || edgeType == kLowerInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } } if (iter->second.get()->GetKind() == kPhiNode) { @@ -285,15 +285,15 @@ void InequalityGraph::DumpDotNodes(IRMap &irMap, std::ostream &out, DumpType dum iterConstEdges != phiNode->GetOutPhiEdgeMap().end(); ++iterConstEdges) { EdgeType edgeType = iterConstEdges->second->GetEdgeType(); if (dumpType == kDumpNone) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } else if ((dumpType == kDumpUpperAndNone) && (edgeType == kUpper || edgeType == kNone || edgeType == kUpperInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } else if ((dumpType == kDumpLowerAndNone) && (edgeType == kLower || edgeType == kNone || edgeType == kLowerInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterConstEdges, out, from); + DumpDotEdges(*iterConstEdges, out, from); } } } @@ -301,27 +301,27 @@ void InequalityGraph::DumpDotNodes(IRMap &irMap, std::ostream &out, DumpType dum iterVarEdges != iter->second.get()->GetOutWithVarEdgeMap().end(); ++iterVarEdges) { EdgeType edgeType = iterVarEdges->second->GetEdgeType(); if (dumpType == kDumpNone) { - DumpDotEdges(irMap, *iterVarEdges, out, from); + DumpDotEdges(*iterVarEdges, out, from); } else if ((dumpType == kDumpUpperAndNone) && (edgeType == kUpper || edgeType == kNone || edgeType == kUpperInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterVarEdges, out, from); + DumpDotEdges(*iterVarEdges, out, from); } else if ((dumpType == kDumpLowerAndNone) && (edgeType == kLower || edgeType == kNone || edgeType == kLowerInvalid || edgeType == kNoneInvalid)) { - DumpDotEdges(irMap, *iterVarEdges, out, from); + DumpDotEdges(*iterVarEdges, out, from); } } } } -void InequalityGraph::DumpDotFile(IRMap &irMap, DumpType dumpType) const { +void InequalityGraph::DumpDotFile(DumpType dumpType) const { std::filebuf fileBuf; std::string dumpT = dumpType == kDumpUpperAndNone ? "Upper_" : "Lower_"; std::string outFile = dumpT + meFunction->GetName() + "-inequalityGraph.dot"; fileBuf.open(outFile, std::ios::trunc | std::ios::out); std::ostream essaDotFile(&fileBuf); essaDotFile << "digraph InequalityGraph {\n"; - DumpDotNodes(irMap, essaDotFile, dumpType, constNodes); - DumpDotNodes(irMap, essaDotFile, dumpType, varNodes); + DumpDotNodes(essaDotFile, dumpType, constNodes); + DumpDotNodes(essaDotFile, dumpType, varNodes); essaDotFile << "}\n"; fileBuf.close(); } diff --git a/src/mapleall/maple_me/src/me_ir.cpp b/src/mapleall/maple_me/src/me_ir.cpp old mode 100755 new mode 100644 index 7413c8daae54744c9ee960a876308184938f1146..24f311d9693a86324d76f5585ab4a36fa88f8460 --- a/src/mapleall/maple_me/src/me_ir.cpp +++ b/src/mapleall/maple_me/src/me_ir.cpp @@ -517,7 +517,7 @@ BB *ScalarMeExpr::GetDefByBBMeStmt(const Dominance &dominance, MeStmtPtr &defMeS } } -bool VarMeExpr::IsPureLocal(const SSATab &ssaTab, const MIRFunction &irFunc) const { +bool VarMeExpr::IsPureLocal(const MIRFunction &irFunc) const { const MIRSymbol *st = GetOst()->GetMIRSymbol(); return st->IsLocal() && !irFunc.IsAFormal(st); } @@ -914,7 +914,7 @@ void NaryMeExpr::Dump(const IRMap *irMap, int32 indent) const { } } -MeExpr *DassignMeStmt::GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { +MeExpr *DassignMeStmt::GetLHSRef(bool excludeLocalRefVar) { VarMeExpr *lhsOpnd = GetVarLHS(); if (lhsOpnd->GetPrimType() != PTY_ref) { return nullptr; @@ -929,7 +929,7 @@ MeExpr *DassignMeStmt::GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { return lhsOpnd; } -MeExpr *MaydassignMeStmt::GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { +MeExpr *MaydassignMeStmt::GetLHSRef(bool excludeLocalRefVar) { VarMeExpr *lhs = GetVarLHS(); if (lhs->GetPrimType() != PTY_ref) { return nullptr; @@ -944,7 +944,7 @@ MeExpr *MaydassignMeStmt::GetLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { return lhs; } -MeExpr *IassignMeStmt::GetLHSRef(SSATab&, bool) { +MeExpr *IassignMeStmt::GetLHSRef(bool) { CHECK_FATAL(lhsVar != nullptr, "lhsVar is null"); MIRType *baseType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(lhsVar->GetTyIdx()); ASSERT(baseType != nullptr, "null ptr check"); @@ -982,7 +982,7 @@ MeExpr *IassignMeStmt::GetLHSRef(SSATab&, bool) { return lhsVar; } -VarMeExpr *AssignedPart::GetAssignedPartLHSRef(SSATab &ssaTab, bool excludeLocalRefVar) { +VarMeExpr *AssignedPart::GetAssignedPartLHSRef(bool excludeLocalRefVar) { if (mustDefList.empty()) { return nullptr; } @@ -1392,7 +1392,7 @@ bool VarMeExpr::PointsToStringLiteral() { MeExpr *MeExpr::FindSymAppearance(OStIdx oidx) { if (meOp == kMeOpVar) { - if (static_cast(this)->GetOst()->GetIndex() == oidx) { + if (static_cast(this)->GetOstIdx() == oidx) { return this; } return nullptr; @@ -1446,7 +1446,7 @@ bool MeExpr::IsDexMerge() const { // check if MeExpr can be a pointer to something that requires incref for its // assigned target -bool MeExpr::PointsToSomethingThatNeedsIncRef(SSATab &ssaTab) { +bool MeExpr::PointsToSomethingThatNeedsIncRef() { if (op == OP_retype) { return true; } diff --git a/src/mapleall/maple_me/src/me_irmap.cpp b/src/mapleall/maple_me/src/me_irmap.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/src/me_loop_canon.cpp b/src/mapleall/maple_me/src/me_loop_canon.cpp index 3ed948c1f278d6e8123e5d2200ee38844a78d170..50d4644d19e846f6a50707b28b9a65fb49f10980 100644 --- a/src/mapleall/maple_me/src/me_loop_canon.cpp +++ b/src/mapleall/maple_me/src/me_loop_canon.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -49,7 +49,8 @@ static bool CompareBackedge(const std::pair &a, const std::pairGetBBId() < (b.first)->GetBBId(); } -bool MeDoLoopCanon::NeedConvert(MeFunction *func, BB &bb, BB &pred, MapleAllocator &localAlloc, MapleMap &swapSuccs) const { +bool MeDoLoopCanon::NeedConvert(MeFunction *func, BB &bb, BB &pred, MapleAllocator &localAlloc, + MapleMap &swapSuccs) const { bb.SetAttributes(kBBAttrIsInLoop); pred.SetAttributes(kBBAttrIsInLoop); // do not convert do-while loop diff --git a/src/mapleall/maple_me/src/me_lower_globals.cpp b/src/mapleall/maple_me/src/me_lower_globals.cpp index 105e0881f939214ed84469e31c131399bae55b44..0ff564814f0bcb78fcb98912b26c523eb7a0f70d 100644 --- a/src/mapleall/maple_me/src/me_lower_globals.cpp +++ b/src/mapleall/maple_me/src/me_lower_globals.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_may2dassign.cpp b/src/mapleall/maple_me/src/me_may2dassign.cpp index fe9b55206693ba37b07a9a0617bba4b53f4af73e..635407f37178971dbc08f2ca5e6d92950bff5317 100644 --- a/src/mapleall/maple_me/src/me_may2dassign.cpp +++ b/src/mapleall/maple_me/src/me_may2dassign.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_rc_lowering.cpp b/src/mapleall/maple_me/src/me_rc_lowering.cpp index 6f2bde0eaf15560c8b59a88caaa1fa36cc102cc2..61952f37ca97aac569b80b0608cdd9a0cd3bf0ac 100644 --- a/src/mapleall/maple_me/src/me_rc_lowering.cpp +++ b/src/mapleall/maple_me/src/me_rc_lowering.cpp @@ -71,21 +71,22 @@ void RCLowering::MarkAllRefOpnds() { // to prevent valid_end from being called repeatedly, don't modify the definition of eIt for (auto bIt = func.valid_begin(), eIt = func.valid_end(); bIt != eIt; ++bIt) { for (auto &stmt : (*bIt)->GetMeStmts()) { - MeExpr *lhsRef = stmt.GetLHSRef(ssaTab, false); + MeExpr *lhsRef = stmt.GetLHSRef(false); if (lhsRef == nullptr) { continue; } if (lhsRef->GetMeOp() == kMeOpVar) { auto *var = static_cast(lhsRef); - cleanUpVars[var->GetOst()->GetIndex()] = var; - ssaTab.UpdateVarOstMap(var->GetOst()->GetIndex(), varOStMap); + const OStIdx &ostIdx = var->GetOstIdx(); + cleanUpVars[ostIdx] = var; + ssaTab.UpdateVarOstMap(ostIdx, varOStMap); } stmt.EnableNeedDecref(); MeExpr *rhs = stmt.GetRHS(); if (rhs == nullptr) { continue; } - if (rhs->PointsToSomethingThatNeedsIncRef(ssaTab)) { + if (rhs->PointsToSomethingThatNeedsIncRef()) { stmt.EnableNeedIncref(); } else { stmt.DisableNeedIncref(); @@ -233,7 +234,7 @@ void RCLowering::HandleCallAssignedMeStmt(MeStmt &stmt, MeExpr *pendingDec) { if (lhs->GetMeOp() != kMeOpVar) { return; } - auto *ost = ssaTab.GetOriginalStFromID(static_cast(lhs)->GetOst()->GetIndex()); + auto *ost = static_cast(lhs)->GetOst(); if (!ost->IsSymbolOst()) { return; } @@ -287,7 +288,7 @@ bool RCLowering::RCFirst(MeExpr &rhs) { } if (rhs.GetMeOp() == kMeOpVar) { auto &rhsVar = static_cast(rhs); - const MIRSymbol *sym = ssaTab.GetMIRSymbolFromID(rhsVar.GetOst()->GetIndex()); + const MIRSymbol *sym = rhsVar.GetOst()->GetMIRSymbol(); return sym->IsLocal(); } return rhs.GetMeOp() == kMeOpReg; @@ -335,7 +336,7 @@ void RCLowering::HandleAssignMeStmtRegLHS(MeStmt &stmt) { } void RCLowering::HandleAssignMeStmtVarLHS(MeStmt &stmt, MeExpr *pendingDec) { - const MIRSymbol *lsym = stmt.GetVarLHS()->GetOst()->GetMIRSymbol(); + const MIRSymbol *lsym =stmt.GetVarLHS()->GetOst()->GetMIRSymbol(); if (lsym->IsGlobal()) { // decref could be optimized away after if null check HandleAssignToGlobalVar(stmt); @@ -614,7 +615,7 @@ void RCLowering::BBLower(BB &bb) { needSpecialHandleException = bb.GetAttributes(kBBAttrIsCatch); for (auto &stmt : bb.GetMeStmts()) { if ((func.GetHints() & kAnalyzeRCed) == 0) { - pendingDec = stmt.GetLHSRef(ssaTab, false); + pendingDec = stmt.GetLHSRef(false); } Opcode opcode = stmt.GetOp(); if (opcode == OP_return) { @@ -958,7 +959,7 @@ void RCLowering::ReplaceDecResetWithDec(MeStmt &prevStmt, const MeStmt &stmt) { auto *addrofMeExpr = static_cast(stmt.GetOpnd(0)); ASSERT_NOT_NULL(addrofMeExpr); auto *dass = static_cast(&prevStmt); - if (dass->GetRHS()->GetMeOp() != kMeOpReg || dass->GetVarLHS()->GetOst()->GetIndex() != addrofMeExpr->GetOstIdx()) { + if (dass->GetRHS()->GetMeOp() != kMeOpReg || dass->GetVarLHS()->GetOstIdx() != addrofMeExpr->GetOstIdx()) { return; } BB *bb = stmt.GetBB(); diff --git a/src/mapleall/maple_me/src/me_rename2preg.cpp b/src/mapleall/maple_me/src/me_rename2preg.cpp old mode 100755 new mode 100644 index 69b50d44e9e72fce6e681500638bd2b56d1c6fac..0ab02072248a73cb33d10918dd4ed48cb950d4b7 --- a/src/mapleall/maple_me/src/me_rename2preg.cpp +++ b/src/mapleall/maple_me/src/me_rename2preg.cpp @@ -415,7 +415,7 @@ class SSARename2Preg { return &newRegExpr; } - const AliasElem *GetAliasElem(const AliasClass &aliasClass, OriginalSt &ost) const { + const AliasElem *GetAliasElem(const AliasClass &aliasClass, const OriginalSt &ost) const { if (ost.GetIndex() >= aliasClass.GetAliasElemCount()) { return nullptr; } diff --git a/src/mapleall/maple_me/src/me_ssa.cpp b/src/mapleall/maple_me/src/me_ssa.cpp index 95f5834046ce804ad015c2b6a0b17e5f64acf7d0..e6b596eeaf6f25cd448b63a1ba42d93508acfe36 100644 --- a/src/mapleall/maple_me/src/me_ssa.cpp +++ b/src/mapleall/maple_me/src/me_ssa.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/me_ssa_lpre.cpp b/src/mapleall/maple_me/src/me_ssa_lpre.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/src/me_ssa_update.cpp b/src/mapleall/maple_me/src/me_ssa_update.cpp old mode 100755 new mode 100644 index be3992e620714c0ee882feeca1141fa722bd8bb0..9bc7e93f39614bf48256d4ce0660d9825e52fd9e --- a/src/mapleall/maple_me/src/me_ssa_update.cpp +++ b/src/mapleall/maple_me/src/me_ssa_update.cpp @@ -74,7 +74,8 @@ void MeSSAUpdate::RenamePhi(const BB &bb) { phi->SetIsLive(true); // always make it live, for correctness if (phi->GetLHS() == nullptr) { // create a new VarMeExpr defined by this phi - VarMeExpr *newVar = irMap.CreateNewVarMeExpr(ssaTab.GetOriginalStFromID(it2->first), ssaTab.GetPrimType(it2->first)); + VarMeExpr *newVar = + irMap.CreateNewVarMeExpr(ssaTab.GetOriginalStFromID(it2->first), ssaTab.GetPrimType(it2->first)); phi->UpdateLHS(*newVar); it1->second->push(newVar); // push the stack } else { @@ -89,7 +90,7 @@ MeExpr *MeSSAUpdate::RenameExpr(MeExpr &meExpr, bool &changed) { switch (meExpr.GetMeOp()) { case kMeOpVar: { auto &varExpr = static_cast(meExpr); - auto it = renameStacks.find(varExpr.GetOst()->GetIndex()); + auto it = renameStacks.find(varExpr.GetOstIdx()); if (it == renameStacks.end()) { return &meExpr; } @@ -200,7 +201,7 @@ void MeSSAUpdate::RenameStmts(BB &bb) { continue; } CHECK_FATAL(lhsVar != nullptr, "stmt doesn't have lhs?"); - auto it = renameStacks.find(lhsVar->GetOst()->GetIndex()); + auto it = renameStacks.find(lhsVar->GetOstIdx()); if (it == renameStacks.end()) { continue; } diff --git a/src/mapleall/maple_me/src/me_ssi.cpp b/src/mapleall/maple_me/src/me_ssi.cpp index bd6709df0efeee4d53085be93204a7338fd6354a..e79d526d8ac6430a3d851c935b4e3ef382657f48 100644 --- a/src/mapleall/maple_me/src/me_ssi.cpp +++ b/src/mapleall/maple_me/src/me_ssi.cpp @@ -212,7 +212,7 @@ void MeSSI::InsertPiNodes() { } bool MeSSI::ExistedPhiNode(BB &bb, VarMeExpr &rhs) { - return bb.GetMePhiList().find(rhs.GetOst()->GetIndex()) != bb.GetMePhiList().end(); + return bb.GetMePhiList().find(rhs.GetOstIdx()) != bb.GetMePhiList().end(); } bool MeSSI::ExistedPiNode(BB &bb, BB &parentBB, const VarMeExpr &rhs) { @@ -244,7 +244,7 @@ void MeSSI::CreatePhi(VarMeExpr &rhs, BB &dfBB) { newPhi->SetDefBB(&dfBB); newPhi->GetOpnds().resize(dfBB.GetPred().size(), &rhs); newPhi->SetPiAdded(); - dfBB.GetMePhiList().insert(std::make_pair(phiNewLHS->GetOst()->GetIndex(), newPhi)); + dfBB.GetMePhiList().insert(std::make_pair(phiNewLHS->GetOstIdx(), newPhi)); DefPoint *newDef = GetMemPool()->New(DefPoint::DefineKind::kDefByPhi); newDef->SetDefPhi(*newPhi); newDefPoints.push_back(newDef); @@ -379,7 +379,7 @@ void MeSSI::ReplacePiPhiInSuccs(BB &bb, VarMeExpr &newVar) { } CHECK_FATAL(index < succBB->GetPred().size(), "must be"); MapleMap &phiList = succBB->GetMePhiList(); - auto it2 = phiList.find(newVar.GetOst()->GetIndex()); + auto it2 = phiList.find(newVar.GetOstIdx()); if (it2 != phiList.end()) { MePhiNode *phi = it2->second; ScalarMeExpr *oldVar = phi->GetOpnd(index); @@ -561,17 +561,17 @@ bool MeSSI::ReplaceStmt(MeStmt &meStmt, VarMeExpr &newVar, VarMeExpr &oldVar) { } else { (void)ReplaceStmtWithNewVar(meStmt, oldVar, newVar, true); } - const OStIdx &ostIdx = newVar.GetOst()->GetIndex(); + const OStIdx &ostIdx = newVar.GetOstIdx(); MapleMap *chiList = meStmt.GetChiList(); if (chiList != nullptr && chiList->find(ostIdx) != chiList->end()) { return true; } MeExpr *lhs = meStmt.GetAssignedLHS(); - if (lhs != nullptr && lhs->GetMeOp() == kMeOpVar && static_cast(lhs)->GetOst()->GetIndex() == ostIdx) { + if (lhs != nullptr && lhs->GetMeOp() == kMeOpVar && static_cast(lhs)->GetOstIdx() == ostIdx) { return true; } lhs = meStmt.GetLHS(); - return (lhs != nullptr && lhs->GetMeOp() == kMeOpVar && static_cast(lhs)->GetOst()->GetIndex() == ostIdx); + return (lhs != nullptr && lhs->GetMeOp() == kMeOpVar && static_cast(lhs)->GetOstIdx() == ostIdx); } void MeSSI::Rename() { diff --git a/src/mapleall/maple_me/src/me_stmt_pre.cpp b/src/mapleall/maple_me/src/me_stmt_pre.cpp old mode 100755 new mode 100644 index a9a5e27e5d9ea7ae47f95db372386c513249763d..1f37bf9fb97a7cf74fc35ad59c5cb203971fefdd --- a/src/mapleall/maple_me/src/me_stmt_pre.cpp +++ b/src/mapleall/maple_me/src/me_stmt_pre.cpp @@ -49,7 +49,7 @@ void MeStmtPre::CodeMotion() { realOcc->GetBB()->RemoveMeStmt(realOcc->GetMeStmt()); if (realOcc->GetOpcodeOfMeStmt() == OP_dassign) { auto *dass = static_cast(realOcc->GetMeStmt()); - OStIdx ostIdx = dass->GetVarLHS()->GetOst()->GetIndex(); + OStIdx ostIdx = dass->GetVarLHS()->GetOstIdx(); if (candsForSSAUpdate.find(ostIdx) == candsForSSAUpdate.end()) { candsForSSAUpdate[ostIdx] = ssaPreMemPool->New>(std::less(), ssaPreAllocator.Adapter()); @@ -59,7 +59,7 @@ void MeStmtPre::CodeMotion() { if (call->GetAssignedLHS() != nullptr) { CHECK_FATAL(call->GetAssignedLHS()->GetMeOp() == kMeOpVar, "should be var"); auto *var = static_cast(call->GetAssignedLHS()); - OStIdx ostIdx = var->GetOst()->GetIndex(); + OStIdx ostIdx = var->GetOstIdx(); if (candsForSSAUpdate.find(ostIdx) == candsForSSAUpdate.end()) { candsForSSAUpdate[ostIdx] = ssaPreMemPool->New>(std::less(), ssaPreAllocator.Adapter()); @@ -80,7 +80,7 @@ void MeStmtPre::CodeMotion() { auto *insertedOcc = static_cast(defOcc); if (insertedOcc->GetOpcodeOfMeStmt() == OP_dassign) { auto *dass = static_cast(insertedOcc->GetMeStmt()); - OStIdx ostIdx = dass->GetVarLHS()->GetOst()->GetIndex(); + OStIdx ostIdx = dass->GetVarLHS()->GetOstIdx(); if (candsForSSAUpdate.find(ostIdx) == candsForSSAUpdate.end()) { MapleSet *bbSet = ssaPreMemPool->New>(std::less(), ssaPreAllocator.Adapter()); @@ -98,7 +98,7 @@ void MeStmtPre::CodeMotion() { CHECK_FATAL(call->GetAssignedLHS()->GetMeOp() == kMeOpVar, "should be var"); auto *var = static_cast(call->GetAssignedLHS()); ASSERT_NOT_NULL(var); - OStIdx ostIdx = var->GetOst()->GetIndex(); + OStIdx ostIdx = var->GetOstIdx(); if (candsForSSAUpdate.find(ostIdx) == candsForSSAUpdate.end()) { MapleSet *bbSet = ssaPreMemPool->New>(std::less(), ssaPreAllocator.Adapter()); @@ -537,7 +537,7 @@ void MeStmtPre::CreateSortedOccs() { if ((stmtWkCand->GetTheMeStmt()->GetOp() == OP_dassign || stmtWkCand->GetTheMeStmt()->GetOp() == OP_callassigned) && stmtWkCand->GetTheMeStmt()->GetVarLHS() != nullptr && !stmtWkCand->LHSIsFinal()) { VarMeExpr *lhsVar = stmtWkCand->GetTheMeStmt()->GetVarLHS(); - OStIdx ostIdx = lhsVar->GetOst()->GetIndex(); + OStIdx ostIdx = lhsVar->GetOstIdx(); MapleMap*>::iterator uMapIt = useOccurMap.find(ostIdx); CHECK_FATAL(uMapIt != useOccurMap.end(), "MeStmtPre::CreateSortedOccs: missing entry in useOccurMap"); useDfns = uMapIt->second; @@ -706,7 +706,7 @@ void MeStmtPre::CreateSortedOccs() { void MeStmtPre::ConstructUseOccurMapExpr(uint32 bbDfn, const MeExpr &meExpr) { if (meExpr.GetMeOp() == kMeOpVar) { - OStIdx ostIdx = static_cast(&meExpr)->GetOst()->GetIndex(); + OStIdx ostIdx = static_cast(&meExpr)->GetOstIdx(); MapleMap*>::iterator mapIt; mapIt = useOccurMap.find(ostIdx); if (mapIt == useOccurMap.end()) { @@ -734,7 +734,7 @@ void MeStmtPre::ConstructUseOccurMap() { if (lhsVar == nullptr) { continue; } - OStIdx ostIdx = lhsVar->GetOst()->GetIndex(); + OStIdx ostIdx = lhsVar->GetOstIdx(); if (useOccurMap.find(ostIdx) == useOccurMap.end()) { // add an entry for ostIdx useOccurMap[ostIdx] = ssaPreMemPool->New>(ssaPreAllocator.Adapter()); @@ -766,7 +766,7 @@ PreStmtWorkCand *MeStmtPre::CreateStmtRealOcc(MeStmt &meStmt, int seqStmt) { } MeExpr *meExpr = nullptr; if ((meStmt.GetOp() == OP_dassign || meStmt.GetOp() == OP_callassigned) && meStmt.GetVarLHS() != nullptr) { - MapleStack *pStack = versionStackVec.at(meStmt.GetVarLHS()->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(meStmt.GetVarLHS()->GetOstIdx()); meExpr = pStack->top(); } MeRealOcc *newOcc = ssaPreMemPool->New(&meStmt, seqStmt, meExpr); @@ -791,7 +791,7 @@ void MeStmtPre::VersionStackChiListUpdate(const MapleMap &ch if (!ost->IsSymbolOst() || ost->GetIndirectLev() != 0) { continue; } - MapleStack *pStack = versionStackVec.at(it->second->GetLHS()->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(it->second->GetLHS()->GetOstIdx()); pStack->push(it->second->GetLHS()); } } @@ -801,7 +801,7 @@ static bool NoPriorUseInBB(const VarMeExpr *lhsVar, MeStmt *defStmt) { for (MeStmt *stmt = defStmt->GetPrev(); stmt != nullptr; stmt = stmt->GetPrev()) { for (size_t i = 0; i < stmt->NumMeStmtOpnds(); ++i) { CHECK_FATAL(stmt->GetOpnd(i) != nullptr, "null ptr check"); - if (stmt->GetOpnd(i)->SymAppears(lhsVar->GetOst()->GetIndex())) { + if (stmt->GetOpnd(i)->SymAppears(lhsVar->GetOstIdx())) { return false; } } @@ -830,7 +830,7 @@ void MeStmtPre::BuildWorkListBB(BB *bb) { if (!ost->IsSymbolOst() || ost->GetIndirectLev() != 0) { continue; } - MapleStack *pStack = versionStackVec.at(phiMeNode->GetLHS()->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(phiMeNode->GetLHS()->GetOstIdx()); pStack->push(phiMeNode->GetLHS()); } // traverse statements @@ -932,7 +932,7 @@ void MeStmtPre::BuildWorkListBB(BB *bb) { (dassMeStmt.GetRHS()->GetOp() == OP_regread && static_cast(dassMeStmt.GetRHS())->GetRegIdx() == -kSregThrownval)) { // update version stacks - MapleStack *pStack = versionStackVec.at(dassMeStmt.GetVarLHS()->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(dassMeStmt.GetVarLHS()->GetOstIdx()); pStack->push(dassMeStmt.GetVarLHS()); VersionStackChiListUpdate(*dassMeStmt.GetChiList()); break; @@ -942,7 +942,7 @@ void MeStmtPre::BuildWorkListBB(BB *bb) { if (ost->IsFinal()) { PreStmtWorkCand *stmtWkCand = CreateStmtRealOcc(stmt, seqStmt); stmtWkCand->SetLHSIsFinal(true); - } else if (!dassMeStmt.GetRHS()->SymAppears(varMeExpr->GetOst()->GetIndex()) && dassMeStmt.GetRHS()->Pure()) { + } else if (!dassMeStmt.GetRHS()->SymAppears(varMeExpr->GetOstIdx()) && dassMeStmt.GetRHS()->Pure()) { if (NoPriorUseInBB(dassMeStmt.GetVarLHS(), &stmt)) { (void)CreateStmtRealOcc(stmt, static_cast(seqStmt)); } @@ -950,7 +950,7 @@ void MeStmtPre::BuildWorkListBB(BB *bb) { RemoveUnnecessaryDassign(dassMeStmt); } // update version stacks - MapleStack *pStack = versionStackVec.at(dassMeStmt.GetVarLHS()->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(dassMeStmt.GetVarLHS()->GetOstIdx()); pStack->push(dassMeStmt.GetVarLHS()); VersionStackChiListUpdate(*dassMeStmt.GetChiList()); break; @@ -1001,7 +1001,7 @@ void MeStmtPre::BuildWorkListBB(BB *bb) { MeExpr *meLHS = mustDefList->front().GetLHS(); if (meLHS->GetMeOp() == kMeOpVar) { auto *lhsVar = static_cast(meLHS); - MapleStack *pStack = versionStackVec.at(lhsVar->GetOst()->GetIndex()); + MapleStack *pStack = versionStackVec.at(lhsVar->GetOstIdx()); pStack->push(lhsVar); } } @@ -1047,7 +1047,7 @@ void MeStmtPre::BuildWorkList() { void MeStmtPre::RemoveUnnecessaryDassign(DassignMeStmt &dssMeStmt) { BB *bb = dssMeStmt.GetBB(); bb->RemoveMeStmt(&dssMeStmt); - OStIdx ostIdx = dssMeStmt.GetVarLHS()->GetOst()->GetIndex(); + OStIdx ostIdx = dssMeStmt.GetVarLHS()->GetOstIdx(); MapleSet *bbSet = nullptr; if (candsForSSAUpdate.find(ostIdx) == candsForSSAUpdate.end()) { bbSet = ssaPreMemPool->New>(std::less(), ssaPreAllocator.Adapter()); diff --git a/src/mapleall/maple_me/src/me_store_pre.cpp b/src/mapleall/maple_me/src/me_store_pre.cpp old mode 100755 new mode 100644 index a348e50619fcf59b7954ae4f0868b3c8abd7a34e..3977cee6ca98e89f8ccde92223d5cf7341a5d6c5 --- a/src/mapleall/maple_me/src/me_store_pre.cpp +++ b/src/mapleall/maple_me/src/me_store_pre.cpp @@ -117,7 +117,7 @@ RegMeExpr *MeStorePre::EnsureRHSInCurTemp(BB &bb) { regPhi->GetOpnds().push_back(regPhiOpnd); } // insert the regPhi - (void)bb.GetMePhiList().insert(std::make_pair(lhsReg->GetOst()->GetIndex(), regPhi)); + (void)bb.GetMePhiList().insert(std::make_pair(lhsReg->GetOstIdx(), regPhi)); return lhsReg; } // continue at immediate dominator @@ -198,7 +198,7 @@ void MeStorePre::CreateRealOcc(const OStIdx &ostIdx, MeStmt &meStmt) { if (mapIt != workCandMap.end()) { wkCand = mapIt->second; } else { - const OriginalSt *ost = ssaTab->GetSymbolOriginalStFromID(ostIdx); + OriginalSt *ost = ssaTab->GetSymbolOriginalStFromID(ostIdx); wkCand = spreMp->New(spreAllocator, *ost); workCandMap[ostIdx] = wkCand; // if it is local symbol, insert artificial real occ at common_exit_bb @@ -263,7 +263,7 @@ void MeStorePre::FindAndCreateSpreUseOccs(const MeExpr &meExpr, BB &bb) const { auto *var = static_cast(&meExpr); const OriginalSt *ost = var->GetOst(); if (!ost->IsVolatile()) { - CreateUseOcc(var->GetOst()->GetIndex(), bb); + CreateUseOcc(var->GetOstIdx(), bb); } return; } @@ -308,7 +308,7 @@ void MeStorePre::BuildWorkListBB(BB *bb) { if (stmt->GetOp() == OP_dassign) { auto *dass = static_cast(to_ptr(stmt)); if (dass->GetLHS()->GetPrimType() != PTY_ref) { - lhsOstIdx = dass->GetVarLHS()->GetOst()->GetIndex(); + lhsOstIdx = dass->GetVarLHS()->GetOstIdx(); } } else if (kOpcodeInfo.IsCallAssigned(stmt->GetOp())) { MapleVector *mustDefList = stmt->GetMustDefList(); @@ -316,7 +316,7 @@ void MeStorePre::BuildWorkListBB(BB *bb) { if (!mustDefList->empty()) { MeExpr *mdLHS = mustDefList->front().GetLHS(); if (mdLHS->GetMeOp() == kMeOpVar && mdLHS->GetPrimType() != PTY_ref) { - lhsOstIdx = static_cast(mdLHS)->GetOst()->GetIndex(); + lhsOstIdx = static_cast(mdLHS)->GetOstIdx(); } } } diff --git a/src/mapleall/maple_me/src/occur.cpp b/src/mapleall/maple_me/src/occur.cpp old mode 100755 new mode 100644 index 39d8470e92a2a3cbeef841236b322d2b18f87219..52aa54ccbe0888a074f5b6b9fec16231df306c9e --- a/src/mapleall/maple_me/src/occur.cpp +++ b/src/mapleall/maple_me/src/occur.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -214,7 +214,7 @@ uint32 PreWorkCandHashTable::ComputeWorkCandHashIndex(const MeExpr &meExpr) { break; case kMeOpVar: { auto &varMeExpr = static_cast(meExpr); - hashIdx = static_cast(varMeExpr.GetOst()->GetIndex()) << kOffsetVarMeExprOstIdx; + hashIdx = static_cast(varMeExpr.GetOstIdx()) << kOffsetVarMeExprOstIdx; break; } case kMeOpReg: { @@ -324,7 +324,7 @@ uint32 PreWorkCandHashTable::ComputeStmtWorkCandHashIndex(const MeStmt &stmt) { CHECK_NULL_FATAL(stmt.GetVarLHS()); CHECK_NULL_FATAL(stmt.GetRHS()); VarMeExpr *varMeExpr = stmt.GetVarLHS(); - hIdx += static_cast(varMeExpr->GetOst()->GetIndex()) << kOffsetVarMeExprOstIdx; + hIdx += static_cast(varMeExpr->GetOstIdx()) << kOffsetVarMeExprOstIdx; hIdx += ComputeWorkCandHashIndex(*stmt.GetRHS()) << 1; break; } @@ -349,7 +349,7 @@ uint32 PreWorkCandHashTable::ComputeStmtWorkCandHashIndex(const MeStmt &stmt) { if (!callAss.GetMustDefList().empty()) { const MeExpr *lhs = callAss.GetMustDefList().front().GetLHS(); auto *lhsVar = static_cast(lhs); - hIdx += static_cast(lhsVar->GetOst()->GetIndex()) << 1; + hIdx += static_cast(lhsVar->GetOstIdx()) << 1; } break; } diff --git a/src/mapleall/maple_me/src/preg_renamer.cpp b/src/mapleall/maple_me/src/preg_renamer.cpp old mode 100755 new mode 100644 diff --git a/src/mapleall/maple_me/src/prop.cpp b/src/mapleall/maple_me/src/prop.cpp old mode 100755 new mode 100644 index f11d89d2fe2fc6a4f018baa569af4587ef7890f9..e91bcdccc8ad9bf95eec5bffcbd04c672e40b002 --- a/src/mapleall/maple_me/src/prop.cpp +++ b/src/mapleall/maple_me/src/prop.cpp @@ -227,13 +227,13 @@ void Prop::PropUpdateDef(MeExpr &meExpr) { ASSERT(meExpr.GetMeOp() == kMeOpVar || meExpr.GetMeOp() == kMeOpReg, "meExpr error"); OStIdx ostIdx; if (meExpr.GetMeOp() == kMeOpVar) { - ostIdx = static_cast(meExpr).GetOst()->GetIndex(); + ostIdx = static_cast(meExpr).GetOstIdx(); } else { auto ®Expr = static_cast(meExpr); if (!regExpr.IsNormalReg()) { return; } - ostIdx = regExpr.GetOst()->GetIndex(); + ostIdx = regExpr.GetOstIdx(); } vstLiveStackVec.at(ostIdx).push(meExpr); } @@ -277,9 +277,9 @@ bool Prop::IsVersionConsistent(const std::vector &vstVec, CHECK_FATAL(subExpr->GetMeOp() == kMeOpVar || subExpr->GetMeOp() == kMeOpReg, "error: sub expr error"); uint32 stackIdx = 0; if (subExpr->GetMeOp() == kMeOpVar) { - stackIdx = static_cast(subExpr)->GetOst()->GetIndex(); + stackIdx = static_cast(subExpr)->GetOstIdx(); } else { - stackIdx = static_cast(subExpr)->GetOst()->GetIndex(); + stackIdx = static_cast(subExpr)->GetOstIdx(); } auto &pStack = vstLiveStack.at(stackIdx); if (pStack.empty()) { diff --git a/src/mapleall/maple_me/src/ssa.cpp b/src/mapleall/maple_me/src/ssa.cpp index eb91957b1e62b0a8dd5a81ef827aed0b610ba758..79223c5042f9d7d1c9228aa89ad8eb90b4b36ff0 100644 --- a/src/mapleall/maple_me/src/ssa.cpp +++ b/src/mapleall/maple_me/src/ssa.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2019-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. diff --git a/src/mapleall/maple_me/src/ssa_devirtual.cpp b/src/mapleall/maple_me/src/ssa_devirtual.cpp index 4cb2d0ddda8502260706546c9cb9564707f862c5..6e88723455b3da3d12dbcc4dcc3ad3254bb07670 100644 --- a/src/mapleall/maple_me/src/ssa_devirtual.cpp +++ b/src/mapleall/maple_me/src/ssa_devirtual.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -351,7 +351,7 @@ void SSADevirtual::VisitVarPhiNode(MePhiNode &varPhi) { auto mapit = inferredTypeCandidatesMap.find(lhsVar->GetExprID()); if (mapit == inferredTypeCandidatesMap.end()) { - MapleVector *tyIdxCandidates = devirtualAlloc.GetMemPool()->New>(devirtualAlloc.Adapter()); + auto tyIdxCandidates = devirtualAlloc.GetMemPool()->New>(devirtualAlloc.Adapter()); inferredTypeCandidatesMap[lhsVar->GetExprID()] = tyIdxCandidates; } MapleVector &inferredTypeCandidates = *inferredTypeCandidatesMap[lhsVar->GetExprID()]; diff --git a/src/mapleall/maple_me/src/ssa_epre.cpp b/src/mapleall/maple_me/src/ssa_epre.cpp old mode 100755 new mode 100644 index 3bd6217a81c2a88bda816a035e548cae9e52134d..a2cc61a99fb29dd32cbcf7db1ccf6f4c21ca6811 --- a/src/mapleall/maple_me/src/ssa_epre.cpp +++ b/src/mapleall/maple_me/src/ssa_epre.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -65,7 +65,7 @@ void SSAEPre::GenerateSaveLHSRealocc(MeRealOcc &realOcc, MeExpr ®OrVar) { rass = irMap->CreateRegassignMeStmt(regOrVar, *localRefVar, *savedBB); regOrVar.SetDefByStmt(*rass); savedBB->InsertMeStmtAfter(dass, rass); - EnterCandsForSSAUpdate(localRefVar->GetOst()->GetIndex(), *savedBB); + EnterCandsForSSAUpdate(localRefVar->GetOstIdx(), *savedBB); } // create new iassign for original lhs IassignMeStmt *newIass = irMap->NewInPool(savedTyIdx, theLHS, ®OrVar, &savedChiList); @@ -115,7 +115,7 @@ void SSAEPre::GenerateSaveRealOcc(MeRealOcc &realOcc) { newMeStmt = irMap->CreateRegassignMeStmt(*regOrVar, *localRefVar, *realOcc.GetMeStmt()->GetBB()); regOrVar->SetDefByStmt(*newMeStmt); realOcc.GetMeStmt()->GetBB()->InsertMeStmtBefore(realOcc.GetMeStmt(), newMeStmt); - EnterCandsForSSAUpdate(localRefVar->GetOst()->GetIndex(), *realOcc.GetMeStmt()->GetBB()); + EnterCandsForSSAUpdate(localRefVar->GetOstIdx(), *realOcc.GetMeStmt()->GetBB()); } // replace realOcc->GetMeStmt()'s occ with regOrVar bool isReplaced = irMap->ReplaceMeExprStmt(*realOcc.GetMeStmt(), *realOcc.GetMeExpr(), *regOrVar); diff --git a/src/mapleall/maple_me/src/ssa_pre.cpp b/src/mapleall/maple_me/src/ssa_pre.cpp old mode 100755 new mode 100644 index 682c8b25a4c417952f8c47985034e6d5c997f50d..3c4961fa91bb9d9e6564cd2ada64f626ec00e77a --- a/src/mapleall/maple_me/src/ssa_pre.cpp +++ b/src/mapleall/maple_me/src/ssa_pre.cpp @@ -80,7 +80,7 @@ MeExpr *SSAPre::CreateNewCurTemp(const MeExpr &meExpr) { } curTemp = regVar; if (preKind == kLoadPre) { - irMap->SetLpreTmps(static_cast(&meExpr)->GetOst()->GetIndex(), *regVar); + irMap->SetLpreTmps(static_cast(&meExpr)->GetOstIdx(), *regVar); } return regVar; } else { @@ -104,7 +104,7 @@ VarMeExpr *SSAPre::CreateNewCurLocalRefVar() { FieldID fieldID = ivarMeExpr->GetFieldID(); curLocalRefVar = irMap->CreateNewLocalRefVarTmp(NewTempStrIdx(), realMIRType->GetPointedTyIdxWithFieldID(fieldID)); ASSERT_NOT_NULL(curLocalRefVar); - ssaTab->SetEPreLocalRefVar(curLocalRefVar->GetOst()->GetIndex(), true); + ssaTab->SetEPreLocalRefVar(curLocalRefVar->GetOstIdx(), true); SetAddedNewLocalRefVars(true); return curLocalRefVar; } @@ -132,7 +132,7 @@ void SSAPre::GenerateSaveInsertedOcc(MeInsertedOcc &insertedOcc) { newMeStmt = irMap->CreateDassignMeStmt(*localRefVar, *insertedOcc.GetMeExpr(), *insertedOcc.GetBB()); localRefVar->SetDefByStmt(*newMeStmt); insertedOcc.GetBB()->InsertMeStmtLastBr(newMeStmt); - EnterCandsForSSAUpdate(localRefVar->GetOst()->GetIndex(), *insertedOcc.GetBB()); + EnterCandsForSSAUpdate(localRefVar->GetOstIdx(), *insertedOcc.GetBB()); newMeStmt = irMap->CreateRegassignMeStmt(*regOrVar, *localRefVar, *insertedOcc.GetBB()); regOrVar->SetDefByStmt(*newMeStmt); insertedOcc.GetBB()->InsertMeStmtLastBr(newMeStmt); @@ -167,7 +167,7 @@ void SSAPre::GenerateSavePhiOcc(MePhiOcc &phiOcc) { phiVar->SetDefBB(phiOcc.GetBB()); phiOcc.SetVarPhi(*phiVar); // update the phi opnds later - EnterCandsForSSAUpdate(localRefVar->GetOst()->GetIndex(), *phiOcc.GetBB()); + EnterCandsForSSAUpdate(localRefVar->GetOstIdx(), *phiOcc.GetBB()); } } @@ -188,7 +188,7 @@ void SSAPre::UpdateInsertedPhiOccOpnd() { } phiReg->GetOpnds().push_back(regOpnd); } - (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiReg->GetOpnd(0)->GetOst()->GetIndex(), phiReg)); + (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiReg->GetOpnd(0)->GetOstIdx(), phiReg)); if (workCand->NeedLocalRefVar() && phiOcc->GetVarPhi() != nullptr) { MePhiNode *phiVar = phiOcc->GetVarPhi(); for (MePhiOpndOcc *phiOpnd : phiOcc->GetPhiOpnds()) { @@ -211,7 +211,7 @@ void SSAPre::UpdateInsertedPhiOccOpnd() { } phiVar->GetOpnds().push_back(localRefVarOpnd); } - (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiVar->GetOpnd(0)->GetOst()->GetIndex(), phiVar)); + (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiVar->GetOpnd(0)->GetOstIdx(), phiVar)); } } else { MePhiNode *phiVar = phiOcc->GetVarPhi(); @@ -223,7 +223,7 @@ void SSAPre::UpdateInsertedPhiOccOpnd() { } phiVar->GetOpnds().push_back(varOpnd); } - (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiVar->GetOpnd(0)->GetOst()->GetIndex(), phiVar)); + (void)phiOcc->GetBB()->GetMePhiList().insert(std::make_pair(phiVar->GetOpnd(0)->GetOstIdx(), phiVar)); } } } @@ -1169,7 +1169,7 @@ bool SSAPre::DefVarDominateOcc(const MeExpr *meExpr, const MeOccur &meOcc) const switch (varMeExpr->GetDefBy()) { case kDefByNo: // zero version vst dominate everything - return ssaTab->IsInitVersion(varMeExpr->GetVstIdx(), varMeExpr->GetOst()->GetIndex()); + return ssaTab->IsInitVersion(varMeExpr->GetVstIdx(), varMeExpr->GetOstIdx()); case kDefByStmt: { MeStmt *meStmt = varMeExpr->GetDefStmt(); CHECK_FATAL(meStmt != nullptr, "should have a def meStmt"); diff --git a/src/mapleall/maple_util/include/mpl_logging.h b/src/mapleall/maple_util/include/mpl_logging.h index 07ddc91be55c44447db545915b612fc29b0fdb04..1300262ab4cfed6f137af1423286439c3458cd6f 100644 --- a/src/mapleall/maple_util/include/mpl_logging.h +++ b/src/mapleall/maple_util/include/mpl_logging.h @@ -203,6 +203,9 @@ class LogInfo { } \ } while (0) +#ifdef LOG +#undef LOG +#endif #define LOG(tag, fmt, ...) \ do { \ if (PRINT_LEVEL_DEV <= kLlLog) { \ @@ -210,6 +213,9 @@ class LogInfo { } \ } while (0) +#ifdef CHECK +#undef CHECK +#endif #define CHECK(cond, fmt, ...) \ do { \ if (!(cond)) { \ @@ -217,6 +223,9 @@ class LogInfo { } \ } while (0) +#ifdef DCHECK +#undef DCHECK +#endif #define DCHECK(cond, fmt, ...) \ do { \ DEBUG_STMT(CHECK(cond, fmt, ##__VA_ARGS__)); \ diff --git a/src/mapleall/mpl2mpl/BUILD.gn b/src/mapleall/mpl2mpl/BUILD.gn old mode 100644 new mode 100755 diff --git a/src/mapleall/mpl2mpl/src/reflection_analysis.cpp b/src/mapleall/mpl2mpl/src/reflection_analysis.cpp old mode 100755 new mode 100644 index 5ca55d7c60e092923fe0c062a058581c90ecabe0..58d0ae179c7d0c1b0446bde1777f2cd4ad45c81a --- a/src/mapleall/mpl2mpl/src/reflection_analysis.cpp +++ b/src/mapleall/mpl2mpl/src/reflection_analysis.cpp @@ -12,6 +12,7 @@ * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ + #include "reflection_analysis.h" #include #include diff --git a/src/mplfe/BUILD.gn b/src/mplfe/BUILD.gn index 9ff431a1b17a1d7f0775de814638398c8aa1c6dc..313deefbbf3e00f53ed042d3d030e4cf478a1b4a 100644 --- a/src/mplfe/BUILD.gn +++ b/src/mplfe/BUILD.gn @@ -17,9 +17,16 @@ if (COV_CHECK == 1) { cflags = [ "-DENABLE_COV_CHECK=1" ] } +cflags += [ + "-DMIR_FEATURE_FULL=1", + "-DMPLFE_FULL_INFO_DUMP=1", +] + include_directories = [ "${MPLFE_ROOT}/common/include", "${MPLFE_ROOT}/jbc_input/include", + "${MPLFE_ROOT}/bc_input/include", + "${MPLFE_ROOT}/dex_input/include", "${MAPLEALL_ROOT}/maple_ir/include", "${MAPLEALL_ROOT}/maple_ipa/include", "${MAPLEALL_ROOT}/maple_util/include", @@ -90,6 +97,8 @@ executable("mplfe") { deps = [ ":lib_mplfe_input", ":lib_mplfe_jbc_input", + ":lib_mplfe_bc_input", + ":lib_mplfe_dex_input", ":lib_mplfe_util", "${MAPLE_ROOT}/third_party/bounds_checking_function:libHWSecureC", "${MAPLEALL_ROOT}/maple_driver:libdriver_option", @@ -134,3 +143,94 @@ static_library("lib_mplfe_jbc_input") { include_dirs = include_jbc_input_directories output_dir = "${root_out_dir}/ar" } + +include_bc_input_directories = [ + "${MPLFE_ROOT}/common/include", + "${MPLFE_ROOT}/bc_input/include", + "${MPLFE_ROOT}/dex_input/include", + "${MAPLEALL_ROOT}/maple_ir/include", + "${MAPLEALL_ROOT}/maple_util/include", + "${MAPLEALL_ROOT}/maple_driver/include", + "${MAPLEALL_ROOT}/mempool/include", + "${MAPLE_ROOT}/third_party/bounds_checking_function/include", +] + +static_library("lib_mplfe_bc_input") { + sources = [ + "${MPLFE_ROOT}/bc_input/src/bc_io.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_parser_base.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_class.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_function.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_class2fe_helper.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_util.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_instruction.cpp", + "${MPLFE_ROOT}/bc_input/src/ark_annotation_map.cpp", + "${MPLFE_ROOT}/bc_input/src/ark_annotation_processor.cpp", + "${MPLFE_ROOT}/bc_input/src/bc_pragma.cpp", + ] + include_dirs = include_bc_input_directories + output_dir = "${root_out_dir}/ar" +} + +include_dex_input_directories = [ + "${MPLFE_ROOT}/common/include", + "${MPLFE_ROOT}/bc_input/include", + "${MPLFE_ROOT}/dex_input/include", + "${MAPLEALL_ROOT}/maple_ir/include", + "${MAPLEALL_ROOT}/maple_util/include", + "${MAPLEALL_ROOT}/maple_driver/include", + "${MAPLEALL_ROOT}/mempool/include", + "${MAPLE_ROOT}/third_party/bounds_checking_function/include", +] + +static_library("lib_mplfe_dex_input") { + sources = [ + "${MPLFE_ROOT}/dex_input/src/dex_class.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_class2fe_helper.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_file_util.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_op.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_strfac.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_pragma.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_encode_value.cpp", + "${MPLFE_ROOT}/dex_input/src/class_loader_context.cpp", + "${MPLFE_ROOT}/dex_input/src/class_linker.cpp", + ] + + # for libdexfile + include_dirs_dex = [ + "${AOSP_ROOT}/system/core/include", + ] + include_dirs_libdexfile = [ + #for libdexfile -start + "${AOSP_ROOT}/system/core/liblog/include", + "${AOSP_ROOT}/system/core/libutils/include", + "${AOSP_ROOT}/system/core/base/include", + "${AOSP_ROOT}/system/core/libziparchive/include", + "${AOSP_ROOT}/art/libartpalette/include", + "${AOSP_ROOT}/art/libartbase", + "${AOSP_ROOT}/art/libdexfile", + "${AOSP_ROOT}/include", + "${AOSP_ROOT}/libnativehelper/include_jni", + #for libdexfile -end + ] + + sources += [ + "${MPLFE_ROOT}/dex_input/src/dex_parser.cpp", + "${MPLFE_ROOT}/dex_input/src/dex_reader.cpp", + "${MPLFE_ROOT}/dex_input/src/dexfile_interface.cpp", + "${MPLFE_ROOT}/dex_input/src/dexfile_factory.cpp", + "${MPLFE_ROOT}/dex_input/src/dexfile_libdexfile.cpp", + ] + deps_libdexfile = [ + "${AOSP_ROOT}/art/libdexfile:libdexfile", + "${AOSP_ROOT}/system/core/libziparchive:libziparchive", + "${AOSP_ROOT}/system/core/base:libbase", + ] + lib_dex = [ + "${AOSP_ROOT}/system/core/liblog/liblog.a", + ] + deps = deps_libdexfile + libs = lib_dex + include_dirs = include_dex_input_directories + include_dirs_libdexfile + include_dirs_dex + output_dir = "${root_out_dir}/ar" +} diff --git a/src/mplfe/bc_input/include/ark_annotation_map.h b/src/mplfe/bc_input/include/ark_annotation_map.h new file mode 100644 index 0000000000000000000000000000000000000000..cb3c9906948e6ca8b90e452810ca908fdfc52194 --- /dev/null +++ b/src/mplfe/bc_input/include/ark_annotation_map.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_MAP_H +#define MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_MAP_H +#include +#include "global_tables.h" + +namespace maple { +namespace bc { +class ArkAnnotationMap { + public: + inline static ArkAnnotationMap &GetArkAnnotationMap() { + return annotationMap; + } + + void Init(); + const std::string &GetAnnotationTypeName(const std::string &orinName); + const std::set &GetArkAnnotationTypeNames() const { + return arkAnnotationTypeNames; + } + + private: + ArkAnnotationMap() = default; + ~ArkAnnotationMap() = default; + + static ArkAnnotationMap annotationMap; + std::map pragmaTypeNameMap; + std::set arkAnnotationTypeNames; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_MAP_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/ark_annotation_processor.h b/src/mplfe/bc_input/include/ark_annotation_processor.h new file mode 100644 index 0000000000000000000000000000000000000000..2d3842a4424b23c2eeda7a3cc328e76320f1f24b --- /dev/null +++ b/src/mplfe/bc_input/include/ark_annotation_processor.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_PROCESSOR_H +#define MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_PROCESSOR_H +#include "global_tables.h" +#include "namemangler.h" +namespace maple { +namespace bc { +class ArkAnnotationProcessor { + public: + static void Process(); +}; + +class ArkAnnotation { + public: + void Init(); + bool IsFastNative(TyIdx tyIdx); + bool IsCriticalNative(TyIdx tyIdx); + bool IsCallerSensitive(TyIdx tyIdx); + static ArkAnnotation &GetInstance() { + return instance; + } + + static GStrIdx GetStrIdxFromDexName(const std::string &name) { + return GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(name)); + } + + private: + ArkAnnotation() = default; + ~ArkAnnotation() = default; + MIRStructType *GetStructType(TyIdx tyIdx); + + static ArkAnnotation instance; + std::set typeNameSetForFastNative; + std::set typeNameSetForCriticalNative; + std::set typeNameSetForCallerSensitive; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_ARK_ANNOTATION_PROCESSOR_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_class.h b/src/mplfe/bc_input/include/bc_class.h new file mode 100644 index 0000000000000000000000000000000000000000..2b35fc93a926d6eb9c332e492daf02e4cd0a8718 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_class.h @@ -0,0 +1,338 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_CLASS_H +#define MPLFE_BC_INPUT_INCLUDE_BC_CLASS_H +#include +#include +#include +#include +#include "types_def.h" +#include "bc_instruction.h" +#include "feir_stmt.h" +#include "bc_parser_base.h" +#include "feir_var.h" +#include "mempool.h" +#include "bc_pragma.h" +namespace maple { +namespace bc { +using BCAttrKind = uint32; +class BCClass; + +class BCAttr { + public: + BCAttr(BCAttrKind k, const GStrIdx &idx) : kind(k), nameIdx(idx) {} + ~BCAttr() = default; + + protected: + BCAttrKind kind; + GStrIdx nameIdx; +}; + +class BCAttrMap { + public: + BCAttrMap() = default; + ~BCAttrMap() = default; + + protected: + std::map>>> mapAttrs; +}; + +class BCClassElem { + public: + BCClassElem(const BCClass &klassIn, uint32 acc, const std::string &nameIn, const std::string &descIn); + virtual ~BCClassElem() = default; + const std::string &GetName() const; + const std::string &GetDescription() const; + uint32 GetItemIdx() const; + uint32 GetIdx() const; + uint32 GetAccessFlag() const; + bool IsStatic() const; + const std::string &GetClassName() const; + const BCClass &GetBCClass() const; + GStrIdx GetClassNameMplIdx() const; + + protected: + virtual uint32 GetItemIdxImpl() const = 0; + virtual uint32 GetIdxImpl() const = 0; + virtual bool IsStaticImpl() const = 0; + const BCClass &klass; + uint32 accessFlag; + std::string name; + std::string descriptor; + BCAttrMap attrMap; +}; + +class BCClassField : public BCClassElem { + public: + BCClassField(const BCClass &klassIn, uint32 acc, const std::string &nameIn, const std::string &descIn) + : BCClassElem(klassIn, acc, nameIn, descIn) {} + ~BCClassField() = default; + + protected: + uint32 GetItemIdxImpl() const override = 0; + uint32 GetIdxImpl() const override = 0; +}; + +class BCCatchInfo { + public: + BCCatchInfo(uint32 handlerAddrIn, const GStrIdx &argExceptionNameIdx, bool isCatchAllIn); + ~BCCatchInfo() = default; + + uint32 GetHandlerAddr() const { + return handlerAddr; + } + + GStrIdx GetExceptionNameIdx() const { + return exceptionNameIdx; + } + + bool GetIsCatchAll() const { + return isCatchAll; + } + + protected: + uint32 handlerAddr; + GStrIdx exceptionNameIdx; + bool isCatchAll = false; +}; + +class BCTryInfo { + public: + BCTryInfo(uint32 startAddrIn, uint32 endAddrIn, std::unique_ptr>> catchesIn) + : startAddr(startAddrIn), endAddr(endAddrIn), catches(std::move(catchesIn)) {} + ~BCTryInfo() = default; + + uint32 GetStartAddr() const { + return startAddr; + } + + uint32 GetEndAddr() const { + return endAddr; + } + + const std::list> *GetCatches() const { + return catches.get(); + } + static void DumpTryCatchInfo(const std::unique_ptr>> &tryInfos); + + protected: + uint32 startAddr; + uint32 endAddr; + std::unique_ptr>> catches; +}; + +class BCClassMethod : public BCClassElem { + public: + BCClassMethod(const BCClass &klassIn, uint32 acc, bool isVirtualIn, const std::string &nameIn, + const std::string &descIn) + : BCClassElem(klassIn, acc, nameIn, descIn), isVirtual(isVirtualIn), + methodMp(memPoolCtrler.NewMemPool("MemPool for BCClassMethod")), + allocator(methodMp) {} + ~BCClassMethod() { + if (methodMp != nullptr) { + delete methodMp; + methodMp = nullptr; + } + } + void SetPCBCInstructionMap(MapleMap *mapIn) { + pcBCInstructionMap = mapIn; + } + void SetMethodInstOffset(const uint16 *pos); + void SetRegisterTotalSize(uint16 size); + uint16 GetRegisterTotalSize() const; + void SetRegisterInsSize(uint16 size); + void AddMethodDepSet(const std::string &depType); + bool IsVirtual() const; + bool IsNative() const; + bool IsInit() const; + bool IsClinit() const; + std::string GetFullName() const; + void ProcessInstructions(); + std::list EmitInstructionsToFEIR() const; + const uint16 *GetInstPos() const; + + void SetTryInfos(std::unique_ptr>> infos) { + tryInfos = std::move(infos); + } + + uint16 GetTriesSize() const { + return tryInfos->size(); + } + + uint32 GetThisRegNum() const { + return IsStatic() ? UINT32_MAX : static_cast(registerTotalSize - registerInsSize); + } + + void SetSrcPositionInfo(const std::map &srcPosInfo) { +#ifdef DEBUG + pSrcPosInfo = &srcPosInfo; +#endif + } + + std::vector> GenArgVarList() const; + void GenArgRegs(); + std::vector GetSigTypeNames() const { + return sigTypeNames; + } + bool HasCode() const { + return pcBCInstructionMap != nullptr && !pcBCInstructionMap->empty(); + } + + const MemPool *GetMemPool() const { + return methodMp; + } + + void ReleaseMempool() { + if (methodMp != nullptr) { + delete methodMp; + methodMp = nullptr; + } + } + + MapleAllocator &GetAllocator() { + return allocator; + } + + protected: + uint32 GetItemIdxImpl() const override = 0; + uint32 GetIdxImpl() const override = 0; + virtual bool IsVirtualImpl() const = 0; + virtual bool IsNativeImpl() const = 0; + virtual bool IsInitImpl() const = 0; + virtual bool IsClinitImpl() const = 0; + void ProcessTryCatch(); + virtual std::vector> GenArgVarListImpl() const = 0; + // This struct is used in TypeInfer only. + struct TypeInferItem { + BCReg *reg = nullptr; + std::set aliveUsedTypes; + TypeInferItem *prev = nullptr; + }; + + void TypeInfer(); + void InsertPhi(const std::vector &dest, std::vector &src); + static TypeInferItem *RegisterTypeInferItem(std::list> &items, BCReg* bcReg, + TypeInferItem *prev); + static std::vector ConstructNewRegTypeMap(const std::vector ®TypeMap, + std::list> &items); + std::list GenReTypeStmtsThroughArgs() const; + void PrecisifyRegType(); + virtual void GenArgRegsImpl() = 0; + static void LinkJumpTarget(const std::map &targetFEIRStmtMap, + const std::list &gotoFEIRStmts, + const std::list &switchFEIRStmts); + void DumpBCInstructionMap() const; + void SetSrcPosInfo(); + MapleMap *pcBCInstructionMap; + std::unique_ptr>> tryInfos; +#ifdef DEBUG + const std::map *pSrcPosInfo = nullptr; +#endif + std::vector> argRegs; + std::vector sigTypeNames; + bool isVirtual = false; + uint16 registerTotalSize = UINT16_MAX; + uint16 registerInsSize = UINT16_MAX; + const uint16 *instPos = nullptr; // method instructions start pos in bc file + std::set visitedPcSet; + std::set multiInDegreeSet; + std::list regTypes; + + MemPool *methodMp; + MapleAllocator allocator; +}; + +class BCClass { + public: + BCClass(uint32 idx, const BCParserBase &parserIn) : classIdx(idx), parser(parserIn) {} + ~BCClass() = default; + + uint32 GetClassIdx() const { + return classIdx; + } + + const BCParserBase &GetBCParser() const { + return parser; + } + + bool IsInterface() const { + return isInterface; + } + + void SetFilePathName(const std::string &path) { + filePathName = path; + } + + void SetSrcFileInfo(const std::string &name); + + uint32 GetSrcFileIdx() const { + return srcFileIdx; + } + + void SetIsInterface(bool flag) { + isInterface = flag; + } + void SetSuperClasses(const std::list &names); + void SetInterface(const std::string &name); + void SetAccFlag(uint32 flag); + void SetField(std::unique_ptr field); + void SetMethod(std::unique_ptr method); + void SetClassName(const std::string &classNameOrinIn); + void SetAnnotationsDirectory(std::unique_ptr annotationsDirectory); + void InsertStaticFieldConstVal(MIRConst *cst); + void InsertFinalStaticStringID(uint32 stringID); + std::vector GetFinalStaticStringIDVec() const { + return finalStaticStringID; + } + std::vector GetStaticFieldsConstVal() const; + const std::string &GetClassName(bool mapled) const; + + GStrIdx GetClassNameMplIdx() const { + return classNameMplIdx; + } + + const std::list &GetSuperClassNames() const; + const std::vector &GetSuperInterfaceNames() const; + std::string GetSourceFileName() const; + uint32 GetAccessFlag() const; + + const std::vector> &GetFields() const; + std::vector> &GetMethods(); + const std::unique_ptr &GetAnnotationsDirectory() const; + + protected: + bool isInterface = false; + uint32 classIdx; + uint32 srcFileIdx = 0; + uint32 accFlag = 0; + GStrIdx classNameOrinIdx; + GStrIdx classNameMplIdx; + GStrIdx srcFileNameIdx; + const BCParserBase &parser; + std::list superClassNameList; + std::vector interfaces; + std::vector> fields; + std::vector> methods; + std::unique_ptr annotationsDirectory; + std::vector staticFieldsConstVal; + std::vector finalStaticStringID; + BCAttrMap attrMap; + std::string filePathName; + mutable std::mutex bcClassMtx; +}; +} +} +#endif // MPLFE_BC_INPUT_INCLUDE_BC_CLASS_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_class2fe_helper.h b/src/mplfe/bc_input/include/bc_class2fe_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..4158a554467f9719be41b49099a8767af1da81f3 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_class2fe_helper.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_CLASS2FE_HELPER_H +#define MPLFE_BC_INPUT_INCLUDE_BC_CLASS2FE_HELPER_H +#include "fe_input_helper.h" +#include "bc_class.h" +#include "bc_pragma.h" +namespace maple { +namespace bc { +class BCClass2FEHelper : public FEInputStructHelper { + public: + BCClass2FEHelper(MapleAllocator &allocator, BCClass &klassIn); + ~BCClass2FEHelper() = default; + + protected: + std::string GetStructNameOrinImpl() const override; + std::string GetStructNameMplImpl() const override; + std::list GetSuperClassNamesImpl() const override; + std::vector GetInterfaceNamesImpl() const override; + std::string GetSourceFileNameImpl() const override; + MIRStructType *CreateMIRStructTypeImpl(bool &error) const override; + uint64 GetRawAccessFlagsImpl() const override; + std::string GetSrcFileNameImpl() const override; + + BCClass &klass; +}; + +class BCClassField2FEHelper : public FEInputFieldHelper { + public: + BCClassField2FEHelper(MapleAllocator &allocator, const BCClassField &fieldIn) + : FEInputFieldHelper(allocator), + field(fieldIn) {} + ~BCClassField2FEHelper() = default; + FieldAttrs AccessFlag2Attribute(uint32 accessFlag) const; + + protected: + virtual FieldAttrs AccessFlag2AttributeImpl(uint32 accessFlag) const = 0; + bool ProcessDeclImpl(MapleAllocator &allocator) override; + bool ProcessDeclWithContainerImpl(MapleAllocator &allocator) override; + const BCClassField &field; +}; + +class BCClassMethod2FEHelper : public FEInputMethodHelper { + public: + BCClassMethod2FEHelper(MapleAllocator &allocator, std::unique_ptr &methodIn); + ~BCClassMethod2FEHelper() = default; + std::unique_ptr &GetMethod() const { + return method; + } + + protected: + bool ProcessDeclImpl(MapleAllocator &allocator) override; + void SolveReturnAndArgTypesImpl(MapleAllocator &allocator) override; + std::string GetMethodNameImpl(bool inMpl, bool full) const override; + bool IsVargImpl() const override; + bool HasThisImpl() const override; + MIRType *GetTypeForThisImpl() const override; + + virtual bool IsClinit() const = 0; + virtual bool IsInit() const = 0; + bool IsVirtualImpl() const override; + bool IsNativeImpl() const override; + bool HasCodeImpl() const override; + + std::unique_ptr &method; +}; + +class BCInputPragmaHelper : public FEInputPragmaHelper { + public: + BCInputPragmaHelper(BCAnnotationsDirectory &bcAnnotationsDirectoryIn) + : bcAnnotationsDirectory(bcAnnotationsDirectoryIn) {} + virtual ~BCInputPragmaHelper() = default; + + protected: + std::vector &GenerateMIRPragmasImpl() override { + return bcAnnotationsDirectory.EmitPragmas(); + } + + private: + BCAnnotationsDirectory &bcAnnotationsDirectory; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_CLASS2FE_HELPER_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_compiler_component-inl.h b/src/mplfe/bc_input/include/bc_compiler_component-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..84947caa02a8d9cc7c74ed7f7e570239be102d34 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_compiler_component-inl.h @@ -0,0 +1,301 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_INL_H_ +#define MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_INL_H_ +#include "bc_compiler_component.h" +#include "fe_timer.h" +#include "bc_function.h" +#include "dex_class2fe_helper.h" +#include "fe_manager.h" +#include "class_loader_context.h" +#include "class_linker.h" + +namespace maple { +namespace bc { +#define SET_FUNC_INFO_PAIR(A, B, C, D) \ + A->PushbackMIRInfo(MIRInfoPair(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(B), C)); \ + A->PushbackIsString(D) +template +BCCompilerComponent::BCCompilerComponent(MIRModule &module) + : MPLFECompilerComponent(module, kSrcLangJava), + mp(memPoolCtrler.NewMemPool("MemPool for BCCompilerComponent")), + allocator(mp), + bcInput(std::make_unique>(module)) {} + +template +BCCompilerComponent::~BCCompilerComponent() { + mp = nullptr; +} + +template +bool BCCompilerComponent::ParseInputImpl() { + FETimer timer; + bool success = true; + timer.StartAndDump("BCCompilerComponent::ParseInput()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::ParseInput() ====="); + const std::list &inputClassNames = {}; + std::vector inputNames; + if (typeid(T) == typeid(DexReader)) { + inputNames = FEOptions::GetInstance().GetInputDexFiles(); + } else { + CHECK_FATAL(false, "Reader is not supported. Exit."); + } + success = success && bcInput->ReadBCFiles(inputNames, inputClassNames); + CHECK_FATAL(success, "BCCompilerComponent::ParseInput failed. Exit."); + bc::BCClass *klass = bcInput->GetFirstClass(); + while (klass != nullptr) { + if (typeid(T) == typeid(DexReader)) { + FEInputStructHelper *structHelper = allocator.GetMemPool()->template New(allocator, *klass); + FEInputPragmaHelper *pragmaHelper = allocator.GetMemPool()->template New( + *(klass->GetAnnotationsDirectory())); + structHelper->SetPragmaHelper(pragmaHelper); + structHelper->SetStaticFieldsConstVal(klass->GetStaticFieldsConstVal()); + if (FEOptions::GetInstance().IsAOT()) { + structHelper->SetFinalStaticStringIDVec(klass->GetFinalStaticStringIDVec()); + } + structHelpers.push_back(structHelper); + } else { + CHECK_FATAL(false, "Reader is not supported. Exit."); + } + klass = bcInput->GetNextClass(); + } + timer.StopAndDumpTimeMS("BCCompilerComponent::ParseInput()"); + return success; +} + +template +bool BCCompilerComponent::LoadOnDemandTypeImpl() { + FETimer timer; + bool success = true; + timer.StartAndDump("BCCompilerComponent::LoadOnDemandType()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::LoadOnDemandType() ====="); + // Collect dependent type names in dexfile + std::unordered_set allDepSet; + success = success && bcInput->CollectDependentTypeNamesOnAllBCFiles(allDepSet); + CHECK_FATAL(success, "BCCompilerComponent::CollectDepTypeNames failed. Exit."); + // Collect class def type names in dexfile + std::unordered_set allClassSet; + success = success && bcInput->CollectClassNamesOnAllBCFiles(allClassSet); + // Find dependent types and resolve types to bcClasses + std::list> klassList; + success = success && LoadOnDemandType2BCClass(allDepSet, allClassSet, klassList); + // All dependent bcClasses are loaded into the mir globaltable and used like mplt + std::list> structHelpers; + success = success && LoadOnDemandBCClass2FEClass(klassList, structHelpers, !FEOptions::GetInstance().IsNoMplFile()); + timer.StopAndDumpTimeMS("BCCompilerComponent::LoadOnDemandType()"); + return success; +} + +template +bool BCCompilerComponent::LoadOnDemandType2BCClass(const std::unordered_set &allDepsSet, + const std::unordered_set &allDefsSet, + std::list> &klassList) { + FETimer timer; + timer.StartAndDump("LoadOnDemandType2BCClass::Open dep dexfiles"); + bool success = true; + ClassLoaderContext *classLoaderContext = nullptr; + const ClassLoaderInfo *classLoader = nullptr; + std::vector> bootClassPaths; + std::string spec = FEOptions::GetInstance().GetXBootClassPath(); + if (!spec.empty()) { // Xbootclasspath + INFO(kLncInfo, "XBootClassPath=%s", spec.c_str()); + success = success && ClassLoaderContext::OpenDexFiles(spec, bootClassPaths); + } + spec = FEOptions::GetInstance().GetClassLoaderContext(); + if (!spec.empty()) { // PCL + INFO(kLncInfo, "PCL=%s", spec.c_str()); + classLoaderContext = ClassLoaderContext::Create(spec, *mp); + if (classLoaderContext != nullptr) { + classLoader = classLoaderContext->GetClassLoader(); + } + } + timer.StopAndDumpTimeMS("LoadOnDemandType2BCClass::Open dep dexfiles"); + ClassLinker *classLinker = mp->New(bootClassPaths); + for (const std::string &className : allDepsSet) { + classLinker->FindClass(className, nullptr, klassList); + } + // if same class name is existed in src dexFile and dependent set, import class from dependent set preferentially + for (const std::string &className : allDefsSet) { + classLinker->FindClass(className, nullptr, klassList, true); + } + return success; +} + +template +bool BCCompilerComponent::LoadOnDemandBCClass2FEClass( + const std::list> &klassList, + std::list> &structHelpers, + bool isEmitDepsMplt) { + for (const std::unique_ptr &klass : klassList) { + std::unique_ptr structHelper = std::make_unique(allocator, *klass); + FEInputPragmaHelper *pragmaHelper = allocator.GetMemPool()->template New( + *(klass->GetAnnotationsDirectory())); + structHelper->SetPragmaHelper(pragmaHelper); + structHelper->SetIsOnDemandLoad(true); + structHelpers.push_back(std::move(structHelper)); + } + for (const std::unique_ptr &helper : structHelpers) { + ASSERT_NOT_NULL(helper); + (void)helper->PreProcessDecl(); + } + for (const std::unique_ptr &helper : structHelpers) { + ASSERT_NOT_NULL(helper); + (void)helper->ProcessDecl(); + helper->ProcessPragma(); + } + if (isEmitDepsMplt) { + std::string outName = module.GetFileName(); + size_t lastDot = outName.find_last_of("."); + std::string outNameWithoutType; + if (lastDot == std::string::npos) { + outNameWithoutType = outName; + } else { + outNameWithoutType = outName.substr(0, lastDot); + } + std::string depFileName = outNameWithoutType + ".Deps.mplt"; + module.GetImportFiles().push_back(module.GetMIRBuilder()->GetOrCreateStringIndex(depFileName)); + module.DumpToHeaderFile(!FEOptions::GetInstance().IsGenAsciiMplt(), depFileName); + } + FEOptions::ModeDepSameNamePolicy mode = FEOptions::GetInstance().GetModeDepSameNamePolicy(); + switch (mode) { + case FEOptions::ModeDepSameNamePolicy::kSys: + // Set kSrcMpltSys flag, loading on-demand dependent types from system + FEManager::GetTypeManager().SetMirImportedTypes(FETypeFlag::kSrcMpltSys); + break; + case FEOptions::ModeDepSameNamePolicy::kSrc: + // Set kSrcMplt flag, same name types are then overridden from src file after loaded on-demand dependent type + FEManager::GetTypeManager().SetMirImportedTypes(FETypeFlag::kSrcMplt); + break; + } + for (uint32 i = 1; i < GlobalTables::GetGsymTable().GetSymbolTableSize(); ++i) { + MIRSymbol *symbol = GlobalTables::GetGsymTable().GetSymbol(i); + if ((symbol != nullptr) && (symbol->GetSKind() == kStFunc)) { + symbol->SetIsImportedDecl(true); + } + } + return true; +} + +template +bool BCCompilerComponent::PreProcessDeclImpl() { + FETimer timer; + timer.StartAndDump("BCCompilerComponent::PreProcessDecl()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::PreProcessDecl() ====="); + bool success = true; + for (FEInputStructHelper *helper : structHelpers) { + ASSERT_NOT_NULL(helper); + success = helper->PreProcessDecl() ? success : false; + } + timer.StopAndDumpTimeMS("BCCompilerComponent::PreProcessDecl()"); + return success; +} + +template +bool BCCompilerComponent::ProcessDeclImpl() { + FETimer timer; + timer.StartAndDump("BCCompilerComponent::ProcessDecl()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::ProcessDecl() ====="); + bool success = true; + for (FEInputStructHelper *helper : structHelpers) { + ASSERT_NOT_NULL(helper); + success = helper->ProcessDecl() ? success : false; + } + timer.StopAndDumpTimeMS("BCCompilerComponent::ProcessDecl()"); + return success; +} + +template +void BCCompilerComponent::ProcessPragmaImpl() { + FETimer timer; + timer.StartAndDump("BCCompilerComponent::ProcessPragmaImpl()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::ProcessPragmaImpl() ====="); + for (FEInputStructHelper *helper : structHelpers) { + ASSERT_NOT_NULL(helper); + helper->ProcessPragma(); + } + timer.StopAndDumpTimeMS("BCCompilerComponent::ProcessPragmaImpl()"); +} + +template +bool BCCompilerComponent::PreProcessWithoutFunctionImpl() { + return false; +} + +template +bool BCCompilerComponent::PreProcessWithFunctionImpl() { + FETimer timer; + timer.StartAndDump("BCCompilerComponent::PreProcessWithFunction()"); + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process BCCompilerComponent::PreProcessWithFunction() ====="); + for (FEInputStructHelper *structHelper : structHelpers) { + ASSERT_NOT_NULL(structHelper); + for (FEInputMethodHelper *methodHelper : structHelper->GetMethodHelpers()) { + ASSERT_NOT_NULL(methodHelper); + BCClassMethod2FEHelper *bcMethodHelper = static_cast(methodHelper); + GStrIdx methodNameIdx = methodHelper->GetMethodNameIdx(); + bool isStatic = methodHelper->IsStatic(); + MIRFunction *mirFunc = FEManager::GetTypeManager().GetMIRFunction(methodNameIdx, isStatic); + CHECK_NULL_FATAL(mirFunc); + std::unique_ptr feFunction = std::make_unique(*bcMethodHelper, *mirFunc, + phaseResultTotal); + module.AddFunction(mirFunc); + if (FEOptions::GetInstance().IsAOT()) { + const std::unique_ptr &method = bcMethodHelper->GetMethod(); + GStrIdx idx = module.GetMIRBuilder()->GetOrCreateStringIndex(bcMethodHelper->GetMethodName(false)); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_fullname", idx, true); + const std::string className = method->GetClassName(); + idx = module.GetMIRBuilder()->GetOrCreateStringIndex(className); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_classname", idx, true); + const std::string methodName = method->GetName(); + idx = module.GetMIRBuilder()->GetOrCreateStringIndex(methodName); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_funcname", idx, true); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_methodidx", method->GetIdx(), false); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_registers", method->GetRegisterTotalSize(), false); + SET_FUNC_INFO_PAIR(mirFunc, "INFO_dexthisreg", method->GetThisRegNum(), false); + } + feFunction->Init(); + feFunction->SetSrcFileName(structHelper->GetSrcFileName()); + functions.push_back(std::move(feFunction)); + } + } + timer.StopAndDumpTimeMS("BCCompilerComponent::PreProcessWithFunction()"); + return true; +} + +template +std::string BCCompilerComponent::GetComponentNameImpl() const { + return "BCCompilerComponent"; +} + +template +bool BCCompilerComponent::ParallelableImpl() const { + return true; +} + +template +void BCCompilerComponent::DumpPhaseTimeTotalImpl() const { + INFO(kLncInfo, "[PhaseTime] BCCompilerComponent"); + MPLFECompilerComponent::DumpPhaseTimeTotalImpl(); +} + +template +void BCCompilerComponent::ReleaseMemPoolImpl() { + if (mp != nullptr) { + delete mp; + mp = nullptr; + } +} +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_INL_H_ diff --git a/src/mplfe/bc_input/include/bc_compiler_component.h b/src/mplfe/bc_input/include/bc_compiler_component.h new file mode 100644 index 0000000000000000000000000000000000000000..b8b76d16c8ae7cb170f5fa745ec893730c913f95 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_compiler_component.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_H +#define MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_H +#include "fe_macros.h" +#include "mplfe_compiler_component.h" +#include "bc_input.h" + +namespace maple { +namespace bc { +template +class BCCompilerComponent : public MPLFECompilerComponent { + public: + explicit BCCompilerComponent(MIRModule &module); + ~BCCompilerComponent(); + + protected: + bool ParseInputImpl() override; + bool LoadOnDemandTypeImpl() override; + bool PreProcessDeclImpl() override; + bool ProcessDeclImpl() override; + void ProcessPragmaImpl() override; + bool PreProcessWithoutFunctionImpl() override; + bool PreProcessWithFunctionImpl() override; + std::string GetComponentNameImpl() const override; + bool ParallelableImpl() const override; + void DumpPhaseTimeTotalImpl() const override; + void ReleaseMemPoolImpl() override; + + private: + bool LoadOnDemandType2BCClass(const std::unordered_set &allDepsSet, + const std::unordered_set &allDefsSet, + std::list> &klassList); + bool LoadOnDemandBCClass2FEClass(const std::list> &klassList, + std::list> &structHelpers, + bool isEmitDepsMplt); + + MemPool *mp; + MapleAllocator allocator; + std::unique_ptr> bcInput; +}; // class BCCompilerComponent +} // namespace bc +} // namespace maple +#include "bc_compiler_component-inl.h" +#endif // MPLFE_BC_INPUT_INCLUDE_BC_COMPILER_COMPONENT_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_function.h b/src/mplfe/bc_input/include/bc_function.h new file mode 100644 index 0000000000000000000000000000000000000000..95811635e3712e4770072025fe2c05b46a7a7ee5 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_function.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPL_FE_BC_INPUT_BC_FUNTION_H +#define MPL_FE_BC_INPUT_BC_FUNTION_H +#include "fe_function.h" +#include "bc_class2fe_helper.h" + +namespace maple { +namespace bc { +class BCFunction : public FEFunction { + public: + BCFunction(const BCClassMethod2FEHelper &argMethodHelper, MIRFunction &mirFunc, + const std::unique_ptr &argPhaseResultTotal); + virtual ~BCFunction() = default; + + protected: + bool GenerateGeneralStmt(const std::string &phaseName) override { + WARN(kLncWarn, "Phase: %s may not need.", phaseName.c_str()); + return true; + } + + bool GenerateArgVarList(const std::string &phaseName) override; + + bool PreProcessTypeNameIdx() override { + return true; + } + + void GenerateGeneralStmtFailCallBack() override {} + + void GenerateGeneralDebugInfo() override {} + + bool VerifyGeneral() override { + return true; + } + + void VerifyGeneralFailCallBack() override {} + + bool HasThis() override { + return methodHelper.HasThis(); + } + + bool IsNative() override { + return methodHelper.IsNative(); + } + + bool EmitToFEIRStmt(const std::string &phaseName) override; + + void InitImpl() override; + void PreProcessImpl() override; + bool ProcessImpl() override; + bool ProcessFEIRFunction() override; + void FinishImpl() override; + bool EmitToMIR(const std::string &phaseName) override; + void AppendFEIRStmts(std::list &stmts); + void InsertFEIRStmtsBefore(FEIRStmt &pos, std::list &stmts); + + const BCClassMethod2FEHelper &methodHelper; + std::unique_ptr &method; + bool error = false; +}; +} // namespace bc +} // namespace maple +#endif \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_input-inl.h b/src/mplfe/bc_input/include/bc_input-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..ab0dccc51e4ced840d4e5d56ed117636b838e4e7 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_input-inl.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_INPUT_INL_H_ +#define MPLFE_BC_INPUT_INCLUDE_BC_INPUT_INL_H_ +#include "bc_input.h" +#include +#include "dex_parser.h" +#include "mplfe_env.h" + +namespace maple { +namespace bc { +template +bool BCInput::ReadBCFile(uint32 index, const std::string &fileName, const std::list &classNamesIn) { + std::unique_ptr bcParser; + if (typeid(T) == typeid(DexReader)) { + bcParser = std::make_unique(index, fileName, classNamesIn); + } else { + CHECK_FATAL(false, "Unsupported BC reader: %s in BCInput", typeid(T).name()); + } + if (bcParser->OpenFile() == false) { + return false; + } + if (bcParser->ParseHeader() == false) { + ERR(kLncErr, "Parse Header failed in : %s.", fileName.c_str()); + return false; + } + if (bcParser->Verify() == false) { + ERR(kLncErr, "Verify file failed in : %s.", fileName.c_str()); + return false; + } + if (bcParser->RetrieveClasses(bcClasses) == false) { + ERR(kLncErr, "Retrieve classes failed in : %s.", fileName.c_str()); + return false; + } + (void)bcParserMap.insert(std::make_pair(fileName, std::move(bcParser))); + return true; +} + +template +bool BCInput::ReadBCFiles(const std::vector &fileNames, const std::list &classNamesIn) { + for (uint32 i = 0; i < fileNames.size(); ++i) { + if (BCInput::ReadBCFile(i, fileNames[i], classNamesIn) == false) { + return false; + } + RegisterFileInfo(fileNames[i]); + } + return true; +} + +template +BCClass *BCInput::GetFirstClass() { + if (bcClasses.size() == 0) { + return nullptr; + } + itKlass = bcClasses.begin(); + return itKlass->get(); +} + +template +BCClass *BCInput::GetNextClass() { + if (itKlass == bcClasses.end()) { + return nullptr; + } + ++itKlass; + if (itKlass == bcClasses.end()) { + return nullptr; + } + return itKlass->get(); +} + +template +void BCInput::RegisterFileInfo(const std::string &fileName) { + GStrIdx fileNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(fileName); + GStrIdx fileInfoIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("INFO_filename"); + module.PushFileInfoPair(MIRInfoPair(fileInfoIdx, fileNameIdx)); + module.PushFileInfoIsString(true); +} + +template +bool BCInput::CollectDependentTypeNamesOnAllBCFiles(std::unordered_set &allDepSet) { + FEOptions::ModeCollectDepTypes mode = FEOptions::GetInstance().GetModeCollectDepTypes(); + bool isSuccess = true; + switch (mode) { + case FEOptions::ModeCollectDepTypes::kAll: + isSuccess = CollectAllDepTypeNamesOnAllBCFiles(allDepSet); + break; + case FEOptions::ModeCollectDepTypes::kFunc: + isSuccess = CollectMethodDepTypeNamesOnAllBCFiles(allDepSet); + break; + } + return isSuccess; +} + +template +bool BCInput::CollectAllDepTypeNamesOnAllBCFiles(std::unordered_set &allDepSet) { + for (auto &item : bcParserMap) { + std::unordered_set depSet; + if (item.second->CollectAllDepTypeNames(depSet) == false) { + ERR(kLncErr, "Collect all dependent typenames failed in : %s.", item.first.c_str()); + return false; + } + allDepSet.insert(depSet.begin(), depSet.end()); + } + return true; +} + +template +bool BCInput::CollectMethodDepTypeNamesOnAllBCFiles(std::unordered_set &depSet) { + bool isSuccess = true; + for (const std::unique_ptr &klass : bcClasses) { + if (klass == nullptr) { + continue; + } + std::list superClassNames = klass->GetSuperClassNames(); + depSet.insert(superClassNames.begin(), superClassNames.end()); + std::vector superInterfaceNames = klass->GetSuperInterfaceNames(); + depSet.insert(superInterfaceNames.begin(), superInterfaceNames.end()); + for (const std::unique_ptr &method : klass->GetMethods()) { + if (method == nullptr) { + continue; + } + klass->GetBCParser().CollectMethodDepTypeNames(depSet, *method); + } + } + std::unordered_set classSet; + isSuccess = isSuccess && CollectClassNamesOnAllBCFiles(classSet); + BCUtil::AddDefaultDepSet(depSet); // DepSet is equal to "DefaultTypeSet + TypeSet - ClassSet" + for (const auto &elem : classSet) { + (void)depSet.erase(elem); + } + return isSuccess; +} + +template +bool BCInput::CollectClassNamesOnAllBCFiles(std::unordered_set &allClassSet) { + for (auto &item : bcParserMap) { + std::unordered_set classSet; + if (item.second->CollectAllClassNames(classSet) == false) { + ERR(kLncErr, "Collect all class names failed in : %s.", item.first.c_str()); + return false; + } + allClassSet.insert(classSet.begin(), classSet.end()); + } + return true; +} +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_INPUT_INL_H_ diff --git a/src/mplfe/bc_input/include/bc_input.h b/src/mplfe/bc_input/include/bc_input.h new file mode 100644 index 0000000000000000000000000000000000000000..eaf6af8e377de4e5c97c250e441aad02280500fb --- /dev/null +++ b/src/mplfe/bc_input/include/bc_input.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ + +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_INPUT_H +#define MPLFE_BC_INPUT_INCLUDE_BC_INPUT_H +#include +#include +#include "mir_module.h" +#include "bc_class.h" +#include "bc_parser.h" + +namespace maple { +namespace bc { +template +class BCInput { + public: + explicit BCInput(MIRModule &moduleIn) : module(moduleIn) {} + ~BCInput() = default; + bool ReadBCFile(uint32 index, const std::string &fileName, const std::list &classNamesIn); + bool ReadBCFiles(const std::vector &fileNames, const std::list &classNamesIn); + const MIRModule &GetModule() const { + return module; + } + BCClass *GetFirstClass(); + BCClass *GetNextClass(); + void RegisterFileInfo(const std::string &fileName); + bool CollectDependentTypeNamesOnAllBCFiles(std::unordered_set &allDepSet); + bool CollectClassNamesOnAllBCFiles(std::unordered_set &allClassSet); + + private: + bool CollectAllDepTypeNamesOnAllBCFiles(std::unordered_set &allDepSet); + bool CollectMethodDepTypeNamesOnAllBCFiles(std::unordered_set &allDepSet); + + std::map> bcParserMap; // map + MIRModule &module; + + std::list> bcClasses; + std::list>::const_iterator itKlass; +}; +} +} +#include "bc_input-inl.h" +#endif // MPLFE_BC_INPUT_INCLUDE_BC_INPUT_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_instruction.h b/src/mplfe/bc_input/include/bc_instruction.h new file mode 100644 index 0000000000000000000000000000000000000000..6e9718240ad4f3702372da3b26393d727d46ceba --- /dev/null +++ b/src/mplfe/bc_input/include/bc_instruction.h @@ -0,0 +1,276 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_INSTRUCTION_H +#define MPLFE_BC_INPUT_INCLUDE_BC_INSTRUCTION_H +#include +#include +#include "types_def.h" +#include "bc_util.h" +#include "feir_stmt.h" +#include "feir_var_reg.h" + +namespace maple { +namespace bc { +class BCClassMethod; +struct BCReg; +class BCInstruction { + public: + BCInstruction(MapleAllocator &allocatorIn, uint32 pcIn, uint8 opcodeIn) + : opcode(opcodeIn), + pc(pcIn), + allocator(allocatorIn), + catchedExTypeNamesIdx(allocator.Adapter()), + handlerTargets(allocator.Adapter()), + defedRegs(allocator.Adapter()), + usedRegs(allocator.Adapter()), + handlers(allocator.Adapter()) {} + virtual ~BCInstruction() = default; + void InitBCInStruction(uint16 kind, bool wide, bool throwable); + BCInstructionKind GetInstKind() const; + bool IsWide() const; + void SetInstructionKind(BCInstructionKind kind); + bool IsConditionBranch() const; + bool IsGoto() const; + bool IsSwitch() const; + bool IsTarget() const; + bool IsTryStart() const; + bool IsTryEnd() const; + bool IsCatch() const; + void SetReturnInst(BCInstruction *inst); + bool HasReturn() const; + bool IsReturn() const; + uint32 GetPC() const; + uint8 GetOpcode() const; + std::vector GetTargets() const; + void SetDefultTarget(BCInstruction *inst); + void AddHandler(BCInstruction *handler); + void SetWidth(uint8 size); + uint8 GetWidth() const; + void SetCatchable(); + bool IsCatchable() const; + bool IsFallThru() const; + void SetBCRegType(const BCInstruction &inst); + void AddHandlerTarget(uint32 target); + MapleVector GetHandlerTargets() const; + MapleList *GetDefedRegs(); + MapleList *GetUsedRegs(); + void SetRegTypeInTypeInfer(); + void SetFuncNameIdx(const GStrIdx &methodIdx); + void SetSrcPositionInfo(uint32 fileIdxIn, uint32 lineNumIn); + void SetOpName(const char *name); + const char *GetOpName() const; + void Parse(const BCClassMethod &method); + void SetExceptionType(const GStrIdx &typeNameIdx); + std::list EmitToFEIRStmts(); + + protected: + virtual std::vector GetTargetsImpl() const; + virtual void ParseImpl(const BCClassMethod &method) = 0; + virtual std::list EmitToFEIRStmtsImpl() = 0; + void GenCommentStmt(std::list &stmts) const; + UniqueFEIRStmt GenLabelStmt() const; + UniqueFEIRStmt GenCatchStmt() const; + UniqueFEIRStmt GenTryLabelStmt() const; + UniqueFEIRStmt GenTryEndLabelStmt() const; + virtual void SetRegTypeInTypeInferImpl() {} + virtual void SetBCRegTypeImpl(const BCInstruction &inst) {} // for move-result and move-exception + std::list GenRetypeStmtsAfterDef() const; + std::list GenRetypeStmtsBeforeUse() const; + void SetSrcFileInfo(std::list &stmts) const; + bool isThrowable = false; + bool isWide = false; + bool isReturn = false; + bool isCatchable = false; + uint8 width = UINT8_MAX; // Default value, unuseable + uint8 opcode; + BCInstructionKind instKind = kUnKnownKind; + uint32 funcNameIdx = UINT32_MAX; + uint32 srcFileIdx = 0; + uint32 srcFileLineNum = 0; + uint32 pc; +#ifdef DEBUG + const char *opName = nullptr; +#endif + BCInstruction *returnInst = nullptr; + BCInstruction *defaultTarget = nullptr; + MapleAllocator &allocator; + MapleSet catchedExTypeNamesIdx; + MapleVector handlerTargets; // This instruction may throw exception and reach these handlers + MapleList defedRegs; + MapleList usedRegs; + MapleList handlers; +}; + +// Forward declaration +struct BCReg; + +struct BCRegTypeItem { + BCRegTypeItem(const GStrIdx &idx, bool isPrimPtrIn = false, bool isIndeterminateIn = false) + : typeNameIdx(idx), isPrimPtr(isPrimPtrIn), isIndeterminate(isIndeterminateIn) {} + BCRegTypeItem(const BCRegTypeItem &item) + : typeNameIdx(item.typeNameIdx), isPrimPtr(item.isPrimPtr), isIndeterminate(item.isIndeterminate) {} + ~BCRegTypeItem() = default; + GStrIdx typeNameIdx; + bool isPrimPtr = false; + bool isIndeterminate = false; + + PrimType GetPrimType() const; + PrimType GetBasePrimType() const; + BCRegTypeItem *Clone(const MapleAllocator &allocator) { + return allocator.GetMemPool()->New(typeNameIdx, isPrimPtr, isIndeterminate); + } + + void Copy(const BCRegTypeItem &src) { + typeNameIdx = src.typeNameIdx; + isPrimPtr = src.isPrimPtr; + isIndeterminate = src.isIndeterminate; + } + bool operator==(const BCRegTypeItem &item) const { + return typeNameIdx == item.typeNameIdx && isPrimPtr == item.isPrimPtr; + } + + bool IsRef() const { + return GetPrimType() == PTY_ref; + } + + bool IsMorePreciseType(const BCRegTypeItem &typeItemIn) const; +}; + +class BCRegType { + public: + BCRegType(MapleAllocator &allocatorIn, BCReg ®, const GStrIdx &typeNameIdxIn, + bool isPrimPtrIn = false, bool isIndeterminateIn = false); + ~BCRegType() = default; + MapleAllocator &GetAllocator() { + return allocator; + } + + void SetTypeNameIdx(const GStrIdx &idx) { + regTypeItem->typeNameIdx = idx; + } + + void SetIsPrimPtr(bool flag) { + regTypeItem->isPrimPtr = flag; + } + + bool IsIndeterminate() const { + return regTypeItem->isIndeterminate; + } + + void SetIsIndeterminate(bool flag) { + regTypeItem->isIndeterminate = flag; + } + + void UpdateDefTypeFromUse(BCRegTypeItem *typeItem); + + void UpdateDefTypeThroughPhi(BCReg &defedReg, const std::set &usedTypes); + + static void InsertUniqueTypeItem(MapleVector &itemSet, BCRegTypeItem *item) { + for (auto &elem : itemSet) { + if (!elem->isIndeterminate && (*elem) == (*item)) { + return; + } + } + itemSet.emplace_back(item); + } + + void UpdateUsedSet(BCRegTypeItem *typeItem) { + if (regTypeItem->isIndeterminate && !typeItem->isIndeterminate && ((*regTypeItem) == (*typeItem))) { + // Make reg type determinate ASAP + regTypeItem->Copy(*typeItem); + } + InsertUniqueTypeItem(typesUsedAs, typeItem); + } + + void SetRegTypeItem(BCRegTypeItem *item) { + regTypeItem = item; + } + + const BCRegTypeItem *GetRegTypeItem() const { + return regTypeItem; + } + + void UpdateTypeSetFromPhi(BCReg &defedReg, const std::set &usedTypes); + + MapleVector *GetUsedTypes() { + return &typesUsedAs; + } + + void PrecisifyTypes(); + + bool IsPrecisified() const { + return precisified; + } + + static BCRegTypeItem *GetMostPreciseType(const MapleVector &types); + + void AddElemType(BCRegType *item) { + elemTypes.emplace(item); + } + + void AddArrayType(BCRegType *regType) { + arrayTypes.emplace(regType); + } + + private: + MapleAllocator allocator; + BCReg &curReg; + BCRegTypeItem *regTypeItem; + // + MapleVector typesUsedAs; + bool precisified = false; + MapleSet elemTypes; + MapleSet arrayTypes; +}; + +struct BCRegValue { + union { + uint64 raw64 = 0; + uint32 raw32; + } primValue; + GStrIdx literalStrIdx = GStrIdx(0); // literal string +}; + +struct BCReg { + BCReg() = default; + virtual ~BCReg() = default; + bool isDef = false; + uint32 regNum; + BCRegType *regType = nullptr; + BCRegValue *regValue = nullptr; + BCRegTypeItem *regTypeItem = nullptr; + bool IsConstZero() const; + UniqueFEIRType GenFEIRType() const; + UniqueFEIRVar GenFEIRVarReg() const; + std::list GenRetypeStmtsAfterDef() const; + std::list GenRetypeStmtsBeforeUse() const; + // a reg maybe store a primitive pointer type var. + // If it is a primitive ptr, GetPrimType() return a PTY_ref + // GetBasePrimType() return a corresponding prim type + // If it is not a primitive pointer type, GetPrimType() and GetBasePrimType() return a same PrimType. + PrimType GetPrimType() const; + PrimType GetBasePrimType() const; + std::unique_ptr Clone() const { + return CloneImpl(); + } + + protected: + virtual UniqueFEIRType GenFEIRTypeImpl() const; + virtual UniqueFEIRVar GenFEIRVarRegImpl() const; + virtual std::unique_ptr CloneImpl() const; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_INSTRUCTION_H diff --git a/src/mplfe/bc_input/include/bc_io.h b/src/mplfe/bc_input/include/bc_io.h new file mode 100644 index 0000000000000000000000000000000000000000..b7d9eb6cc29d79dc911bb90dab56005d320ac6b4 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_io.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPL_FE_BC_INPUT_BC_IO_H +#define MPL_FE_BC_INPUT_BC_IO_H +#include +#include "basic_io.h" + +namespace maple { +namespace bc { +class BCIO : public BasicIOMapFile { + public: + explicit BCIO(const std::string &fileName); + ~BCIO() = default; + + static bool IsBigEndian() { + union { + uint16 v16; + uint8 a[sizeof(uint16) / sizeof(uint8)]; + } u; + u.v16 = 0x1234; + return u.a[0] == 0x12; + } + + protected: + bool isBigEndianHost = true; +}; + +struct RawData { + const uint8 *context; + uint32 size; +}; + +class BCReader : public BCIO, public BasicIORead { + public: + explicit BCReader(const std::string &fileName); + ~BCReader(); + bool RetrieveHeader(RawData &data); + void SetEndianTag(bool isBigEndian); + template + T GetRealInteger(T value) const { + if (isBigEndian == isBigEndianHost || sizeof(T) == sizeof(uint8)) { + return value; // Same Endian, not need to convert + } else { + union U { + uint8 a[sizeof(T)]; + T val; + } u0; + u0.val = value; + U u1; + for (size_t i = 0; i < sizeof(T); ++i) { + u1.a[i] = u0.a[sizeof(T) - 1 - i]; + } + return u1.val; + } + } + + struct ClassElem { + std::string className; + std::string elemName; + std::string typeName; + }; + + std::string GetStringFromIdx(uint32 idx) const; + std::string GetTypeNameFromIdx(uint32 idx) const; + ClassElem GetClassMethodFromIdx(uint32 idx) const; + ClassElem GetClassFieldFromIdx(uint32 idx) const; + std::string GetSignature(uint32 idx) const; + uint32 GetFileIndex() const; + + protected: + virtual std::string GetStringFromIdxImpl(uint32 idx) const = 0; + virtual std::string GetTypeNameFromIdxImpl(uint32 idx) const = 0; + virtual ClassElem GetClassMethodFromIdxImpl(uint32 idx) const = 0; + virtual ClassElem GetClassFieldFromIdxImpl(uint32 idx) const = 0; + virtual std::string GetSignatureImpl(uint32 idx) const = 0; + virtual uint32 GetFileIndexImpl() const = 0; + virtual bool RetrieveHeaderImpl(RawData &data); +}; +} // namespace bc +} // namespace maple +#endif // MPL_FE_BC_INPUT_BC_IO_H diff --git a/src/mplfe/bc_input/include/bc_op_factory.h b/src/mplfe/bc_input/include/bc_op_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..ca3c274ff2497a1ca4cc4e6bbe589f43c169a865 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_op_factory.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPL_FE_BC_INPUT_BC_OP_FACTORY_H +#define MPL_FE_BC_INPUT_BC_OP_FACTORY_H +#include +#include +#include "mempool_allocator.h" +#include "types_def.h" +#include "bc_instruction.h" + +namespace maple { +namespace bc { +class BCOpFactory { + public: + template + static BCInstruction *BCOpGenerator(MapleAllocator &allocator, uint32 pc) { + MemPool *mp = allocator.GetMemPool(); + BCInstruction *op = mp->New(allocator, pc, opcode); + op->InitBCInStruction(kind, wide, throwable); + return op; + } + using funcPtr = BCInstruction*(*)(MapleAllocator&, uint32); +}; +} // namespace bc +} // namespace maple +#endif // MPL_FE_BC_INPUT_BC_OP_FACTORY_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_parser-inl.h b/src/mplfe/bc_input/include/bc_parser-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..4cf4885ef739aa40bdfcf7a16302b7f79254c24a --- /dev/null +++ b/src/mplfe/bc_input/include/bc_parser-inl.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_PARSER_INL_H_ +#define MPLFE_BC_INPUT_INCLUDE_BC_PARSER_INL_H_ +#include "bc_parser.h" + +namespace maple { +namespace bc { +template +BCParser::BCParser(uint32 fileIdxIn, const std::string &fileNameIn, const std::list &classNamesIn) + : BCParserBase(fileIdxIn, fileNameIn, classNamesIn), reader(std::make_unique(fileIdxIn, fileNameIn)) {} + +template +bool BCParser::OpenFileImpl() { + return reader->OpenAndMap(); +} + +template +int MethodProcessTask::RunImpl(MplTaskParam *param) { + (void)param; + parser.ProcessDexClassMethod(klass, isVirtual, index, idxPair); + return 0; +} + +template +int MethodProcessTask::FinishImpl(MplTaskParam *param) { + (void)param; + return 0; +} + +template +void MethodProcessSchedular::AddMethodProcessTask(T &parser, + std::unique_ptr &klass, bool isVirtual, uint32 index, std::pair &idxPair) { + std::unique_ptr> task = + std::make_unique>(parser, klass, isVirtual, index, idxPair); + AddTask(task.get()); + tasks.push_back(std::move(task)); +} + +template +void MethodProcessSchedular::CallbackThreadMainStart() { + std::thread::id tid = std::this_thread::get_id(); + if (FEOptions::GetInstance().GetDumpLevel() >= FEOptions::kDumpLevelInfoDebug) { + INFO(kLncInfo, "Start Run Thread (tid=%lx)", tid); + } + FEConfigParallel::GetInstance().RegisterRunThreadID(tid); +} +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_PARSER_INL_H_ \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_parser.h b/src/mplfe/bc_input/include/bc_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..92189e8e6803d03cfee5976459bbd916d019724f --- /dev/null +++ b/src/mplfe/bc_input/include/bc_parser.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPL_FE_BC_INPUT_BC_PARSER_H +#define MPL_FE_BC_INPUT_BC_PARSER_H +#include +#include +#include +#include "bc_io.h" +#include "bc_class.h" +#include "bc_parser_base.h" +#include "mpl_scheduler.h" +#include "fe_options.h" + +namespace maple { +namespace bc { +template +class BCParser : public BCParserBase { + public: + BCParser(uint32 fileIdxIn, const std::string &fileNameIn, const std::list &classNamesIn); + ~BCParser() = default; + + protected: + bool OpenFileImpl(); + uint32 CalculateCheckSumImpl(const uint8 *data, uint32 size) = 0; + bool ParseHeaderImpl() = 0; + bool VerifyImpl() = 0; + virtual bool RetrieveIndexTables() = 0; + bool RetrieveUserSpecifiedClasses(std::list> &klasses) = 0; + bool RetrieveAllClasses(std::list> &klasses) = 0; + bool CollectAllDepTypeNamesImpl(std::unordered_set &depSet) = 0; + bool CollectMethodDepTypeNamesImpl(std::unordered_set &depSet, BCClassMethod &bcMethod) const = 0; + bool CollectAllClassNamesImpl(std::unordered_set &classSet) = 0; + + std::unique_ptr reader; +}; + +template +class MethodProcessTask : public MplTask { + public: + MethodProcessTask(T &argParser, std::unique_ptr &argKlass, + bool argIsVirtual, uint32 index, std::pair argIdxPair) + : isVirtual(argIsVirtual), + index(index), + klass(argKlass), + idxPair(argIdxPair), + parser(argParser) {} + virtual ~MethodProcessTask() = default; + + protected: + int RunImpl(MplTaskParam *param) override; + int FinishImpl(MplTaskParam *param) override; + + private: + bool isVirtual; + uint32 index; + std::unique_ptr &klass; + std::pair idxPair; + T &parser; +}; + +template +class MethodProcessSchedular : public MplScheduler { + public: + MethodProcessSchedular(const std::string &name) + : MplScheduler(name) {} + ~MethodProcessSchedular() { + FEConfigParallel::GetInstance().RunThreadIDCleanUp(); + } + + void AddMethodProcessTask(T &parser, std::unique_ptr &klass, + bool isVirtual, uint32 index, std::pair &idxPair); + void SetDumpTime(bool arg) { + dumpTime = arg; + } + + protected: + void CallbackThreadMainStart() override; + + private: + std::list>> tasks; +}; +} // namespace bc +} // namespace maple +#include "bc_parser-inl.h" +#endif // MPL_FE_BC_INPUT_BC_PARSER_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_parser_base.h b/src/mplfe/bc_input/include/bc_parser_base.h new file mode 100644 index 0000000000000000000000000000000000000000..0e53d5eef7b3c9d92f82295e45cd3f78263fa506 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_parser_base.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_PARSER_BASE_H +#define MPLFE_BC_INPUT_INCLUDE_BC_PARSER_BASE_H +#include +#include +#include +#include "types_def.h" +#include "bc_io.h" + +namespace maple { +namespace bc { +class BCClass; +class BCClassMethod; +class BCParserBase { + public: + BCParserBase(uint32 fileIdxIn, const std::string &fileNameIn, const std::list &classNamesIn); + virtual ~BCParserBase() = default; + bool OpenFile(); + bool ParseHeader(); + bool Verify(); + uint32 GetFileNameHashId() const { + return fileNameHashId; + } + uint32 CalculateCheckSum(const uint8 *data, uint32 size); + bool RetrieveClasses(std::list> &klasses); + const BCReader *GetReader() const; + bool CollectAllDepTypeNames(std::unordered_set &depSet); + bool CollectMethodDepTypeNames(std::unordered_set &depSet, BCClassMethod &bcMethod) const; + bool CollectAllClassNames(std::unordered_set &classSet); + void ProcessMethodBody(BCClassMethod &method, uint32 classIdx, uint32 methodItemIdx, bool isVirtual) const { + ProcessMethodBodyImpl(method, classIdx, methodItemIdx, isVirtual); + } + + protected: + virtual const BCReader *GetReaderImpl() const = 0; + virtual bool OpenFileImpl() = 0; + virtual uint32 CalculateCheckSumImpl(const uint8 *data, uint32 size) = 0; + virtual bool ParseHeaderImpl() = 0; + virtual bool VerifyImpl() = 0; + virtual bool RetrieveIndexTables() = 0; + virtual bool RetrieveUserSpecifiedClasses(std::list> &klasses) = 0; + virtual bool RetrieveAllClasses(std::list> &klasses) = 0; + virtual bool CollectAllDepTypeNamesImpl(std::unordered_set &depSet) = 0; + virtual bool CollectMethodDepTypeNamesImpl(std::unordered_set &depSet, + BCClassMethod &bcMethod) const = 0; + virtual bool CollectAllClassNamesImpl(std::unordered_set &classSet) = 0; + virtual void ProcessMethodBodyImpl(BCClassMethod &method, + uint32 classIdx, uint32 methodItemIdx, bool isVirtual) const = 0; + + uint32 fileIdx; + const std::string fileName; + const std::list &classNames; + const int32 fileNameHashId; + RawData header; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_PARSER_BASE_H \ No newline at end of file diff --git a/src/mplfe/bc_input/include/bc_pragma.h b/src/mplfe/bc_input/include/bc_pragma.h new file mode 100644 index 0000000000000000000000000000000000000000..b85076771009504222e17eef42867843d3e6e996 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_pragma.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under the Mulan PSL v1. + * You can use this software according to the terms and conditions of the Mulan PSL v1. + * You may obtain a copy of Mulan PSL v1 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v1 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_PRAGMA_H +#define MPLFE_BC_INPUT_INCLUDE_BC_PRAGMA_H +#include +#include +#include +#include "mir_module.h" +#include "mir_pragma.h" +#include "mempool.h" +namespace maple { +namespace bc { +class BCAnnotationsDirectory { + public: + BCAnnotationsDirectory(MIRModule &moduleArg, MemPool &mpArg) : module(moduleArg), mp(mpArg) {} + virtual ~BCAnnotationsDirectory() = default; + std::vector &EmitPragmas() { + return EmitPragmasImpl(); + } + + protected: + virtual std::vector &EmitPragmasImpl() = 0; + MIRModule &module; + MemPool ∓ + std::vector pragmas; +}; +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_PRAGMA_H diff --git a/src/mplfe/bc_input/include/bc_util.h b/src/mplfe/bc_input/include/bc_util.h new file mode 100644 index 0000000000000000000000000000000000000000..3446ca1747892b7a5dbc5a51d210fc66530f96a1 --- /dev/null +++ b/src/mplfe/bc_input/include/bc_util.h @@ -0,0 +1,261 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#ifndef MPLFE_BC_INPUT_INCLUDE_BC_UTIL_H +#define MPLFE_BC_INPUT_INCLUDE_BC_UTIL_H +#include +#include +#include +#include +#include "types_def.h" +#include "cfg_primitive_types.h" +#include "global_tables.h" +namespace maple { +namespace bc { +enum BCInstructionKind : uint16 { + kUnKnownKind = 0, + kFallThru = 0x0001, + kConditionBranch = 0x0002, + kGoto = 0x0004, + kSwitch = 0x0008, + kTarget = 0x0010, + kTryStart = 0x0020, + kTryEnd = 0x0040, + kCatch = 0x0080, + kReturn = 0x0100, +}; + +enum BCRegVarType { + kUnknownType = 0, + kPrimitive = 1, + kBoolean = 3, + kLong = 17, + kFloat = 33, + kDouble = 65, + kRef = 2, +}; + +class BCUtil { + public: + static const std::string kUnknown; + static const std::string kPrimitive; + static const std::string kBoolean; + static const std::string kByte; + static const std::string kChar; + static const std::string kShort; + static const std::string kInt; + static const std::string kLong; + static const std::string kFloat; + static const std::string kDouble; + static const std::string kVoid; + static const std::string kWide; + static const std::string kAggregate; + static const std::string kJavaObjectName; + static const std::string kJavaStringName; + static const std::string kJavaByteClassName; + static const std::string kJavaShortClassName; + static const std::string kJavaIntClassName; + static const std::string kJavaLongClassName; + static const std::string kJavaFloatClassName; + static const std::string kJavaDoubleClassName; + static const std::string kJavaCharClassName; + static const std::string kJavaBoolClassName; + static const std::string kJavaClassName; + static const std::string kJavaMethodHandleName; + static const std::string kJavaExceptionName; + static const std::string kJavaThrowableName; + + static const std::string kJavaMethodHandleInvoke; + static const std::string kJavaMethodHandleInvokeExact; + + static const std::string kABoolean; + static const std::string kAByte; + static const std::string kAShort; + static const std::string kAChar; + static const std::string kAInt; + static const std::string kALong; + static const std::string kAFloat; + static const std::string kADouble; + static const std::string kAJavaObjectName; + + static inline GStrIdx &GetBooleanIdx() { + static GStrIdx booleanIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kBoolean); + return booleanIdx; + } + + static inline GStrIdx &GetIntIdx() { + static GStrIdx intIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kInt); + return intIdx; + } + + static inline GStrIdx &GetLongIdx() { + static GStrIdx longIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kLong); + return longIdx; + } + + static inline GStrIdx &GetFloatIdx() { + static GStrIdx floatIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kFloat); + return floatIdx; + } + + static inline GStrIdx &GetDoubleIdx() { + static GStrIdx doubleIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kDouble); + return doubleIdx; + } + + static inline GStrIdx &GetByteIdx() { + static GStrIdx byteIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kByte); + return byteIdx; + } + + static inline GStrIdx &GetCharIdx() { + static GStrIdx charIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kChar); + return charIdx; + } + + static inline GStrIdx &GetShortIdx() { + static GStrIdx shortIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kShort); + return shortIdx; + } + + static inline GStrIdx &GetVoidIdx() { + static GStrIdx voidIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kVoid); + return voidIdx; + } + + static inline GStrIdx &GetJavaObjectNameMplIdx() { + static GStrIdx javaObjectNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaObjectName)); + return javaObjectNameMplIdx; + } + + static inline GStrIdx &GetJavaStringNameMplIdx() { + static GStrIdx javaStringNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaStringName)); + return javaStringNameMplIdx; + } + + static inline GStrIdx &GetJavaClassNameMplIdx() { + static GStrIdx javaClassNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaClassName)); + return javaClassNameMplIdx; + } + + static inline GStrIdx &GetJavaExceptionNameMplIdx() { + static GStrIdx javaExceptionNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaExceptionName)); + return javaExceptionNameMplIdx; + } + + static inline GStrIdx &GetJavaThrowableNameMplIdx() { + static GStrIdx javaThrowableNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaThrowableName)); + return javaThrowableNameMplIdx; + } + + static inline GStrIdx &GetJavaMethodHandleNameMplIdx() { + static GStrIdx javaMethodHandleNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kJavaMethodHandleName)); + return javaMethodHandleNameMplIdx; + } + + static inline GStrIdx &GetABooleanIdx() { + static GStrIdx aBooleanIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kABoolean); + return aBooleanIdx; + } + + static inline GStrIdx &GetAIntIdx() { + static GStrIdx aIntIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kAInt); + return aIntIdx; + } + + static inline GStrIdx &GetALongIdx() { + static GStrIdx aLongIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kALong); + return aLongIdx; + } + + static inline GStrIdx &GetAByteIdx() { + static GStrIdx aByteIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kAByte); + return aByteIdx; + } + + static inline GStrIdx &GetACharIdx() { + static GStrIdx aCharIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kAChar); + return aCharIdx; + } + + static inline GStrIdx &GetAShortIdx() { + static GStrIdx aShortIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kAShort); + return aShortIdx; + } + + static inline GStrIdx &GetAFloatIdx() { + static GStrIdx aFloatIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kAFloat); + return aFloatIdx; + } + + static inline GStrIdx &GetADoubleIdx() { + static GStrIdx aDoubleIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kADouble); + return aDoubleIdx; + } + + static inline GStrIdx &GetAJavaObjectNameMplIdx() { + static GStrIdx aJavaObjectNameMplIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(kAJavaObjectName)); + return aJavaObjectNameMplIdx; + } + + // JavaMultiANewArray + static inline GStrIdx &GetMultiANewArrayFullIdx() { + static GStrIdx multiANewArrayFullIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( + namemangler::EncodeName("Ljava/lang/reflect/Array;|newInstance|(Ljava/lang/Class;[I)Ljava/lang/Object;")); + return multiANewArrayFullIdx; + } + + static inline GStrIdx &GetMultiANewArrayClassIdx() { + static GStrIdx multiANewArrayClassIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( + namemangler::EncodeName("Ljava/lang/reflect/Array;")); + return multiANewArrayClassIdx; + } + + static inline GStrIdx &GetMultiANewArrayElemIdx() { + static GStrIdx multiANewArrayElemIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( + namemangler::EncodeName("newInstance")); + return multiANewArrayElemIdx; + } + + static inline GStrIdx &GetMultiANewArrayTypeIdx() { + static GStrIdx multiANewArrayTypeIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( + namemangler::EncodeName("(Ljava/lang/Class;[I)Ljava/lang/Object;")); + return multiANewArrayTypeIdx; + } + + // value element name + static inline GStrIdx &GetPragmaElementNameValueIdx() { + static GStrIdx pragmaElementNameValueIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("value"); + return pragmaElementNameValueIdx; + } + + static bool IsWideType(const GStrIdx &name); + static bool IsMorePrecisePrimitiveType(const GStrIdx &name0, const GStrIdx &name1); + static PrimType GetPrimType(const GStrIdx &name); + static bool IsJavaReferenceType(const GStrIdx &typeNameIdx); + static bool IsJavaPrimitveType(const GStrIdx &typeNameIdx); + static bool IsArrayType(const GStrIdx &typeNameIdx); + static std::string TrimArrayModifier(const std::string &typeName); + static void AddDefaultDepSet(std::unordered_set &typeSet); +}; // BCUtil +} // namespace bc +} // namespace maple +#endif // MPLFE_BC_INPUT_INCLUDE_BC_UTIL_H \ No newline at end of file diff --git a/src/mplfe/bc_input/src/ark_annotation_map.cpp b/src/mplfe/bc_input/src/ark_annotation_map.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21087cfc64541fc6e48eae250a8ad812aba43c60 --- /dev/null +++ b/src/mplfe/bc_input/src/ark_annotation_map.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "ark_annotation_map.h" + +namespace maple { +namespace bc { +ArkAnnotationMap ArkAnnotationMap::annotationMap; + +void ArkAnnotationMap::Init() { + // AnnotationDefault + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FAnnotationDefault_3B", + "Lark_2Fannotation_2FAnnotationDefault_3B")); + // EnclosingClass + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FEnclosingClass_3B", + "Lark_2Fannotation_2FEnclosingClass_3B")); + // EnclosingMethod + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FEnclosingMethod_3B", + "Lark_2Fannotation_2FEnclosingMethod_3B")); + // InnerClass + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FInnerClass_3B", + "Lark_2Fannotation_2FInnerClass_3B")); + // KnownFailure + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FKnownFailure_3B", + "Lark_2Fannotation_2FKnownFailure_3B")); + // MemberClasses + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FMemberClasses_3B", + "Lark_2Fannotation_2FMemberClasses_3B")); + // MethodParameters + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FMethodParameters_3B", + "Lark_2Fannotation_2FMethodParameters_3B")); + // Signature + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FSignature_3B", + "Lark_2Fannotation_2FSignature_3B")); + // SourceDebugExtension + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FSourceDebugExtension_3B", + "Lark_2Fannotation_2FSourceDebugExtension_3B")); + // TestTargetClass + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FTestTargetClass_3B", + "Lark_2Fannotation_2FTestTargetClass_3B")); + // TestTarget + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FTestTarget_3B", + "Lark_2Fannotation_2FTestTarget_3B")); + // Throws + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2FThrows_3B", + "Lark_2Fannotation_2FThrows_3B")); + // compact + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Fcompat_2FUnsupportedAppUsage_3B", + "Lark_2Fannotation_2Fcompat_2FUnsupportedAppUsage_3B")); + // codegen + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Fcodegen_2FCovariantReturnType_3B", + "Lark_2Fannotation_2Fcodegen_2FCovariantReturnType_3B")); + // optimization + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Foptimization_2FCriticalNative_3B", + "Lark_2Fannotation_2Foptimization_2FCriticalNative_3B")); + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Foptimization_2FDeadReferenceSafe_3B", + "Lark_2Fannotation_2Foptimization_2FDeadReferenceSafe_3B")); + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Foptimization_2FFastNative_3B", + "Lark_2Fannotation_2Foptimization_2FFastNative_3B")); + pragmaTypeNameMap.insert(std::make_pair("Ldalvik_2Fannotation_2Foptimization_2FReachabilitySensitive_3B", + "Lark_2Fannotation_2Foptimization_2FReachabilitySensitive_3B")); + for (auto &it : pragmaTypeNameMap) { + (void)arkAnnotationTypeNames.insert(it.second); + } +} + +const std::string &ArkAnnotationMap::GetAnnotationTypeName(const std::string &orinName) { + std::map::iterator it = pragmaTypeNameMap.find(orinName); + if (it == pragmaTypeNameMap.end()) { + return orinName; + } else { + return it->second; + } +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/ark_annotation_processor.cpp b/src/mplfe/bc_input/src/ark_annotation_processor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..659e5977a652a8e065ab37ed465d73b7b0385f34 --- /dev/null +++ b/src/mplfe/bc_input/src/ark_annotation_processor.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "ark_annotation_processor.h" +#include "ark_annotation_map.h" +#include "fe_manager.h" +#include "mpl_logging.h" +namespace maple { +namespace bc { +void ArkAnnotationProcessor::Process() { + ArkAnnotationMap::GetArkAnnotationMap().Init(); + ArkAnnotation::GetInstance().Init(); + const std::set &arkAnnotationTypeNames = + ArkAnnotationMap::GetArkAnnotationMap().GetArkAnnotationTypeNames(); + for (const std::string &arkAnnotationTypeName : arkAnnotationTypeNames) { + (void)FEManager::GetTypeManager().CreateClassOrInterfaceType(arkAnnotationTypeName, true, FETypeFlag::kSrcUnknown); + } +} + +// ---------- ArkAnnotation ---------- +ArkAnnotation ArkAnnotation::instance; + +void ArkAnnotation::Init() { + // FastNative + typeNameSetForFastNative.insert(GetStrIdxFromDexName("Ldalvik/annotation/optimization/FastNative;")); + typeNameSetForFastNative.insert(GetStrIdxFromDexName("Lark/annotation/optimization/FastNative;")); + // CriticalNative + typeNameSetForCriticalNative.insert(GetStrIdxFromDexName("Ldalvik/annotation/optimization/CriticalNative;")); + typeNameSetForCriticalNative.insert(GetStrIdxFromDexName("Lark/annotation/optimization/CriticalNative;")); + // CallerSensitive + typeNameSetForCallerSensitive.insert(GetStrIdxFromDexName("Lsun/reflect/CallerSensitive;")); +} + +bool ArkAnnotation::IsFastNative(TyIdx tyIdx) { + MIRStructType *sType = GetStructType(tyIdx); + return sType == nullptr ? + false : typeNameSetForFastNative.find(sType->GetNameStrIdx()) != typeNameSetForFastNative.end(); +} + +bool ArkAnnotation::IsCriticalNative(TyIdx tyIdx) { + MIRStructType *sType = GetStructType(tyIdx); + return sType == nullptr ? + false : typeNameSetForCriticalNative.find(sType->GetNameStrIdx()) != typeNameSetForCriticalNative.end(); +} + +bool ArkAnnotation::IsCallerSensitive(TyIdx tyIdx) { + MIRStructType *sType = GetStructType(tyIdx); + return sType == nullptr ? + false : typeNameSetForCallerSensitive.find(sType->GetNameStrIdx()) != typeNameSetForCallerSensitive.end(); +} + +MIRStructType *ArkAnnotation::GetStructType(TyIdx tyIdx) { + MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx); + if (!type->IsMIRClassType() && !type->IsMIRInterfaceType()) { + return nullptr; + } + return static_cast(type); +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_class.cpp b/src/mplfe/bc_input/src/bc_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46bc05d5b0d1b264cab26612c8fca13fc83e1c34 --- /dev/null +++ b/src/mplfe/bc_input/src/bc_class.cpp @@ -0,0 +1,587 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_class.h" +#include "global_tables.h" +#include "fe_utils_java.h" +#include "fe_utils.h" +#include "fe_manager.h" +#include "fe_options.h" + +namespace maple { +namespace bc { +// ========== BCClassElem ========== +BCClassElem::BCClassElem(const BCClass &klassIn, uint32 acc, const std::string &nameIn, const std::string &descIn) + : klass(klassIn), + accessFlag(acc), + name(nameIn), + descriptor(descIn) {} + +const std::string &BCClassElem::GetName() const { + return name; +} + +const std::string &BCClassElem::GetDescription() const { + return descriptor; +} + +uint32 BCClassElem::GetItemIdx() const { + return GetItemIdxImpl(); +} + +uint32 BCClassElem::GetIdx() const { + return GetIdxImpl(); +} + +uint32 BCClassElem::GetAccessFlag() const { + return accessFlag; +} + +bool BCClassElem::IsStatic() const { + return IsStaticImpl(); +} + +const std::string &BCClassElem::GetClassName() const { + return klass.GetClassName(false); +} + +GStrIdx BCClassElem::GetClassNameMplIdx() const { + return klass.GetClassNameMplIdx(); +} + +const BCClass &BCClassElem::GetBCClass() const { + return klass; +} + +// ========== BCTryInfo ========== +void BCTryInfo::DumpTryCatchInfo(const std::unique_ptr>> &tryInfos) { + DEBUG_STMT( + for (const auto &tryInfo : *tryInfos) { + LogInfo::MapleLogger(kLlDbg) << "tryBlock: [" << std::hex << "0x" << tryInfo->GetStartAddr() << ", 0x" << + tryInfo->GetEndAddr() << ")"; + LogInfo::MapleLogger(kLlDbg) << " handler: "; + for (const auto &e : (*tryInfo->GetCatches())) { + LogInfo::MapleLogger(kLlDbg) << "0x" << e->GetHandlerAddr() << " "; + } + LogInfo::MapleLogger(kLlDbg) << std::endl; + }) +} + +// ========== BCClassMethod ========== +void BCClassMethod::SetMethodInstOffset(const uint16 *pos) { + instPos = pos; +} + +void BCClassMethod::SetRegisterTotalSize(uint16 size) { + registerTotalSize = size; +} + +uint16 BCClassMethod::GetRegisterTotalSize() const{ + return registerTotalSize; +} + +void BCClassMethod::SetRegisterInsSize(uint16 size) { + registerInsSize = size; +} + +bool BCClassMethod::IsVirtual() const { + return IsVirtualImpl(); +} + +bool BCClassMethod::IsNative() const { + return IsNativeImpl(); +} + +bool BCClassMethod::IsInit() const { + return IsInitImpl(); +} + +bool BCClassMethod::IsClinit() const { + return IsClinitImpl(); +} + +std::string BCClassMethod::GetFullName() const { + return GetClassName() + "|" + GetName() + "|" + GetDescription(); +} + +void BCClassMethod::SetSrcPosInfo() { +#ifdef DEBUG + if ((FEOptions::GetInstance().IsDumpComment() || FEOptions::GetInstance().IsDumpLOC()) && + pSrcPosInfo != nullptr) { + uint32 srcPos = 0; + for (auto &[pos, inst] : *pcBCInstructionMap) { + auto it = pSrcPosInfo->find(pos); + if (it != pSrcPosInfo->end()) { + srcPos = it->second; // when pSrcPosInfo is valid, update srcPos + } + inst->SetSrcPositionInfo(klass.GetSrcFileIdx(), srcPos); + } + } +#endif +} + +void BCClassMethod::ProcessInstructions() { + if (pcBCInstructionMap->empty()) { + return; + } + // some instructions depend on exception handler, so we process try-catch info first + ProcessTryCatch(); + visitedPcSet.emplace(pcBCInstructionMap->begin()->first); + GStrIdx methodIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(GetFullName())); + for (auto itor = pcBCInstructionMap->begin(); itor != pcBCInstructionMap->end();) { + BCInstruction *inst = itor->second; + inst->SetFuncNameIdx(methodIdx); + inst->Parse(*this); + ++itor; + if (inst->IsConditionBranch() || inst->IsGoto() || inst->IsSwitch()) { + std::vector targets = inst->GetTargets(); + for (uint32 target : targets) { + auto it = pcBCInstructionMap->find(target); + CHECK_FATAL(it != pcBCInstructionMap->end(), "Invalid branch target 0x%x in method: %s", + target, GetFullName().c_str()); + it->second->SetInstructionKind(kTarget); + if (visitedPcSet.emplace(target).second == false) { + multiInDegreeSet.emplace(target); + } + } + if (inst->IsSwitch() && itor != pcBCInstructionMap->end()) { + itor->second->SetInstructionKind(kTarget); + inst->SetDefultTarget(itor->second); + if (visitedPcSet.emplace(itor->first).second == false) { + multiInDegreeSet.emplace(itor->first); + } + } + } + if (itor == pcBCInstructionMap->end()) { + continue; + } + if (inst->IsFallThru()) { + if (visitedPcSet.emplace(itor->first).second == false) { + multiInDegreeSet.emplace(itor->first); + } + } + if (itor->second->IsReturn()) { + inst->SetReturnInst(itor->second); + } + } + SetSrcPosInfo(); + if (FEOptions::GetInstance().GetTypeInferKind() == FEOptions::kLinearScan) { + TypeInfer(); + } +} + +void BCClassMethod::ProcessTryCatch() { + if (tryInfos == nullptr) { + return; + } + for (const auto &e : *tryInfos) { + uint32 tryStart = e->GetStartAddr(); + uint32 tryEnd = e->GetEndAddr(); + auto it = pcBCInstructionMap->find(tryStart); + CHECK_FATAL(it != pcBCInstructionMap->end(), "Invalid try start pos 0x%x in method: %s", tryStart, + GetFullName().c_str()); + it->second->SetInstructionKind(kTryStart); + BCInstruction *inst = it->second; + auto it1 = pcBCInstructionMap->find(tryEnd); + if (tryStart == tryEnd) { + it->second->SetInstructionKind(kTryEnd); + } else if (it1 != pcBCInstructionMap->end()) { + --it1; + it1->second->SetInstructionKind(kTryEnd); + } else { + // behind the last instruction + pcBCInstructionMap->rbegin()->second->SetInstructionKind(kTryEnd); + } + // Calculate catchable instructions + std::list catchableInsts; + while (it->second->GetPC() < tryEnd) { + it->second->SetCatchable(); + if (it->second->IsCatchable()) { + catchableInsts.emplace_back(it->second); + } + ++it; + if (it == pcBCInstructionMap->end()) { + break; + } + } + for (const auto &handler: *(e->GetCatches())) { + uint32 handlerPc = handler->GetHandlerAddr(); + auto elem = pcBCInstructionMap->find(handlerPc); + CHECK_FATAL(elem != pcBCInstructionMap->end(), "Invalid catch pos 0x%x in method: %s", handlerPc, + GetFullName().c_str()); + elem->second->SetInstructionKind(kCatch); + elem->second->SetExceptionType(handler->GetExceptionNameIdx()); + inst->AddHandler(elem->second); + for (auto catchableInst : catchableInsts) { + catchableInst->AddHandlerTarget(handlerPc); + if (visitedPcSet.emplace(handlerPc).second == false) { + multiInDegreeSet.emplace(handlerPc); + } + } + } + } +} + +// Use linear scan with SSA +// We insert phi behind the def in a edge before the dominance if the reg is alive under this dominance. +// A reg is default dead at its definition, we mark a reg alive only when it was used. +// We transfer reg live info through shared memory, record live-interval in dominancesMap. +// After a multi-in pos, we create a new TypeInferItem for a new live range. +void BCClassMethod::TypeInfer() { + std::list> typeInferItems; + std::set visitedSet; + // [pc, [regNum, TypeInferItem*]] + std::list>> pcDefedRegsList; + // [pc, [regNum, TypeInferItem*]] + std::vector> dominances((*pcBCInstructionMap).rbegin()->first + 1); + std::vector regTypeMap(registerTotalSize, nullptr); + for (auto ® : argRegs) { + regTypeMap[reg->regNum] = RegisterTypeInferItem(typeInferItems, reg.get(), nullptr); + regTypes.emplace_back(reg->regType); + } + pcDefedRegsList.emplace_front(0, regTypeMap); + dominances[0] = regTypeMap; + visitedSet.emplace(0); + while (!pcDefedRegsList.empty()) { + auto head = pcDefedRegsList.front(); + pcDefedRegsList.pop_front(); + BCInstruction *currInst = (*pcBCInstructionMap)[head.first]; + std::vector nextRegTypeMap = head.second; + auto usedRegs = currInst->GetUsedRegs(); + for (auto usedReg : *usedRegs) { + auto defedItem = nextRegTypeMap[usedReg->regNum]; + CHECK_FATAL(defedItem != nullptr && defedItem->reg != nullptr, + "Cannot find Reg%u defination at 0x%x:0x%x in method %s", + usedReg->regNum, head.first, currInst->GetOpcode(), GetFullName().c_str()); + if (usedReg->regTypeItem == nullptr) { + usedReg->regTypeItem = defedItem->reg->regTypeItem; + usedReg->regValue = defedItem->reg->regValue; + } else { + if (defedItem->reg->regTypeItem->isIndeterminate || + !(*(defedItem->reg->regTypeItem) == *(usedReg->regTypeItem))) { + defedItem->reg->regType->UpdateDefTypeFromUse(usedReg->regTypeItem); + } + } + usedReg->regType = defedItem->reg->regType; + currInst->SetRegTypeInTypeInfer(); + // Make the reg alive when it used, live range [defPos, usePos] + defedItem->aliveUsedTypes.emplace(usedReg->regTypeItem); + TypeInferItem *item = defedItem->prev; + while (item != nullptr) { + item->aliveUsedTypes.emplace(usedReg->regTypeItem); + item = item->prev; + } + } + auto defedRegs = currInst->GetDefedRegs(); + auto exHandlerTargets = currInst->GetHandlerTargets(); + uint32 next = currInst->GetPC() + currInst->GetWidth(); + for (auto exHandlerTarget : exHandlerTargets) { + if (visitedSet.emplace(exHandlerTarget).second == false) { + auto &domIt = dominances[exHandlerTarget]; + InsertPhi(domIt, nextRegTypeMap); + continue; + } + if ((multiInDegreeSet.find(exHandlerTarget) != multiInDegreeSet.end())) { + std::vector typeMap = ConstructNewRegTypeMap(nextRegTypeMap, typeInferItems); + pcDefedRegsList.emplace_front(exHandlerTarget, typeMap); + if (multiInDegreeSet.find(exHandlerTarget) != multiInDegreeSet.end()) { + dominances[exHandlerTarget] = typeMap; + } + } else { + pcDefedRegsList.emplace_front(exHandlerTarget, nextRegTypeMap); + } + } + for (auto defedReg : *defedRegs) { + TypeInferItem *item = RegisterTypeInferItem(typeInferItems, defedReg, nullptr); + nextRegTypeMap[defedReg->regNum] = item; + regTypes.emplace_back(defedReg->regType); + } + if (currInst->IsFallThru() && next <= pcBCInstructionMap->rbegin()->first) { + if (visitedSet.emplace(next).second == false) { + auto &domIt = dominances[next]; + InsertPhi(domIt, nextRegTypeMap); + } else { + if (multiInDegreeSet.find(next) != multiInDegreeSet.end()) { + std::vector typeMap = ConstructNewRegTypeMap(nextRegTypeMap, typeInferItems); + pcDefedRegsList.emplace_front(next, typeMap); + if (multiInDegreeSet.find(next) != multiInDegreeSet.end()) { + dominances[next] = typeMap; + } + } else { + pcDefedRegsList.emplace_front(next, nextRegTypeMap); + } + } + } + auto normalTargets = currInst->GetTargets(); + for (auto normalTarget : normalTargets) { + if (visitedSet.emplace(normalTarget).second == false) { + auto domIt = dominances[normalTarget]; + InsertPhi(domIt, nextRegTypeMap); + continue; + } + if (multiInDegreeSet.find(normalTarget) != multiInDegreeSet.end()) { + std::vector typeMap = ConstructNewRegTypeMap(nextRegTypeMap, typeInferItems); + pcDefedRegsList.emplace_front(normalTarget, typeMap); + dominances[normalTarget] = typeMap; + } else { + pcDefedRegsList.emplace_front(normalTarget, nextRegTypeMap); + } + } + } + PrecisifyRegType(); +} + +void BCClassMethod::InsertPhi(const std::vector &dest, std::vector &src) { + for (auto &d : dest) { + if (d == nullptr || d->aliveUsedTypes.empty()) { + continue; + } + auto item = src[d->reg->regNum]; + if (item != nullptr) { + for (auto aliveType : d->aliveUsedTypes) { + item->aliveUsedTypes.emplace(aliveType); + } + TypeInferItem *prevItem = item->prev; + while (prevItem != nullptr) { + for (auto aliveType : d->aliveUsedTypes) { + prevItem->aliveUsedTypes.emplace(aliveType); + } + prevItem = prevItem->prev; + } + item->reg->regType->UpdateDefTypeThroughPhi(*(d->reg), d->aliveUsedTypes); + } + } +} + +BCClassMethod::TypeInferItem *BCClassMethod::RegisterTypeInferItem( + std::list> &items, BCReg *bcReg, TypeInferItem *prev) { + std::unique_ptr item = std::make_unique(); + item->reg = bcReg; + item->prev = prev; + TypeInferItem *ptr = item.get(); + items.emplace_back(std::move(item)); + return ptr; +} + +std::vector BCClassMethod::ConstructNewRegTypeMap( + const std::vector ®TypeMap, + std::list> &items) { + std::vector res(regTypeMap.size(), nullptr); + size_t i = 0; + for (const auto &elem : regTypeMap) { + if (elem != nullptr) { + res[i] = RegisterTypeInferItem(items, elem->reg, elem); + } + ++i; + } + return res; +} + +std::list BCClassMethod::GenReTypeStmtsThroughArgs() const { + std::list stmts; + for (const auto &argReg : argRegs) { + std::list stmts0 = argReg->GenRetypeStmtsAfterDef(); + for (auto &stmt : stmts0) { + stmts.emplace_back(std::move(stmt)); + } + } + return stmts; +} + +void BCClassMethod::PrecisifyRegType() { + for (auto elem : regTypes) { + elem->PrecisifyTypes(); + } +} + +std::list BCClassMethod::EmitInstructionsToFEIR() const { + std::list stmts; + if (!HasCode()) { + return stmts; // Skip abstract and native method, not emit it to mpl but mplt. + } + if (IsStatic() && GetName().compare("") != 0) { // Not insert JAVA_CLINIT_CHECK in + GStrIdx containerNameIdx = GetClassNameMplIdx(); + uint32 typeID = UINT32_MAX; + if (FEOptions::GetInstance().IsAOT()) { + const std::string &mplClassName = GetBCClass().GetClassName(true); + typeID = FEManager::GetTypeManager().GetTypeIDFromMplClassName(mplClassName); + } + UniqueFEIRStmt stmt = + std::make_unique(INTRN_JAVA_CLINIT_CHECK, + std::make_unique(PTY_ref, containerNameIdx), + nullptr, typeID); + stmts.emplace_back(std::move(stmt)); + } + std::map targetFEIRStmtMap; + std::list gotoFEIRStmts; + std::list switchFEIRStmts; + std::list retypeStmts = GenReTypeStmtsThroughArgs(); + for (auto &stmt : retypeStmts) { + stmts.emplace_back(std::move(stmt)); + } + for (const auto &elem : *pcBCInstructionMap) { + std::list instStmts = elem.second->EmitToFEIRStmts(); + for (auto &e : instStmts) { + if (e->GetKind() == kStmtPesudoLabel) { + targetFEIRStmtMap.emplace(static_cast(e.get())->GetPos(), + static_cast(e.get())); + } + if (e->GetKind() == kStmtGoto || e->GetKind() == kStmtCondGoto) { + gotoFEIRStmts.emplace_back(static_cast(e.get())); + } + if (e->GetKind() == kStmtSwitch) { + switchFEIRStmts.emplace_back(static_cast(e.get())); + } + stmts.emplace_back(std::move(e)); + } + } + LinkJumpTarget(targetFEIRStmtMap, gotoFEIRStmts, switchFEIRStmts); // Link jump target + return stmts; +} + +void BCClassMethod::LinkJumpTarget(const std::map &targetFEIRStmtMap, + const std::list &gotoFEIRStmts, + const std::list &switchFEIRStmts) { + for (auto &e : gotoFEIRStmts) { + auto target = targetFEIRStmtMap.find(e->GetTarget()); + CHECK_FATAL(target != targetFEIRStmtMap.end(), "Cannot find the target for goto/condGoto"); + e->SetStmtTarget(*(target->second)); + } + for (auto &e : switchFEIRStmts) { + uint32 label = e->GetDefaultLabelIdx(); + if (label != UINT32_MAX) { + auto defaultTarget = targetFEIRStmtMap.find(label); + CHECK_FATAL(defaultTarget != targetFEIRStmtMap.end(), "Cannot find the default target for Switch"); + e->SetDefaultTarget(defaultTarget->second); + } + for (const auto &valueLabel : e->GetMapValueLabelIdx()) { + auto target = targetFEIRStmtMap.find(valueLabel.second); + CHECK_FATAL(target != targetFEIRStmtMap.end(), "Cannot find the target for Switch"); + e->AddTarget(valueLabel.first, target->second); + } + } +} + +void BCClassMethod::DumpBCInstructionMap() const { + // Only used in DEBUG manually + DEBUG_STMT( + uint32 idx = 0; + for (const auto &[pos, instPtr] : *pcBCInstructionMap) { + LogInfo::MapleLogger(kLlDbg) << "index: " << std::dec << idx++ << " pc: 0x" << std::hex << pos << + " opcode: 0x" << instPtr->GetOpcode() << std::endl; + }); +} + +const uint16 *BCClassMethod::GetInstPos() const { + return instPos; +} + +std::vector> BCClassMethod::GenArgVarList() const { + return GenArgVarListImpl(); +} + +void BCClassMethod::GenArgRegs() { + return GenArgRegsImpl(); +} + +// ========== BCCatchInfo ========== +BCCatchInfo::BCCatchInfo(uint32 handlerAddrIn, const GStrIdx &argExceptionNameIdx, bool iscatchAllIn) + : handlerAddr(handlerAddrIn), + exceptionNameIdx(argExceptionNameIdx), + isCatchAll(iscatchAllIn) {} +// ========== BCClass ========== +void BCClass::SetSrcFileInfo(const std::string &name) { + srcFileNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name); + srcFileIdx = FEManager::GetManager().RegisterSourceFileIdx(srcFileNameIdx); +} + +void BCClass::SetSuperClasses(const std::list &names) { + if (names.empty()) { + return; // No parent class + } + superClassNameList = names; +} + +void BCClass::SetInterface(const std::string &name) { + interfaces.push_back(name); +} + +void BCClass::SetAccFlag(uint32 flag) { + accFlag = flag; +} + +void BCClass::SetField(std::unique_ptr field) { + (void)fields.push_back(std::move(field)); +} + +void BCClass::SetMethod(std::unique_ptr method) { + std::lock_guard lock(bcClassMtx); + (void)methods.push_back(std::move(method)); +} + +void BCClass::InsertFinalStaticStringID(uint32 stringID) { + finalStaticStringID.push_back(stringID); +} + +void BCClass::SetClassName(const std::string &classNameOrin) { + classNameOrinIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(classNameOrin); + classNameMplIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(classNameOrin)); +} + +const std::unique_ptr &BCClass::GetAnnotationsDirectory() const { + return annotationsDirectory; +} + +void BCClass::SetAnnotationsDirectory(std::unique_ptr annotationsDirectoryIn) { + annotationsDirectory = std::move(annotationsDirectoryIn); +} + +std::vector BCClass::GetStaticFieldsConstVal() const { + return staticFieldsConstVal; +} + +void BCClass::InsertStaticFieldConstVal(MIRConst *cst) { + staticFieldsConstVal.push_back(cst); +} + +const std::string &BCClass::GetClassName(bool mapled) const { + return mapled ? GlobalTables::GetStrTable().GetStringFromStrIdx(classNameMplIdx) : + GlobalTables::GetStrTable().GetStringFromStrIdx(classNameOrinIdx); +} + +const std::list &BCClass::GetSuperClassNames() const { + return superClassNameList; +} + +const std::vector &BCClass::GetSuperInterfaceNames() const { + return interfaces; +} + +std::string BCClass::GetSourceFileName() const { + return GlobalTables::GetStrTable().GetStringFromStrIdx(srcFileNameIdx); +} + +uint32 BCClass::GetAccessFlag() const { + return accFlag; +} + +const std::vector> &BCClass::GetFields() const { + return fields; +} + +std::vector> &BCClass::GetMethods() { + return methods; +} +} // namespace bc +} // namespace maple diff --git a/src/mplfe/bc_input/src/bc_class2fe_helper.cpp b/src/mplfe/bc_input/src/bc_class2fe_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d19144ce7751db1e03faef1b8af5359a312726e --- /dev/null +++ b/src/mplfe/bc_input/src/bc_class2fe_helper.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_class2fe_helper.h" +#include "fe_macros.h" +#include "fe_manager.h" +#include "fe_utils_java.h" +namespace maple { +namespace bc { +BCClass2FEHelper::BCClass2FEHelper(MapleAllocator &allocator, bc::BCClass &klassIn) + : FEInputStructHelper(allocator), klass(klassIn) { + srcLang = kSrcLangJava; +} + +std::string BCClass2FEHelper::GetStructNameOrinImpl() const { + return klass.GetClassName(false); +} + +std::string BCClass2FEHelper::GetStructNameMplImpl() const { + return klass.GetClassName(true); +} + +std::list BCClass2FEHelper::GetSuperClassNamesImpl() const { + return klass.GetSuperClassNames(); +} + +std::vector BCClass2FEHelper::GetInterfaceNamesImpl() const { + return klass.GetSuperInterfaceNames(); +} + +std::string BCClass2FEHelper::GetSourceFileNameImpl() const { + return klass.GetSourceFileName(); +} + +MIRStructType *BCClass2FEHelper::CreateMIRStructTypeImpl(bool &error) const { + std::string classNameMpl = GetStructNameMplImpl(); + if (classNameMpl.empty()) { + error = true; + ERR(kLncErr, "class name is empty"); + return nullptr; + } + FE_INFO_LEVEL(FEOptions::kDumpLevelInfoDetail, "CreateMIRStrucType for %s", classNameMpl.c_str()); + bool isCreate = false; + MIRStructType *type = FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType(classNameMpl, klass.IsInterface(), + FETypeFlag::kSrcInput, isCreate); + error = false; + // fill global type name table + GStrIdx typeNameIdx = type->GetNameStrIdx(); + TyIdx prevTyIdx = GlobalTables::GetTypeNameTable().GetTyIdxFromGStrIdx(typeNameIdx); + if (prevTyIdx == TyIdx(0)) { + GlobalTables::GetTypeNameTable().SetGStrIdxToTyIdx(typeNameIdx, type->GetTypeIndex()); + } + // setup eh root type + if (FEManager::GetModule().GetThrowableTyIdx() == 0 && + (type->GetKind() == kTypeClass || type->GetKind() == kTypeClassIncomplete)) { + GStrIdx ehTypeNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName( + namemangler::GetInternalNameLiteral(namemangler::kJavaLangObjectStr)); + if (ehTypeNameIdx == type->GetNameStrIdx()) { + FEManager::GetModule().SetThrowableTyIdx(type->GetTypeIndex()); + } + } + return isCreate ? type : nullptr; +} + +uint64 BCClass2FEHelper::GetRawAccessFlagsImpl() const { + return static_cast(klass.GetAccessFlag()); +} + +std::string BCClass2FEHelper::GetSrcFileNameImpl() const { + return klass.GetSourceFileName(); +} + +// ========== BCClassField2FEHelper ========== +FieldAttrs BCClassField2FEHelper::AccessFlag2Attribute(uint32 accessFlag) const { + return AccessFlag2AttributeImpl(accessFlag); +} + +bool BCClassField2FEHelper::ProcessDeclImpl(MapleAllocator &allocator) { + CHECK_FATAL(false, "should not run here"); + return false; +} + +bool BCClassField2FEHelper::ProcessDeclWithContainerImpl(MapleAllocator &allocator) { + std::string klassNameMpl; + std::string fieldNameMpl; + std::string typeNameMpl; + bool isStatic = field.IsStatic(); + uint64 mapIdx = (static_cast(field.GetBCClass().GetBCParser().GetReader()->GetFileIndex()) << 32) | + field.GetIdx(); + StructElemNameIdx *structElemNameIdx = FEManager::GetManager().GetFieldStructElemNameIdx(mapIdx); + if (structElemNameIdx == nullptr) { + klassNameMpl = namemangler::EncodeName(field.GetClassName()); + fieldNameMpl = namemangler::EncodeName(field.GetName()); + typeNameMpl = namemangler::EncodeName(field.GetDescription()); + if (fieldNameMpl.empty()) { + ERR(kLncErr, "invalid name for %s field: %u in class %s", field.IsStatic() ? "static" : "instance", + field.GetItemIdx(), klassNameMpl.c_str()); + return false; + } + if (typeNameMpl.empty()) { + ERR(kLncErr, "invalid descriptor for %s field: %u in class %s", field.IsStatic() ? "static" : "instance", + field.GetItemIdx(), klassNameMpl.c_str()); + return false; + } + structElemNameIdx = FEManager::GetManager().GetStructElemMempool()->New( + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(klassNameMpl), + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(fieldNameMpl), + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(typeNameMpl), + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(klassNameMpl + namemangler::kNameSplitterStr + + fieldNameMpl + namemangler::kNameSplitterStr + typeNameMpl)); + FEManager::GetManager().SetFieldStructElemNameIdx(mapIdx, *structElemNameIdx); + } else { + klassNameMpl = GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx->klass); + fieldNameMpl = GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx->elem); + typeNameMpl = GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx->type); + } + FEStructElemInfo *elemInfo = FEManager::GetTypeManager().RegisterStructFieldInfo( + *structElemNameIdx, kSrcLangJava, isStatic); + elemInfo->SetDefined(); + elemInfo->SetFromDex(); + // control anti-proguard through FEOptions only. + FEOptions::ModeJavaStaticFieldName modeStaticField = FEOptions::GetInstance().GetModeJavaStaticFieldName(); + bool withType = (modeStaticField == FEOptions::kAllType) || + (isStatic && modeStaticField == FEOptions::kSmart); + GStrIdx idx; + if (!isStatic && !withType) { + idx = structElemNameIdx->elem; + } else if (isStatic && withType) { + idx = structElemNameIdx->full; + } else { + std::string name = isStatic ? (klassNameMpl + namemangler::kNameSplitterStr) : ""; + name += fieldNameMpl; + name += withType ? (namemangler::kNameSplitterStr + typeNameMpl) : ""; + idx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name); + } + FieldAttrs attrs = AccessFlag2Attribute(field.GetAccessFlag()); + MIRType *fieldType = FEManager::GetTypeManager().GetOrCreateTypeFromName(typeNameMpl, FETypeFlag::kSrcUnknown, true); + ASSERT(fieldType != nullptr, "nullptr check for fieldType"); + mirFieldPair.first = idx; + mirFieldPair.second.first = fieldType->GetTypeIndex(); + mirFieldPair.second.second = attrs; + return true; +} + +// ========== BCClassMethod2FEHelper ========== +BCClassMethod2FEHelper::BCClassMethod2FEHelper(MapleAllocator &allocator, std::unique_ptr &methodIn) + : FEInputMethodHelper(allocator), + method(methodIn) { + srcLang = kSrcLangJava; +} + +bool BCClassMethod2FEHelper::ProcessDeclImpl(MapleAllocator &allocator) { + uint64 mapIdx = (static_cast(method->GetBCClass().GetBCParser().GetReader()->GetFileIndex()) << 32) | + method->GetIdx(); + StructElemNameIdx *structElemNameIdx = FEManager::GetManager().GetMethodStructElemNameIdx(mapIdx); + if (structElemNameIdx == nullptr) { + structElemNameIdx = FEManager::GetManager().GetStructElemMempool()->New( + method->GetClassName(), method->GetName(), method->GetDescription()); + FEManager::GetManager().SetMethodStructElemNameIdx(mapIdx, *structElemNameIdx); + } + const std::string &methodShortName = method->GetName(); + CHECK_FATAL(!methodShortName.empty(), "error: method name is empty"); + if (methodShortName.compare("main") == 0) { + FEManager::GetMIRBuilder().GetMirModule().SetEntryFuncName( + GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx->full)); + } + methodNameIdx = structElemNameIdx->full; + SolveReturnAndArgTypes(allocator); + FuncAttrs attrs = GetAttrs(); + bool isStatic = IsStatic(); + bool isVarg = IsVarg(); + CHECK_FATAL(retType != nullptr, "function must have return type"); + MIRType *mirReturnType = nullptr; + bool usePtr = (srcLang == kSrcLangJava); + if (retType->GetPrimType() == PTY_void) { + mirReturnType = retType->GenerateMIRType(srcLang, false); + } else { + mirReturnType = retType->GenerateMIRType(srcLang, usePtr); + } + ASSERT(mirReturnType != nullptr, "return type is nullptr"); + std::vector argsTypeIdx; + for (FEIRType *type : argTypes) { + MIRType *argType = type->GenerateMIRType(srcLang, usePtr); + argsTypeIdx.emplace_back(argType->GetTypeIndex()); + } + FEStructElemInfo *elemInfo = FEManager::GetTypeManager().RegisterStructMethodInfo( + *structElemNameIdx, kSrcLangJava, isStatic); + elemInfo->SetDefined(); + elemInfo->SetFromDex(); + mirFunc = FEManager::GetTypeManager().CreateFunction(methodNameIdx, mirReturnType->GetTypeIndex(), + argsTypeIdx, isVarg, isStatic); + mirMethodPair.first = mirFunc->GetStIdx(); + mirMethodPair.second.first = mirFunc->GetMIRFuncType()->GetTypeIndex(); + mirMethodPair.second.second = attrs; + mirFunc->SetFuncAttrs(attrs); + return true; +} + +std::string BCClassMethod2FEHelper::GetMethodNameImpl(bool inMpl, bool full) const { + std::string klassName = method->GetClassName(); + std::string methodName = method->GetName(); + if (!full) { + return inMpl ? namemangler::EncodeName(methodName) : methodName; + } + std::string descName = method->GetDescription(); + std::string fullName = klassName + "|" + methodName + "|" + descName; + return inMpl ? namemangler::EncodeName(fullName) : fullName; +} + +void BCClassMethod2FEHelper::SolveReturnAndArgTypesImpl(MapleAllocator &allocator) { + MemPool *mp = allocator.GetMemPool(); + ASSERT(mp != nullptr, "mempool is nullptr"); + std::string klassName = method->GetClassName(); + std::string methodName = GetMethodName(false); + if (HasThis()) { + FEIRTypeDefault *type = mp->New(); + type->LoadFromJavaTypeName(klassName, false); + argTypes.push_back(type); + } + const std::vector &returnAndArgTypeNames = FEUtilJava::SolveMethodSignature(methodName); + bool first = true; + for (const std::string &typeName : returnAndArgTypeNames) { + FEIRTypeDefault *type = mp->New(); + type->LoadFromJavaTypeName(typeName, false); + if (first) { + retType = type; + first = false; + } else { + argTypes.push_back(type); + } + } +} + +bool BCClassMethod2FEHelper::IsVargImpl() const { + return false; // No variable arguments +} + +bool BCClassMethod2FEHelper::HasThisImpl() const { + return !IsStatic(); +} + +MIRType *BCClassMethod2FEHelper::GetTypeForThisImpl() const { + FEIRTypeDefault type; + const std::string &klassName = method->GetClassName(); + type.LoadFromJavaTypeName(klassName, false); + return type.GenerateMIRType(true); +} + +bool BCClassMethod2FEHelper::IsVirtualImpl() const { + return method->IsVirtual(); +} + +bool BCClassMethod2FEHelper::IsNativeImpl() const { + return method->IsNative(); +} + +bool BCClassMethod2FEHelper::HasCodeImpl() const { + return method->HasCode(); +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_function.cpp b/src/mplfe/bc_input/src/bc_function.cpp new file mode 100644 index 0000000000000000000000000000000000000000..911a331ba15713b43c47692753e775acdf9670ff --- /dev/null +++ b/src/mplfe/bc_input/src/bc_function.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_function.h" +#include "fe_macros.h" +#include "fe_manager.h" +namespace maple { +namespace bc { +BCFunction::BCFunction(const BCClassMethod2FEHelper &argMethodHelper, MIRFunction &mirFunc, + const std::unique_ptr &argPhaseResultTotal) + : FEFunction(mirFunc, argPhaseResultTotal), + methodHelper(argMethodHelper), + method(methodHelper.GetMethod()) {} + +void BCFunction::PreProcessImpl() { + ; // Empty +} + +void BCFunction::InitImpl() { + FEFunction::InitImpl(); +} + +bool BCFunction::ProcessImpl() { + FE_INFO_LEVEL(FEOptions::kDumpLevelInfoDetail, "BCFunction::Process() for %s", method->GetFullName().c_str()); + bool success = true; + method->GetBCClass().GetBCParser().ProcessMethodBody(*method, + method->GetBCClass().GetClassIdx(), + method->GetItemIdx(), + method->IsVirtual()); + success = success && GenerateArgVarList("gen arg var list"); + success = success && EmitToFEIRStmt("emit to feir"); + success = success && ProcessFEIRFunction(); + if (!success) { + error = true; + ERR(kLncErr, "BCFunction::Process() failed for %s", method->GetFullName().c_str()); + } + return success; +} + +bool BCFunction::ProcessFEIRFunction() { + bool success = true; + success = success && UpdateRegNum2This("fe/update reg num to this pointer"); + if (FEOptions::GetInstance().GetTypeInferKind() == FEOptions::kRoahAlgorithm) { + success = success && BuildFEIRBB("fe/build feir bb"); + success = success && BuildFEIRCFG("fe/build feir CFG"); + success = success && BuildFEIRDFG("fe/build feir DFG"); + success = success && BuildFEIRUDDU("fe/build feir UDDU"); + success = success && TypeInfer("fe/type infer"); + } + return success; +} + +bool BCFunction::GenerateArgVarList(const std::string &phaseName) { + phaseResult.RegisterPhaseNameAndStart(phaseName); + argVarList = method->GenArgVarList(); + return phaseResult.Finish(); +} + +bool BCFunction::EmitToFEIRStmt(const std::string &phaseName) { + phaseResult.RegisterPhaseNameAndStart(phaseName); + std::list feirStmts = method->EmitInstructionsToFEIR(); + AppendFEIRStmts(feirStmts); + return phaseResult.Finish(true); +} + +void BCFunction::AppendFEIRStmts(std::list &stmts) { + ASSERT_NOT_NULL(feirStmtTail); + InsertFEIRStmtsBefore(*feirStmtTail, stmts); +} + +void BCFunction::InsertFEIRStmtsBefore(FEIRStmt &pos, std::list &stmts) { + while (stmts.size() > 0) { + FEIRStmt *ptrFEIRStmt = RegisterFEIRStmt(std::move(stmts.front())); + stmts.pop_front(); + pos.InsertBefore(ptrFEIRStmt); + } +} + +void BCFunction::FinishImpl() { + (void)UpdateFormal("finish/update formal"); + (void)EmitToMIR("finish/emit to mir"); + bool recordTime = FEOptions::GetInstance().IsDumpPhaseTime() || FEOptions::GetInstance().IsDumpPhaseTimeDetail(); + if (phaseResultTotal != nullptr && recordTime) { + phaseResultTotal->Combine(phaseResult); + } + if (FEOptions::GetInstance().IsDumpPhaseTimeDetail()) { + INFO(kLncInfo, "[PhaseTime] function: %s", method->GetFullName().c_str()); + phaseResult.Dump(); + } + method->ReleaseMempool(); + BCClassMethod *methodPtr = method.release(); + delete methodPtr; +} + +bool BCFunction::EmitToMIR(const std::string &phaseName) { + phaseResult.RegisterPhaseNameAndStart(phaseName); + // Not gen funcbody for abstract method + if (methodHelper.HasCode() || methodHelper.IsNative()) { + mirFunction.NewBody(); + FEManager::GetMIRBuilder().SetCurrentFunction(mirFunction); + EmitToMIRStmt(); + } + return phaseResult.Finish(); +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_instruction.cpp b/src/mplfe/bc_input/src/bc_instruction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f844e0b64c4528f885d6fe1c1550e7f27644c0f8 --- /dev/null +++ b/src/mplfe/bc_input/src/bc_instruction.cpp @@ -0,0 +1,533 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_instruction.h" +#include +#include "bc_class.h" +#include "feir_builder.h" +#include "fe_manager.h" +#include "fe_options.h" + +namespace maple { +namespace bc { +void BCInstruction::InitBCInStruction(uint16 kind, bool wide, bool throwable) { + instKind = static_cast(instKind | kind); + isWide = wide; + isThrowable = throwable; +} + +void BCInstruction::SetWidth(uint8 size) { + width = size; +} + +uint8 BCInstruction::GetWidth() const { + return width; +} + +void BCInstruction::SetCatchable() { + isCatchable = isThrowable; +} + +bool BCInstruction::IsCatchable() const { + return isCatchable; +} + +BCInstructionKind BCInstruction::GetInstKind() const { + return instKind; +} + +bool BCInstruction::IsWide() const { + return isWide; +} + +void BCInstruction::SetInstructionKind(BCInstructionKind kind) { + instKind = static_cast(static_cast(instKind) | static_cast(kind)); +} + +void BCInstruction::Parse(const BCClassMethod &method) { + ParseImpl(method); +} + +void BCInstruction::SetExceptionType(const GStrIdx &typeNameIdx) { + catchedExTypeNamesIdx.emplace(typeNameIdx); + SetBCRegType(*this); +} + +std::list BCInstruction::EmitToFEIRStmts() { + std::list stmts; + // Do not modify following stmt order + GenCommentStmt(stmts); + if ((instKind & kTarget) || (instKind & kCatch)) { + if (instKind & kCatch) { + UniqueFEIRStmt stmt = GenCatchStmt(); + stmts.emplace_back(std::move(stmt));; + } else { + UniqueFEIRStmt stmt = GenLabelStmt(); + stmts.emplace_back(std::move(stmt)); + } + } + if (instKind & kTryStart) { + UniqueFEIRStmt stmt = GenTryLabelStmt(); + stmts.emplace_back(std::move(stmt)); + } + std::list instStmts = EmitToFEIRStmtsImpl(); + for (auto it = instStmts.begin(); it != instStmts.end(); ++it) { + it->get()->SetThrowable(isThrowable); + if (FEOptions::GetInstance().IsAOT()) { + it->get()->SetHexPC(pc); + } + stmts.emplace_back(std::move(*it)); + } + std::list retypeStmts = GenRetypeStmtsAfterDef(); + for (auto it = retypeStmts.begin(); it != retypeStmts.end(); ++it) { + stmts.emplace_back(std::move(*it)); + } + if (instKind & kTryEnd) { + UniqueFEIRStmt stmt = GenTryEndLabelStmt(); + stmts.emplace_back(std::move(stmt)); + } + SetSrcFileInfo(stmts); + return stmts; +} + +void BCInstruction::SetSrcFileInfo(std::list &stmts) const { +#ifdef DEBUG + if (FEOptions::GetInstance().IsDumpLOC() && !stmts.empty()) { + (*stmts.begin())->SetSrcFileInfo(srcFileIdx, srcFileLineNum); + } +#endif +} + +bool BCInstruction::IsFallThru() const { + return instKind & kFallThru; +} + +bool BCInstruction::IsConditionBranch() const { + return instKind & kConditionBranch; +} + +bool BCInstruction::IsGoto() const { + return instKind & kGoto; +} + +bool BCInstruction::IsSwitch() const { + return instKind & kSwitch; +} + +bool BCInstruction::IsTarget() const { + return instKind & kTarget; +} + +bool BCInstruction::IsTryStart() const { + return instKind & kTryStart; +} + +bool BCInstruction::IsTryEnd() const { + return instKind & kTryEnd; +} + +bool BCInstruction::IsCatch() const { + return instKind & kCatch; +} + +void BCInstruction::SetReturnInst(BCInstruction *inst) { + inst->SetBCRegType(*this); + returnInst = inst; +} + +void BCInstruction::SetBCRegType(const BCInstruction &inst) { + SetBCRegTypeImpl(inst); +} + +bool BCInstruction::HasReturn() const { + return returnInst != nullptr; +} + +bool BCInstruction::IsReturn() const { + return isReturn; +} + +uint32 BCInstruction::GetPC() const { + return pc; +} + +uint8 BCInstruction::GetOpcode() const { + return opcode; +} + +std::vector BCInstruction::GetTargets() const { + return GetTargetsImpl(); +} + +void BCInstruction::SetDefultTarget(BCInstruction *inst) { + defaultTarget = inst; +} + +void BCInstruction::AddHandler(BCInstruction *handler) { + auto it = std::find(handlers.begin(), handlers.end(), handler); + if (it == handlers.end()) { + handlers.emplace_back(handler); + } +} + +void BCInstruction::AddHandlerTarget(uint32 target) { + handlerTargets.emplace_back(target); +} + +MapleVector BCInstruction::GetHandlerTargets() const { + return handlerTargets; +} + +MapleList *BCInstruction::GetDefedRegs() { + return &defedRegs; +} + +MapleList *BCInstruction::GetUsedRegs() { + return &usedRegs; +} + +void BCInstruction::SetRegTypeInTypeInfer() { + SetRegTypeInTypeInferImpl(); +} + +std::vector BCInstruction::GetTargetsImpl() const { + return std::vector{}; // Default empty, means invalid +} + +void BCInstruction::GenCommentStmt(std::list &stmts) const { +#ifdef DEBUG + if (FEOptions::GetInstance().IsDumpComment()) { + std::ostringstream oss; + // 4 means 4-character width + oss << "LINE " << FEManager::GetManager().GetSourceFileNameFromIdx(srcFileIdx) << " : " << srcFileLineNum << + ", INST_IDX : " << pc << " ||" << std::setfill('0') << std::setw(4) << std::hex << pc << ": " << + (opName == nullptr ? "invalid op" : opName); + stmts.emplace_back(FEIRBuilder::CreateStmtComment(oss.str())); + } +#endif +} + +UniqueFEIRStmt BCInstruction::GenLabelStmt() const { + return std::make_unique(funcNameIdx, pc); +} + +UniqueFEIRStmt BCInstruction::GenCatchStmt() const { + std::unique_ptr stmt = std::make_unique(funcNameIdx, pc); + for (const auto &exTypeNameIdx : catchedExTypeNamesIdx) { + stmt->AddCatchTypeNameIdx(exTypeNameIdx); + } + return stmt; +} + +UniqueFEIRStmt BCInstruction::GenTryLabelStmt() const { + std::unique_ptr javaTry = std::make_unique(funcNameIdx); + for (const auto &handler : handlers) { + javaTry->AddCatchLabelIdx(handler->GetPC()); + } + return javaTry; +} + +UniqueFEIRStmt BCInstruction::GenTryEndLabelStmt() const { + return std::make_unique(); +} + +std::list BCInstruction::GenRetypeStmtsAfterDef() const { + std::list stmts; + for (BCReg *reg : defedRegs) { + std::list stmts0 = reg->GenRetypeStmtsAfterDef(); + for (auto &stmt : stmts0) { + stmts.emplace_back(std::move(stmt)); + } + } + return stmts; +} + +std::list BCInstruction::GenRetypeStmtsBeforeUse() const { + std::list stmts; + for (BCReg *reg : usedRegs) { + std::list stmts0 = reg->GenRetypeStmtsBeforeUse(); + for (auto &stmt : stmts0) { + stmts.emplace_back(std::move(stmt)); + } + } + return stmts; +} + +void BCInstruction::SetFuncNameIdx(const GStrIdx &methodIdx) { + funcNameIdx = methodIdx; +} + +void BCInstruction::SetSrcPositionInfo(uint32 fileIdxIn, uint32 lineNumIn) { + srcFileIdx = fileIdxIn; + srcFileLineNum = lineNumIn; +} + + +void BCInstruction::SetOpName(const char *name) { +#ifdef DEBUG + opName = name; +#endif +} + +const char *BCInstruction::GetOpName() const { +#ifdef DEBUG + return opName; +#else + return nullptr; +#endif +} + +// ========== BCRegTypeItem ========== +PrimType BCRegTypeItem::GetPrimType() const { + if (isPrimPtr) { + return PTY_ref; + } else { + return GetBasePrimType(); + } +} + +PrimType BCRegTypeItem::GetBasePrimType() const { + return BCUtil::GetPrimType(typeNameIdx); +} + +bool BCRegTypeItem::IsMorePreciseType(const BCRegTypeItem &typeItemIn) const { + if (IsRef() && !typeItemIn.IsRef()) { + return true; + } else if (!IsRef() && typeItemIn.IsRef()) { + return false; + } else if (IsRef() && typeItemIn.IsRef()) { + const std::string &name0 = GlobalTables::GetStrTable().GetStringFromStrIdx(typeNameIdx); + const std::string &name1 = GlobalTables::GetStrTable().GetStringFromStrIdx(typeItemIn.typeNameIdx); + uint8 dim0 = FEUtils::GetDim(name0); + uint8 dim1 = FEUtils::GetDim(name1); + if (dim0 == dim1) { + return name0.substr(dim0).compare(BCUtil::kJavaObjectName) != 0; + } else { + return dim0 > dim1; + } + } else { + if (!isIndeterminate && typeItemIn.isIndeterminate) { + return true; + } else if (isIndeterminate && !typeItemIn.isIndeterminate) { + return false; + } else { + return BCUtil::IsMorePrecisePrimitiveType(typeNameIdx, typeItemIn.typeNameIdx); + } + } +} + +// ========== BCRegType ========== +BCRegType::BCRegType(MapleAllocator &allocatorIn, BCReg ®, const GStrIdx &typeNameIdxIn, + bool isPrimPtrIn, bool isIndeterminateIn) + : allocator(allocatorIn), curReg(reg), + regTypeItem(allocator.GetMemPool()->New(typeNameIdxIn, isPrimPtrIn, isIndeterminateIn)), + typesUsedAs(allocator.Adapter()), + elemTypes(allocator.Adapter()), + arrayTypes(allocator.Adapter()) { + curReg.regTypeItem = regTypeItem; +} + +void BCRegType::UpdateDefTypeFromUse(BCRegTypeItem *typeItem) { + UpdateUsedSet(typeItem); +} + +void BCRegType::UpdateDefTypeThroughPhi(BCReg &defedReg, const std::set &usedTypes) { + UpdateTypeSetFromPhi(defedReg, usedTypes); +} + +void BCRegType::UpdateTypeSetFromPhi(BCReg &defedReg, const std::set &usedTypes) { + bool isIndeterminate = true; + for (auto &elem : usedTypes) { + if (!elem->isIndeterminate) { + isIndeterminate = false; + } + InsertUniqueTypeItem(typesUsedAs, elem); + } + if (isIndeterminate) { + defedReg.regType->UpdateUsedSet(regTypeItem); + } +} + +void BCRegType::PrecisifyTypes() { + if (precisified) { + return; + } + precisified = true; + if (regTypeItem->isIndeterminate) { + BCRegTypeItem *realType = GetMostPreciseType(typesUsedAs); + if (realType != nullptr) { + regTypeItem->Copy(*realType); + } + if (regTypeItem->isIndeterminate) { + // Get type from array elem + for (auto elem : elemTypes) { + elem->PrecisifyTypes(); + std::string arrTypeName = "A" + GlobalTables::GetStrTable().GetStringFromStrIdx(elem->regTypeItem->typeNameIdx); + GStrIdx arrayTypeIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(arrTypeName); + regTypeItem->typeNameIdx = arrayTypeIdx; + regTypeItem->isIndeterminate = false; + } + } else { + const std::string &arrTypeName = GlobalTables::GetStrTable().GetStringFromStrIdx(regTypeItem->typeNameIdx); + for (auto elem : elemTypes) { + if (arrTypeName.size() > 1 && arrTypeName.at(0) == 'A') { + elem->regTypeItem->typeNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(arrTypeName.substr(1)); + elem->regTypeItem->isIndeterminate = false; + } else { + INFO(kLncInfo, "Could not determine the array type thouth its USE, set by its element."); + } + } + } + } + for (auto elem : arrayTypes) { + elem->PrecisifyTypes(); + // Generally, array type could be determined by it USE. + // Otherwise, set it though its element type. + if (elem->IsIndeterminate() || !BCUtil::IsArrayType(elem->regTypeItem->typeNameIdx)) { + std::string arrayTypeName = "A" + GlobalTables::GetStrTable().GetStringFromStrIdx(regTypeItem->typeNameIdx); + GStrIdx arrayTypeIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(arrayTypeName); + elem->regTypeItem->typeNameIdx = arrayTypeIdx; + elem->regTypeItem->isIndeterminate = false; + } + } +} + +BCRegTypeItem *BCRegType::GetMostPreciseType(const MapleVector &types) { + BCRegTypeItem *retType = nullptr; + if (types.empty()) { + return retType; + } + auto it = types.begin(); + retType = *it; + ++it; + while (it != types.end()) { + if ((*it)->IsMorePreciseType(*retType)) { + retType = *it; + } + ++it; + } + return retType; +} + +// ========== BCReg ========== +PrimType BCReg::GetPrimType() const { + return regTypeItem->GetPrimType(); +} + +PrimType BCReg::GetBasePrimType() const { + return regTypeItem->GetBasePrimType(); +} + +bool BCReg::IsConstZero() const { + if (regValue != nullptr) { + return regValue->primValue.raw32 == 0; + } + return false; +} + +UniqueFEIRType BCReg::GenFEIRType() const { + return GenFEIRTypeImpl(); +} + +UniqueFEIRVar BCReg::GenFEIRVarReg() const { + return GenFEIRVarRegImpl(); +} + +UniqueFEIRVar BCReg::GenFEIRVarRegImpl() const { + return std::make_unique(regNum, GenFEIRTypeImpl()); +} + +UniqueFEIRType BCReg::GenFEIRTypeImpl() const { + PrimType pty = GetBasePrimType(); + if (regTypeItem->isPrimPtr && pty != PTY_ref) { + return std::make_unique(std::make_unique(pty, regTypeItem->typeNameIdx)); + } else { + return std::make_unique(pty, regTypeItem->typeNameIdx); + } +} + +std::list BCReg::GenRetypeStmtsAfterDef() const { + std::list retypeStmts; + // Not gen retype stmt for use reg, same def-use type reg. + if (!isDef) { + return retypeStmts; + } + std::unique_ptr dstReg = this->Clone(); + std::unique_ptr tmpItem = std::make_unique(GStrIdx(0), false); + dstReg->regTypeItem = tmpItem.get(); + PrimType ptyDef = regTypeItem->GetPrimType(); + + std::list unqTypeItems; + for (const auto &usedType : *(regType->GetUsedTypes())) { + bool exist = false; + for (const auto &elem : unqTypeItems) { + if ((*usedType) == (*elem)) { + exist = true; + break; + } + } + if (exist == false) { + unqTypeItems.emplace_back(usedType); + } + } + + for (const auto &usedType : unqTypeItems) { + PrimType ptyUsed = usedType->GetPrimType(); + if ((*usedType) == (*regTypeItem) || + (usedType->isIndeterminate && + ((ptyUsed == PTY_i64 && ptyDef == PTY_f64) || (ptyUsed == PTY_i32 && ptyDef == PTY_f32)))) { + continue; + } + // Create retype stmt + dstReg->regTypeItem->Copy(*usedType); + UniqueFEIRStmt retypeStmt = + FEIRBuilder::CreateStmtRetype(dstReg->GenFEIRVarReg(), this->GenFEIRVarReg()); + if (retypeStmt != nullptr) { + retypeStmts.emplace_back(std::move(retypeStmt)); + } + } + return retypeStmts; +} + +std::list BCReg::GenRetypeStmtsBeforeUse() const { + std::list retypeStmts; + // Not gen retype stmt for def reg, same def-use type reg. + // And Not gen retype stmt, if the defiend type is indeterminate. + const BCRegTypeItem *defed = regType->GetRegTypeItem(); + if (isDef) { + return retypeStmts; + } + if (!((*regTypeItem) == (*defed))) { + BCReg srcReg; + std::unique_ptr tmpItem = std::make_unique(GStrIdx(0), false); + srcReg.regTypeItem = tmpItem.get(); + // Create retype stmt + srcReg.regNum = regNum; + srcReg.regTypeItem->Copy(*defed); + UniqueFEIRStmt retypeStmt = + FEIRBuilder::CreateStmtRetype(this->GenFEIRVarReg(), srcReg.GenFEIRVarReg()); + if (retypeStmt != nullptr) { + retypeStmts.emplace_back(std::move(retypeStmt)); + } + } + return retypeStmts; +} + +std::unique_ptr BCReg::CloneImpl() const { + auto reg = std::make_unique(); + *reg = *this; + return reg; +} +} // namespace bc +} // namespace maple diff --git a/src/mplfe/bc_input/src/bc_io.cpp b/src/mplfe/bc_input/src/bc_io.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f7fff6f320f4b6f1945a106cb52afd5a19d7ef6 --- /dev/null +++ b/src/mplfe/bc_input/src/bc_io.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_io.h" +namespace maple { +namespace bc { +BCIO::BCIO(const std::string &fileName) : BasicIOMapFile(fileName), isBigEndianHost(IsBigEndian()) {} + +BCReader::BCReader(const std::string &fileName) : BCIO(fileName), BasicIORead(*this, false) {} + +BCReader::~BCReader() { + Close(); +} + +bool BCReader::RetrieveHeader(RawData &data) { + return RetrieveHeaderImpl(data); +} + +void BCReader::SetEndianTag(bool isBigEndianIn) { + isBigEndian = isBigEndianIn; +} + +bool BCReader::RetrieveHeaderImpl(RawData &data) { + return false; +} + +std::string BCReader::GetStringFromIdx(uint32 idx) const { + return GetStringFromIdxImpl(idx); +} + +std::string BCReader::GetTypeNameFromIdx(uint32 idx) const { + return GetTypeNameFromIdxImpl(idx); +} + +BCReader::ClassElem BCReader::GetClassMethodFromIdx(uint32 idx) const { + return GetClassMethodFromIdxImpl(idx); +} + +BCReader::ClassElem BCReader::GetClassFieldFromIdx(uint32 idx) const { + return GetClassFieldFromIdxImpl(idx); +} + +std::string BCReader::GetSignature(uint32 idx) const { + return GetSignatureImpl(idx); +} + +uint32 BCReader::GetFileIndex() const { + return GetFileIndexImpl(); +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_parser_base.cpp b/src/mplfe/bc_input/src/bc_parser_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89ba8f0bf287b5dac8d16c38843dca212df70876 --- /dev/null +++ b/src/mplfe/bc_input/src/bc_parser_base.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_parser_base.h" +#include "mpl_logging.h" +#include "mir_module.h" +namespace maple { +namespace bc { +BCParserBase::BCParserBase(uint32 fileIdxIn, const std::string &fileNameIn, const std::list &classNamesIn) + : fileIdx(fileIdxIn), fileName(fileNameIn), classNames(classNamesIn), + fileNameHashId(-1) {} + +const BCReader *BCParserBase::GetReader() const { + return GetReaderImpl(); +} + +bool BCParserBase::OpenFile() { + return OpenFileImpl(); +} + +bool BCParserBase::ParseHeader() { + return ParseHeaderImpl(); +} + +bool BCParserBase::Verify() { + return VerifyImpl(); +} + +uint32 BCParserBase::CalculateCheckSum(const uint8 *data, uint32 size) { + return CalculateCheckSumImpl(data, size); +} + +bool BCParserBase::RetrieveClasses(std::list> &klasses) { + if (RetrieveIndexTables() == false) { + ERR(kLncErr, "RetrieveIndexTables failed"); + return false; + } + if (!classNames.empty()) { + return RetrieveUserSpecifiedClasses(klasses); + } else { + return RetrieveAllClasses(klasses); + } +} + +bool BCParserBase::CollectAllDepTypeNames(std::unordered_set &depSet) { + return CollectAllDepTypeNamesImpl(depSet); +} + +bool BCParserBase::CollectMethodDepTypeNames(std::unordered_set &depSet, BCClassMethod &bcMethod) const { + return CollectMethodDepTypeNamesImpl(depSet, bcMethod); +} + +bool BCParserBase::CollectAllClassNames(std::unordered_set &classSet) { + return CollectAllClassNamesImpl(classSet); +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_pragma.cpp b/src/mplfe/bc_input/src/bc_pragma.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d432ec58cae12dba602a297b3afa69bd96c5cbd --- /dev/null +++ b/src/mplfe/bc_input/src/bc_pragma.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_pragma.h" +namespace maple { +namespace bc { +std::vector &BCAnnotationsDirectory::EmitPragmasImpl() { + CHECK_FATAL(false, "this method must be overrided!!!"); + return pragmas; +} +} // namespace bc +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/bc_input/src/bc_util.cpp b/src/mplfe/bc_input/src/bc_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e948aa948ec8496565a692385b16199845f0d014 --- /dev/null +++ b/src/mplfe/bc_input/src/bc_util.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * + * OpenArkCompiler is licensed under Mulan PSL v2. + * You can use this software according to the terms and conditions of the Mulan PSL v2. + * You may obtain a copy of Mulan PSL v2 at: + * + * http://license.coscl.org.cn/MulanPSL2 + * + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR + * FIT FOR A PARTICULAR PURPOSE. + * See the Mulan PSL v2 for more details. + */ +#include "bc_util.h" +#include "fe_utils.h" +#include "fe_options.h" +#include "mpl_logging.h" +namespace maple { +namespace bc { +const std::string BCUtil::kUnknown = "Unknown"; +const std::string BCUtil::kPrimitive = "Primitive"; +const std::string BCUtil::kBoolean = "Z"; +const std::string BCUtil::kByte = "B"; +const std::string BCUtil::kShort = "S"; +const std::string BCUtil::kChar = "C"; +const std::string BCUtil::kInt = "I"; +const std::string BCUtil::kLong = "J"; +const std::string BCUtil::kFloat = "F"; +const std::string BCUtil::kDouble = "D"; +const std::string BCUtil::kVoid = "V"; +const std::string BCUtil::kWide = "wide"; +const std::string BCUtil::kAggregate = "Aggregate"; +const std::string BCUtil::kJavaObjectName = "Ljava/lang/Object;"; +const std::string BCUtil::kJavaStringName = "Ljava/lang/String;"; +const std::string BCUtil::kJavaByteClassName = "Ljava/lang/Byte;"; +const std::string BCUtil::kJavaShortClassName = "Ljava/lang/Short;"; +const std::string BCUtil::kJavaIntClassName = "Ljava/lang/Integer;"; +const std::string BCUtil::kJavaLongClassName = "Ljava/lang/Long;"; +const std::string BCUtil::kJavaFloatClassName = "Ljava/lang/Float;"; +const std::string BCUtil::kJavaDoubleClassName = "Ljava/lang/Double;"; +const std::string BCUtil::kJavaCharClassName = "Ljava/lang/Character;"; +const std::string BCUtil::kJavaBoolClassName = "Ljava/lang/Boolean;"; +const std::string BCUtil::kJavaClassName = "Ljava/lang/Class;"; +const std::string BCUtil::kJavaMethodHandleName = "Ljava/lang/invoke/MethodHandle;"; +const std::string BCUtil::kJavaExceptionName = "Ljava/lang/Exception;"; +const std::string BCUtil::kJavaThrowableName = "Ljava/lang/Throwable;"; + +const std::string BCUtil::kJavaMethodHandleInvoke = "Ljava/lang/invoke/MethodHandle;|invoke|"; +const std::string BCUtil::kJavaMethodHandleInvokeExact = "Ljava/lang/invoke/MethodHandle;|invokeExact|"; + +const std::string BCUtil::kABoolean = "AZ"; +const std::string BCUtil::kAByte = "AB"; +const std::string BCUtil::kAShort = "AS"; +const std::string BCUtil::kAChar = "AC"; +const std::string BCUtil::kAInt = "AI"; +const std::string BCUtil::kALong = "AJ"; +const std::string BCUtil::kAFloat = "AF"; +const std::string BCUtil::kADouble = "AD"; +const std::string BCUtil::kAJavaObjectName = "ALjava/lang/Object;"; + +bool BCUtil::IsWideType(const GStrIdx &name) { + return name == GetDoubleIdx() || name == GetLongIdx(); +} + +bool BCUtil::IsMorePrecisePrimitiveType(const GStrIdx &name0, const GStrIdx &name1) { + static std::vector typeWidthMap = { + BCUtil::GetVoidIdx(), + BCUtil::GetBooleanIdx(), + BCUtil::GetByteIdx(), + BCUtil::GetCharIdx(), + BCUtil::GetShortIdx(), + BCUtil::GetFloatIdx(), + BCUtil::GetIntIdx(), + BCUtil::GetDoubleIdx(), + BCUtil::GetLongIdx() + }; + if (name0 == name1) { + return false; + } + uint32 name0Idx = UINT32_MAX; + uint32 name1Idx = UINT32_MAX; + for (uint32 i = 0; i < typeWidthMap.size(); ++i) { + if (typeWidthMap[i] == name0) { + name0Idx = i; + continue; + } + if (typeWidthMap[i] == name1) { + name1Idx = i; + continue; + } + } + CHECK_FATAL(name0Idx != UINT32_MAX && name1Idx != UINT32_MAX, "name0's or name1's primitive type is not supported."); + return name0Idx > name1Idx; +} + +PrimType BCUtil::GetPrimType(const GStrIdx &typeNameIdx) { + if (typeNameIdx == BCUtil::GetBooleanIdx()) { + return PTY_u1; + } + if (typeNameIdx == BCUtil::GetByteIdx()) { + return PTY_i8; + } + if (typeNameIdx == BCUtil::GetShortIdx()) { + return PTY_i16; + } + if (typeNameIdx == BCUtil::GetCharIdx()) { + return PTY_u16; + } + if (typeNameIdx == BCUtil::GetIntIdx()) { + return PTY_i32; + } + if (typeNameIdx == BCUtil::GetLongIdx()) { + return PTY_i64; + } + if (typeNameIdx == BCUtil::GetFloatIdx()) { + return PTY_f32; + } + if (typeNameIdx == BCUtil::GetDoubleIdx()) { + return PTY_f64; + } + if (typeNameIdx == BCUtil::GetVoidIdx()) { + return PTY_void; + } + // Wide, Primitive, Agg + return PTY_ref; +} + +bool BCUtil::IsJavaReferenceType(const GStrIdx &typeNameIdx) { + PrimType primType = GetPrimType(typeNameIdx); + return (primType == PTY_ref); +} + +bool BCUtil::IsJavaPrimitveType(const GStrIdx &typeNameIdx) { + return !IsJavaReferenceType(typeNameIdx); +} + +bool BCUtil::IsArrayType(const GStrIdx &typeNameIdx) { + std::string typeName = GlobalTables::GetStrTable().GetStringFromStrIdx(typeNameIdx); + uint8 dim = FEUtils::GetDim(typeName); + return dim != 0; +} + +std::string BCUtil::TrimArrayModifier(const std::string &typeName) { + int index = 0; + for (; index < typeName.size(); ++index) { + if (typeName[index] != '[') { + break; + } + } + if (index != 0) { + return typeName.substr(index, typeName.size()); + } else { + return typeName; + } +} + +void BCUtil::AddDefaultDepSet(std::unordered_set &typeTable) { + typeTable.insert("Ljava/lang/Class;"); + typeTable.insert("Ljava/lang/Runnable;"); + typeTable.insert("Ljava/lang/ClassLoader;"); + typeTable.insert("Ljava/lang/StringFactory;"); + // pre-load dependent types for maple_ipa preinline phase + typeTable.insert("Ljava/lang/System;"); + typeTable.insert("Ljava/lang/String;"); + typeTable.insert("Ljava/lang/Math;"); + typeTable.insert("Ljava/lang/Long;"); + typeTable.insert("Ljava/lang/Throwable;"); + typeTable.insert("Ljava/io/PrintStream;"); + typeTable.insert("Ljava/io/InputStream;"); + typeTable.insert("Lsun/misc/FloatingDecimal;"); + typeTable.insert("Ljava/lang/reflect/Field;"); + typeTable.insert("Ljava/lang/annotation/Annotation;"); + typeTable.insert("Ljava/lang/AbstractStringBuilder;"); + typeTable.insert("Ljava/io/UnixFileSystem;"); + typeTable.insert("Ljava/util/concurrent/atomic/AtomicInteger;"); + typeTable.insert("Ljava/lang/reflect/Method;"); +} +} // namespace bc +} // namespace maple diff --git a/src/mplfe/common/include/basic_io.h b/src/mplfe/common/include/basic_io.h index 084318dc564d78eacf74c97ba2d7ee18aa243fb1..c1f8977fa4fd2870c0231c627e9b1c2c8b095dd2 100644 --- a/src/mplfe/common/include/basic_io.h +++ b/src/mplfe/common/include/basic_io.h @@ -94,7 +94,7 @@ class BasicIOMapFile { explicit BasicIOMapFile(const std::string &name); BasicIOMapFile(const std::string &name, const uint8 *ptrIn, long lengthIn); virtual ~BasicIOMapFile(); - bool OpenAndMap(); + virtual bool OpenAndMap(); void Close(); static std::unique_ptr GenFileInMemory(const std::string &name, const uint8 *buf, size_t len); diff --git a/src/mplfe/common/include/fe_config_parallel.h b/src/mplfe/common/include/fe_config_parallel.h index 554cdfd681f6db42cbfc5674a65c4305b819360b..2e2b0ccf8111bd9c94914ea4e35d4fac3f6d4500 100644 --- a/src/mplfe/common/include/fe_config_parallel.h +++ b/src/mplfe/common/include/fe_config_parallel.h @@ -59,6 +59,10 @@ class FEConfigParallel { return runThreadIDs.find(tid) != runThreadIDs.end(); } + void RunThreadIDCleanUp() { + runThreadIDs.clear(); + } + private: static FEConfigParallel instance; uint32 nThread; diff --git a/src/mplfe/common/include/fe_file_type.h b/src/mplfe/common/include/fe_file_type.h index 8f66df5c935b1e21bd8fdaa425b85080d206795b..e615da83e2c7ff496187b499b4789d41802fd59d 100644 --- a/src/mplfe/common/include/fe_file_type.h +++ b/src/mplfe/common/include/fe_file_type.h @@ -23,9 +23,10 @@ namespace maple { class FEFileType { public: enum FileType { - kUnknown, + kUnknownType, kClass, kJar, + kDex, }; inline static FEFileType &GetInstance() { @@ -49,6 +50,7 @@ class FEFileType { static FEFileType fileType; static const uint32 kMagicClass = 0xBEBAFECA; static const uint32 kMagicZip = 0x04034B50; + static const uint32 kMagicDex = 0x0A786564; std::map mapExtNameType; std::map mapTypeMagic; std::map mapMagicType; @@ -57,4 +59,4 @@ class FEFileType { ~FEFileType() = default; }; } -#endif \ No newline at end of file +#endif diff --git a/src/mplfe/common/include/fe_function.h b/src/mplfe/common/include/fe_function.h index 5262d6799b5da16788906560c7b95256a110263a..12aa93427f47d9c398ab092137c420c0ebd718ac 100644 --- a/src/mplfe/common/include/fe_function.h +++ b/src/mplfe/common/include/fe_function.h @@ -29,6 +29,7 @@ #include "fe_timer_ns.h" #include "general_cfg.h" #include "fe_function_phase_result.h" +#include "feir_type_infer.h" namespace maple { class FEFunction { @@ -44,7 +45,10 @@ class FEFunction { const std::unique_ptr &RegisterGeneralStmtUniqueReturn(std::unique_ptr stmt); GeneralBB *RegisterGeneralBB(std::unique_ptr bb); FEIRStmt *RegisterFEIRStmt(UniqueFEIRStmt stmt); - GeneralBB *RegisterFEIRBB(std::unique_ptr bb); + FEIRBB *RegisterFEIRBB(std::unique_ptr bb); + std::string GetDescription(); + void OutputUseDefChain(); + void OutputDefUseChain(); void SetSrcFileName(const std::string &fileName) { srcFileName = fileName; @@ -58,14 +62,18 @@ class FEFunction { PreProcessImpl(); } - void Process() { - ProcessImpl(); + bool Process() { + return ProcessImpl(); } void Finish() { FinishImpl(); } + uint32 GetStmtCount() const { + return stmtCount; + } + LLT_PROTECTED: // run phase routines virtual bool GenerateGeneralStmt(const std::string &phaseName) = 0; @@ -74,23 +82,31 @@ class FEFunction { virtual bool CheckDeadBB(const std::string &phaseName); virtual bool LabelGeneralStmts(const std::string &phaseName); virtual bool LabelGeneralBBs(const std::string &phaseName); - bool ProcessFEIRFunction(); + virtual bool ProcessFEIRFunction(); virtual bool GenerateArgVarList(const std::string &phaseName) = 0; virtual bool EmitToFEIRStmt(const std::string &phaseName) = 0; - bool BuildMapLabelStmt(const std::string &phaseName); - bool SetupFEIRStmtJavaTry(const std::string &phaseName); - bool SetupFEIRStmtBranch(const std::string &phaseName); + virtual bool BuildMapLabelStmt(const std::string &phaseName); + virtual bool SetupFEIRStmtJavaTry(const std::string &phaseName); + virtual bool SetupFEIRStmtBranch(const std::string &phaseName); + virtual bool UpdateRegNum2This(const std::string &phaseName); + bool BuildFEIRBB(const std::string &phaseName); // build fe ir bb chain + bool BuildFEIRCFG(const std::string &phaseName); // build fe ir CFG + bool BuildFEIRDFG(const std::string &phaseName); // process fe ir check point, build fe ir DFG + bool BuildFEIRUDDU(const std::string &phaseName); // build fe ir UD DU chain + bool TypeInfer(const std::string &phaseName); // feir based Type Infer // finish phase routines bool BuildGeneralStmtBBMap(const std::string &phaseName); bool UpdateFormal(const std::string &phaseName); - bool EmitToMIR(const std::string &phaseName); - bool ReleaseGenStmts(const std::string &phaseName); + virtual bool EmitToMIR(const std::string &phaseName); // interface methods virtual void InitImpl(); virtual void PreProcessImpl() {} - virtual void ProcessImpl() {} + virtual bool ProcessImpl() { + return true; + } + virtual void FinishImpl() {} virtual bool PreProcessTypeNameIdx() = 0; virtual void GenerateGeneralStmtFailCallBack() = 0; @@ -111,7 +127,9 @@ class FEFunction { virtual void DumpGeneralCFGGraphForCFGEdge(std::ofstream &file); virtual void DumpGeneralCFGGraphForDFGEdge(std::ofstream &file); virtual bool HasThis() = 0; + virtual bool IsNative() = 0; void BuildMapLabelIdx(); + bool CheckPhaseResult(const std::string &phaseName); GeneralStmt *genStmtHead; GeneralStmt *genStmtTail; @@ -121,33 +139,72 @@ class FEFunction { std::unique_ptr generalCFG; FEIRStmt *feirStmtHead; FEIRStmt *feirStmtTail; - GeneralBB *feirBBHead; - GeneralBB *feirBBTail; + FEIRBB *feirBBHead; + FEIRBB *feirBBTail; std::unique_ptr feirCFG; std::map genStmtBBMap; - std::list> argVarList; + std::vector> argVarList; std::map mapLabelIdx; std::map mapLabelStmt; FEFunctionPhaseResult phaseResult; const std::unique_ptr &phaseResultTotal; std::string srcFileName = ""; + MIRSrcLang srcLang = kSrcLangJava; + MIRFunction &mirFunction; LLT_PRIVATE: - void BuildFEIRBB(); - void BuildFEIRCFG(); - void BuildFEIRDFG(); - void BuildFEIRUDDU(); - void TypeInfer(); + void OutputStmts(); bool SetupFEIRStmtGoto(FEIRStmtGoto &stmt); bool SetupFEIRStmtSwitch(FEIRStmtSwitch &stmt); - FEIRStmtPesudoLOC *GetLOCForStmt(const FEIRStmt &feStmt); - + const FEIRStmtPesudoLOC *GetLOCForStmt(const FEIRStmt &feStmt) const; + void AddLocForStmt(const FEIRStmt &feIRStmt, std::list &mirStmts) const; + void LabelFEIRStmts(); // label fe ir stmts + FEIRBB *NewFEIRBB(uint32 &id); + bool IsBBEnd(const FEIRStmt &stmt) const; + bool MayBeBBEnd(const FEIRStmt &stmt) const; + bool ShouldNewBB(const FEIRBB *currBB, const FEIRStmt &currStmt) const; + void LinkFallThroughBBAndItsNext(FEIRBB &bb); + void LinkBranchBBAndItsTargets(FEIRBB &bb); + void LinkGotoBBAndItsTarget(FEIRBB &bb, const FEIRStmt &stmtTail); + void LinkSwitchBBAndItsTargets(FEIRBB &bb, const FEIRStmt &stmtTail); + void LinkBB(FEIRBB &predBB, FEIRBB &succBB); + FEIRBB &GetFEIRBBByStmt(const FEIRStmt &stmt); + bool CheckBBsStmtNoAuxTail(const FEIRBB &bb); + void ProcessCheckPoints(); + void InsertCheckPointForBBs(); + void InsertCheckPointForTrys(); + void LinkCheckPointBetweenBBs(); + void LinkCheckPointInsideBBs(); + void LinkCheckPointForTrys(); + void LinkCheckPointForTry(FEIRStmtCheckPoint &checkPoint); + void InitFirstVisibleStmtForCheckPoints(); + void InitFEIRStmtCheckPointMap(); + void RegisterDFGNodes2CheckPoints(); + void RegisterDFGNodesForFuncParameters(); + void RegisterDFGNodesForStmts(); + bool CalculateDefs4AllUses(); + void InitTrans4AllVars(); + void InsertRetypeStmtsAfterDef(const UniqueFEIRVar& def); + FEIRStmtPesudoJavaTry2 &GetJavaTryByCheckPoint(FEIRStmtCheckPoint &checkPoint); + FEIRStmtCheckPoint &GetCheckPointByFEIRStmt(const FEIRStmt &stmt); + void SetUpDefVarTypeScatterStmtMap(); + FEIRStmt &GetStmtByDefVarTypeScatter(const FEIRVarTypeScatter &varTypeScatter); + void InsertRetypeStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType); + void InsertCvtStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType); + void InsertJavaMergeStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType); + void InsertDAssignStmt4TypeCvt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType, UniqueFEIRExpr expr); std::list> genStmtList; std::list> genBBList; std::list feirStmtList; - std::list> feirBBList; - MIRFunction &mirFunction; - std::unique_ptr varThis; + std::list> feirBBList; + std::map feirStmtBBMap; + std::map feirStmtCheckPointMap; + std::map checkPointJavaTryMap; + FEIRUseDefChain useDefChain; + FEIRDefUseChain defUseChain; + std::unique_ptr typeInfer; + uint32 stmtCount = 0; + std::map defVarTypeScatterStmtMap; }; } // namespace maple #endif // MPLFE_INCLUDE_COMMON_FE_FUNCTION_H \ No newline at end of file diff --git a/src/mplfe/common/include/fe_input.h b/src/mplfe/common/include/fe_input.h index cbf2f60b5292b893d6f70fb381e3703ad203275f..56c04f52f8488f1ff84131284c130f88deeac900 100644 --- a/src/mplfe/common/include/fe_input.h +++ b/src/mplfe/common/include/fe_input.h @@ -54,7 +54,7 @@ class FEInputContent { public: FEInputContent(MapleAllocator &alloc); ~FEInputContent() = default; - void RegisterItem(T *item); + void RegisterItem(T &item); void CheckSameName(); private: diff --git a/src/mplfe/common/include/fe_input_helper.h b/src/mplfe/common/include/fe_input_helper.h index 0553e530da823a9a65c4066728bc0da16cab6f99..f22fee67fa8460173a1816853cc44123365f0715 100644 --- a/src/mplfe/common/include/fe_input_helper.h +++ b/src/mplfe/common/include/fe_input_helper.h @@ -38,19 +38,18 @@ class FEInputPragmaHelper { public: FEInputPragmaHelper() = default; virtual ~FEInputPragmaHelper() = default; - MIRPragma *GenerateMIRPragma(MapleAllocator &allocator) { - return GenerateMIRPragmaImpl(allocator); + std::vector &GenerateMIRPragmas() { + return GenerateMIRPragmasImpl(); } protected: - virtual MIRPragma *GenerateMIRPragmaImpl(MapleAllocator &allocator) = 0; + virtual std::vector &GenerateMIRPragmasImpl() = 0; }; class FEInputStructHelper; class FEInputFieldHelper { public: - FEInputFieldHelper(MapleAllocator &allocator) - : pragmaHelpers(allocator.Adapter()) {} + FEInputFieldHelper(MapleAllocator &allocator) {} virtual ~FEInputFieldHelper() = default; const FieldPair &GetMIRFieldPair() const { return mirFieldPair; @@ -64,16 +63,14 @@ class FEInputFieldHelper { return ProcessDeclImpl(allocator); } - bool ProcessDeclWithContainer(MapleAllocator &allocator, const FEInputStructHelper &structHelper) { - return ProcessDeclWithContainerImpl(allocator, structHelper); + bool ProcessDeclWithContainer(MapleAllocator &allocator) { + return ProcessDeclWithContainerImpl(allocator); } protected: virtual bool ProcessDeclImpl(MapleAllocator &allocator) = 0; - virtual bool ProcessDeclWithContainerImpl(MapleAllocator &allocator, const FEInputStructHelper &structHelper) = 0; - + virtual bool ProcessDeclWithContainerImpl(MapleAllocator &allocator) = 0; FieldPair mirFieldPair; - MapleList pragmaHelpers; }; class FEInputMethodHelper { @@ -82,7 +79,6 @@ class FEInputMethodHelper { : srcLang(kSrcLangUnknown), feFunc(nullptr), mirFunc(nullptr), - pragmaHelpers(allocator.Adapter()), retType(nullptr), argTypes(allocator.Adapter()), methodNameIdx(GStrIdx(0)) {} @@ -125,6 +121,14 @@ class FEInputMethodHelper { return IsStaticImpl(); } + bool IsVirtual() const { + return IsVirtualImpl(); + } + + bool IsNative() const { + return IsNativeImpl(); + } + bool IsVarg() const { return IsVargImpl(); } @@ -141,21 +145,32 @@ class FEInputMethodHelper { return methodNameIdx; } + bool HasCode() const { + return HasCodeImpl(); + } + + void SetClassTypeInfo(const MIRStructType &structType) { + mirFunc->SetClassTyIdx(structType.GetTypeIndex()); + } + + protected: virtual bool ProcessDeclImpl(MapleAllocator &allocator); virtual void SolveReturnAndArgTypesImpl(MapleAllocator &allocator) = 0; virtual std::string GetMethodNameImpl(bool inMpl, bool full) const = 0; virtual FuncAttrs GetAttrsImpl() const = 0; virtual bool IsStaticImpl() const = 0; + virtual bool IsVirtualImpl() const = 0; + virtual bool IsNativeImpl() const = 0; virtual bool IsVargImpl() const = 0; virtual bool HasThisImpl() const = 0; virtual MIRType *GetTypeForThisImpl() const = 0; + virtual bool HasCodeImpl() const = 0; MIRSrcLang srcLang; FEFunction *feFunc; MIRFunction *mirFunc; MethodPair mirMethodPair; - MapleList pragmaHelpers; FEIRType *retType; MapleVector argTypes; GStrIdx methodNameIdx; @@ -169,13 +184,14 @@ class FEInputStructHelper : public FEInputContainer { mirSymbol(nullptr), fieldHelpers(allocator.Adapter()), methodHelpers(allocator.Adapter()), - pragmaHelpers(allocator.Adapter()), + pragmaHelper(nullptr), isSkipped(false), srcLang(kSrcLangUnknown) {} virtual ~FEInputStructHelper() { mirStructType = nullptr; mirSymbol = nullptr; + pragmaHelper = nullptr; } bool IsSkipped() const { @@ -213,7 +229,7 @@ class FEInputStructHelper : public FEInputContainer { return GetStructNameMplImpl(); } - std::vector GetSuperClassNames() const { + std::list GetSuperClassNames() const { return GetSuperClassNamesImpl(); } @@ -249,13 +265,31 @@ class FEInputStructHelper : public FEInputContainer { InitMethodHelpersImpl(); } + void SetPragmaHelper(FEInputPragmaHelper *pragmaHelperIn) { + pragmaHelper = pragmaHelperIn; + } + + void SetStaticFieldsConstVal(const std::vector &val) { + staticFieldsConstVal = val; + } + + void SetFinalStaticStringIDVec(const std::vector &stringIDVec) { + finalStaticStringID = stringIDVec; + } + + void SetIsOnDemandLoad(bool flag) { + isOnDemandLoad = flag; + } + + void ProcessPragma(); + protected: MIRStructType *GetContainerImpl(); virtual bool PreProcessDeclImpl(); virtual bool ProcessDeclImpl(); virtual std::string GetStructNameOrinImpl() const = 0; virtual std::string GetStructNameMplImpl() const = 0; - virtual std::vector GetSuperClassNamesImpl() const = 0; + virtual std::list GetSuperClassNamesImpl() const = 0; virtual std::vector GetInterfaceNamesImpl() const = 0; virtual std::string GetSourceFileNameImpl() const = 0; virtual std::string GetSrcFileNameImpl() const; @@ -273,15 +307,19 @@ class FEInputStructHelper : public FEInputContainer { void ProcessDeclDefInfoImplementNameForJava(); void ProcessFieldDef(); void ProcessMethodDef(); + void ProcessStaticFields(); MapleAllocator &allocator; MIRStructType *mirStructType; MIRSymbol *mirSymbol; MapleList fieldHelpers; MapleList methodHelpers; - MapleList pragmaHelpers; + FEInputPragmaHelper *pragmaHelper; + std::vector staticFieldsConstVal; + std::vector finalStaticStringID; bool isSkipped; MIRSrcLang srcLang; + bool isOnDemandLoad = false; }; class FEInputHelper { @@ -295,16 +333,16 @@ class FEInputHelper { bool PreProcessDecl(); bool ProcessDecl(); bool ProcessImpl() const; - void RegisterFieldHelper(FEInputFieldHelper *helper) { - fieldHelpers.push_back(helper); + void RegisterFieldHelper(FEInputFieldHelper &helper) { + fieldHelpers.push_back(&helper); } - void RegisterMethodHelper(FEInputMethodHelper *helper) { - methodHelpers.push_back(helper); + void RegisterMethodHelper(FEInputMethodHelper &helper) { + methodHelpers.push_back(&helper); } - void RegisterStructHelper(FEInputStructHelper *helper) { - structHelpers.push_back(helper); + void RegisterStructHelper(FEInputStructHelper &helper) { + structHelpers.push_back(&helper); } private: diff --git a/src/mplfe/common/include/fe_java_string_manager.h b/src/mplfe/common/include/fe_java_string_manager.h index 54ed5cdf266537a98e15ae02333d667307debbee..563724cd318ef06b8bfc571fa4866993fee55d17 100644 --- a/src/mplfe/common/include/fe_java_string_manager.h +++ b/src/mplfe/common/include/fe_java_string_manager.h @@ -23,8 +23,9 @@ namespace maple { class FEJavaStringManager { public: - explicit FEJavaStringManager(MIRModule &argModule); + FEJavaStringManager(MIRModule &argModule, MIRBuilder &mirBuilderIn); ~FEJavaStringManager(); + void ClearStringMetaClassSymbolExternFlag(); // profiling void LoadProfilingData(const std::string &profileFileName); MIRSymbol *GetLiteralPtrVar(const MIRSymbol *var) const; @@ -37,6 +38,7 @@ class FEJavaStringManager { MIRSymbol *GetLiteralVar(const std::u16string &strU16) const; static std::string GetLiteralGlobalName(const std::u16string &strU16); static bool IsAllASCII(const std::u16string &strU16); + void GenStringMetaClassVar(); private: using DWBuffer = struct { @@ -53,12 +55,14 @@ class FEJavaStringManager { static void FinishByteArray(MIRAggConst &newConst, MemPool &mp, DWBuffer &buf, MIRType &uInt64); MIRModule &module; + MIRBuilder &mirBuilder; bool useCompressedJavaString = true; std::unordered_set preloadSet; std::unordered_set literalSet; std::unordered_set fieldValueSet; std::map literalMap; MIRType *typeString = nullptr; + MIRSymbol *stringMetaClassSymbol = nullptr; }; } // namespace maple #endif // MPLFE_INCLUDE_COMMON_FE_JAVA_STRING_MANAGER_H \ No newline at end of file diff --git a/src/mplfe/common/include/fe_manager.h b/src/mplfe/common/include/fe_manager.h index d55c8da5031707cd8622c60f4b42d2670533572f..bb865aa34a9d2298256f237ac0f55da2c6c95c51 100644 --- a/src/mplfe/common/include/fe_manager.h +++ b/src/mplfe/common/include/fe_manager.h @@ -24,25 +24,30 @@ namespace maple { class FEManager { public: static FEManager &GetManager() { - ASSERT(manager, "manager is not initialize"); + ASSERT(manager != nullptr, "manager is not initialize"); return *manager; } static FETypeManager &GetTypeManager() { - ASSERT(manager, "manager is not initialize"); + ASSERT(manager != nullptr, "manager is not initialize"); return manager->typeManager; } static FEJavaStringManager &GetJavaStringManager() { - ASSERT(manager, "manager is not initialize"); + ASSERT(manager != nullptr, "manager is not initialize"); return manager->javaStringManager; } static MIRBuilder &GetMIRBuilder() { - ASSERT(manager, "manager is not initialize"); + ASSERT(manager != nullptr, "manager is not initialize"); return manager->builder; } + static MIRModule &GetModule() { + ASSERT(manager != nullptr, "manager is not initialize"); + return manager->module; + } + static void Init(MIRModule &moduleIn) { manager = new FEManager(moduleIn); } @@ -55,15 +60,93 @@ class FEManager { } } + StructElemNameIdx *GetFieldStructElemNameIdx(uint64 index) { + auto it = mapFieldStructElemNameIdx.find(index); + if (it != mapFieldStructElemNameIdx.end()) { + return it->second; + } + return nullptr; + } + + void SetFieldStructElemNameIdx(uint64 index, StructElemNameIdx &structElemNameIdx) { + std::lock_guard lk(feManagerMapStructElemNameIdxMtx); + mapFieldStructElemNameIdx[index] = &structElemNameIdx; + } + + StructElemNameIdx *GetMethodStructElemNameIdx(uint64 index) { + auto it = mapMethodStructElemNameIdx.find(index); + if (it != mapMethodStructElemNameIdx.end()) { + return it->second; + } + return nullptr; + } + + void SetMethodStructElemNameIdx(uint64 index, StructElemNameIdx &structElemNameIdx) { + std::lock_guard lk(feManagerMapStructElemNameIdxMtx); + mapMethodStructElemNameIdx[index] = &structElemNameIdx; + } + + MemPool *GetStructElemMempool() { + return structElemMempool; + } + + void ReleaseStructElemMempool() { + if (structElemMempool != nullptr) { + delete structElemMempool; + structElemMempool = nullptr; + } + } + + uint32 RegisterSourceFileIdx(const GStrIdx &strIdx) { + auto it = sourceFileIdxMap.find(strIdx); + if (it != sourceFileIdxMap.end()) { + return it->second; + } else { + // make src files start from #2, #1 is mpl file + size_t num = sourceFileIdxMap.size() + 2; + (void)sourceFileIdxMap.emplace(strIdx, num); +#ifdef DEBUG + idxSourceFileMap.emplace(num, strIdx); +#endif + module.PushbackFileInfo(MIRInfoPair(strIdx, num)); + return static_cast(num); + } + } + + std::string GetSourceFileNameFromIdx(uint32 idx) const { + auto it = idxSourceFileMap.find(idx); + if (it != idxSourceFileMap.end()) { + return GlobalTables::GetStrTable().GetStringFromStrIdx(it->second); + } + return "unknown"; + } + private: static FEManager *manager; MIRModule &module; FETypeManager typeManager; - FEJavaStringManager javaStringManager; MIRBuilder builder; + FEJavaStringManager javaStringManager; + MemPool *structElemMempool; + MapleAllocator structElemAllocator; + std::unordered_map mapFieldStructElemNameIdx; + std::unordered_map mapMethodStructElemNameIdx; + std::map sourceFileIdxMap; + std::map idxSourceFileMap; explicit FEManager(MIRModule &moduleIn) - : module(moduleIn), typeManager(module), javaStringManager(moduleIn), builder(&module) {} - ~FEManager() = default; + : module(moduleIn), + typeManager(module), + builder(&module), + javaStringManager(moduleIn, builder), + structElemMempool(memPoolCtrler.NewMemPool("MemPool for StructElemNameIdx")), + structElemAllocator(structElemMempool) {} + ~FEManager() { + if (structElemMempool != nullptr) { + delete structElemMempool; + structElemMempool = nullptr; + } + } + mutable std::mutex feManagerMapStructElemNameIdxMtx; }; } // namespace maple -#endif // MPLFE_INCLUDE_COMMON_FE_MANAGER_H \ No newline at end of file +#endif // MPLFE_INCLUDE_COMMON_FE_MANAGER_H diff --git a/src/mplfe/common/include/fe_options.h b/src/mplfe/common/include/fe_options.h index cdc8b544d3f1cc5d30c722dfdf1ae2db75c25f82..c2eca3d85574d627e2ec71182212ae5bdc7867ad 100644 --- a/src/mplfe/common/include/fe_options.h +++ b/src/mplfe/common/include/fe_options.h @@ -15,6 +15,7 @@ #ifndef MPLFE_INCLUDE_COMMON_FE_OPTIONS_H #define MPLFE_INCLUDE_COMMON_FE_OPTIONS_H #include +#include #include #include #include "mpl_logging.h" @@ -34,6 +35,22 @@ class FEOptions { kSmart // auto anti-proguard }; + enum ModeCollectDepTypes { + kAll = 0, // collect all dependent types + kFunc // collect func dependent types + }; + + enum ModeDepSameNamePolicy { + kSys = 0, // load type form sys when on-demand load same name type + kSrc // load type form src when on-demand load same name type + }; + + enum TypeInferKind { + kNo = 0, + kRoahAlgorithm, + kLinearScan + }; + static FEOptions &GetInstance() { return options; } @@ -53,6 +70,11 @@ class FEOptions { return inputJarFiles; } + void AddInputDexFile(const std::string &fileName); + const std::vector &GetInputDexFiles() const { + return inputDexFiles; + } + void AddInputMpltFileFromSys(const std::string &fileName) { inputMpltFilesFromSys.push_back(fileName); @@ -78,6 +100,47 @@ class FEOptions { return inputMpltFiles; } + // On Demand Type Creation + void SetXBootClassPath(const std::string &fileName) { + strXBootClassPath = fileName; + } + + const std::string &GetXBootClassPath() const { + return strXBootClassPath; + } + + void SetClassLoaderContext(const std::string &fileName) { + strClassLoaderContext = fileName; + } + + const std::string &GetClassLoaderContext() const { + return strClassLoaderContext; + } + + void SetCompileFileName(const std::string &fileName) { + strCompileFileName = fileName; + } + + const std::string &GetCompileFileName() const { + return strCompileFileName; + } + + void SetModeCollectDepTypes(ModeCollectDepTypes mode) { + modeCollectDepTypes = mode; + } + + ModeCollectDepTypes GetModeCollectDepTypes() const { + return modeCollectDepTypes; + } + + void SetModeDepSameNamePolicy(ModeDepSameNamePolicy mode) { + modeDepSameNamePolicy = mode; + } + + ModeDepSameNamePolicy GetModeDepSameNamePolicy() const { + return modeDepSameNamePolicy; + } + // output control options void SetIsGenMpltOnly(bool flag) { isGenMpltOnly = flag; @@ -123,6 +186,14 @@ class FEOptions { return isDumpInstComment; } + void SetNoMplFile() { + isNoMplFile = true; + } + + bool IsNoMplFile() const { + return isNoMplFile; + } + // debug info control options void SetDumpLevel(int level) { dumpLevel = level; @@ -140,6 +211,22 @@ class FEOptions { return isDumpTime; } + void SetIsDumpComment(bool flag) { + isDumpComment = flag; + } + + bool IsDumpComment() const { + return isDumpComment; + } + + void SetIsDumpLOC(bool flag) { + isDumpLOC = flag; + } + + bool IsDumpLOC() const { + return isDumpLOC; + } + void SetIsDumpPhaseTime(bool flag) { isDumpPhaseTime = flag; } @@ -254,14 +341,6 @@ class FEOptions { return dumpThreadTime; } - void SetReleaseAfterEmit(bool arg) { - isReleaseAfterEmit = arg; - } - - bool IsReleaseAfterEmit() const { - return isReleaseAfterEmit; - } - void AddDumpJBCFuncName(const std::string &funcName) { if (!funcName.empty()) { CHECK_FATAL(dumpJBCFuncNames.insert(funcName).second, "dumpJBCFuncNames insert failed"); @@ -276,25 +355,56 @@ class FEOptions { return dumpJBCFuncNames.find(funcName) != dumpJBCFuncNames.end(); } + void SetTypeInferKind(TypeInferKind arg) { + typeInferKind = arg; + } + + TypeInferKind GetTypeInferKind() const { + return typeInferKind; + } + + bool HasJBC() const { + return ((inputClassFiles.size() != 0) || (inputJarFiles.size() != 0)); + } + + void SetIsAOT(bool flag) { + isAOT = flag; + } + + bool IsAOT() const { + return isAOT; + } + private: static FEOptions options; // input control options std::list inputClassFiles; std::list inputJarFiles; + std::vector inputDexFiles; std::list inputMpltFilesFromSys; std::list inputMpltFilesFromApk; std::list inputMpltFiles; + // On Demand Type Creation + std::string strXBootClassPath; + std::string strClassLoaderContext; + std::string strCompileFileName; + ModeCollectDepTypes modeCollectDepTypes = ModeCollectDepTypes::kFunc; + ModeDepSameNamePolicy modeDepSameNamePolicy = ModeDepSameNamePolicy::kSys; + // output control options bool isGenMpltOnly; bool isGenAsciiMplt; std::string outputPath; std::string outputName; bool isDumpInstComment = false; + bool isNoMplFile = false; // debug info control options int dumpLevel; bool isDumpTime; + bool isDumpComment = false; + bool isDumpLOC = false; bool isDumpPhaseTime = false; bool isDumpPhaseTimeDetail = false; @@ -316,7 +426,12 @@ class FEOptions { // parallel uint32 nthreads; bool dumpThreadTime; - bool isReleaseAfterEmit = false; + + // type-infer + TypeInferKind typeInferKind = kLinearScan; + + // symbol resolve + bool isAOT = false; FEOptions(); ~FEOptions() = default; diff --git a/src/mplfe/common/include/fe_struct_elem_info.h b/src/mplfe/common/include/fe_struct_elem_info.h index 8a17329366fa19fe17478a4c0cdbf3d3e8c87bf1..2c479ae8f31e422c03226bac7e09163a9a718b76 100644 --- a/src/mplfe/common/include/fe_struct_elem_info.h +++ b/src/mplfe/common/include/fe_struct_elem_info.h @@ -21,9 +21,28 @@ #include "feir_type.h" namespace maple { +struct StructElemNameIdx { + GStrIdx klass; + GStrIdx elem; + GStrIdx type; + GStrIdx full; + + StructElemNameIdx(const GStrIdx &argKlass, const GStrIdx &argElem, const GStrIdx &argType, const GStrIdx &argFull) + : klass(argKlass), elem(argElem), type(argType), full(argFull) {} + StructElemNameIdx(const std::string &klassStr, const std::string &elemStr, const std::string &typeStr) { + const std::string &fullName = klassStr + "|" + elemStr + "|" + typeStr; + klass = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(klassStr)); + elem = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(elemStr)); + type = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(typeStr)); + full = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(fullName)); + } + ~StructElemNameIdx() = default; +}; + class FEStructElemInfo { public: - FEStructElemInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic); + FEStructElemInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic); virtual ~FEStructElemInfo() = default; void Prepare(MIRBuilder &mirBuilder, bool argIsStatic) { @@ -31,15 +50,15 @@ class FEStructElemInfo { } const std::string &GetStructName() const { - return GlobalTables::GetStrTable().GetStringFromStrIdx(structNameIdx); + return GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx.klass); } const std::string &GetElemName() const { - return GlobalTables::GetStrTable().GetStringFromStrIdx(elemNameIdx); + return GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx.elem); } const std::string &GetSignatureName() const { - return GlobalTables::GetStrTable().GetStringFromStrIdx(signatureNameIdx); + return GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx.type); } bool IsStatic() const { @@ -78,28 +97,30 @@ class FEStructElemInfo { srcLang = lang; } + UniqueFEIRType GetActualContainerType() const; + const std::string &GetActualContainerName() const { + return actualContainer; + } + LLT_PROTECTED: - void Init(); - void InitJava(); virtual void PrepareImpl(MIRBuilder &mirBuilder, bool argIsStatic) = 0; - GStrIdx fullNameIdx; // in maple format + StructElemNameIdx structElemNameIdx; MIRSrcLang srcLang : 8; bool isStatic : 1; bool isMethod : 1; bool isDefined : 1; bool isFromDex : 1; bool isPrepared : 1; - GStrIdx structNameIdx; // in maple format - GStrIdx elemNameIdx; // in maple format - GStrIdx signatureNameIdx; // in maple format + std::string actualContainer; // in maple format }; using UniqueFEStructElemInfo = std::unique_ptr; class FEStructFieldInfo : public FEStructElemInfo { public: - FEStructFieldInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic); + FEStructFieldInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic); ~FEStructFieldInfo() = default; GStrIdx GetFieldNameIdx() const { return fieldNameIdx; @@ -109,6 +130,10 @@ class FEStructFieldInfo : public FEStructElemInfo { return fieldID; } + void SetFieldID(const FieldID argFieldID) { + fieldID = argFieldID; + } + const UniqueFEIRType &GetType() const { return fieldType; } @@ -120,7 +145,7 @@ class FEStructFieldInfo : public FEStructElemInfo { void LoadFieldType(); void LoadFieldTypeJava(); void PrepareStaticField(const MIRStructType &structType); - void PrepareNonStaticField(MIRStructType &structType, MIRBuilder &mirBuilder); + void PrepareNonStaticField(MIRBuilder &mirBuilder); bool SearchStructFieldJava(MIRStructType &structType, MIRBuilder &mirBuilder, bool argIsStatic, bool allowPrivate = true); bool SearchStructFieldJava(const TyIdx &tyIdx, MIRBuilder &mirBuilder, bool argIsStatic, bool allowPrivate = true); @@ -133,7 +158,8 @@ class FEStructFieldInfo : public FEStructElemInfo { class FEStructMethodInfo : public FEStructElemInfo { public: - FEStructMethodInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic); + FEStructMethodInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic); ~FEStructMethodInfo(); PUIdx GetPuIdx() const; bool IsConstructor() const { diff --git a/src/mplfe/common/include/fe_type_manager.h b/src/mplfe/common/include/fe_type_manager.h index a28147621ab62a4a977a80c087b60487244c953d..b0f11e670de1d047538f421ab2b235d7465ef665 100644 --- a/src/mplfe/common/include/fe_type_manager.h +++ b/src/mplfe/common/include/fe_type_manager.h @@ -23,6 +23,7 @@ #include "mir_builder.h" #include "feir_type.h" #include "fe_struct_elem_info.h" +#include "fe_utils.h" namespace maple { enum FETypeFlag : uint16 { @@ -124,6 +125,8 @@ class FETypeManager { return GetOrCreateClassOrInterfacePtrType(nameIdx, isInterface, typeFlag, isCreate); } + + uint32 GetTypeIDFromMplClassName(const std::string &mplClassName) const; MIRStructType *GetStructTypeFromName(const std::string &name); MIRStructType *GetStructTypeFromName(const GStrIdx &nameIdx); MIRType *GetOrCreateTypeFromName(const std::string &name, FETypeFlag typeFlag, bool usePtr); @@ -134,8 +137,10 @@ class FETypeManager { // ---------- methods for StructElemInfo ---------- // structIdx = 0: global field/function without owner structure - FEStructElemInfo *RegisterStructFieldInfo(const GStrIdx &fullNameIdx, MIRSrcLang argSrcLang, bool isStatic); - FEStructElemInfo *RegisterStructMethodInfo(const GStrIdx &fullNameIdx, MIRSrcLang argSrcLang, bool isStatic); + FEStructElemInfo *RegisterStructFieldInfo( + const StructElemNameIdx &argStructElemNameIdx, MIRSrcLang argSrcLang, bool isStatic); + FEStructElemInfo *RegisterStructMethodInfo( + const StructElemNameIdx &argStructElemNameIdx, MIRSrcLang argSrcLang, bool isStatic); FEStructElemInfo *GetStructElemInfo(const GStrIdx &fullNameIdx) const; // ---------- methods for MIRFunction ---------- @@ -195,16 +200,23 @@ class FETypeManager { uint32 dim = 0; return GetBaseTypeName(name, dim, inMpl); } - static void SetComplete(MIRStructType &structType); static std::string TypeAttrsToString(const TypeAttrs &attrs); + bool IsImportedType(const GStrIdx &typeNameIdx) const { + return structNameTypeMap.find(typeNameIdx) != structNameTypeMap.end(); + } + void MarkExternStructType(); + void SetMirImportedTypes(FETypeFlag flag); private: void UpdateStructNameTypeMapFromTypeTable(const std::string &mpltName, FETypeFlag flag); void UpdateNameFuncMapFromTypeTable(); + void UpdateDupTypes(const GStrIdx &nameIdx, bool isInterface, + const std::unordered_map::iterator &importedTypeIt); // MCC function void InitFuncMCCGetOrInsertLiteral(); + void InitFuncMCCStaticField(); MIRModule &module; MemPool *mp; @@ -219,9 +231,11 @@ class FETypeManager { FETypeSameNamePolicy sameNamePolicy; MIRSrcLang srcLang; + // ---------- class name ---> type id map info ---------- + std::unordered_map classNameTypeIDMap; + // ---------- struct elem info ---------- std::map mapStructElemInfo; - std::list listStructElemInfo; // ---------- function list ---------- std::unordered_map nameFuncMap; @@ -237,8 +251,29 @@ class FETypeManager { std::unordered_map nameMCCFuncMap; MIRFunction *funcMCCGetOrInsertLiteral; + MIRFunction *funcMCCStaticFieldGetBool = nullptr; + MIRFunction *funcMCCStaticFieldGetByte = nullptr; + MIRFunction *funcMCCStaticFieldGetShort = nullptr; + MIRFunction *funcMCCStaticFieldGetChar = nullptr; + MIRFunction *funcMCCStaticFieldGetInt = nullptr; + MIRFunction *funcMCCStaticFieldGetLong = nullptr; + MIRFunction *funcMCCStaticFieldGetFloat = nullptr; + MIRFunction *funcMCCStaticFieldGetDouble = nullptr; + MIRFunction *funcMCCStaticFieldGetObject = nullptr; + + MIRFunction *funcMCCStaticFieldSetBool = nullptr; + MIRFunction *funcMCCStaticFieldSetByte = nullptr; + MIRFunction *funcMCCStaticFieldSetShort = nullptr; + MIRFunction *funcMCCStaticFieldSetChar = nullptr; + MIRFunction *funcMCCStaticFieldSetInt = nullptr; + MIRFunction *funcMCCStaticFieldSetLong = nullptr; + MIRFunction *funcMCCStaticFieldSetFloat = nullptr; + MIRFunction *funcMCCStaticFieldSetDouble = nullptr; + MIRFunction *funcMCCStaticFieldSetObject = nullptr; + // ---------- antiproguard ---------- std::set setAntiProguardFieldStructIdx; + mutable std::mutex feTypeManagerMtx; }; } // namespace maple #endif // MPLFE_INCLUDE_COMMON_FE_TYPE_MANAGER_H diff --git a/src/mplfe/common/include/fe_utils.h b/src/mplfe/common/include/fe_utils.h index 8d1565a90f49f1084e83596af30504c11c8fde96..740e6e0e9ff006d5a7d0e6efd465d58c938c6406 100644 --- a/src/mplfe/common/include/fe_utils.h +++ b/src/mplfe/common/include/fe_utils.h @@ -19,6 +19,7 @@ #include #include "mpl_logging.h" #include "prim_types.h" +#include "global_tables.h" namespace maple { class FEUtils { @@ -31,6 +32,191 @@ class FEUtils { static bool IsSignedInteger(PrimType primType); static bool IsUnsignedInteger(PrimType primType); static PrimType MergePrimType(PrimType primType1, PrimType primType2); + static uint8 GetDim(const std::string &typeName); + static std::string GetBaseTypeName(const std::string &typeName); + static PrimType GetPrimType(const GStrIdx &typeNameIdx); + + static const std::string kBoolean; + static const std::string kByte; + static const std::string kShort; + static const std::string kChar; + static const std::string kInt; + static const std::string kLong; + static const std::string kFloat; + static const std::string kDouble; + static const std::string kVoid; + static const std::string kMCCStaticFieldGetBool; + static const std::string kMCCStaticFieldGetByte; + static const std::string kMCCStaticFieldGetChar; + static const std::string kMCCStaticFieldGetShort; + static const std::string kMCCStaticFieldGetInt; + static const std::string kMCCStaticFieldGetLong; + static const std::string kMCCStaticFieldGetFloat; + static const std::string kMCCStaticFieldGetDouble; + static const std::string kMCCStaticFieldGetObject; + + static const std::string kMCCStaticFieldSetBool; + static const std::string kMCCStaticFieldSetByte; + static const std::string kMCCStaticFieldSetChar; + static const std::string kMCCStaticFieldSetShort; + static const std::string kMCCStaticFieldSetInt; + static const std::string kMCCStaticFieldSetLong; + static const std::string kMCCStaticFieldSetFloat; + static const std::string kMCCStaticFieldSetDouble; + static const std::string kMCCStaticFieldSetObject; + + static inline GStrIdx &GetBooleanIdx() { + static GStrIdx booleanIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kBoolean); + return booleanIdx; + } + + static inline GStrIdx &GetByteIdx() { + static GStrIdx byteIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kByte); + return byteIdx; + } + + static inline GStrIdx &GetShortIdx() { + static GStrIdx shortIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kShort); + return shortIdx; + } + + static inline GStrIdx &GetCharIdx() { + static GStrIdx charIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kChar); + return charIdx; + } + + static inline GStrIdx &GetIntIdx() { + static GStrIdx intIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kInt); + return intIdx; + } + + static inline GStrIdx &GetLongIdx() { + static GStrIdx longIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kLong); + return longIdx; + } + + static inline GStrIdx &GetFloatIdx() { + static GStrIdx floatIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kFloat); + return floatIdx; + } + + static inline GStrIdx &GetDoubleIdx() { + static GStrIdx doubleIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kDouble); + return doubleIdx; + } + + static inline GStrIdx &GetVoidIdx() { + static GStrIdx voidIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kVoid); + return voidIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetBoolIdx() { + static GStrIdx mccStaticFieldGetBoolIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetBool); + return mccStaticFieldGetBoolIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetByteIdx() { + static GStrIdx mccStaticFieldGetByteIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetByte); + return mccStaticFieldGetByteIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetShortIdx() { + static GStrIdx mccStaticFieldGetShortIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetShort); + return mccStaticFieldGetShortIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetCharIdx() { + static GStrIdx mccStaticFieldGetCharIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetChar); + return mccStaticFieldGetCharIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetIntIdx() { + static GStrIdx mccStaticFieldGetIntIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetInt); + return mccStaticFieldGetIntIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetLongIdx() { + static GStrIdx mccStaticFieldGetLongIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetLong); + return mccStaticFieldGetLongIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetFloatIdx() { + static GStrIdx mccStaticFieldGetFloatIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetFloat); + return mccStaticFieldGetFloatIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetDoubleIdx() { + static GStrIdx mccStaticFieldGetDoubleIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetDouble); + return mccStaticFieldGetDoubleIdx; + } + + static inline GStrIdx &GetMCCStaticFieldGetObjectIdx() { + static GStrIdx mccStaticFieldGetObjectIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldGetObject); + return mccStaticFieldGetObjectIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetBoolIdx() { + static GStrIdx mccStaticFieldSetBoolIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetBool); + return mccStaticFieldSetBoolIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetByteIdx() { + static GStrIdx mccStaticFieldSetByteIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetByte); + return mccStaticFieldSetByteIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetShortIdx() { + static GStrIdx mccStaticFieldSetShortIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetShort); + return mccStaticFieldSetShortIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetCharIdx() { + static GStrIdx mccStaticFieldSetCharIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetChar); + return mccStaticFieldSetCharIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetIntIdx() { + static GStrIdx mccStaticFieldSetIntIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetInt); + return mccStaticFieldSetIntIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetLongIdx() { + static GStrIdx mccStaticFieldSetLongIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetLong); + return mccStaticFieldSetLongIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetFloatIdx() { + static GStrIdx mccStaticFieldSetFloatIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetFloat); + return mccStaticFieldSetFloatIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetDoubleIdx() { + static GStrIdx mccStaticFieldSetDoubleIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetDouble); + return mccStaticFieldSetDoubleIdx; + } + + static inline GStrIdx &GetMCCStaticFieldSetObjectIdx() { + static GStrIdx mccStaticFieldSetObjectIdx = + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(kMCCStaticFieldSetObject); + return mccStaticFieldSetObjectIdx; + } private: static bool LogicXOR(bool v1, bool v2) { diff --git a/src/mplfe/common/include/fe_utils_java.h b/src/mplfe/common/include/fe_utils_java.h index 503071a7ef06ccb95b8fd477e8ed2fd9683e41d8..b201eccce0882ace98af14b257bfb50adee39d0f 100644 --- a/src/mplfe/common/include/fe_utils_java.h +++ b/src/mplfe/common/include/fe_utils_java.h @@ -21,7 +21,7 @@ namespace maple { class FEUtilJava { public: - static std::vector SolveMethodSignature(std::string signature, bool inMpl = true); + static std::vector SolveMethodSignature(const std::string &signature); static std::string SolveParamNameInJavaFormat(const std::string &signature); private: diff --git a/src/mplfe/common/include/feir_bb.h b/src/mplfe/common/include/feir_bb.h index e5ebcf17e7addef547d735b812f87f91af70aa42..436d6d7eee252494595e99a058b5517aebc71417 100644 --- a/src/mplfe/common/include/feir_bb.h +++ b/src/mplfe/common/include/feir_bb.h @@ -15,18 +15,104 @@ #ifndef MPLFE_INCLUDE_COMMON_FEIR_BB_H #define MPLFE_INCLUDE_COMMON_FEIR_BB_H #include -#include "types_def.h" -#include "mempool_allocator.h" -#include "fe_configs.h" -#include "fe_utils.h" -#include "feir_stmt.h" +#include #include "general_bb.h" +#include "feir_stmt.h" namespace maple { class FEIRBB : public GeneralBB { public: - FEIRBB(MapleAllocator &allocator, uint8 argKind); + FEIRBB(uint8 argKind) : GeneralBB(argKind) {} virtual ~FEIRBB() = default; + void SetCheckPointIn(std::unique_ptr argCheckPointIn) { + checkPointIn = std::move(argCheckPointIn); + } + + FEIRStmtCheckPoint &GetCheckPointIn() const { + return *(checkPointIn.get()); + } + + void SetCheckPointOut(std::unique_ptr argCheckPointOut) { + checkPointOut = std::move(argCheckPointOut); + } + + FEIRStmtCheckPoint &GetCheckPointOut() const { + return *(checkPointOut.get());; + } + + void AddCheckPointInside(std::unique_ptr checkPoint) { + checkPointsInside.push_back(std::move(checkPoint)); + } + + FEIRStmtCheckPoint *GetLatestCheckPointInside() const { + if (checkPointsInside.size() == 0) { + return nullptr; + } + return checkPointsInside.back().get(); + } + + const std::vector> &GetCheckPointsInside() const { + return checkPointsInside; + } + + bool IsFallThru() const { + return stmtNoAuxTail->IsFallThru(); + } + + bool IsBranch() const { + return stmtNoAuxTail->IsBranch(); + } + + const std::map &GetFEIRStmtCheckPointMap() const { + return feirStmtCheckPointMap; + } + + void LinkSuccBBsCheckPoints() { + for (GeneralBB *generalBB : succBBs) { + FEIRBB *succBB = static_cast(generalBB); + FEIRStmtCheckPoint &cpIn = succBB->GetCheckPointIn(); + cpIn.AddPredCheckPoint(GetCheckPointOut()); + } + } + + void LinkCheckPointsInside() { + FEIRStmtCheckPoint *lastCheckPoint = checkPointIn.get(); + for (std::unique_ptr &cp : checkPointsInside) { + cp->AddPredCheckPoint(*lastCheckPoint); + lastCheckPoint = cp.get(); + } + checkPointOut->AddPredCheckPoint(*lastCheckPoint); + } + + void InitFirstVisibleStmtForCheckPoints() { + FELinkListNode *node = nullptr; + FEIRStmt *currStmt = nullptr; + FEIRStmtCheckPoint *currCheckPoint = checkPointOut.get(); + node = currCheckPoint->GetPrev(); + while (node != checkPointIn.get()) { + currStmt = static_cast(node); + if (currStmt->GetKind() == FEIRNodeKind::kStmtCheckPoint) { + currCheckPoint = static_cast(currStmt); + } else { + currCheckPoint->SetFirstVisibleStmt(*currStmt); + (void)feirStmtCheckPointMap.insert(std::make_pair(currStmt, currCheckPoint)); + } + node = node->GetPrev(); + } + } + + void RegisterDFGNodes2CheckPoints() { + for (std::unique_ptr &cp : checkPointsInside) { + cp->RegisterDFGNodeFromAllVisibleStmts(); + } + checkPointOut->RegisterDFGNodeFromAllVisibleStmts(); + } + + private: + std::unique_ptr checkPointIn; + std::vector> checkPointsInside; + std::unique_ptr checkPointOut; + std::map feirStmtCheckPointMap; }; // class FEIRBB } // namespace maple #endif // MPLFE_INCLUDE_COMMON_FEIR_BB_H \ No newline at end of file diff --git a/src/mplfe/common/include/feir_builder.h b/src/mplfe/common/include/feir_builder.h index f908ceefbc7236c26917734d3cc3a5548c856b95..7dee8cc0e9916e4a463fd483133383fe171b49d3 100644 --- a/src/mplfe/common/include/feir_builder.h +++ b/src/mplfe/common/include/feir_builder.h @@ -27,6 +27,7 @@ class FEIRBuilder { ~FEIRBuilder() = default; // Type static UniqueFEIRType CreateType(PrimType basePty, const GStrIdx &baseNameIdx, uint32 dim); + static UniqueFEIRType CreateArrayElemType(const UniqueFEIRType &arrayType); static UniqueFEIRType CreateRefType(const GStrIdx &baseNameIdx, uint32 dim); static UniqueFEIRType CreateTypeByJavaName(const std::string &typeName, bool inMpl); // Var @@ -39,21 +40,26 @@ class FEIRBuilder { // Expr static UniqueFEIRExpr CreateExprDRead(UniqueFEIRVar srcVar); static UniqueFEIRExpr CreateExprConstRefNull(); + static UniqueFEIRExpr CreateExprConstI8(int8 val); + static UniqueFEIRExpr CreateExprConstI16(int16 val); static UniqueFEIRExpr CreateExprConstI32(int32 val); static UniqueFEIRExpr CreateExprConstI64(int64 val); static UniqueFEIRExpr CreateExprConstF32(float val); static UniqueFEIRExpr CreateExprConstF64(double val); static UniqueFEIRExpr CreateExprMathUnary(Opcode op, UniqueFEIRVar var0); + static UniqueFEIRExpr CreateExprMathUnary(Opcode op, UniqueFEIRExpr expr); static UniqueFEIRExpr CreateExprMathBinary(Opcode op, UniqueFEIRVar var0, UniqueFEIRVar var1); static UniqueFEIRExpr CreateExprMathBinary(Opcode op, UniqueFEIRExpr expr0, UniqueFEIRExpr expr1); static UniqueFEIRExpr CreateExprSExt(UniqueFEIRVar srcVar); - static UniqueFEIRExpr CreateExprSExt(UniqueFEIRExpr srcExpr); + static UniqueFEIRExpr CreateExprSExt(UniqueFEIRExpr srcExpr, PrimType dstType); static UniqueFEIRExpr CreateExprZExt(UniqueFEIRVar srcVar); - static UniqueFEIRExpr CreateExprZExt(UniqueFEIRExpr srcExpr); + static UniqueFEIRExpr CreateExprZExt(UniqueFEIRExpr srcExpr, PrimType dstType); static UniqueFEIRExpr CreateExprCvtPrim(UniqueFEIRVar srcVar, PrimType dstType); static UniqueFEIRExpr CreateExprCvtPrim(UniqueFEIRExpr srcExpr, PrimType dstType); static UniqueFEIRExpr CreateExprJavaNewInstance(UniqueFEIRType type); + static UniqueFEIRExpr CreateExprJavaNewInstance(UniqueFEIRType type, uint32 argTypeID); static UniqueFEIRExpr CreateExprJavaNewArray(UniqueFEIRType type, UniqueFEIRExpr exprSize); + static UniqueFEIRExpr CreateExprJavaNewArray(UniqueFEIRType type, UniqueFEIRExpr exprSize, uint32 typeID); static UniqueFEIRExpr CreateExprJavaArrayLength(UniqueFEIRExpr exprArray); // Stmt static UniqueFEIRStmt CreateStmtDAssign(UniqueFEIRVar dstVar, UniqueFEIRExpr srcExpr, bool hasException = false); @@ -63,11 +69,21 @@ class FEIRBuilder { static UniqueFEIRStmt CreateStmtJavaConstClass(UniqueFEIRVar dstVar, UniqueFEIRType type); static UniqueFEIRStmt CreateStmtJavaConstString(UniqueFEIRVar dstVar, const GStrIdx &strIdx); static UniqueFEIRStmt CreateStmtJavaCheckCast(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type); + static UniqueFEIRStmt CreateStmtJavaCheckCast(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type, + uint32 argTypeID); static UniqueFEIRStmt CreateStmtJavaInstanceOf(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type); + static UniqueFEIRStmt CreateStmtJavaInstanceOf(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type, + uint32 argTypeID); + static UniqueFEIRStmt CreateStmtJavaFillArrayData(UniqueFEIRVar argVar, const int8 *arrayData, + uint32 size, const std::string &arrayName); static std::list CreateStmtArrayStore(UniqueFEIRVar varElem, UniqueFEIRVar varArray, - UniqueFEIRVar varIndex, PrimType elemPrimType); + UniqueFEIRVar varIndex); + static UniqueFEIRStmt CreateStmtArrayStoreOneStmt(UniqueFEIRVar varElem, UniqueFEIRVar varArray, + UniqueFEIRExpr exprIndex); static std::list CreateStmtArrayLoad(UniqueFEIRVar varElem, UniqueFEIRVar varArray, - UniqueFEIRVar varIndex, PrimType elemPrimType); + UniqueFEIRVar varIndex); + static UniqueFEIRStmt CreateStmtArrayLength(UniqueFEIRVar varLength, UniqueFEIRVar varArray); + static UniqueFEIRStmt CreateStmtRetype(UniqueFEIRVar varDst, const UniqueFEIRVar &varSrc); static UniqueFEIRStmt CreateStmtComment(const std::string &comment); }; // class FEIRBuilder } // namespace maple diff --git a/src/mplfe/common/include/feir_dfg.h b/src/mplfe/common/include/feir_dfg.h index 7b6fefebd2755ebe5a9373f4520b895f9e850387..4cc2053a50f2a84a4f5c638d4dc9dddafc017242 100644 --- a/src/mplfe/common/include/feir_dfg.h +++ b/src/mplfe/common/include/feir_dfg.h @@ -21,10 +21,8 @@ class FEIRDFG { public: FEIRDFG() = default; ~FEIRDFG() = default; - static void CalculateDefUseByUseDef(std::map> &mapDefUse, - const std::map> &mapUseDef); - static void CalculateUseDefByDefUse(std::map> &mapUseDef, - const std::map> &mapDefUse); + static void CalculateDefUseByUseDef(FEIRDefUseChain &mapDefUse, const FEIRUseDefChain &mapUseDef); + static void CalculateUseDefByDefUse(FEIRUseDefChain &mapUseDef, const FEIRDefUseChain &mapDefUse); }; } // namespace maple #endif // MPLFE_INCLUDE_FEIR_DFG_H \ No newline at end of file diff --git a/src/mplfe/common/include/feir_node_kind.def b/src/mplfe/common/include/feir_node_kind.def new file mode 100644 index 0000000000000000000000000000000000000000..4337b207cf7e91815c738ef89119074b70651664 --- /dev/null +++ b/src/mplfe/common/include/feir_node_kind.def @@ -0,0 +1,58 @@ +// FEIR_NODE_KIND (kind, description) +FEIR_NODE_KIND(Stmt, "Stmt") +FEIR_NODE_KIND(FEIRStmtNary, "FEIRStmtNary") +FEIR_NODE_KIND(StmtAssign, "StmtAssign") +FEIR_NODE_KIND(StmtNonAssign, "StmtNonAssign") +FEIR_NODE_KIND(StmtPesudo, "StmtPesudo") +FEIR_NODE_KIND(StmtDAssign, "StmtDAssign") +FEIR_NODE_KIND(StmtJavaTypeCheck, "StmtJavaTypeCheck") +FEIR_NODE_KIND(StmtJavaConstClass, "StmtJavaConstClass") +FEIR_NODE_KIND(StmtJavaConstString, "StmtJavaConstString") +FEIR_NODE_KIND(StmtJavaMultiANewArray, "StmtJavaMultiANewArray") +FEIR_NODE_KIND(StmtCallAssign, "StmtCallAssign") +FEIR_NODE_KIND(StmtJavaDynamicCallAssign, "StmtJavaDynamicCallAssign") +FEIR_NODE_KIND(StmtIntrinsicCallAssign, "StmtIntrinsicCallAssign") +FEIR_NODE_KIND(StmtIAssign, "StmtIAssign") +FEIR_NODE_KIND(StmtUseOnly, "StmtUseOnly") +FEIR_NODE_KIND(StmtReturn, "StmtReturn") +FEIR_NODE_KIND(StmtBranch, "StmtBranch") +FEIR_NODE_KIND(StmtGoto, "StmtGoto") +FEIR_NODE_KIND(StmtCondGoto, "StmtCondGoto") +FEIR_NODE_KIND(StmtSwitch, "StmtSwitch") +FEIR_NODE_KIND(StmtArrayStore, "StmtArrayStore") +FEIR_NODE_KIND(StmtFieldStore, "StmtFieldStore") +FEIR_NODE_KIND(StmtFieldLoad, "StmtFieldLoad") +FEIR_NODE_KIND(Expr, "Expr") +FEIR_NODE_KIND(ExprNestable, "ExprNestable") +FEIR_NODE_KIND(ExprNonNestable, "ExprNonNestable") +FEIR_NODE_KIND(ExprConst, "ExprConst") +FEIR_NODE_KIND(ExprDRead, "ExprDRead") +FEIR_NODE_KIND(ExprRegRead, "ExprRegRead") +FEIR_NODE_KIND(ExprConvert, "ExprConvert") +FEIR_NODE_KIND(ExprIntExt, "ExprIntExt") +FEIR_NODE_KIND(ExprRetype, "ExprRetype") +FEIR_NODE_KIND(ExprCompare, "ExprCompare") +FEIR_NODE_KIND(ExprUnary, "ExprUnary") +FEIR_NODE_KIND(ExprBinary, "ExprBinary") +FEIR_NODE_KIND(ExprTernary, "ExprTernary") +FEIR_NODE_KIND(ExprNary, "ExprNary") +FEIR_NODE_KIND(ExprArray, "ExprArray") +FEIR_NODE_KIND(ExprIntrinsicop, "ExprIntrinsicop") +FEIR_NODE_KIND(FEIRExprJavaMerge, "FEIRExprJavaMerge") +FEIR_NODE_KIND(ExprTypeCvt, "ExprTypeCvt") +FEIR_NODE_KIND(ExprJavaNewInstance, "ExprJavaNewInstance") +FEIR_NODE_KIND(ExprJavaNewArray, "ExprJavaNewArray") +FEIR_NODE_KIND(ExprJavaArrayLength, "ExprJavaArrayLength") +FEIR_NODE_KIND(ExprJavaInstanceOf, "ExprJavaInstanceOf") +FEIR_NODE_KIND(ExprArrayLoad, "ExprArrayLoad") +FEIR_NODE_KIND(StmtJavaFillArrayData, "StmtJavaFillArrayData") +FEIR_NODE_KIND(StmtPesudoFuncStart, "StmtPesudoFuncStart") +FEIR_NODE_KIND(StmtPesudoFuncEnd, "StmtPesudoFuncEnd") +FEIR_NODE_KIND(StmtCheckPoint, "StmtCheckPoint") +FEIR_NODE_KIND(StmtPesudoLOC, "StmtPesudoLOC") +FEIR_NODE_KIND(StmtPesudoLabel, "StmtPesudoLabel") +FEIR_NODE_KIND(StmtPesudoJavaTry, "StmtPesudoJavaTry") +FEIR_NODE_KIND(StmtPesudoEndTry, "StmtPesudoEndTry") +FEIR_NODE_KIND(StmtPesudoJavaCatch, "StmtPesudoJavaCatch") +FEIR_NODE_KIND(StmtPesudoComment, "StmtPesudoComment") +FEIR_NODE_KIND(StmtPesudoCommentForInst, "StmtPesudoCommentForInst") \ No newline at end of file diff --git a/src/mplfe/common/include/feir_stmt.h b/src/mplfe/common/include/feir_stmt.h index 321a46d15e676f6177d546df03114eb08b6a1611..9d18fab07dbc094819b965f42ce83c907101de70 100644 --- a/src/mplfe/common/include/feir_stmt.h +++ b/src/mplfe/common/include/feir_stmt.h @@ -31,65 +31,21 @@ #include "general_stmt.h" #include "feir_var.h" #include "fe_struct_elem_info.h" +#include "feir_var_type_scatter.h" +#include "fe_options.h" namespace maple { class FEIRBuilder; enum FEIRNodeKind : uint8 { - kStmt, - kStmtAssign, - kStmtNonAssign, - kStmtPesudo, - kStmtDAssign, - kStmtJavaTypeCheck, - kStmtJavaConstClass, - kStmtJavaConstString, - kStmtJavaMultiANewArray, - kStmtCallAssign, - kStmtJavaDynamicCallAssign, - kStmtIAssign, - kStmtUseOnly, - kStmtReturn, - kStmtBranch, - kStmtGoto, - kStmtCondGoto, - kStmtSwitch, - kStmtArrayStore, - kStmtFieldStore, - kStmtFieldLoad, - kExpr, - kExprNestable, - kExprNonNestable, - kExprConst, - kExprDRead, - kExprConvert, - kExprIntExt, - kExprRetype, - kExprCompare, - kExprUnary, - kExprBinary, - kExprTernary, - kExprNary, - kExprArray, - kExprIntrinsicop, - kExprTypeCvt, - kExprJavaNewInstance, - kExprJavaNewArray, - kExprJavaArrayLength, - kExprJavaInstanceOf, - kExprArrayLoad, - kStmtPesudoFuncStart, - kStmtPesudoFuncEnd, - kStmtCheckPoint, - kStmtPesudoLOC, - kStmtPesudoLabel, - kStmtPesudoJavaTry, - kStmtPesudoEndTry, - kStmtPesudoJavaCatch, - kStmtPesudoComment, - kStmtPesudoCommentForInst, +#define FEIR_NODE_KIND(kind, description) \ + k##kind, +#include "feir_node_kind.def" +#undef FEIR_NODE_KIND }; +std::string GetFEIRNodeKindDescription(FEIRNodeKind kindArg); + // ---------- FEIRNode ---------- class FEIRNode { public: @@ -135,6 +91,7 @@ class FEIRDFGNodeHash { using UniqueFEIRDFGNode = std::unique_ptr; +class FEIRStmtCheckPoint; // ---------- FEIRStmt ---------- class FEIRStmt : public GeneralStmt { public: @@ -146,8 +103,26 @@ class FEIRStmt : public GeneralStmt { kind(argKind) {} virtual ~FEIRStmt() = default; + void RegisterDFGNodes2CheckPoint(FEIRStmtCheckPoint &checkPoint) { + RegisterDFGNodes2CheckPointImpl(checkPoint); + } + + bool CalculateDefs4AllUses(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return CalculateDefs4AllUsesImpl(checkPoint, udChain); + } + + void InitTrans4AllVars() { + InitTrans4AllVarsImpl(); + } + + FEIRVarTypeScatter* GetTypeScatterDefVar() const { + return GetTypeScatterDefVarImpl(); + } + std::list GenMIRStmts(MIRBuilder &mirBuilder) const { - return GenMIRStmtsImpl(mirBuilder); + std::list stmts = GenMIRStmtsImpl(mirBuilder); + SetSrcPos(stmts); + return stmts; } FEIRNodeKind GetKind() const { @@ -157,13 +132,86 @@ class FEIRStmt : public GeneralStmt { void SetKind(FEIRNodeKind argKind) { kind = argKind; } + + bool IsFallThrough() const { + return IsFallThroughImpl(); + } + + bool IsTarget() const { + return IsTargetImpl(); + } + + bool HasDef() const { + return HasDefImpl(); + } + + bool SetHexPC(uint32 argHexPC) { + return SetHexPCImpl(argHexPC); + } + + uint32 GetHexPC(void) const { + return GetHexPCImpl(); + } + bool IsStmtInstComment() const; bool ShouldHaveLOC() const; + void SetSrcFileInfo(uint32 srcFileIdxIn, uint32 srcFileLineNumIn) { + srcFileIndex = srcFileIdxIn; + srcFileLineNum = srcFileLineNumIn; + } + protected: + std::string DumpDotStringImpl() const override; + virtual void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) {} + virtual bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return true; + } + + virtual FEIRVarTypeScatter* GetTypeScatterDefVarImpl() const { + return nullptr; + } + + virtual void InitTrans4AllVarsImpl() {} virtual std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const; - virtual bool IsStmtInstImpl() const; + virtual bool IsStmtInstImpl() const override; + virtual bool IsFallThroughImpl() const { + return true; + } + + bool IsBranchImpl() const override { + return false; + } + + virtual bool IsTargetImpl() const { + return false; + } + + virtual bool HasDefImpl() const { + return false; + } + + bool SetHexPCImpl(uint32 argHexPC) { + hexPC = argHexPC; + return true; + } + + uint32 GetHexPCImpl(void) const { + return hexPC; + } + + void SetSrcPos(std::list &stmts) const { +#ifdef DEBUG + if (FEOptions::GetInstance().IsDumpLOC() && !stmts.empty()) { + (*stmts.begin())->GetSrcPos().SetFileNum(srcFileIndex); + (*stmts.begin())->GetSrcPos().SetLineNum(srcFileLineNum); + } +#endif + } FEIRNodeKind kind; + uint32 srcFileIndex = 0; + uint32 srcFileLineNum = 0; + uint32 hexPC = UINT32_MAX; }; using UniqueFEIRStmt = std::unique_ptr; @@ -172,24 +220,36 @@ using UniqueFEIRStmt = std::unique_ptr; class FEIRStmtCheckPoint : public FEIRStmt { public: FEIRStmtCheckPoint() - : FEIRStmt(FEIRNodeKind::kStmtCheckPoint) {} - ~FEIRStmtCheckPoint() = default; + : FEIRStmt(FEIRNodeKind::kStmtCheckPoint), + firstVisibleStmt(nullptr) {} + ~FEIRStmtCheckPoint() { + firstVisibleStmt = nullptr; + } + void Reset(); void RegisterDFGNode(UniqueFEIRVar &var); void RegisterDFGNodes(const std::list &vars); - void AddPredCheckPoint(const UniqueFEIRStmt &stmtCheckPoint); - std::set &CalcuDef(const UniqueFEIRVar &use); + void RegisterDFGNodeFromAllVisibleStmts(); + void AddPredCheckPoint(FEIRStmtCheckPoint &stmtCheckPoint); + std::set &CalcuDef(UniqueFEIRVar &use); + void SetFirstVisibleStmt(FEIRStmt &stmt) { + CHECK_FATAL((stmt.GetKind() != FEIRNodeKind::kStmtCheckPoint), "check point should not be DFG Node."); + firstVisibleStmt = &stmt; + } + + protected: + std::string DumpDotStringImpl() const override; private: void CalcuDefDFS(std::set &result, const UniqueFEIRVar &use, const FEIRStmtCheckPoint &cp, std::set &visitSet) const; - std::set predCPs; std::list defs; std::list uses; - std::map> localUD; + FEIRUseDefChain localUD; std::unordered_map lastDef; std::unordered_map, FEIRDFGNodeHash> cacheUD; + FEIRStmt *firstVisibleStmt; }; // ---------- FEIRExpr ---------- @@ -200,6 +260,7 @@ class FEIRExpr { virtual ~FEIRExpr() = default; FEIRExpr(const FEIRExpr&) = delete; FEIRExpr& operator=(const FEIRExpr&) = delete; + std::string DumpDotString() const; std::unique_ptr Clone() { return CloneImpl(); } @@ -247,10 +308,23 @@ class FEIRExpr { return type->GetPrimType(); } + void RegisterDFGNodes2CheckPoint(FEIRStmtCheckPoint &checkPoint) { + RegisterDFGNodes2CheckPointImpl(checkPoint); + } + + bool CalculateDefs4AllUses(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return CalculateDefs4AllUsesImpl(checkPoint, udChain); + } + protected: virtual std::unique_ptr CloneImpl() const = 0; virtual BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const = 0; virtual std::vector GetVarUsesImpl() const; + virtual void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) {} + virtual bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return true; + } + virtual bool IsNestableImpl() const; virtual bool IsAddrofImpl() const; virtual bool HasExceptionImpl() const; @@ -288,6 +362,7 @@ class FEIRExprConst : public FEIRExpr { BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: + void CheckRawValue2SetZero(); union { int64 valueI64; uint64 valueU64; @@ -304,9 +379,29 @@ class FEIRExprDRead : public FEIRExpr { FEIRExprDRead(std::unique_ptr argType, std::unique_ptr argVarSrc); ~FEIRExprDRead() = default; void SetVarSrc(std::unique_ptr argVarSrc); + void SetTrans(UniqueFEIRVarTrans argTrans) { + varSrc->SetTrans(std::move(argTrans)); + } + + UniqueFEIRVarTrans CreateTransDirect() { + UniqueFEIRVarTrans trans = std::make_unique(FEIRVarTransKind::kFEIRVarTransDirect, varSrc); + return trans; + } + + UniqueFEIRVarTrans CreateTransArrayDimDecr() { + UniqueFEIRVarTrans trans = std::make_unique(FEIRVarTransKind::kFEIRVarTransArrayDimDecr, varSrc); + return trans; + } + + UniqueFEIRVarTrans CreateTransArrayDimIncr() { + UniqueFEIRVarTrans trans = std::make_unique(FEIRVarTransKind::kFEIRVarTransArrayDimIncr, varSrc); + return trans; + } protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; std::vector GetVarUsesImpl() const override; @@ -314,6 +409,20 @@ class FEIRExprDRead : public FEIRExpr { std::unique_ptr varSrc; }; +// ---------- FEIRExprRegRead ---------- +class FEIRExprRegRead : public FEIRExpr { + public: + FEIRExprRegRead(PrimType pty, int32 regNumIn); + ~FEIRExprRegRead() = default; + + protected: + std::unique_ptr CloneImpl() const override; + BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; + + PrimType prmType; + int32 regNum; +}; + // ---------- FEIRExprUnary ---------- class FEIRExprUnary : public FEIRExpr { public: @@ -325,6 +434,8 @@ class FEIRExprUnary : public FEIRExpr { protected: virtual std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; virtual BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; std::vector GetVarUsesImpl() const override; @@ -344,9 +455,12 @@ class FEIRExprTypeCvt : public FEIRExprUnary { FEIRExprTypeCvt(std::unique_ptr exprType, Opcode argOp, std::unique_ptr argOpnd); ~FEIRExprTypeCvt() = default; static std::map InitMapOpNestableForTypeCvt(); + static Opcode ChooseOpcodeByFromVarAndToVar(const FEIRVar &fromVar, const FEIRVar &toVar); protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: @@ -387,6 +501,8 @@ class FEIRExprExtractBits : public FEIRExprUnary { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: @@ -409,6 +525,8 @@ class FEIRExprIRead : public FEIRExprUnary { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: @@ -427,6 +545,8 @@ class FEIRExprBinary : public FEIRExpr { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; std::vector GetVarUsesImpl() const override; bool IsNestableImpl() const override; @@ -460,6 +580,8 @@ class FEIRExprTernary : public FEIRExpr { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; std::vector GetVarUsesImpl() const override; bool IsNestableImpl() const override; @@ -484,6 +606,8 @@ class FEIRExprNary : public FEIRExpr { void ResetOpnd(); protected: + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::vector GetVarUsesImpl() const override; Opcode op; @@ -500,6 +624,8 @@ class FEIRExprArray : public FEIRExprNary { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; bool IsNestableImpl() const override; bool IsAddrofImpl() const override; @@ -513,6 +639,10 @@ class FEIRExprIntrinsicop : public FEIRExprNary { std::unique_ptr argParamType); FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, const std::vector> &argOpnds); + FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, + std::unique_ptr argParamType, uint32 argTypeID); + FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, + std::unique_ptr argParamType, uint32 argTypeID, uint32 argArraySize); FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, std::unique_ptr argParamType, const std::vector> &argOpnds); @@ -520,6 +650,8 @@ class FEIRExprIntrinsicop : public FEIRExprNary { protected: std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; bool IsNestableImpl() const override; bool IsAddrofImpl() const override; @@ -527,23 +659,39 @@ class FEIRExprIntrinsicop : public FEIRExprNary { private: MIRIntrinsicID intrinsicID; std::unique_ptr paramType; + uint32 typeID = UINT32_MAX; + uint32 arraySize = UINT32_MAX; }; // class FEIRExprIntrinsicop +class FEIRExprJavaMerge : public FEIRExprNary { + public: + FEIRExprJavaMerge(std::unique_ptr mergedTypeArg, const std::vector> &argOpnds); + + protected: + std::unique_ptr CloneImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; +}; + // ---------- FEIRExprJavaNewInstance ---------- class FEIRExprJavaNewInstance : public FEIRExpr { public: explicit FEIRExprJavaNewInstance(UniqueFEIRType argType); + FEIRExprJavaNewInstance(UniqueFEIRType argType, uint32 argTypeID); ~FEIRExprJavaNewInstance() = default; protected: std::unique_ptr CloneImpl() const override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; + uint32 typeID = UINT32_MAX; }; // ---------- FEIRExprJavaNewArray ---------- class FEIRExprJavaNewArray : public FEIRExpr { public: FEIRExprJavaNewArray(UniqueFEIRType argArrayType, UniqueFEIRExpr argExprSize); + FEIRExprJavaNewArray(UniqueFEIRType argArrayType, UniqueFEIRExpr argExprSize, uint32 argTypeID); ~FEIRExprJavaNewArray() = default; void SetArrayType(UniqueFEIRType argArrayType) { CHECK_NULL_FATAL(argArrayType); @@ -557,11 +705,15 @@ class FEIRExprJavaNewArray : public FEIRExpr { protected: std::unique_ptr CloneImpl() const override; + std::vector GetVarUsesImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: UniqueFEIRType arrayType; UniqueFEIRExpr exprSize; + uint32 typeID = UINT32_MAX; }; // ---------- FEIRExprJavaArrayLength ---------- @@ -576,6 +728,9 @@ class FEIRExprJavaArrayLength : public FEIRExpr { protected: std::unique_ptr CloneImpl() const override; + std::vector GetVarUsesImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: @@ -593,8 +748,22 @@ class FEIRExprArrayLoad : public FEIRExpr { return typeElem; } + UniqueFEIRVarTrans CreateTransArrayDimDecr() { + FEIRExprDRead *dRead = static_cast(exprArray.get()); + return dRead->CreateTransArrayDimDecr(); + } + + void SetTrans(UniqueFEIRVarTrans argTrans) { + CHECK_FATAL(argTrans->GetTransKind() == kFEIRVarTransArrayDimIncr, "ArrayLoad must hold DimIncr Transfer Function"); + FEIRExprDRead *dRead = static_cast(exprArray.get()); + dRead->SetTrans(std::move(argTrans)); + } + protected: std::unique_ptr CloneImpl() const override; + std::vector GetVarUsesImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; BaseNode *GenMIRNodeImpl(MIRBuilder &mirBuilder) const override; private: @@ -603,6 +772,18 @@ class FEIRExprArrayLoad : public FEIRExpr { UniqueFEIRType typeArray; }; +// ---------- FEIRStmtNary ---------- +class FEIRStmtNary : public FEIRStmt { + public: + FEIRStmtNary(Opcode opIn, std::list> argExprsIn); + ~FEIRStmtNary() = default; + + protected: + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + Opcode op; + std::list> argExprs; +}; + // ---------- FEIRStmtAssign ---------- class FEIRStmtAssign : public FEIRStmt { public: @@ -614,6 +795,7 @@ class FEIRStmtAssign : public FEIRStmt { void SetVar(std::unique_ptr argVar) { var = std::move(argVar); + var->SetDef(HasDef()); } bool HasException() const { @@ -625,6 +807,23 @@ class FEIRStmtAssign : public FEIRStmt { } protected: + bool HasDefImpl() const override { + return ((var != nullptr) && (var.get() != nullptr)); + } + + FEIRVarTypeScatter* GetTypeScatterDefVarImpl() const override { + if (!HasDefImpl()) { + return nullptr; + } + if (var->GetKind() == kFEIRVarTypeScatter) { + FEIRVarTypeScatter *varTypeScatter = static_cast(var.get()); + return varTypeScatter; + } + return nullptr; + } + + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; bool hasException; std::unique_ptr var; }; @@ -643,6 +842,10 @@ class FEIRStmtDAssign : public FEIRStmtAssign { } protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + void InitTrans4AllVarsImpl() override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; std::unique_ptr expr; int32 fieldID; @@ -658,11 +861,17 @@ class FEIRStmtJavaTypeCheck : public FEIRStmtAssign { FEIRStmtJavaTypeCheck(std::unique_ptr argVar, std::unique_ptr argExpr, std::unique_ptr argType, CheckKind argCheckKind); + FEIRStmtJavaTypeCheck(std::unique_ptr argVar, std::unique_ptr argExpr, + std::unique_ptr argType, CheckKind argCheckKind, uint32 argTypeID); ~FEIRStmtJavaTypeCheck() = default; protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; CheckKind checkKind; + uint32 typeID = UINT32_MAX; std::unique_ptr expr; std::unique_ptr type; }; @@ -674,6 +883,7 @@ class FEIRStmtJavaConstClass : public FEIRStmtAssign { ~FEIRStmtJavaConstClass() = default; protected: + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; std::unique_ptr type; }; @@ -682,13 +892,40 @@ class FEIRStmtJavaConstClass : public FEIRStmtAssign { class FEIRStmtJavaConstString : public FEIRStmtAssign { public: FEIRStmtJavaConstString(std::unique_ptr argVar, const GStrIdx &argStrIdx); + FEIRStmtJavaConstString(std::unique_ptr argVar, const GStrIdx &argStrIdx, uint32 argStringID); ~FEIRStmtJavaConstString() = default; protected: + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: GStrIdx strIdx; + uint32 stringID = UINT32_MAX; +}; + +// ---------- FEIRStmtJavaFillArrayData ---------- +class FEIRStmtJavaFillArrayData : public FEIRStmtAssign { + public: + FEIRStmtJavaFillArrayData(std::unique_ptr arrayExprIn, const int8 *arrayDataIn, + uint32 sizeIn, const std::string &arrayNameIn); + ~FEIRStmtJavaFillArrayData() = default; + + protected: + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + LLT_PRIVATE: + PrimType ProcessArrayElemPrimType() const; + MIRSymbol *ProcessArrayElemData(MIRBuilder &mirBuilder, PrimType elemPrimType) const; + MIRAggConst *FillArrayElem(MIRBuilder &mirBuilder, PrimType elemPrimType, MIRType &arrayTypeWithSize, + const int8 *arrayData, uint32 size) const; + + std::unique_ptr arrayExpr; + const int8 *arrayData = nullptr; + uint32 size = 0; + const std::string arrayName; }; // ---------- FEIRStmtJavaMultiANewArray ---------- @@ -700,6 +937,9 @@ class FEIRStmtJavaMultiANewArray : public FEIRStmtAssign { void AddVarSizeRev(std::unique_ptr argVarSize); protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -724,8 +964,17 @@ class FEIRStmtUseOnly : public FEIRStmt { ~FEIRStmtUseOnly() = default; protected: - std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + bool IsFallThroughImpl() const override { + if ((op == OP_return) || (op == OP_throw)) { + return false; + } + return true; + } + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; Opcode op; std::unique_ptr expr; }; @@ -756,12 +1005,38 @@ class FEIRStmtPesudoLabel : public FEIRStmt { } protected: - std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + bool IsTargetImpl() const override { + return true; + } + std::string DumpDotStringImpl() const override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; uint32 labelIdx; LabelIdx mirLabelIdx; }; +class FEIRStmtPesudoLabel2 : public FEIRStmt { + public: + FEIRStmtPesudoLabel2(uint32 qIdx0, uint32 qIdx1) + : FEIRStmt(FEIRNodeKind::kStmtPesudoLabel), labelIdxOuter(qIdx0), labelIdxInner(qIdx1) {} + + ~FEIRStmtPesudoLabel2() = default; + static LabelIdx GenMirLabelIdx(MIRBuilder &mirBuilder, uint32 qIdx0, uint32 qIdx1); + std::pair GetLabelIdx() const; + uint32 GetPos() const { + return labelIdxInner; + } + + protected: + bool IsTargetImpl() const override { + return true; + } + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + uint32 labelIdxOuter; + uint32 labelIdxInner; +}; + // ---------- FEIRStmtGoto ---------- class FEIRStmtGoto : public FEIRStmt { public: @@ -775,8 +1050,8 @@ class FEIRStmtGoto : public FEIRStmt { return labelIdx; } - void SetStmtTarget(FEIRStmtPesudoLabel *argStmtTarget) { - stmtTarget = argStmtTarget; + void SetStmtTarget(FEIRStmtPesudoLabel &argStmtTarget) { + stmtTarget = &argStmtTarget; } const FEIRStmtPesudoLabel &GetStmtTargetRef() const { @@ -785,12 +1060,55 @@ class FEIRStmtGoto : public FEIRStmt { } protected: - std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + bool IsFallThroughImpl() const override { + return false; + } + bool IsBranchImpl() const override { + return true; + } + + std::string DumpDotStringImpl() const override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; uint32 labelIdx; FEIRStmtPesudoLabel *stmtTarget; }; +// ---------- FEIRStmtGoto2 ---------- +class FEIRStmtGoto2 : public FEIRStmt { + public: + FEIRStmtGoto2(uint32 qIdx0, uint32 qIdx1); + virtual ~FEIRStmtGoto2() = default; + std::pair GetLabelIdx() const; + uint32 GetTarget() const { + return labelIdxInner; + } + + void SetStmtTarget(FEIRStmtPesudoLabel2 &argStmtTarget) { + stmtTarget = &argStmtTarget; + } + + const FEIRStmtPesudoLabel2 &GetStmtTargetRef() const { + CHECK_NULL_FATAL(stmtTarget); + return *stmtTarget; + } + + protected: + bool IsFallThroughImpl() const override { + return false; + } + + bool IsBranchImpl() const override { + return true; + } + + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + uint32 labelIdxOuter; + uint32 labelIdxInner; + FEIRStmtPesudoLabel2 *stmtTarget = nullptr; +}; + // ---------- FEIRStmtCondGoto ---------- class FEIRStmtCondGoto : public FEIRStmtGoto { public: @@ -810,6 +1128,39 @@ class FEIRStmtCondGoto : public FEIRStmtGoto { } protected: + bool IsFallThroughImpl() const override { + return true; + } + + bool IsBranchImpl() const override { + return true; + } + + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + private: + Opcode op; + UniqueFEIRExpr expr; +}; + +// ---------- FEIRStmtCondGoto2 ---------- +class FEIRStmtCondGoto2 : public FEIRStmtGoto2 { + public: + FEIRStmtCondGoto2(Opcode argOp, uint32 qIdx0, uint32 qIdx1, UniqueFEIRExpr argExpr); + ~FEIRStmtCondGoto2() = default; + + protected: + bool IsFallThroughImpl() const override { + return true; + } + + bool IsBranchImpl() const override { + return true; + } + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -830,20 +1181,28 @@ class FEIRStmtSwitch : public FEIRStmt { return defaultLabelIdx; } - void SetDefaultTarget(FEIRStmtPesudoLabel *stmtTarget) { - defaultTarget = stmtTarget; + void SetDefaultTarget(FEIRStmtPesudoLabel &stmtTarget) { + defaultTarget = &stmtTarget; + } + + const FEIRStmtPesudoLabel &GetDefaultTarget() const { + return *defaultTarget; } const std::map &GetMapValueLabelIdx() const { return mapValueLabelIdx; } + const std::map &GetMapValueTargets() const { + return mapValueTargets; + } + void AddTarget(int32 value, uint32 labelIdx) { mapValueLabelIdx[value] = labelIdx; } - void AddTarget(int32 value, FEIRStmtPesudoLabel *target) { - mapValueTargets[value] = target; + void AddTarget(int32 value, FEIRStmtPesudoLabel &target) { + mapValueTargets[value] = ⌖ } void SetExpr(UniqueFEIRExpr argExpr) { @@ -852,6 +1211,17 @@ class FEIRStmtSwitch : public FEIRStmt { } protected: + bool IsFallThroughImpl() const override { + return true; + } + + bool IsBranchImpl() const override { + return true; + } + + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -862,6 +1232,69 @@ class FEIRStmtSwitch : public FEIRStmt { UniqueFEIRExpr expr; }; +// ---------- FEIRStmtSwitch2 ---------- +class FEIRStmtSwitch2 : public FEIRStmt { + public: + explicit FEIRStmtSwitch2(uint32 outerIdxIn, UniqueFEIRExpr argExpr); + ~FEIRStmtSwitch2(); + void SetDefaultLabelIdx(uint32 labelIdx) { + defaultLabelIdx = labelIdx; + } + + uint32 GetDefaultLabelIdx() const { + return defaultLabelIdx; + } + + void SetDefaultTarget(FEIRStmtPesudoLabel2 *stmtTarget) { + defaultTarget = stmtTarget; + } + + const FEIRStmtPesudoLabel2 &GetDefaultTarget() const { + return *defaultTarget; + } + + const std::map &GetMapValueLabelIdx() const { + return mapValueLabelIdx; + } + + const std::map &GetMapValueTargets() const { + return mapValueTargets; + } + + void AddTarget(int32 value, uint32 labelIdx) { + mapValueLabelIdx[value] = labelIdx; + } + + void AddTarget(int32 value, FEIRStmtPesudoLabel2 *target) { + mapValueTargets[value] = target; + } + + void SetExpr(UniqueFEIRExpr argExpr) { + CHECK_NULL_FATAL(argExpr); + expr = std::move(argExpr); + } + + protected: + bool IsFallThroughImpl() const override { + return true; + } + + bool IsBranchImpl() const override { + return true; + } + + std::string DumpDotStringImpl() const override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + private: + uint32 outerIdx; + uint32 defaultLabelIdx = UINT32_MAX; + FEIRStmtPesudoLabel2 *defaultTarget; + std::map mapValueLabelIdx; + std::map mapValueTargets; + UniqueFEIRExpr expr; +}; + // ---------- FEIRStmtArrayStore ---------- class FEIRStmtArrayStore : public FEIRStmt { public: @@ -870,6 +1303,10 @@ class FEIRStmtArrayStore : public FEIRStmt { ~FEIRStmtArrayStore() = default; protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; + void InitTrans4AllVarsImpl() override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -887,9 +1324,17 @@ class FEIRStmtFieldStore : public FEIRStmt { ~FEIRStmtFieldStore() = default; protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: + void RegisterDFGNodes2CheckPointForStatic(FEIRStmtCheckPoint &checkPoint); + void RegisterDFGNodes2CheckPointForNonStatic(FEIRStmtCheckPoint &checkPoint); + bool CalculateDefs4AllUsesForStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain); + bool CalculateDefs4AllUsesForNonStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain); + uint32 GetTypeIDForStatic() const; std::list GenMIRStmtsImplForStatic(MIRBuilder &mirBuilder) const; std::list GenMIRStmtsImplForNonStatic(MIRBuilder &mirBuilder) const; @@ -907,9 +1352,17 @@ class FEIRStmtFieldLoad : public FEIRStmtAssign { ~FEIRStmtFieldLoad() = default; protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: + void RegisterDFGNodes2CheckPointForStatic(FEIRStmtCheckPoint &checkPoint); + void RegisterDFGNodes2CheckPointForNonStatic(FEIRStmtCheckPoint &checkPoint); + bool CalculateDefs4AllUsesForStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain); + bool CalculateDefs4AllUsesForNonStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain); + uint32 GetTypeIDForStatic() const; std::list GenMIRStmtsImplForStatic(MIRBuilder &mirBuilder) const; std::list GenMIRStmtsImplForNonStatic(MIRBuilder &mirBuilder) const; @@ -935,6 +1388,9 @@ class FEIRStmtCallAssign : public FEIRStmtAssign { static std::map InitMapOpToOpAssign(); protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + bool CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; std::list GenMIRStmtsUseZeroReturn(MIRBuilder &mirBuilder) const; @@ -949,6 +1405,41 @@ class FEIRStmtCallAssign : public FEIRStmtAssign { static std::map mapOpToOpAssign; }; +// ---------- FEIRStmtIntrinsicCallAssign ---------- +class FEIRStmtIntrinsicCallAssign : public FEIRStmtAssign { + public: + FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, UniqueFEIRVar argVarRet); + FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, UniqueFEIRVar argVarRet, + std::unique_ptr> exprListIn); + FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, const std::string &funcNameIn, const std::string &protoIN, + std::unique_ptr> argsIn); + FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, const std::string &funcNameIn, const std::string &protoIN, + std::unique_ptr> argsIn, uint32 callerClassTypeIDIn, + bool isInStaticFuncIn); + FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, UniqueFEIRVar argVarRet, + uint32 typeIDIn); + ~FEIRStmtIntrinsicCallAssign() = default; + + protected: + std::string DumpDotStringImpl() const override; + void RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + private: + void ConstructArgsForInvokePolyMorphic(MIRBuilder &mirBuilder, MapleVector &intrnCallargs) const; + std::list GenMIRStmtsForInvokePolyMorphic(MIRBuilder &mirBuilder) const; + MIRIntrinsicID intrinsicId; + UniqueFEIRType type; + std::unique_ptr> exprList; + // for polymorphic + const std::string funcName; + const std::string proto; + std::unique_ptr> polyArgs; + uint32 typeID = UINT32_MAX; + uint32 callerClassTypeID = UINT32_MAX; + bool isInStaticFunc = false; +}; + // ---------- FEIRStmtPesudoLOC ---------- class FEIRStmtPesudoLOC : public FEIRStmt { public: @@ -963,6 +1454,7 @@ class FEIRStmtPesudoLOC : public FEIRStmt { } protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -983,11 +1475,16 @@ class FEIRStmtPesudoJavaTry : public FEIRStmt { return catchLabelIdxVec; } - void AddCatchTarget(FEIRStmtPesudoLabel *stmtLabel) { - catchTargets.push_back(stmtLabel); + void AddCatchTarget(FEIRStmtPesudoLabel &stmtLabel) { + catchTargets.push_back(&stmtLabel); + } + + const std::vector &GetCatchTargets() const { + return catchTargets; } protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -995,6 +1492,37 @@ class FEIRStmtPesudoJavaTry : public FEIRStmt { std::vector catchTargets; }; +// ---------- FEIRStmtPesudoJavaTry2 ---------- +class FEIRStmtPesudoJavaTry2 : public FEIRStmt { + public: + FEIRStmtPesudoJavaTry2(uint32 outerIdxIn); + ~FEIRStmtPesudoJavaTry2() = default; + void AddCatchLabelIdx(uint32 labelIdx) { + catchLabelIdxVec.push_back(labelIdx); + } + + const std::vector GetCatchLabelIdxVec() const { + return catchLabelIdxVec; + } + + void AddCatchTarget(FEIRStmtPesudoLabel2 *stmtLabel) { + catchTargets.push_back(stmtLabel); + } + + const std::vector &GetCatchTargets() const { + return catchTargets; + } + + protected: + std::string DumpDotStringImpl() const override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + private: + uint32 outerIdx; + std::vector catchLabelIdxVec; + std::vector catchTargets; +}; + // ---------- FEIRStmtPesudoEndTry ---------- class FEIRStmtPesudoEndTry : public FEIRStmt { public: @@ -1002,6 +1530,7 @@ class FEIRStmtPesudoEndTry : public FEIRStmt { ~FEIRStmtPesudoEndTry() = default; protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; }; @@ -1013,6 +1542,22 @@ class FEIRStmtPesudoCatch : public FEIRStmtPesudoLabel { void AddCatchTypeNameIdx(GStrIdx typeNameIdx); protected: + std::string DumpDotStringImpl() const override; + std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; + + private: + std::list catchTypes; +}; + +// ---------- FEIRStmtPesudoCatch2 ---------- +class FEIRStmtPesudoCatch2 : public FEIRStmtPesudoLabel2 { + public: + explicit FEIRStmtPesudoCatch2(uint32 qIdx0, uint32 qIdx1); + ~FEIRStmtPesudoCatch2() = default; + void AddCatchTypeNameIdx(GStrIdx typeNameIdx); + + protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: @@ -1030,6 +1575,7 @@ class FEIRStmtPesudoComment : public FEIRStmt { } protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; std::string content = ""; @@ -1053,6 +1599,7 @@ class FEIRStmtPesudoCommentForInst : public FEIRStmtPesudoComment { } protected: + std::string DumpDotStringImpl() const override; std::list GenMIRStmtsImpl(MIRBuilder &mirBuilder) const override; private: diff --git a/src/mplfe/common/include/feir_type.h b/src/mplfe/common/include/feir_type.h index 44c0d44d07f834d6da2c6d4b5a39fa4cc9b90b93..c1f1a9da349efe71eb464ed5aaa21ec82a244adf 100644 --- a/src/mplfe/common/include/feir_type.h +++ b/src/mplfe/common/include/feir_type.h @@ -57,6 +57,10 @@ class FEIRType { SetPrimTypeImpl(pt); } + MIRSrcLang GetSrcLang() const { + return srcLang; + } + bool IsZero() const { return isZero; } @@ -145,7 +149,10 @@ class FEIRType { virtual bool IsEqualToImpl(const std::unique_ptr &argType) const; virtual bool IsEqualToImpl(const FEIRType &argType) const; virtual size_t HashImpl() const = 0; - virtual PrimType GetPrimTypeImpl() const = 0; + virtual PrimType GetPrimTypeImpl() const { + return PTY_begin; // Means no valid primtype + } + virtual void SetPrimTypeImpl(PrimType pt) = 0; virtual bool IsRefImpl() const = 0; virtual bool IsArrayImpl() const = 0; @@ -296,7 +303,7 @@ class FEIRTypePointer : public FEIRType { virtual PrimType GetPrimTypeImpl() const override; virtual void SetPrimTypeImpl(PrimType pt) override; virtual bool IsRefImpl() const override { - return baseType->IsRef(); + return true; // pointer type is ref } virtual bool IsArrayImpl() const override { diff --git a/src/mplfe/common/include/feir_type_helper.h b/src/mplfe/common/include/feir_type_helper.h index ca855c9a5b271f8fa6e13eb8e9d9be25cb15832e..e53cbe60d467cee532fecb582eb5b3ea1fc6085f 100644 --- a/src/mplfe/common/include/feir_type_helper.h +++ b/src/mplfe/common/include/feir_type_helper.h @@ -23,7 +23,7 @@ namespace maple { class FEIRTypeHelper { public: static UniqueFEIRType CreateTypeByPrimType(PrimType primType, TypeDim dim = 0, bool usePtr = false); - static UniqueFEIRType CreateTypeByJavaName(const std::string typeName, bool inMpl, bool usePtr); + static UniqueFEIRType CreateTypeByJavaName(const std::string &typeName, bool inMpl, bool usePtr); static UniqueFEIRType CreatePointerType(UniqueFEIRType baseType, PrimType primType = PTY_ptr); static UniqueFEIRType CreateTypeByDimIncr(const UniqueFEIRType &srcType, uint8 delta, bool usePtr = false, PrimType primType = PTY_ptr); diff --git a/src/mplfe/common/include/feir_type_infer.h b/src/mplfe/common/include/feir_type_infer.h index 8c5eafcc056613b5b430086af9dd6e403f727515..0afe6e11eb0c6a9139411a1caa09184965157d0d 100644 --- a/src/mplfe/common/include/feir_type_infer.h +++ b/src/mplfe/common/include/feir_type_infer.h @@ -52,7 +52,7 @@ class FEIRTypeMergeHelper { class FEIRTypeInfer { public: - FEIRTypeInfer(MIRSrcLang argSrcLang, const std::map> &argMapDefUse); + FEIRTypeInfer(MIRSrcLang argSrcLang, const FEIRDefUseChain &argMapDefUse); ~FEIRTypeInfer() = default; void LoadTypeDefault(); void Reset(); @@ -65,10 +65,19 @@ class FEIRTypeInfer { MIRSrcLang srcLang; UniqueFEIRType typeDefault; FEIRTypeMergeHelper mergeHelper; - const std::map> &mapDefUse; + const FEIRDefUseChain &mapDefUse; std::set visitVars; bool withCircle = false; bool first = false; }; + +class FEIRTypeCvtHelper { + public: + static Opcode ChooseCvtOpcodeByFromTypeAndToType(const FEIRType &fromType, const FEIRType &toType); + + private: + static bool IsRetypeable(const FEIRType &fromType, const FEIRType &toType); + static bool IsIntCvt2Ref(const FEIRType &fromType, const FEIRType &toType); +}; } // namespace maple #endif // MPLFE_INCLUDE_FEIR_TYPE_INFER_H diff --git a/src/mplfe/common/include/feir_var.h b/src/mplfe/common/include/feir_var.h index b98e31eecd2bd8168966b7eb2cc00275a80e11b3..7863bf13883cbffc866cbec00f338a31ed6981b6 100644 --- a/src/mplfe/common/include/feir_var.h +++ b/src/mplfe/common/include/feir_var.h @@ -44,6 +44,10 @@ class FEIRVarTrans { kind = argKind; } + FEIRVarTransKind GetTransKind() const { + return kind; + } + private: FEIRVarTransKind kind; std::unique_ptr &var; @@ -58,6 +62,7 @@ enum FEIRVarKind : uint8 { kFEIRVarDefault = 0, kFEIRVarSpecial, kFEIRVarReg, + kFEIRVarAccumulator, kFEIRVarName, kFEIRVarNameSpec, kFEIRVarTypeScatter, @@ -156,5 +161,9 @@ class FEIRVar { }; using UniqueFEIRVar = std::unique_ptr; +// FEIRUseDefChain key is use, value is def set +using FEIRUseDefChain = std::map>; +// FEIRUseDefChain key is def, value is use set +using FEIRDefUseChain = std::map>; } // namespace maple #endif // MPLFE_INCLUDE_FEIR_VAR_H diff --git a/src/mplfe/common/include/feir_var_reg.h b/src/mplfe/common/include/feir_var_reg.h index 3ece97f7bd616b9c2dce65232e079162a39c96c3..82c602a416dc300140a24c2bfdd324c4c31f6cf5 100644 --- a/src/mplfe/common/include/feir_var_reg.h +++ b/src/mplfe/common/include/feir_var_reg.h @@ -20,8 +20,8 @@ namespace maple { class FEIRVarReg : public FEIRVar { public: - FEIRVarReg(uint32 argRegNum) - : FEIRVar(FEIRVarKind::kFEIRVarReg), + FEIRVarReg(uint32 argRegNum, FEIRVarKind kind = FEIRVarKind::kFEIRVarReg) + : FEIRVar(kind), regNum(argRegNum) {} FEIRVarReg(uint32 argRegNum, PrimType argPrimType) @@ -29,8 +29,8 @@ class FEIRVarReg : public FEIRVar { type->SetPrimType(argPrimType); } - FEIRVarReg(uint32 argRegNum, std::unique_ptr argType) - : FEIRVar(FEIRVarKind::kFEIRVarReg, std::move(argType)), + FEIRVarReg(uint32 argRegNum, std::unique_ptr argType, FEIRVarKind kind = FEIRVarKind::kFEIRVarReg) + : FEIRVar(kind, std::move(argType)), regNum(argRegNum) {} ~FEIRVarReg() = default; @@ -44,9 +44,28 @@ class FEIRVarReg : public FEIRVar { std::unique_ptr CloneImpl() const override; bool EqualsToImpl(const std::unique_ptr &var) const override; size_t HashImpl() const override; - - private: uint32 regNum; }; + +class FEIRVarAccumulator : public FEIRVarReg { + public: + FEIRVarAccumulator(uint32 argRegNum) + : FEIRVarReg(argRegNum, FEIRVarKind::kFEIRVarAccumulator) {} + + FEIRVarAccumulator(uint32 argRegNum, PrimType argPrimType) + : FEIRVarAccumulator(argRegNum) { + type->SetPrimType(argPrimType); + } + + FEIRVarAccumulator(uint32 argRegNum, std::unique_ptr argType) + : FEIRVarReg(argRegNum, std::move(argType), FEIRVarKind::kFEIRVarAccumulator) {} + + ~FEIRVarAccumulator() = default; + + protected: + std::string GetNameImpl(const MIRType &mirType) const override; + std::string GetNameRawImpl() const override; + std::unique_ptr CloneImpl() const override; +}; } // namespace maple #endif // MPLFE_INCLUDE_FEIR_VAR_REG_H \ No newline at end of file diff --git a/src/mplfe/common/include/feir_var_type_scatter.h b/src/mplfe/common/include/feir_var_type_scatter.h index a414603e1ea872ed6838972db85ef0b860ce77c4..e4cd48eebef53a4fd76a8a6d498fe9cb73ffd97b 100644 --- a/src/mplfe/common/include/feir_var_type_scatter.h +++ b/src/mplfe/common/include/feir_var_type_scatter.h @@ -33,6 +33,9 @@ class FEIRVarTypeScatter : public FEIRVar { } protected: + MIRSymbol *GenerateGlobalMIRSymbolImpl(MIRBuilder &builder) const override; + MIRSymbol *GenerateLocalMIRSymbolImpl(MIRBuilder &builder) const override; + MIRSymbol *GenerateMIRSymbolImpl(MIRBuilder &builder) const override; std::string GetNameImpl(const MIRType &mirType) const override; std::string GetNameRawImpl() const override; std::unique_ptr CloneImpl() const override; diff --git a/src/mplfe/common/include/general_bb.h b/src/mplfe/common/include/general_bb.h index b7069422cee1e99a975a9196c78b17f9ca0aa6b1..cac959d9c3c073b5ec6bf624b5d3c47faf135187 100644 --- a/src/mplfe/common/include/general_bb.h +++ b/src/mplfe/common/include/general_bb.h @@ -34,40 +34,58 @@ class GeneralBB : public FELinkListNode { GeneralBB(); explicit GeneralBB(uint8 argKind); virtual ~GeneralBB(); - void AppendStmt(const GeneralStmt *stmt); - void AddStmtAuxPre(const GeneralStmt *stmt); - void AddStmtAuxPost(const GeneralStmt *stmt); + void AppendStmt(GeneralStmt &stmt); + void AddStmtAuxPre(GeneralStmt &stmt); + void AddStmtAuxPost(GeneralStmt &stmt); bool IsPredBB(uint32 bbID); bool IsSuccBB(uint32 bbID); uint8 GetBBKind() const { return kind; } - const GeneralStmt *GetStmtHead() const { + GeneralStmt *GetStmtHead() const { return stmtHead; } - const GeneralStmt *GetStmtTail() const { + void SetStmtHead(GeneralStmt &stmtHeadIn) { + stmtHead = &stmtHeadIn; + } + + void InsertAndUpdateNewHead(GeneralStmt &newHead) { + stmtHead->InsertBefore(&newHead); + stmtHead = &newHead; + } + + GeneralStmt *GetStmtTail() const { return stmtTail; } - const GeneralStmt *GetStmtNoAuxHead() const { + void SetStmtTail(GeneralStmt &stmtTailIn) { + stmtTail = &stmtTailIn; + } + + void InsertAndUpdateNewTail(GeneralStmt &newTail) { + stmtTail->InsertAfter(&newTail); + stmtTail = &newTail; + } + + GeneralStmt *GetStmtNoAuxHead() const { return stmtNoAuxHead; } - const GeneralStmt *GetStmtNoAuxTail() const { + GeneralStmt *GetStmtNoAuxTail() const { return stmtNoAuxTail; } - void AddPredBB(GeneralBB *bb) { - if (predBBs.find(bb) == predBBs.end()) { - CHECK_FATAL(predBBs.insert(bb).second, "predBBs insert failed"); + void AddPredBB(GeneralBB &bb) { + if (predBBs.find(&bb) == predBBs.end()) { + CHECK_FATAL(predBBs.insert(&bb).second, "predBBs insert failed"); } } - void AddSuccBB(GeneralBB *bb) { - if (succBBs.find(bb) == succBBs.end()) { - CHECK_FATAL(succBBs.insert(bb).second, "succBBs insert failed"); + void AddSuccBB(GeneralBB &bb) { + if (succBBs.find(&bb) == succBBs.end()) { + CHECK_FATAL(succBBs.insert(&bb).second, "succBBs insert failed"); } } @@ -87,12 +105,12 @@ class GeneralBB : public FELinkListNode { id = arg; } - bool IsPredBB(GeneralBB *bb) { - return predBBs.find(bb) != predBBs.end(); + bool IsPredBB(GeneralBB &bb) { + return predBBs.find(&bb) != predBBs.end(); } - bool IsSuccBB(GeneralBB *bb) { - return succBBs.find(bb) != succBBs.end(); + bool IsSuccBB(GeneralBB &bb) { + return succBBs.find(&bb) != succBBs.end(); } bool IsDead() { @@ -113,10 +131,10 @@ class GeneralBB : public FELinkListNode { virtual std::string GetBBKindNameImpl() const; uint8 kind; - const GeneralStmt *stmtHead; - const GeneralStmt *stmtTail; - const GeneralStmt *stmtNoAuxHead; - const GeneralStmt *stmtNoAuxTail; + GeneralStmt *stmtHead; + GeneralStmt *stmtTail; + GeneralStmt *stmtNoAuxHead; + GeneralStmt *stmtNoAuxTail; std::set predBBs; std::set succBBs; uint32 id; diff --git a/src/mplfe/common/include/general_stmt.h b/src/mplfe/common/include/general_stmt.h index d6f7e05e9a99aa6be1aa7e2f3e8d36b7efc721c3..40563cf1c1b82da8cbafc3cf146589de1f63976e 100644 --- a/src/mplfe/common/include/general_stmt.h +++ b/src/mplfe/common/include/general_stmt.h @@ -46,6 +46,14 @@ class GeneralStmt : public FELinkListNode { isFallThru = arg; } + bool IsThrowable() const { + return isThrowable; + } + + void SetThrowable(bool argIsThrowable) { + isThrowable = argIsThrowable; + } + bool IsAuxPre() const { return isAuxPre; } @@ -58,6 +66,10 @@ class GeneralStmt : public FELinkListNode { return isAuxPre || isAuxPost; } + bool IsBranch() const { + return IsBranchImpl(); + } + uint32 GetID() const { return id; } @@ -70,9 +82,8 @@ class GeneralStmt : public FELinkListNode { return predsOrSuccs; } - void AddPredOrSucc(GeneralStmt *stmt) { - ASSERT(stmt != nullptr, "null ptr check"); - predsOrSuccs.push_back(stmt); + void AddPredOrSucc(GeneralStmt &stmt) { + predsOrSuccs.push_back(&stmt); } const std::vector &GetPreds() const { @@ -85,16 +96,14 @@ class GeneralStmt : public FELinkListNode { return predsOrSuccs; } - void AddPred(GeneralStmt *stmt) { + void AddPred(GeneralStmt &stmt) { ASSERT(genKind == GeneralStmtKind::kStmtMultiIn, "invalid general kind"); - ASSERT(stmt != nullptr, "null ptr check"); - predsOrSuccs.push_back(stmt); + predsOrSuccs.push_back(&stmt); } - void AddSucc(GeneralStmt *stmt) { + void AddSucc(GeneralStmt &stmt) { ASSERT(genKind == GeneralStmtKind::kStmtMultiOut, "invalid general kind"); - ASSERT(stmt != nullptr, "null ptr check"); - predsOrSuccs.push_back(stmt); + predsOrSuccs.push_back(&stmt); } void Dump(const std::string &prefix = "") const { @@ -118,11 +127,12 @@ class GeneralStmt : public FELinkListNode { virtual std::string DumpDotStringImpl() const; virtual std::string GetStmtKindNameImpl() const; virtual bool IsStmtInstImpl() const; - + virtual bool IsBranchImpl() const; GeneralStmtKind genKind : 4; bool isFallThru : 1; bool isAuxPre : 1; bool isAuxPost : 1; + bool isThrowable : 1; uint32 id; std::vector predsOrSuccs; }; diff --git a/src/mplfe/common/include/mplfe_compiler.h b/src/mplfe/common/include/mplfe_compiler.h index cee7cb816fc7f630ba8dae6f507d124cb9c2a132..89fee519ba129e7655b2f5dea5850aa4fd05f106 100644 --- a/src/mplfe/common/include/mplfe_compiler.h +++ b/src/mplfe/common/include/mplfe_compiler.h @@ -16,9 +16,20 @@ #define MPLFE_INCLUDE_COMMON_MPLFE_COMPILER_NEW_H #include #include -#include "mpl_logging.h" #include "fe_macros.h" #include "mplfe_compiler_component.h" +#include "mpl_logging.h" +#include "mplfe_options.h" +#include "jbc_compiler_component.h" +#include "fe_options.h" +#include "bc_compiler_component.h" +#include "ark_annotation_processor.h" +#include "dex_reader.h" +#include "fe_errno.h" +#include "mpl_timer.h" +#include "mplfe_env.h" +#include "fe_manager.h" +#include "fe_type_hierarchy.h" namespace maple { class MPLFECompiler { @@ -26,6 +37,7 @@ class MPLFECompiler { explicit MPLFECompiler(MIRModule &argModule); ~MPLFECompiler(); // common process + void Run(); void Init(); void Release(); void CheckInput(); @@ -36,22 +48,25 @@ class MPLFECompiler { // component process void RegisterCompilerComponent(std::unique_ptr comp); - void InitFromOptions(); void ParseInputs(); + void LoadOnDemandTypes(); void PreProcessDecls(); void ProcessDecls(); + void ProcessPragmas(); void PreProcessWithFunctions(); void ProcessFunctions(); private: + inline void InsertImportInMpl(const std::list &mplt) const; + void FindMinCompileFailedFEFunctions(); MIRModule &module; MemPool *mp; MapleAllocator allocator; std::string firstInputName; - std::string selfMpltName; std::string outputPath; std::string outputName; std::list> components; + std::set compileFailedFEFunctions; }; } // namespace maple -#endif // MPLFE_INCLUDE_COMMON_MPLFE_COMPILER_NEW_H \ No newline at end of file +#endif // MPLFE_INCLUDE_COMMON_MPLFE_COMPILER_NEW_H diff --git a/src/mplfe/common/include/mplfe_compiler_component.h b/src/mplfe/common/include/mplfe_compiler_component.h index 726f6c2f4605def55d3aa53b73135d91196f3bef..b0f41efd38cfdf069d6fca1bd6c264dd47ce98d9 100644 --- a/src/mplfe/common/include/mplfe_compiler_component.h +++ b/src/mplfe/common/include/mplfe_compiler_component.h @@ -26,7 +26,7 @@ namespace maple { class FEFunctionProcessTask : public MplTask { public: - FEFunctionProcessTask(FEFunction &argFunction); + FEFunctionProcessTask(std::unique_ptr &argFunction); virtual ~FEFunctionProcessTask() = default; protected: @@ -34,7 +34,7 @@ class FEFunctionProcessTask : public MplTask { int FinishImpl(MplTaskParam *param) override; private: - FEFunction &function; + std::unique_ptr &function; }; class FEFunctionProcessSchedular : public MplScheduler { @@ -42,7 +42,7 @@ class FEFunctionProcessSchedular : public MplScheduler { FEFunctionProcessSchedular(const std::string &name) : MplScheduler(name) {} virtual ~FEFunctionProcessSchedular() = default; - void AddFunctionProcessTask(const std::unique_ptr &function); + void AddFunctionProcessTask(std::unique_ptr &function); void SetDumpTime(bool arg) { dumpTime = arg; } @@ -58,13 +58,14 @@ class MPLFECompilerComponent { public: MPLFECompilerComponent(MIRModule &argModule, MIRSrcLang argSrcLang); virtual ~MPLFECompilerComponent() = default; - bool InitFromOptions() { - return InitFromOptionsImpl(); - } bool ParseInput() { return ParseInputImpl(); } + bool LoadOnDemandType() { + return LoadOnDemandTypeImpl(); + } + bool PreProcessDecl() { return PreProcessDeclImpl(); } @@ -73,6 +74,10 @@ class MPLFECompilerComponent { return ProcessDeclImpl(); } + void ProcessPragma() { + ProcessPragmaImpl(); + } + bool PreProcessWithoutFunction() { return PreProcessWithoutFunctionImpl(); } @@ -105,11 +110,20 @@ class MPLFECompilerComponent { return static_cast(functions.size()); } + const std::set &GetCompileFailedFEFunctions() const { + return compileFailedFEFunctions; + } + + void ReleaseMemPool() { + ReleaseMemPoolImpl(); + } + protected: - virtual bool InitFromOptionsImpl() = 0; virtual bool ParseInputImpl() = 0; + virtual bool LoadOnDemandTypeImpl() = 0; virtual bool PreProcessDeclImpl() = 0; virtual bool ProcessDeclImpl() = 0; + virtual void ProcessPragmaImpl() = 0; virtual bool PreProcessWithoutFunctionImpl() = 0; virtual bool PreProcessWithFunctionImpl() = 0; virtual bool ProcessFunctionSerialImpl(); @@ -117,14 +131,16 @@ class MPLFECompilerComponent { virtual std::string GetComponentNameImpl() const; virtual bool ParallelableImpl() const; virtual void DumpPhaseTimeTotalImpl() const; + virtual void ReleaseMemPoolImpl() = 0; MIRModule &module; MIRSrcLang srcLang; std::list> fieldHelpers; std::list> methodHelpers; - std::list> structHelpers; + std::list structHelpers; std::list> functions; std::unique_ptr phaseResultTotal; + std::set compileFailedFEFunctions; }; } // namespace maple #endif diff --git a/src/mplfe/common/include/mplfe_options.h b/src/mplfe/common/include/mplfe_options.h index 316cb180bd00e71401d7c6f9ec4fd24411f28146..fcd727c2efddf0a8d737152a111e9d8ad5ae6d38 100644 --- a/src/mplfe/common/include/mplfe_options.h +++ b/src/mplfe/common/include/mplfe_options.h @@ -25,7 +25,8 @@ namespace maple { class MPLFEOptions : public maple::MapleDriverOptionBase { public: - static MPLFEOptions &GetInstance() { + static inline MPLFEOptions &GetInstance() { + static MPLFEOptions options; return options; } void Init(); @@ -38,9 +39,11 @@ class MPLFEOptions : public maple::MapleDriverOptionBase { static void Split(const std::string &s, char delim, Out result); static std::list SplitByComma(const std::string &s); + // non-option process + void ProcessInputFiles(const std::vector &inputs); + private: using OptionProcessFactory = FunctionFactory; - static MPLFEOptions options; MPLFEOptions(); ~MPLFEOptions() = default; @@ -52,6 +55,7 @@ class MPLFEOptions : public maple::MapleDriverOptionBase { // input control options bool ProcessInClass(const mapleOption::Option &opt); bool ProcessInJar(const mapleOption::Option &opt); + bool ProcessInDex(const mapleOption::Option &opt); bool ProcessInputMplt(const mapleOption::Option &opt); bool ProcessInputMpltFromSys(const mapleOption::Option &opt); bool ProcessInputMpltFromApk(const mapleOption::Option &opt); @@ -62,10 +66,13 @@ class MPLFEOptions : public maple::MapleDriverOptionBase { bool ProcessGenMpltOnly(const mapleOption::Option &opt); bool ProcessGenAsciiMplt(const mapleOption::Option &opt); bool ProcessDumpInstComment(const mapleOption::Option &opt); + bool ProcessNoMplFile(const mapleOption::Option &opt); // debug info control options bool ProcessDumpLevel(const mapleOption::Option &opt); bool ProcessDumpTime(const mapleOption::Option &opt); + bool ProcessDumpComment(const mapleOption::Option &opt); + bool ProcessDumpLOC(const mapleOption::Option &opt); bool ProcessDumpPhaseTime(const mapleOption::Option &opt); bool ProcessDumpPhaseTimeDetail(const mapleOption::Option &opt); @@ -87,8 +94,15 @@ class MPLFEOptions : public maple::MapleDriverOptionBase { bool ProcessDumpThreadTime(const mapleOption::Option &opt); bool ProcessReleaseAfterEmit(const mapleOption::Option &opt); - // non-option process - void ProcessInputFiles(const std::vector &inputs); + // On Demand Type Creation + bool ProcessXbootclasspath(const mapleOption::Option &opt); + bool ProcessClassLoaderContext(const mapleOption::Option &opt); + bool ProcessCompilefile(const mapleOption::Option &opt); + bool ProcessCollectDepTypes(const mapleOption::Option &opt); + bool ProcessDepSameNamePolicy(const mapleOption::Option &opt); + + // symbol resolve + bool ProcessAOT(const mapleOption::Option &opt); }; // class MPLFEOptions } // namespace maple #endif // MPLFE_INCLUDE_COMMON_MPLFE_OPTIONS_H \ No newline at end of file diff --git a/src/mplfe/common/include/simple_zip.h b/src/mplfe/common/include/simple_zip.h index d4fbeeb004c55dc569563b50f322eb46b1b7777e..310182611dd89e303029097b3875b0b2153ad368 100644 --- a/src/mplfe/common/include/simple_zip.h +++ b/src/mplfe/common/include/simple_zip.h @@ -117,7 +117,7 @@ class SimpleZip : public BasicIORead { public: SimpleZip(BasicIOMapFile &file); ~SimpleZip(); - bool ParseFile(); + void ParseFile(); const std::list> &GetFiles() const { return files; diff --git a/src/mplfe/common/src/fe_config_parallel.cpp b/src/mplfe/common/src/fe_config_parallel.cpp index 78bc325da054f7e55373b65c75b38a4902281935..6cbc33b787874000947e8c34812ba29b86406e3f 100644 --- a/src/mplfe/common/src/fe_config_parallel.cpp +++ b/src/mplfe/common/src/fe_config_parallel.cpp @@ -19,5 +19,5 @@ namespace maple { FEConfigParallel FEConfigParallel::instance; FEConfigParallel::FEConfigParallel() - : nThread(1), enableParallel(false) {} + : nThread(0), enableParallel(false) {} } // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/fe_file_type.cpp b/src/mplfe/common/src/fe_file_type.cpp index 27018cc46f8ef8ca00dcbe0d8743f44031279b31..e079ff515d12dc41e93a7629a04c855f92440feb 100644 --- a/src/mplfe/common/src/fe_file_type.cpp +++ b/src/mplfe/common/src/fe_file_type.cpp @@ -26,12 +26,12 @@ FEFileType::FEFileType() { FEFileType::FileType FEFileType::GetFileTypeByExtName(const std::string &extName) const { if (extName.empty()) { WARN(kLncWarn, "Empty input for GetFileTypeByExtName()...skipped"); - return kUnknown; + return kUnknownType; } auto itExtNameType = mapExtNameType.find(extName); if (itExtNameType == mapExtNameType.end()) { WARN(kLncWarn, "Unknown file extension name %s...skipped", extName.c_str()); - return kUnknown; + return kUnknownType; } return itExtNameType->second; } @@ -45,10 +45,11 @@ FEFileType::FileType FEFileType::GetFileTypeByMagicNumber(const std::string &pat std::ifstream file(pathName); if (!file.is_open()) { ERR(kLncErr, "unable to open file %s", pathName.c_str()); - return kUnknown; + return kUnknownType; } uint32 magic = 0; - (void)file.read(reinterpret_cast(&magic), sizeof(uint32)); + int lenght = static_cast(sizeof(uint32)); + (void)file.read(reinterpret_cast(&magic), lenght); file.close(); return GetFileTypeByMagicNumber(magic); } @@ -59,7 +60,7 @@ FEFileType::FileType FEFileType::GetFileTypeByMagicNumber(BasicIOMapFile &file) uint32 magic = fileReader.ReadUInt32(success); if (!success) { ERR(kLncErr, "unable to open file %s", file.GetFileName().c_str()); - return kUnknown; + return kUnknownType; } return GetFileTypeByMagicNumber(magic); } @@ -69,7 +70,7 @@ FEFileType::FileType FEFileType::GetFileTypeByMagicNumber(uint32 magic) const { if (it != mapMagicType.end()) { return it->second; } else { - return kUnknown; + return kUnknownType; } } @@ -85,10 +86,12 @@ void FEFileType::LoadDefault() { RegisterMagicNumber(kClass, kMagicClass); RegisterExtName(kJar, "jar"); RegisterMagicNumber(kJar, kMagicZip); + RegisterExtName(kDex, "dex"); + RegisterMagicNumber(kDex, kMagicDex); } void FEFileType::RegisterExtName(FileType argFileType, const std::string &extName) { - if (extName.empty() || argFileType == kUnknown) { + if (extName.empty() || argFileType == kUnknownType) { WARN(kLncWarn, "Invalid input for RegisterMagicNumber()...skipped"); return; } @@ -97,7 +100,7 @@ void FEFileType::RegisterExtName(FileType argFileType, const std::string &extNam } void FEFileType::RegisterMagicNumber(FileType argFileType, uint32 magicNumber) { - if (magicNumber == 0 || argFileType == kUnknown) { + if (magicNumber == 0 || argFileType == kUnknownType) { WARN(kLncWarn, "Invalid input for RegisterMagicNumber()...skipped"); return; } @@ -127,7 +130,7 @@ std::string FEFileType::GetName(const std::string &pathName, bool withExt) { } size_t posDot = name.find_last_of('.'); if (posDot != std::string::npos) { - return name.substr(0, pos); + return name.substr(0, posDot); } else { return name; } diff --git a/src/mplfe/common/src/fe_function.cpp b/src/mplfe/common/src/fe_function.cpp index f4f220bf505184a26a53d1168fb5a340c2c02e97..806f460e207f228518daed6c6d272b8f6f7b2f4a 100644 --- a/src/mplfe/common/src/fe_function.cpp +++ b/src/mplfe/common/src/fe_function.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -21,6 +21,10 @@ #include "feir_var_reg.h" #include "mplfe_env.h" #include "feir_builder.h" +#include "feir_dfg.h" +#include "feir_type_helper.h" +#include "feir_var_type_scatter.h" +#include "fe_options.h" namespace maple { FEFunction::FEFunction(MIRFunction &argMIRFunction, const std::unique_ptr &argPhaseResultTotal) @@ -65,8 +69,8 @@ void FEFunction::InitImpl() { FEIRNodeKind::kStmtPesudoFuncEnd)); feirStmtHead->SetNext(feirStmtTail); feirStmtTail->SetPrev(feirStmtHead); - feirBBHead = RegisterFEIRBB(std::make_unique(GeneralBBKind::kBBKindPesudoHead)); - feirBBTail = RegisterFEIRBB(std::make_unique(GeneralBBKind::kBBKindPesudoTail)); + feirBBHead = RegisterFEIRBB(std::make_unique(GeneralBBKind::kBBKindPesudoHead)); + feirBBTail = RegisterFEIRBB(std::make_unique(GeneralBBKind::kBBKindPesudoTail)); feirBBHead->SetNext(feirBBTail); feirBBTail->SetPrev(feirBBHead); } @@ -91,7 +95,7 @@ FEIRStmt *FEFunction::RegisterFEIRStmt(UniqueFEIRStmt stmt) { return feirStmtList.back().get(); } -GeneralBB *FEFunction::RegisterFEIRBB(std::unique_ptr bb) { +FEIRBB *FEFunction::RegisterFEIRBB(std::unique_ptr bb) { feirBBList.push_back(std::move(bb)); return feirBBList.back().get(); } @@ -122,7 +126,7 @@ bool FEFunction::BuildGeneralBB(const std::string &phaseName) { genBBTail->InsertBefore(currBB); } CHECK_FATAL(currBB != nullptr, "nullptr check for currBB"); - currBB->AppendStmt(stmt); + currBB->AppendStmt(*stmt); // check end of BB if (stmt->IsFallThru() == false || stmt->GetGeneralStmtKind() == GeneralStmtKind::kStmtMultiOut) { currBB = nullptr; @@ -137,9 +141,9 @@ bool FEFunction::BuildGeneralBB(const std::string &phaseName) { // add pre nodeStmt = bb->GetStmtHead()->GetPrev(); while (nodeStmt != nullptr && nodeStmt != genStmtHead) { - const GeneralStmt *stmt = static_cast(nodeStmt); + GeneralStmt *stmt = static_cast(nodeStmt); if (stmt->IsAuxPre()) { - bb->AddStmtAuxPre(stmt); + bb->AddStmtAuxPre(*stmt); } else { break; } @@ -150,7 +154,7 @@ bool FEFunction::BuildGeneralBB(const std::string &phaseName) { while (nodeStmt != nullptr && nodeStmt != genStmtTail) { GeneralStmt *stmt = static_cast(nodeStmt); if (stmt->IsAuxPost()) { - bb->AddStmtAuxPost(stmt); + bb->AddStmtAuxPost(*stmt); } else { break; } @@ -184,8 +188,8 @@ bool FEFunction::BuildGeneralCFG(const std::string &phaseName) { while (nodeBB != nullptr && nodeBB != genBBTail) { GeneralBB *bb = static_cast(nodeBB); if (firstBB) { - bb->AddPredBB(genBBHead); - genBBHead->AddSuccBB(bb); + bb->AddPredBB(*genBBHead); + genBBHead->AddSuccBB(*bb); firstBB = false; } const GeneralStmt *stmtTail = bb->GetStmtNoAuxTail(); @@ -197,16 +201,16 @@ bool FEFunction::BuildGeneralCFG(const std::string &phaseName) { return phaseResult.Finish(false); } GeneralBB *bbNext = static_cast(nodeBBNext); - bb->AddSuccBB(bbNext); - bbNext->AddPredBB(bb); + bb->AddSuccBB(*bbNext); + bbNext->AddPredBB(*bb); } if (stmtTail->GetGeneralStmtKind() == GeneralStmtKind::kStmtMultiOut) { for (GeneralStmt *stmt : stmtTail->GetSuccs()) { auto itBB = mapTargetStmtBB.find(stmt); CHECK_FATAL(itBB != mapTargetStmtBB.end(), "Target BB is not found"); GeneralBB *bbNext = itBB->second; - bb->AddSuccBB(bbNext); - bbNext->AddPredBB(bb); + bb->AddSuccBB(*bbNext); + bbNext->AddPredBB(*bb); } } nodeBB = nodeBB->GetNext(); @@ -423,14 +427,7 @@ bool FEFunction::UpdateFormal(const std::string &phaseName) { mirFunction.ClearFormals(); FEManager::GetMIRBuilder().SetCurrentFunction(mirFunction); for (const std::unique_ptr &argVar : argVarList) { - MIRSymbol *sym = nullptr; - if (idx == 0 && HasThis()) { - GStrIdx thisNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("_this"); - varThis = std::make_unique(thisNameIdx, argVar->GetType()->Clone()); - sym = varThis->GenerateMIRSymbol(FEManager::GetMIRBuilder()); - } else { - sym = argVar->GenerateMIRSymbol(FEManager::GetMIRBuilder()); - } + MIRSymbol *sym = argVar->GenerateMIRSymbol(FEManager::GetMIRBuilder()); sym->SetStorageClass(kScFormal); mirFunction.AddArgument(sym); idx++; @@ -438,6 +435,27 @@ bool FEFunction::UpdateFormal(const std::string &phaseName) { return phaseResult.Finish(); } +std::string FEFunction::GetDescription() { + std::stringstream ss; + std::string oriFuncName = GetGeneralFuncName(); + std::string mplFuncName = namemangler::EncodeName(oriFuncName); + ss << "ori function name: " << oriFuncName << std::endl; + ss << "mpl function name: " << mplFuncName << std::endl; + ss << "parameter list:" << "("; + for (const std::unique_ptr &argVar : argVarList) { + ss << argVar->GetNameRaw() << ", "; + } + ss << ") {" << std::endl; + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + ss << currStmt->DumpDotString() << std::endl; + node = node->GetNext(); + } + ss << "}" << std::endl; + return ss.str(); +} + bool FEFunction::EmitToMIR(const std::string &phaseName) { phaseResult.RegisterPhaseNameAndStart(phaseName); mirFunction.NewBody(); @@ -447,15 +465,7 @@ bool FEFunction::EmitToMIR(const std::string &phaseName) { return phaseResult.Finish(); } -bool FEFunction::ReleaseGenStmts(const std::string &phaseName) { - phaseResult.RegisterPhaseNameAndStart(phaseName); - if (FEOptions::GetInstance().IsReleaseAfterEmit()) { - genStmtList.clear(); - } - return phaseResult.Finish(); -} - -FEIRStmtPesudoLOC *FEFunction::GetLOCForStmt(const FEIRStmt &feIRStmt) { +const FEIRStmtPesudoLOC *FEFunction::GetLOCForStmt(const FEIRStmt &feIRStmt) const { if (!feIRStmt.ShouldHaveLOC()) { return nullptr; } @@ -487,11 +497,25 @@ void FEFunction::BuildMapLabelIdx() { } } +bool FEFunction::CheckPhaseResult(const std::string &phaseName) { + phaseResult.RegisterPhaseNameAndStart(phaseName); + bool success = phaseResult.IsSuccess(); + return phaseResult.Finish(success); +} + bool FEFunction::ProcessFEIRFunction() { bool success = true; success = success && BuildMapLabelStmt("fe/build map label stmt"); success = success && SetupFEIRStmtJavaTry("fe/setup stmt javatry"); success = success && SetupFEIRStmtBranch("fe/setup stmt branch"); + success = success && UpdateRegNum2This("fe/update reg num to this pointer"); + if (FEOptions::GetInstance().GetTypeInferKind() == FEOptions::kRoahAlgorithm) { + success = success && BuildFEIRBB("fe/build feir bb"); + success = success && BuildFEIRCFG("fe/build feir CFG"); + success = success && BuildFEIRDFG("fe/build feir DFG"); + success = success && BuildFEIRUDDU("fe/build feir UDDU"); + success = success && TypeInfer("fe/type infer"); + } return success; } @@ -526,7 +550,7 @@ bool FEFunction::SetupFEIRStmtJavaTry(const std::string &phaseName) { for (uint32 labelIdx : stmtJavaTry->GetCatchLabelIdxVec()) { auto it = mapLabelStmt.find(labelIdx); CHECK_FATAL(it != mapLabelStmt.end(), "label is not found"); - stmtJavaTry->AddCatchTarget(it->second); + stmtJavaTry->AddCatchTarget(*(it->second)); } } nodeStmt = nodeStmt->GetNext(); @@ -563,7 +587,7 @@ bool FEFunction::SetupFEIRStmtGoto(FEIRStmtGoto &stmt) { ERR(kLncErr, "target not found for stmt goto"); return false; } - stmt.SetStmtTarget(it->second); + stmt.SetStmtTarget(*(it->second)); return true; } @@ -574,7 +598,7 @@ bool FEFunction::SetupFEIRStmtSwitch(FEIRStmtSwitch &stmt) { ERR(kLncErr, "target not found for stmt goto"); return false; } - stmt.SetDefaultTarget(itDefault->second); + stmt.SetDefaultTarget(*(itDefault->second)); // value targets for (const auto &itItem : stmt.GetMapValueLabelIdx()) { @@ -583,33 +607,600 @@ bool FEFunction::SetupFEIRStmtSwitch(FEIRStmtSwitch &stmt) { ERR(kLncErr, "target not found for stmt goto"); return false; } - stmt.AddTarget(itItem.first, itTarget->second); + stmt.AddTarget(itItem.first, *(itTarget->second)); } return true; } -void FEFunction::EmitToMIRStmt() { - if (HasThis()) { - // Insert _this assignment - UniqueFEIRExpr exprDRead = FEIRBuilder::CreateExprDRead(varThis->Clone()); - UniqueFEIRStmt stmtDAssign = FEIRBuilder::CreateStmtDAssign(argVarList.begin()->get()->Clone(), - std::move(exprDRead)); - FEIRStmt *ptrFEIRStmt = RegisterFEIRStmt(std::move(stmtDAssign)); - feirStmtHead->InsertAfter(ptrFEIRStmt); +bool FEFunction::UpdateRegNum2This(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + if (!HasThis()) { + return success; + } + const std::unique_ptr &firstArg = argVarList.front(); + std::unique_ptr varReg = firstArg->Clone(); + GStrIdx thisNameIdx = GlobalTables::GetStrTable().GetStrIdxFromName("_this"); + uint32 nameIdx = static_cast(thisNameIdx); + CHECK_FATAL((nameIdx != 0), "StringIndex for \"_this\" should has been created before this phase"); + std::unique_ptr varThisAsParam = std::make_unique(thisNameIdx, varReg->GetType()->Clone()); + if (!IsNative()) { + std::unique_ptr varThisAsLocalVar = std::make_unique(thisNameIdx, varReg->GetType()->Clone()); + std::unique_ptr dReadThis = std::make_unique(std::move(varThisAsLocalVar)); + std::unique_ptr daStmt = std::make_unique(std::move(varReg), std::move(dReadThis)); + FEIRStmt *stmt = RegisterFEIRStmt(std::move(daStmt)); + FELinkListNode::InsertAfter(stmt, feirStmtHead); + } + argVarList[0].reset(varThisAsParam.release()); + return success; +} + +void FEFunction::OutputStmts() { + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + LogInfo::MapleLogger() << currStmt->DumpDotString() << "\n"; + node = node->GetNext(); + } +} + +bool FEFunction::BuildFEIRBB(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + LabelFEIRStmts(); + FEIRBB *currBB = nullptr; + uint32 bbID = 1; + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + if (ShouldNewBB(currBB, *currStmt)) { + currBB = NewFEIRBB(bbID); + FELinkListNode::InsertBefore(currBB, feirBBTail); + } + currBB->AppendStmt(*currStmt); + (void)feirStmtBBMap.insert(std::make_pair(currStmt, currBB)); + if (IsBBEnd(*currStmt)) { + currBB = nullptr; + } + node = node->GetNext(); + } + return phaseResult.Finish(success); +} + +bool FEFunction::BuildFEIRCFG(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + LinkFallThroughBBAndItsNext(*currBB); + LinkBranchBBAndItsTargets(*currBB); + node = currBB->GetNext(); + } + return phaseResult.Finish(success); +} + +bool FEFunction::BuildFEIRDFG(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + ProcessCheckPoints(); + return phaseResult.Finish(success); +} + +bool FEFunction::BuildFEIRUDDU(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + InitFirstVisibleStmtForCheckPoints(); + InitFEIRStmtCheckPointMap(); + RegisterDFGNodes2CheckPoints(); + success = success && CalculateDefs4AllUses(); // build Use-Def Chain + FEIRDFG::CalculateDefUseByUseDef(defUseChain, useDefChain); // build Def-Use Chain + return phaseResult.Finish(success); +} + +bool FEFunction::TypeInfer(const std::string &phaseName) { + bool success = CheckPhaseResult(phaseName); + if (!success) { + return success; + } + InitTrans4AllVars(); + typeInfer = std::make_unique(srcLang, defUseChain); + for (auto it : defUseChain) { + UniqueFEIRVar *def = it.first; + typeInfer->ProcessVarDef(*def); + } + SetUpDefVarTypeScatterStmtMap(); + if (defVarTypeScatterStmtMap.size() == 0) { + return phaseResult.Finish(success); + } + for (auto it : defUseChain) { + UniqueFEIRVar *def = it.first; + InsertRetypeStmtsAfterDef(*def); + } + return phaseResult.Finish(success); +} + +void FEFunction::OutputUseDefChain() { + std::cout << "useDefChain : {" << std::endl; + for (auto it : useDefChain) { + UniqueFEIRVar *use = it.first; + std::cout << " use : " << (*use)->GetNameRaw() << "_" << GetPrimTypeName((*use)->GetType()->GetPrimType()); + std::cout << " defs : ["; + std::set &defs = it.second; + for (UniqueFEIRVar *def : defs) { + std::cout << (*def)->GetNameRaw() << "_" << GetPrimTypeName((*def)->GetType()->GetPrimType()) << ", "; + } + if (defs.size() == 0) { + std::cout << "empty defs"; + } + std::cout << " ]" << std::endl; + } + std::cout << "}" << std::endl; +} + +void FEFunction::OutputDefUseChain() { + std::cout << "defUseChain : {" << std::endl; + for (auto it : defUseChain) { + UniqueFEIRVar *def = it.first; + std::cout << " def : " << (*def)->GetNameRaw() << "_" << GetPrimTypeName((*def)->GetType()->GetPrimType()); + std::cout << " uses : ["; + std::set &uses = it.second; + for (UniqueFEIRVar *use : uses) { + std::cout << (*use)->GetNameRaw() << "_" << GetPrimTypeName((*use)->GetType()->GetPrimType()) << ", "; + } + if (uses.size() == 0) { + std::cout << "empty uses"; + } + std::cout << " ]" << std::endl; + } + std::cout << "}" << std::endl; +} + +void FEFunction::LabelFEIRStmts() { + // stmt idx start from 1 + FELinkListNode *node = feirStmtHead->GetNext(); + uint32 id = 1; + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + currStmt->SetID(id++); + node = node->GetNext(); + } + stmtCount = --id; +} + +FEIRBB *FEFunction::NewFEIRBB(uint32 &bbID) { + std::unique_ptr uniqueFEIRBB = std::make_unique(GeneralBBKind::kBBKindDefault); + uniqueFEIRBB->SetID(bbID); + bbID++; + return RegisterFEIRBB(std::move(uniqueFEIRBB)); +} + +bool FEFunction::ShouldNewBB(const FEIRBB *currBB, const FEIRStmt &currStmt) const { + if (currBB == nullptr) { + return true; + } + if (currStmt.IsTarget()) { + if (currBB->GetStmtNoAuxTail() != nullptr) { + return true; + } + } + return false; +} + +bool FEFunction::IsBBEnd(const FEIRStmt &stmt) const { + bool currStmtMayBeBBEnd = MayBeBBEnd(stmt); + if (currStmtMayBeBBEnd) { + FELinkListNode *node = stmt.GetNext(); + FEIRStmt *nextStmt = static_cast(node); + if (nextStmt->IsAuxPost()) { // if curr stmt my be BB end, but next stmt is AuxPost + return false; // curr stmt should not be BB end + } + return true; + } + if (stmt.IsAuxPost()) { + FELinkListNode *node = stmt.GetPrev(); + FEIRStmt *prevStmt = static_cast(node); + bool prevStmtMayBeBBEnd = MayBeBBEnd(*prevStmt); // if curr stmt is AuxPost, and prev stmt my be BB end + return prevStmtMayBeBBEnd; // return prev stmt my be BB end as result + } + return currStmtMayBeBBEnd; +} + +bool FEFunction::MayBeBBEnd(const FEIRStmt &stmt) const { + return (stmt.IsBranch() || !stmt.IsFallThrough()); +} + +void FEFunction::LinkFallThroughBBAndItsNext(FEIRBB &bb) { + if (!CheckBBsStmtNoAuxTail(bb)) { + return; + } + if (!bb.IsFallThru()) { + return; + } + FELinkListNode *node = bb.GetNext(); + FEIRBB *nextBB = static_cast(node); + if (nextBB != feirBBTail) { + LinkBB(bb, *nextBB); + } +} + +void FEFunction::LinkBranchBBAndItsTargets(FEIRBB &bb) { + if (!CheckBBsStmtNoAuxTail(bb)) { + return; + } + if (!bb.IsBranch()) { + return; } + const GeneralStmt *generalStmtTail = bb.GetStmtNoAuxTail(); + const FEIRStmt *stmtTail = static_cast(generalStmtTail); + FEIRNodeKind nodeKind = stmtTail->GetKind(); + switch (nodeKind) { + case FEIRNodeKind::kStmtCondGoto: + // should fallthrough + [[fallthrough]]; + case FEIRNodeKind::kStmtGoto: { + LinkGotoBBAndItsTarget(bb, *stmtTail); + break; + } + case FEIRNodeKind::kStmtSwitch: { + LinkSwitchBBAndItsTargets(bb, *stmtTail); + break; + } + default: { + CHECK_FATAL(false, "nodeKind %u is not branch", nodeKind); + break; + } + } +} + +void FEFunction::LinkGotoBBAndItsTarget(FEIRBB &bb, const FEIRStmt &stmtTail) { + const FEIRStmtGoto2 &gotoStmt = static_cast(stmtTail); + const FEIRStmtPesudoLabel2 &targetStmt = gotoStmt.GetStmtTargetRef(); + FEIRBB &targetBB = GetFEIRBBByStmt(targetStmt); + LinkBB(bb, targetBB); +} + +void FEFunction::LinkSwitchBBAndItsTargets(FEIRBB &bb, const FEIRStmt &stmtTail) { + const FEIRStmtSwitch2 &switchStmt = static_cast(stmtTail); + const std::map &mapValueTargets = switchStmt.GetMapValueTargets(); + for (auto it : mapValueTargets) { + FEIRStmtPesudoLabel2 *pesudoLabel = it.second; + FEIRBB &targetBB = GetFEIRBBByStmt(*pesudoLabel); + LinkBB(bb, targetBB); + } + FEIRBB &targetBB = GetFEIRBBByStmt(switchStmt.GetDefaultTarget()); + LinkBB(bb, targetBB); +} + +void FEFunction::LinkBB(FEIRBB &predBB, FEIRBB &succBB) { + predBB.AddSuccBB(succBB); + succBB.AddPredBB(predBB); +} + +FEIRBB &FEFunction::GetFEIRBBByStmt(const FEIRStmt &stmt) { + auto it = feirStmtBBMap.find(&stmt); + return *(it->second); +} + +bool FEFunction::CheckBBsStmtNoAuxTail(const FEIRBB &bb) { + bool bbHasStmtNoAuxTail = (bb.GetStmtNoAuxTail() != nullptr); + CHECK_FATAL(bbHasStmtNoAuxTail, "Error accured in BuildFEIRBB phase, bb.GetStmtNoAuxTail() should not be nullptr"); + return true; +} + +void FEFunction::ProcessCheckPoints() { + InsertCheckPointForBBs(); + InsertCheckPointForTrys(); + LabelFEIRStmts(); + LinkCheckPointBetweenBBs(); + LinkCheckPointInsideBBs(); + LinkCheckPointForTrys(); +} + +void FEFunction::InsertCheckPointForBBs() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); // get currBB + // create chekPointIn + std::unique_ptr chekPointIn = std::make_unique(); + currBB->SetCheckPointIn(std::move(chekPointIn)); // set to currBB's checkPointIn + FEIRStmtCheckPoint &cpIn = currBB->GetCheckPointIn(); + currBB->InsertAndUpdateNewHead(cpIn); // insert and update new head to chekPointIn + (void)feirStmtBBMap.insert(std::make_pair(&cpIn, currBB)); // add pair to feirStmtBBMap + // create chekPointOut + std::unique_ptr chekPointOut = std::make_unique(); + currBB->SetCheckPointOut(std::move(chekPointOut)); // set to currBB's checkPointOut + FEIRStmtCheckPoint &cpOut = currBB->GetCheckPointOut(); + currBB->InsertAndUpdateNewTail(cpOut); // insert and update new tail to chekPointOut + (void)feirStmtBBMap.insert(std::make_pair(&cpOut, currBB)); // add pair to feirStmtBBMap + // get next BB + node = node->GetNext(); + } +} + +void FEFunction::InsertCheckPointForTrys() { + FEIRStmtPesudoJavaTry2 *currTry = nullptr; + FEIRStmtCheckPoint *checkPointInTry = nullptr; + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + if (currStmt->GetKind() == FEIRNodeKind::kStmtPesudoJavaTry) { + currTry = static_cast(currStmt); + checkPointInTry = nullptr; + } + if ((currTry != nullptr) && + (currStmt->IsThrowable()) && + ((checkPointInTry == nullptr) || currStmt->HasDef())) { + FEIRBB &currBB = GetFEIRBBByStmt(*currStmt); + if (currStmt == currBB.GetStmtNoAuxHead()) { + checkPointInTry = &(currBB.GetCheckPointIn()); + (void)checkPointJavaTryMap.insert(std::make_pair(checkPointInTry, currTry)); + if (currStmt == currBB.GetStmtHead()) { + currBB.SetStmtHead(*currStmt); + } + node = node->GetNext(); + continue; + } + std::unique_ptr newCheckPoint = std::make_unique(); + currBB.AddCheckPointInside(std::move(newCheckPoint)); + checkPointInTry = currBB.GetLatestCheckPointInside(); + CHECK_NULL_FATAL(checkPointInTry); + FELinkListNode::InsertBefore(checkPointInTry, currStmt); + (void)feirStmtBBMap.insert(std::make_pair(checkPointInTry, &currBB)); + (void)checkPointJavaTryMap.insert(std::make_pair(checkPointInTry, currTry)); + if (currStmt == currBB.GetStmtHead()) { + currBB.SetStmtHead(*currStmt); + } + } + if (currStmt->GetKind() == FEIRNodeKind::kStmtPesudoEndTry) { + currTry = nullptr; + } + node = node->GetNext(); + } +} + +void FEFunction::LinkCheckPointBetweenBBs() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + currBB->LinkSuccBBsCheckPoints(); + node = node->GetNext(); + } +} + +void FEFunction::LinkCheckPointInsideBBs() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + currBB->LinkCheckPointsInside(); + node = node->GetNext(); + } +} + +void FEFunction::LinkCheckPointForTrys() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + FEIRStmtCheckPoint &checkPointIn = currBB->GetCheckPointIn(); + if (checkPointJavaTryMap.find(&checkPointIn) != checkPointJavaTryMap.end()) { + LinkCheckPointForTry(checkPointIn); + } + const std::vector> &checkPointsInside = currBB->GetCheckPointsInside(); + for (const std::unique_ptr &currCheckPoint : checkPointsInside) { + LinkCheckPointForTry(*(currCheckPoint.get())); + } + node = node->GetNext(); + } +} + +void FEFunction::LinkCheckPointForTry(FEIRStmtCheckPoint &checkPoint) { + FEIRStmtPesudoJavaTry2 &currTry = GetJavaTryByCheckPoint(checkPoint); + const std::vector &catchTargets = currTry.GetCatchTargets(); + for (FEIRStmtPesudoLabel2 *label : catchTargets) { + FEIRBB &targetBB = GetFEIRBBByStmt(*label); + FEIRStmtCheckPoint &checkPointIn = targetBB.GetCheckPointIn(); + checkPointIn.AddPredCheckPoint(checkPoint); + } +} + +void FEFunction::InitFirstVisibleStmtForCheckPoints() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + currBB->InitFirstVisibleStmtForCheckPoints(); + node = node->GetNext(); + } +} + +void FEFunction::InitFEIRStmtCheckPointMap() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + const std::map &stmtCheckPointMap = currBB->GetFEIRStmtCheckPointMap(); + feirStmtCheckPointMap.insert(stmtCheckPointMap.begin(), stmtCheckPointMap.end()); + node = node->GetNext(); + } +} + +void FEFunction::RegisterDFGNodes2CheckPoints() { + RegisterDFGNodesForFuncParameters(); + RegisterDFGNodesForStmts(); +} + +void FEFunction::RegisterDFGNodesForStmts() { + FELinkListNode *node = feirBBHead->GetNext(); + while (node != feirBBTail) { + FEIRBB *currBB = static_cast(node); + currBB->RegisterDFGNodes2CheckPoints(); + node = node->GetNext(); + } +} + +void FEFunction::RegisterDFGNodesForFuncParameters() { + if (argVarList.size() == 0) { + return; + } + FELinkListNode *node = feirBBHead->GetNext(); + if (node == feirBBTail) { + OutputStmts(); + CHECK_FATAL((feirStmtHead->GetNext() == feirStmtTail), "there is no bb in function"); + } + FEIRBB *funcHeadBB = static_cast(node); + FEIRStmtCheckPoint &checkPointIn = funcHeadBB->GetCheckPointIn(); + for (std::unique_ptr &argVar : argVarList) { + argVar->SetDef(true); + checkPointIn.RegisterDFGNode(argVar); + } +} + +bool FEFunction::CalculateDefs4AllUses() { + bool success = true; + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + if (currStmt->GetKind() != FEIRNodeKind::kStmtCheckPoint) { + FEIRStmtCheckPoint &checkPoint = GetCheckPointByFEIRStmt(*currStmt); + success = success && currStmt->CalculateDefs4AllUses(checkPoint, useDefChain); + } + node = node->GetNext(); + } + return success; +} + +void FEFunction::InitTrans4AllVars() { + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + currStmt->InitTrans4AllVars(); + node = node->GetNext(); + } +} + +FEIRStmtPesudoJavaTry2 &FEFunction::GetJavaTryByCheckPoint(FEIRStmtCheckPoint &checkPoint) { + auto it = checkPointJavaTryMap.find(&checkPoint); + return *(it->second); +} + +FEIRStmtCheckPoint &FEFunction::GetCheckPointByFEIRStmt(const FEIRStmt &stmt) { + auto it = feirStmtCheckPointMap.find(&stmt); + return *(it->second); +} + +void FEFunction::SetUpDefVarTypeScatterStmtMap() { + FELinkListNode *node = feirStmtHead->GetNext(); + while (node != feirStmtTail) { + FEIRStmt *currStmt = static_cast(node); + FEIRVarTypeScatter *defVarTypeScatter = currStmt->GetTypeScatterDefVar(); + if (defVarTypeScatter != nullptr) { + (void)defVarTypeScatterStmtMap.insert(std::make_pair(defVarTypeScatter, currStmt)); + } + node = node->GetNext(); + } +} + +void FEFunction::InsertRetypeStmtsAfterDef(const UniqueFEIRVar& def) { + bool defIsTypeScatter = (def->GetKind() == kFEIRVarTypeScatter); + if (!defIsTypeScatter) { + return; + } + FEIRVarTypeScatter &fromVar = *(static_cast(def.get())); + const std::unordered_set &scatterTypes = fromVar.GetScatterTypes(); + for (auto &it : scatterTypes) { + const maple::FEIRTypeKey &typeKey = it; + FEIRType &toType = *(typeKey.GetType()); + FEIRType &fromType = *(fromVar.GetType()); + Opcode opcode = FEIRTypeCvtHelper::ChooseCvtOpcodeByFromTypeAndToType(fromType, toType); + if (opcode == OP_retype) { + InsertRetypeStmt(fromVar, toType); + } else if (opcode == OP_cvt) { + InsertCvtStmt(fromVar, toType); + } else { + InsertJavaMergeStmt(fromVar, toType); + } + } +} + +void FEFunction::InsertRetypeStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType) { + // create DRead Expr + std::unique_ptr exprDRead = std::make_unique(fromVar.GetVar()->Clone()); + std::unique_ptr typeDst = FEIRTypeHelper::CreatePointerType(toType.Clone(), toType.GetPrimType()); + // create expr for retype + std::unique_ptr expr = std::make_unique(std::move(typeDst), OP_retype, + std::move(exprDRead)); + // after expr created, insert dassign stmt + InsertDAssignStmt4TypeCvt(fromVar, toType, std::move(expr)); +} + +void FEFunction::InsertCvtStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType) { + // create DRead Expr + std::unique_ptr exprDRead = std::make_unique(fromVar.GetVar()->Clone()); + // create expr for type cvt + std::unique_ptr expr = std::make_unique(OP_cvt, std::move(exprDRead)); + expr->GetType()->SetPrimType(toType.GetPrimType()); + // after expr created, insert dassign stmt + InsertDAssignStmt4TypeCvt(fromVar, toType, std::move(expr)); +} + +void FEFunction::InsertJavaMergeStmt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType) { + // create DRead Expr + std::unique_ptr exprDRead = std::make_unique(fromVar.GetVar()->Clone()); + // create expr for java merge + std::vector> argOpnds; + argOpnds.push_back(std::move(exprDRead)); + std::unique_ptr javaMergeExpr = std::make_unique(toType.Clone(), argOpnds); + // after expr created, insert dassign stmt + InsertDAssignStmt4TypeCvt(fromVar, toType, std::move(javaMergeExpr)); +} + +void FEFunction::InsertDAssignStmt4TypeCvt(const FEIRVarTypeScatter &fromVar, const FEIRType &toType, + UniqueFEIRExpr expr) { + FEIRVar *var = fromVar.GetVar().get(); + CHECK_FATAL((var->GetKind() == FEIRVarKind::kFEIRVarReg), "fromVar's inner var must be var reg kind"); + FEIRVarReg *varReg = static_cast(var); + uint32 regNum = varReg->GetRegNum(); + UniqueFEIRVar toVar = FEIRBuilder::CreateVarReg(regNum, toType.Clone()); + std::unique_ptr daStmt = std::make_unique(std::move(toVar), std::move(expr)); + FEIRStmt *insertedStmt = RegisterFEIRStmt(std::move(daStmt)); + FEIRStmt &stmt = GetStmtByDefVarTypeScatter(fromVar); + FELinkListNode::InsertAfter(insertedStmt, &stmt); +} + +FEIRStmt &FEFunction::GetStmtByDefVarTypeScatter(const FEIRVarTypeScatter &varTypeScatter) { + auto it = defVarTypeScatterStmtMap.find(&varTypeScatter); + return *(it->second); +} + +void FEFunction::EmitToMIRStmt() { FELinkListNode *nodeStmt = feirStmtHead->GetNext(); while (nodeStmt != nullptr && nodeStmt != feirStmtTail) { FEIRStmt *stmt = static_cast(nodeStmt); - FEIRStmtPesudoLOC *pesudoLoc = GetLOCForStmt(*stmt); std::list mirStmts = stmt->GenMIRStmts(FEManager::GetMIRBuilder()); - if (pesudoLoc != nullptr) { - mirStmts.front()->GetSrcPos().SetFileNum(static_cast(pesudoLoc->GetSrcFileIdx())); - mirStmts.front()->GetSrcPos().SetLineNum(pesudoLoc->GetLineNumber()); - } +#ifdef DEBUG + // LOC info has been recorded in FEIRStmt already, this could be removed later. + AddLocForStmt(*stmt, mirStmts); +#endif for (StmtNode *mirStmt : mirStmts) { FEManager::GetMIRBuilder().AddStmtInCurrentFunctionBody(*mirStmt); } nodeStmt = nodeStmt->GetNext(); } } + +void FEFunction::AddLocForStmt(const FEIRStmt &stmt, std::list &mirStmts) const { + const FEIRStmtPesudoLOC *pesudoLoc = GetLOCForStmt(stmt); + if (pesudoLoc != nullptr) { + mirStmts.front()->GetSrcPos().SetFileNum(static_cast(pesudoLoc->GetSrcFileIdx())); + mirStmts.front()->GetSrcPos().SetLineNum(pesudoLoc->GetLineNumber()); + } +} } // namespace maple diff --git a/src/mplfe/common/src/fe_input_helper.cpp b/src/mplfe/common/src/fe_input_helper.cpp index fb31e6d9801d0bfd82e69ff95ecc12a327e1001b..943ec2f3f0f06fca53e1585d310981406f2614dc 100644 --- a/src/mplfe/common/src/fe_input_helper.cpp +++ b/src/mplfe/common/src/fe_input_helper.cpp @@ -32,8 +32,6 @@ MIRStructType *FEInputStructHelper::GetContainerImpl() { bool FEInputStructHelper::PreProcessDeclImpl() { bool error = false; - std::string structNameOrin = GetStructNameOrin(); - FE_INFO_LEVEL(FEOptions::kDumpLevelInfoDetail, "PreProcessDecl for %s", structNameOrin.c_str()); MIRStructType *structType = CreateMIRStructType(error); if (error) { return false; @@ -48,16 +46,16 @@ bool FEInputStructHelper::PreProcessDeclImpl() { } bool FEInputStructHelper::ProcessDeclImpl() { - std::string structNameOrin = GetStructNameOrin(); - FE_INFO_LEVEL(FEOptions::kDumpLevelInfoDetail, "ProcessDecl for %s", structNameOrin.c_str()); if (isSkipped) { return true; } if (mirStructType == nullptr) { return false; } - // Create Symbol - CreateSymbol(); + if (!FEOptions::GetInstance().IsGenMpltOnly() && !isOnDemandLoad) { + // Create Symbol + CreateSymbol(); + } // Process SuperClass ProcessDeclSuperClass(); // Process Interface @@ -67,6 +65,9 @@ bool FEInputStructHelper::ProcessDeclImpl() { // Process Fields InitFieldHelpers(); ProcessFieldDef(); + if (!FEOptions::GetInstance().IsGenMpltOnly() && !isOnDemandLoad) { + ProcessStaticFields(); + } // Process Methods InitMethodHelpers(); ProcessMethodDef(); @@ -100,11 +101,11 @@ void FEInputStructHelper::ProcessDeclSuperClass() { } void FEInputStructHelper::ProcessDeclSuperClassForJava() { - std::vector superNames = GetSuperClassNames(); + const std::list &superNames = GetSuperClassNames(); ASSERT(superNames.size() <= 1, "there must be zero or one super class for java class: %s", GetStructNameOrin().c_str()); if (superNames.size() == 1) { - std::string superNameMpl = namemangler::EncodeName(superNames[0]); + const std::string &superNameMpl = namemangler::EncodeName(superNames.front()); bool isCreate = false; MIRStructType *superType = FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType(superNameMpl, false, FETypeFlag::kSrcExtern, @@ -134,10 +135,10 @@ void FEInputStructHelper::ProcessDeclSuperClassForJava() { } void FEInputStructHelper::ProcessDeclImplements() { - std::vector interfaceNames = GetInterfaceNames(); + const std::vector &interfaceNames = GetInterfaceNames(); std::vector interfaceTypes; for (const std::string &name : interfaceNames) { - std::string interfaceNameMpl = namemangler::EncodeName(name); + const std::string &interfaceNameMpl = namemangler::EncodeName(name); bool isCreate = false; MIRStructType *interfaceType = FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType(interfaceNameMpl, true, FETypeFlag::kSrcExtern, @@ -204,12 +205,12 @@ void FEInputStructHelper::ProcessDeclDefInfo() { } void FEInputStructHelper::ProcessDeclDefInfoSuperNameForJava() { - std::vector superNames = GetSuperClassNames(); + std::list superNames = GetSuperClassNames(); if (superNames.size() > 1) { ASSERT(false, "There is one super class at most in java"); return; } - std::string superName = superNames.size() == 0 ? "unknown" : superNames[0]; + std::string superName = superNames.size() == 0 ? "unknown" : superNames.front(); std::string superNameMpl = namemangler::EncodeName(superName); GStrIdx superNameMplIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(superNameMpl.c_str()); SET_CLASS_INFO_PAIR(mirStructType, "INFO_superclassname", superNameMplIdx.GetIdx(), true); @@ -230,9 +231,50 @@ void FEInputStructHelper::ProcessDeclDefInfoImplementNameForJava() { } } +void FEInputStructHelper::ProcessStaticFields() { + uint32 i = 0; + uint32 stringIDCount = 0; + FieldVector::iterator it; + for (it = mirStructType->GetStaticFields().begin(); it != mirStructType->GetStaticFields().end(); ++i, ++it) { + StIdx stIdx = GlobalTables::GetGsymTable().GetStIdxFromStrIdx(it->first); + const std::string &fieldName = GlobalTables::GetStrTable().GetStringFromStrIdx(it->first); + MIRConst *cst = nullptr; + MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(it->second.first); + if (i < staticFieldsConstVal.size()) { + cst = staticFieldsConstVal[i]; + if (cst != nullptr && cst->GetKind() == kConstStr16Const) { + std::u16string str16 = + GlobalTables::GetU16StrTable().GetStringFromStrIdx(static_cast(cst)->GetValue()); + MIRSymbol *literalVar = FEManager::GetJavaStringManager().GetLiteralVar(str16); + if (literalVar == nullptr) { + literalVar = FEManager::GetJavaStringManager().CreateLiteralVar(FEManager::GetMIRBuilder(), str16, true); + } + if (!FEOptions::GetInstance().IsAOT()) { + AddrofNode *expr = FEManager::GetMIRBuilder().CreateExprAddrof(0, *literalVar, + FEManager::GetModule().GetMemPool()); + MIRType *ptrType = GlobalTables::GetTypeTable().GetTypeTable()[PTY_ptr]; + // Judge null pointer is not required. + cst = new(std::nothrow) MIRAddrofConst(expr->GetStIdx(), expr->GetFieldID(), *ptrType); + } else { + uint32 stringID = finalStaticStringID[stringIDCount++]; + cst = new(std::nothrow) MIRIntConst(stringID, *GlobalTables::GetTypeTable().GetInt64()); + } + } + } + MIRSymbol *fieldVar = GlobalTables::GetGsymTable().GetSymbolFromStidx(stIdx.Idx()); + if (fieldVar == nullptr) { + fieldVar = FEManager::GetMIRBuilder().GetOrCreateGlobalDecl(fieldName, *type); + fieldVar->SetAttrs(it->second.second.ConvertToTypeAttrs()); + } + if (cst != nullptr) { + fieldVar->SetKonst(cst); + } + } +} + void FEInputStructHelper::ProcessFieldDef() { for (FEInputFieldHelper *fieldHelper : fieldHelpers) { - bool success = fieldHelper->ProcessDeclWithContainer(allocator, *this); + bool success = fieldHelper->ProcessDeclWithContainer(allocator); if (success) { if (fieldHelper->IsStatic()) { mirStructType->GetStaticFields().push_back(fieldHelper->GetMIRFieldPair()); @@ -250,12 +292,24 @@ void FEInputStructHelper::ProcessMethodDef() { bool success = methodHelper->ProcessDecl(allocator); if (success) { mirStructType->GetMethods().push_back(methodHelper->GetMIRMethodPair()); + methodHelper->SetClassTypeInfo(*mirStructType); } else { - ERR(kLncErr, "Error occurs in ProcessFieldDef for %s", GetStructNameOrin().c_str()); + ERR(kLncErr, "Error occurs in ProcessMethodDef for %s", GetStructNameOrin().c_str()); } } } +void FEInputStructHelper::ProcessPragma() { + if (isSkipped) { + return; + } + std::vector pragmas = pragmaHelper->GenerateMIRPragmas(); + std::vector &pragmaVec = mirStructType->GetPragmaVec(); + for (MIRPragma *pragma : pragmas) { + pragmaVec.push_back(pragma); + } +} + // ---------- FEInputMethodHelper ---------- bool FEInputMethodHelper::ProcessDeclImpl(MapleAllocator &allocator) { MPLFE_PARALLEL_FORBIDDEN(); diff --git a/src/mplfe/common/src/fe_java_string_manager.cpp b/src/mplfe/common/src/fe_java_string_manager.cpp index 046cc34d303be254d56125592a95f518106e7dac..298ca572344c064b37bc090cfd5335af539c123e 100644 --- a/src/mplfe/common/src/fe_java_string_manager.cpp +++ b/src/mplfe/common/src/fe_java_string_manager.cpp @@ -20,10 +20,13 @@ #include "literalstrname.h" #include "fe_config_parallel.h" #include "feir_type.h" +#include "fe_manager.h" +#include "fe_options.h" namespace maple { -FEJavaStringManager::FEJavaStringManager(MIRModule &argModule) - : module(argModule) {} +FEJavaStringManager::FEJavaStringManager(MIRModule &argModule, MIRBuilder &mirBuilderIn) + : module(argModule), mirBuilder(mirBuilderIn) { +} FEJavaStringManager::~FEJavaStringManager() { typeString = nullptr; @@ -63,13 +66,13 @@ MIRSymbol *FEJavaStringManager::GetLiteralPtrVar(const std::u16string &strU16) c return GetLiteralPtrVar(literalVar); } -MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilder, const std::string &str, bool isFieldValue) { +MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilderIn, const std::string &str, bool isFieldValue) { std::u16string strU16; (void)namemangler::UTF8ToUTF16(strU16, str); - return CreateLiteralVar(mirBuilder, strU16, isFieldValue); + return CreateLiteralVar(mirBuilderIn, strU16, isFieldValue); } -MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilder, const std::u16string &strU16, +MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilderIn, const std::u16string &strU16, bool isFieldValue) { MPLFE_PARALLEL_FORBIDDEN(); if (typeString == nullptr) { @@ -84,7 +87,7 @@ MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilder, const s std::string literalGlobalName = GetLiteralGlobalName(strU16); bool compress = useCompressedJavaString && IsAllASCII(strU16); MIRArrayType *byteArrayType = ConstructArrayType4Str(strU16, compress); - literalVar = mirBuilder.GetOrCreateGlobalDecl(literalGlobalName.c_str(), *byteArrayType); + literalVar = mirBuilderIn.GetOrCreateGlobalDecl(literalGlobalName.c_str(), *byteArrayType); MIRAggConst *strConst = CreateByteArrayConst(strU16, *byteArrayType, compress); literalVar->SetKonst(strConst); literalVar->SetAttr(ATTR_readonly); @@ -97,14 +100,15 @@ MIRSymbol *FEJavaStringManager::CreateLiteralVar(MIRBuilder &mirBuilder, const s if (isFieldValue) { (void)fieldValueSet.insert(literalVar); } - if (isFieldValue || isHotLiteral) { + if ((isFieldValue || isHotLiteral) && (!FEOptions::GetInstance().IsAOT())) { std::string literalGlobalPtrName = namemangler::kPtrPrefixStr + literalGlobalName; - MIRSymbol *literalVarPtr = mirBuilder.GetOrCreateGlobalDecl(literalGlobalPtrName.c_str(), *typeString); + MIRSymbol *literalVarPtr = mirBuilderIn.GetOrCreateGlobalDecl(literalGlobalPtrName.c_str(), *typeString); literalVarPtr->SetStorageClass(literalVar->GetStorageClass()); - AddrofNode *expr = mirBuilder.CreateExprAddrof(0, *literalVar, module.GetMemPool()); + AddrofNode *expr = mirBuilderIn.CreateExprAddrof(0, *literalVar, module.GetMemPool()); MIRConst *cst = module.GetMemPool()->New( expr->GetStIdx(), expr->GetFieldID(), *GlobalTables::GetTypeTable().GetPtr()); literalVarPtr->SetKonst(cst); + literalVarPtr->SetAttr(ATTR_readonly); literalMap[literalVar] = literalVarPtr; } (void)GlobalTables::GetConstPool().GetConstU16StringPool().insert(std::make_pair(strU16, literalVar)); @@ -131,7 +135,7 @@ std::string FEJavaStringManager::GetLiteralGlobalName(const std::u16string &strU if (strU16.length() == 0) { literalGlobalName = LiteralStrName::GetLiteralStrName(swapped.data(), 0); } else { - literalGlobalName = LiteralStrName::GetLiteralStrName(swapped.data(), strU16.length() << 1); + literalGlobalName = LiteralStrName::GetLiteralStrName(swapped.data(), static_cast(strU16.length() << 1)); } return literalGlobalName; } @@ -152,17 +156,18 @@ bool FEJavaStringManager::IsAllASCII(const std::u16string &strU16) { MIRArrayType *FEJavaStringManager::ConstructArrayType4Str(const std::u16string &strU16, bool compressible) const { MPLFE_PARALLEL_FORBIDDEN(); uint32 arraySize[1]; - int length = compressible ? strU16.length() : (strU16.length() * 2); // use 2 bytes per char in uncompress mode + // use 2 bytes per char in uncompress mode + uint32 length = compressible ? static_cast(strU16.length()) : static_cast(strU16.length() * 2); #ifdef JAVA_OBJ_IN_MFILE #ifdef USE_32BIT_REF - int sizeInBytes = 16 + length; // shadow(4B)+monitor(4B)+count(4B)+hash(4B)+content -#else // !USE_32BIT_REF - int sizeInBytes = 20 + length; // shadow(8B)+monitor(4B)+count(4B)+hash(4B)+content -#endif // USE_32BIT_REF -#else // !JAVA_OBJ_IN_MFILE - int sizeInBytes = 8 + length; // count(4B)+hash(4B)+content -#endif // JAVA_OBJ_IN_MFILE - int sizeInLongs = (sizeInBytes - 1) / 8 + 1; // round up to 8B units + uint32 sizeInBytes = 16 + length; // shadow(4B)+monitor(4B)+count(4B)+hash(4B)+content +#else // !USE_32BIT_REF + uint32 sizeInBytes = 20 + length; // shadow(8B)+monitor(4B)+count(4B)+hash(4B)+content +#endif // USE_32BIT_REF +#else // !JAVA_OBJ_IN_MFILE + uint32 sizeInBytes = 8 + length; // count(4B)+hash(4B)+content +#endif // JAVA_OBJ_IN_MFILE + uint32 sizeInLongs = (sizeInBytes - 1) / 8 + 1; // round up to 8B units arraySize[0] = sizeInLongs; MIRArrayType *byteArrayType = static_cast( GlobalTables::GetTypeTable().GetOrCreateArrayType(*GlobalTables::GetTypeTable().GetUInt64(), 1, arraySize)); @@ -190,11 +195,12 @@ MIRAggConst *FEJavaStringManager::CreateByteArrayConst(const std::u16string &str #endif // JAVA_OBJ_IN_MFILE // @count - uint32_t strCount = strU16.length() ? ((strU16.length() * 2) | compressible) : 0; + uint32 strCount = strU16.length() ? static_cast((strU16.length() * 2) | compressible) : 0; AddDataIntoByteArray(*newconst, *mp, currData, strCount, *uInt64); // @hash - uint32_t hash = LiteralStrName::CalculateHashSwapByte(strU16.data(), strU16.length()); + uint32 hash = static_cast( + LiteralStrName::CalculateHashSwapByte(strU16.data(), static_cast(strU16.length()))); AddDataIntoByteArray(*newconst, *mp, currData, hash, *uInt64); // @content @@ -250,4 +256,34 @@ void FEJavaStringManager::FinishByteArray(MIRAggConst &newConst, MemPool &mp, DW buf.pos = 0; } } + +void FEJavaStringManager::GenStringMetaClassVar() { + std::unique_ptr metaClassType = std::make_unique(kTypeStruct); + + GStrIdx strIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("dummy"); + metaClassType->GetFields().emplace_back( + strIdx, TyIdxFieldAttrPair(GlobalTables::GetTypeTable().GetVoidPtr()->GetTypeIndex(), FieldAttrs())); + + GStrIdx metaStrIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::kClassMetadataTypeName); + TyIdx tyIdx = GlobalTables::GetTypeTable().GetOrCreateMIRType(metaClassType.get()); + // Global? + module.GetTypeNameTab()->SetGStrIdxToTyIdx(metaStrIdx, tyIdx); + CHECK_FATAL(GlobalTables::GetTypeTable().GetTypeTable().size() > tyIdx, "empty check"); + if (GlobalTables::GetTypeTable().GetTypeTable()[tyIdx]->GetNameStrIdx() == 0) { + GlobalTables::GetTypeTable().GetTypeTable()[tyIdx]->SetNameStrIdx(metaStrIdx); + } + metaClassType->SetTypeIndex(tyIdx); + module.AddClass(tyIdx); + std::string buf(CLASSINFO_PREFIX_STR); + (void)buf.append("Ljava_2Flang_2FString_3B"); + stringMetaClassSymbol = mirBuilder.GetOrCreateGlobalDecl(buf.c_str(), *metaClassType); + GStrIdx typeNameIdxForString = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("Ljava_2Flang_2FString_3B"); + if (FEManager::GetTypeManager().IsImportedType(typeNameIdxForString)) { + stringMetaClassSymbol->SetStorageClass(kScExtern); + } +} + +void FEJavaStringManager::ClearStringMetaClassSymbolExternFlag() { + stringMetaClassSymbol->SetStorageClass(kScGlobal); +} } // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/fe_options.cpp b/src/mplfe/common/src/fe_options.cpp index e52779dce7877e113e0369bea9babd8786cdc6fa..1928b47f10ad2aa15f00097ddb2ce3c6a1e9dac9 100644 --- a/src/mplfe/common/src/fe_options.cpp +++ b/src/mplfe/common/src/fe_options.cpp @@ -40,7 +40,16 @@ void FEOptions::AddInputJarFile(const std::string &fileName) { if (type == FEFileType::FileType::kJar) { inputJarFiles.push_back(fileName); } else { - WARN(kLncWarn, "invalid input class file %s...skipped", fileName.c_str()); + WARN(kLncWarn, "invalid input jar file %s...skipped", fileName.c_str()); + } +} + +void FEOptions::AddInputDexFile(const std::string &fileName) { + FEFileType::FileType type = FEFileType::GetInstance().GetFileTypeByMagicNumber(fileName); + if (type == FEFileType::FileType::kDex) { + inputDexFiles.push_back(fileName); + } else { + WARN(kLncWarn, "invalid input dex file %s...skipped", fileName.c_str()); } } diff --git a/src/mplfe/common/src/fe_struct_elem_info.cpp b/src/mplfe/common/src/fe_struct_elem_info.cpp index dcd6b7541772ec3d299c9fa8018f291f82fe2a0a..2565ac28f0d6833d7feee62725c82682b6279b8f 100644 --- a/src/mplfe/common/src/fe_struct_elem_info.cpp +++ b/src/mplfe/common/src/fe_struct_elem_info.cpp @@ -16,55 +16,36 @@ #include "global_tables.h" #include "mpl_logging.h" #include "namemangler.h" +#include "feir_builder.h" +#include "feir_var_name.h" #include "fe_utils.h" #include "fe_manager.h" #include "jbc_util.h" +#include "fe_options.h" +#include "bc_util.h" namespace maple { // ---------- FEStructElemInfo ---------- -FEStructElemInfo::FEStructElemInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic) - : fullNameIdx(argFullNameIdx), +FEStructElemInfo::FEStructElemInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic) + : structElemNameIdx(argStructElemNameIdx), srcLang(argSrcLang), isStatic(argIsStatic), isMethod(false), isDefined(false), isFromDex(false), - isPrepared(false), - structNameIdx(0) { - // fieldNameIdx(0), - // typeNameIdx(0), - // fieldID(0) { - Init(); + isPrepared(false) { } -void FEStructElemInfo::Init() { - switch (srcLang) { - case kSrcLangJava: - InitJava(); - break; - default: - WARN(kLncWarn, "unsupported language"); - break; - } -} - -void FEStructElemInfo::InitJava() { - std::string fullNameMpl = GlobalTables::GetStrTable().GetStringFromStrIdx(fullNameIdx); - std::string fullNameJava = namemangler::DecodeName(fullNameMpl); - std::vector names = FEUtils::Split(fullNameJava, '|'); - // 3 parts: ClassName|ElemName|Signature - CHECK_FATAL(names.size() == 3, "invalid elem name %s", fullNameJava.c_str()); - // names[0]: structName - structNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(names[0])); - // names[1]: elemName - elemNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(names[1])); - // names[2]: signature - signatureNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(names[2])); +UniqueFEIRType FEStructElemInfo::GetActualContainerType() const { + // Invokable after prepared + return FEIRBuilder::CreateTypeByJavaName(actualContainer, true); } // ---------- FEStructFieldInfo ---------- -FEStructFieldInfo::FEStructFieldInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic) - : FEStructElemInfo(argFullNameIdx, argSrcLang, argIsStatic), +FEStructFieldInfo::FEStructFieldInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic) + : FEStructElemInfo(argStructElemNameIdx, argSrcLang, argIsStatic), fieldType(nullptr), fieldNameIdx(0), fieldID(0) { @@ -77,11 +58,10 @@ void FEStructFieldInfo::PrepareImpl(MIRBuilder &mirBuilder, bool argIsStatic) { return; } // Prepare - const std::string &structName = GetStructName(); - std::string rawName = structName + namemangler::kNameSplitterStr + GetElemName(); + actualContainer = GetStructName(); + std::string rawName = actualContainer + namemangler::kNameSplitterStr + GetElemName(); fieldNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(rawName); - fieldID = static_cast(UINT32_MAX); - MIRStructType *structType = FEManager::GetTypeManager().GetStructTypeFromName(structName); + MIRStructType *structType = FEManager::GetTypeManager().GetStructTypeFromName(actualContainer); if (structType == nullptr) { isDefined = false; isPrepared = true; @@ -123,13 +103,14 @@ void FEStructFieldInfo::PrepareStaticField(const MIRStructType &structType) { isStatic = true; } -void FEStructFieldInfo::PrepareNonStaticField(MIRStructType &structType, MIRBuilder &mirBuilder) { +void FEStructFieldInfo::PrepareNonStaticField(MIRBuilder &mirBuilder) { FEIRTypeDefault feType(PTY_unknown); feType.LoadFromJavaTypeName(GetSignatureName(), true); MIRType *fieldMIRType = feType.GenerateMIRTypeAuto(srcLang); uint32 idx = 0; uint32 idx1 = 0; - mirBuilder.TraverseToNamedFieldWithType(structType, elemNameIdx, fieldMIRType->GetTypeIndex(), idx1, idx); + MIRStructType *structType = FEManager::GetTypeManager().GetStructTypeFromName(GetStructName()); + mirBuilder.TraverseToNamedFieldWithType(*structType, structElemNameIdx.elem, fieldMIRType->GetTypeIndex(), idx1, idx); fieldID = static_cast(idx); isPrepared = true; isStatic = false; @@ -140,12 +121,18 @@ bool FEStructFieldInfo::SearchStructFieldJava(MIRStructType &structType, MIRBuil if (structType.IsIncomplete()) { return false; } - GStrIdx nameIdx = elemNameIdx; + GStrIdx nameIdx = structElemNameIdx.elem; if (argIsStatic) { - // suppose anti-proguard is off + // suppose anti-proguard is off in jbc. + // Turn on anti-proguard in jbc: -java-staticfield-name=smart && JBCClass2FEHelper::isStaticFieldProguard(false) + // Turn on anti-proguard in BC: -java-staticfield-name=smart std::string fullName = structType.GetCompactMplTypeName() + namemangler::kNameSplitterStr + GetElemName(); + if (FEOptions::GetInstance().GetModeJavaStaticFieldName() != FEOptions::ModeJavaStaticFieldName::kNoType) { + fullName += namemangler::kNameSplitterStr + GetSignatureName(); + } nameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(fullName); } + actualContainer = structType.GetCompactMplTypeName(); const FieldVector &fields = argIsStatic ? structType.GetStaticFields() : structType.GetFields(); for (const FieldPair &fieldPair : fields) { if (fieldPair.first != nameIdx) { @@ -158,7 +145,7 @@ bool FEStructFieldInfo::SearchStructFieldJava(MIRStructType &structType, MIRBuil if (argIsStatic) { PrepareStaticField(structType); } else { - PrepareNonStaticField(structType, mirBuilder); + PrepareNonStaticField(mirBuilder); } return true; } @@ -166,13 +153,13 @@ bool FEStructFieldInfo::SearchStructFieldJava(MIRStructType &structType, MIRBuil // search parent bool found = false; if (structType.GetKind() == kTypeClass) { - // parent MIRClassType &classType = static_cast(structType); - found = SearchStructFieldJava(classType.GetParentTyIdx(), mirBuilder, argIsStatic, false); // implemented for (const TyIdx &tyIdx : classType.GetInterfaceImplemented()) { found = found || SearchStructFieldJava(tyIdx, mirBuilder, argIsStatic, false); } + // parent + found = found || SearchStructFieldJava(classType.GetParentTyIdx(), mirBuilder, argIsStatic, false); } else if (structType.GetKind() == kTypeInterface) { // parent MIRInterfaceType &interfaceType = static_cast(structType); @@ -216,9 +203,10 @@ bool FEStructFieldInfo::CompareFieldType(const FieldPair &fieldPair) const { // ---------- FEStructMethodInfo ---------- std::map> FEStructMethodInfo::javaPolymorphicWhiteList; -FEStructMethodInfo::FEStructMethodInfo(const GStrIdx &argFullNameIdx, MIRSrcLang argSrcLang, bool argIsStatic) - : FEStructElemInfo(argFullNameIdx, argSrcLang, argIsStatic), - methodNameIdx(fullNameIdx), +FEStructMethodInfo::FEStructMethodInfo(const StructElemNameIdx &argStructElemNameIdx, + MIRSrcLang argSrcLang, bool argIsStatic) + : FEStructElemInfo(argStructElemNameIdx, argSrcLang, argIsStatic), + methodNameIdx(argStructElemNameIdx.full), mirFunc(nullptr), isReturnVoid(false), isJavaPolymorphicCall(false), @@ -235,8 +223,7 @@ void FEStructMethodInfo::InitJavaPolymorphicWhiteList() { MPLFE_PARALLEL_FORBIDDEN(); std::map> &ans = javaPolymorphicWhiteList; StringTable &strTable = GlobalTables::GetStrTable(); - GStrIdx idxMethodHandle = - strTable.GetOrCreateStrIdxFromName(namemangler::EncodeName("Ljava/lang/invoke/MethodHandle;")); + GStrIdx idxMethodHandle = bc::BCUtil::GetJavaMethodHandleNameMplIdx(); bool success = true; success = success && ans[idxMethodHandle].insert(strTable.GetOrCreateStrIdxFromName("invoke")).second; success = success && ans[idxMethodHandle].insert(strTable.GetOrCreateStrIdxFromName("invokeBasic")).second; @@ -265,12 +252,12 @@ void FEStructMethodInfo::PrepareImpl(MIRBuilder &mirBuilder, bool argIsStatic) { void FEStructMethodInfo::PrepareImplJava(MIRBuilder &mirBuilder, bool argIsStatic) { // Prepare - const std::string &structName = GetStructName(); + actualContainer = GetStructName(); MIRStructType *structType = nullptr; - if (!structName.empty() && structName[0] == 'A') { + if (!actualContainer.empty() && actualContainer[0] == 'A') { structType = FEManager::GetTypeManager().GetStructTypeFromName("Ljava_2Flang_2FObject_3B"); } else { - structType = FEManager::GetTypeManager().GetStructTypeFromName(structName); + structType = FEManager::GetTypeManager().GetStructTypeFromName(actualContainer); } isStatic = argIsStatic; isDefined = false; @@ -280,12 +267,12 @@ void FEStructMethodInfo::PrepareImplJava(MIRBuilder &mirBuilder, bool argIsStati return; } } else if (isJavaDynamicCall) { - methodNameIdx = fullNameIdx; + methodNameIdx = structElemNameIdx.full; isDefined = true; PrepareMethod(); return; } - std::string methodName = GlobalTables::GetStrTable().GetStringFromStrIdx(fullNameIdx); + std::string methodName = GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx.full); WARN(kLncWarn, "undefined %s method: %s", isStatic ? "static" : "", methodName.c_str()); } @@ -302,7 +289,7 @@ void FEStructMethodInfo::LoadMethodType() { void FEStructMethodInfo::LoadMethodTypeJava() { std::string signatureJava = - namemangler::DecodeName(GlobalTables::GetStrTable().GetStringFromStrIdx(fullNameIdx)); + namemangler::DecodeName(GlobalTables::GetStrTable().GetStringFromStrIdx(structElemNameIdx.full)); std::vector typeNames = jbc::JBCUtil::SolveMethodSignature(signatureJava); CHECK_FATAL(typeNames.size() > 0, "invalid method signature: %s", signatureJava.c_str()); // constructor check @@ -331,13 +318,33 @@ void FEStructMethodInfo::PrepareMethod() { if (mirFunc == nullptr) { MIRType *mirRetType = retType->GenerateMIRTypeAuto(srcLang); // args type + std::vector> argVarList; std::vector argsTypeIdx; + if (!isStatic) { + GStrIdx nameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("_this"); + UniqueFEIRVar regVar = std::make_unique(nameIdx, ownerType->Clone(), false); + argVarList.emplace_back(std::move(regVar)); + argsTypeIdx.emplace_back(ownerType->GenerateMIRType(srcLang, true)->GetTypeIndex()); + } + uint8 regNum = 1; for (const UniqueFEIRType &argType : argTypes) { + UniqueFEIRVar regVar = FEIRBuilder::CreateVarReg(regNum, argType->Clone(), false); + ++regNum; + argVarList.emplace_back(std::move(regVar)); MIRType *mirArgType = argType->GenerateMIRTypeAuto(srcLang); argsTypeIdx.push_back(mirArgType->GetTypeIndex()); } mirFunc = FEManager::GetTypeManager().CreateFunction(methodNameIdx, mirRetType->GetTypeIndex(), argsTypeIdx, false, isStatic); + // Update formals for external function, + // defined function will be update formals later in FEFunction::UpdateFormal + for (const std::unique_ptr &argVar : argVarList) { + MIRType *mirTy = argVar->GetType()->GenerateMIRTypeAuto(); + std::string name = argVar->GetName(*mirTy); + MIRSymbol *sym = FEManager::GetMIRBuilder().GetOrCreateDeclInFunc(name, *mirTy, *mirFunc); + sym->SetStorageClass(kScFormal); + mirFunc->AddArgument(sym); + } } isPrepared = true; } @@ -347,6 +354,7 @@ bool FEStructMethodInfo::SearchStructMethodJava(MIRStructType &structType, MIRBu if (structType.IsIncomplete()) { return false; } + actualContainer = structType.GetCompactMplTypeName(); std::string fullName = structType.GetCompactMplTypeName() + namemangler::kNameSplitterStr + GetElemName() + namemangler::kNameSplitterStr + GetSignatureName(); GStrIdx nameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(fullName); @@ -421,10 +429,10 @@ bool FEStructMethodInfo::SearchStructMethodJava(const TyIdx &tyIdx, MIRBuilder & } bool FEStructMethodInfo::CheckJavaPolymorphicCall() const { - auto it = javaPolymorphicWhiteList.find(structNameIdx); + auto it = javaPolymorphicWhiteList.find(structElemNameIdx.klass); if (it == javaPolymorphicWhiteList.end()) { return false; } - return it->second.find(elemNameIdx) != it->second.end(); + return it->second.find(structElemNameIdx.elem) != it->second.end(); } } // namespace maple diff --git a/src/mplfe/common/src/fe_type_manager.cpp b/src/mplfe/common/src/fe_type_manager.cpp index 11ea27e59871047ec53e897a1320834a80666c23..599d7f00e885402299179de86d93d09dc9dcf818 100644 --- a/src/mplfe/common/src/fe_type_manager.cpp +++ b/src/mplfe/common/src/fe_type_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -21,6 +21,7 @@ #include "fe_timer.h" #include "fe_config_parallel.h" #include "feir_type_helper.h" +#include "fe_macros.h" namespace maple { const UniqueFEIRType FETypeManager::kPrimFEIRTypeUnknown = std::make_unique(PTY_unknown); @@ -49,15 +50,36 @@ FETypeManager::FETypeManager(MIRModule &moduleIn) static_cast(kFEIRTypeJavaObject.get())->LoadFromJavaTypeName("Ljava/lang/Object;", false); static_cast(kFEIRTypeJavaClass.get())->LoadFromJavaTypeName("Ljava/lang/Class;", false); static_cast(kFEIRTypeJavaString.get())->LoadFromJavaTypeName("Ljava/lang/String;", false); + sameNamePolicy.SetFlag(FETypeSameNamePolicy::kFlagUseLastest); } FETypeManager::~FETypeManager() { mp = nullptr; funcMCCGetOrInsertLiteral = nullptr; + + funcMCCStaticFieldGetBool = nullptr; + funcMCCStaticFieldGetByte = nullptr; + funcMCCStaticFieldGetShort = nullptr; + funcMCCStaticFieldGetChar = nullptr; + funcMCCStaticFieldGetInt = nullptr; + funcMCCStaticFieldGetLong = nullptr; + funcMCCStaticFieldGetFloat = nullptr; + funcMCCStaticFieldGetDouble = nullptr; + funcMCCStaticFieldGetObject = nullptr; + + funcMCCStaticFieldSetBool = nullptr; + funcMCCStaticFieldSetByte = nullptr; + funcMCCStaticFieldSetShort = nullptr; + funcMCCStaticFieldSetChar = nullptr; + funcMCCStaticFieldSetInt = nullptr; + funcMCCStaticFieldSetLong = nullptr; + funcMCCStaticFieldSetFloat = nullptr; + funcMCCStaticFieldSetDouble = nullptr; + funcMCCStaticFieldSetObject = nullptr; } void FETypeManager::ReleaseMemPool() { - memPoolCtrler.DeleteMemPool(mp); + delete mp; mp = nullptr; } @@ -118,6 +140,16 @@ void FETypeManager::UpdateStructNameTypeMapFromTypeTable(const std::string &mplt } } +void FETypeManager::SetMirImportedTypes(FETypeFlag flag) { + for (auto &item : structNameTypeMap) { + MIRStructType *type = item.second.first; + if ((type != nullptr) && FETypeManager::IsStructType(*type)) { + type->SetIsImported(true); + item.second.second = flag; + } + } +} + void FETypeManager::UpdateNameFuncMapFromTypeTable() { for (uint32 i = 1; i < GlobalTables::GetGsymTable().GetSymbolTableSize(); i++) { MIRSymbol *symbol = GlobalTables::GetGsymTable().GetSymbol(i); @@ -192,15 +224,19 @@ MIRStructType *FETypeManager::CreateClassOrInterfaceType(const GStrIdx &nameIdx, MIRStructType *FETypeManager::GetOrCreateClassOrInterfaceType(const GStrIdx &nameIdx, bool isInterface, FETypeFlag typeFlag, bool &isCreate) { // same name policy: mpltSys > dex > mpltApk > mplt - auto it = structNameTypeMap.find(nameIdx); + const std::unordered_map::iterator &it = structNameTypeMap.find(nameIdx); if (it != structNameTypeMap.end()) { - // type is existed uint16 flagExist = it->second.second & FETypeFlag::kSrcMask; uint16 flagNew = typeFlag & FETypeFlag::kSrcMask; + // type is existed, use existed type if (flagNew > flagExist) { isCreate = false; return it->second.first; } + // type is existed when src input, replace with new type + if (typeFlag == FETypeFlag::kSrcInput && it->second.second != FETypeFlag::kSrcMpltApk) { + UpdateDupTypes(nameIdx, isInterface, it); + } } MIRStructType *structType = CreateClassOrInterfaceType(nameIdx, isInterface, typeFlag); isCreate = true; @@ -208,6 +244,38 @@ MIRStructType *FETypeManager::GetOrCreateClassOrInterfaceType(const GStrIdx &nam return structType; } +void FETypeManager::UpdateDupTypes(const GStrIdx &nameIdx, bool isInterface, + const std::unordered_map::iterator &importedTypeIt) { + FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "duplicated type %s from src", + GlobalTables::GetStrTable().GetStringFromStrIdx(nameIdx).c_str()); + MIRStructType *importedType = importedTypeIt->second.first; + MIRStructType *newType = nullptr; + // If locally defined type and imported type have the same name, but one is of interface and another one + // is of class type, we need to update the type + if ((importedType->IsMIRClassType() && isInterface) || + (importedType->IsMIRInterfaceType() && !isInterface)) { + if (isInterface) { + newType = new MIRInterfaceType(kTypeInterfaceIncomplete); + } else { + newType = new MIRClassType(kTypeClassIncomplete); + } + newType->SetTypeIndex(importedType->GetTypeIndex()); + importedType->SetTypeIndex(TyIdx(-1)); + newType->SetNameStrIdx(importedType->GetNameStrIdx()); + importedType->SetNameStrIdxItem(0); + CHECK_FATAL(newType->GetTypeIndex() < GlobalTables::GetTypeTable().GetTypeTable().size(), + "newType->_ty_idx >= GlobalTables::GetTypeTable().type_table_.size()"); + GlobalTables::GetTypeTable().GetTypeTable()[newType->GetTypeIndex()] = newType; + } else { + importedType->ClearContents(); + } + (void)structNameTypeMap.erase(importedTypeIt); + auto it = structNameSrcMap.find(nameIdx); + if (it != structNameSrcMap.end()) { + (void)structNameSrcMap.erase(it); + } +} + MIRType *FETypeManager::GetOrCreateClassOrInterfacePtrType(const GStrIdx &nameIdx, bool isInterface, FETypeFlag typeFlag, bool &isCreate) { MIRStructType *structType = GetOrCreateClassOrInterfaceType(nameIdx, isInterface, typeFlag, isCreate); @@ -230,6 +298,14 @@ MIRStructType *FETypeManager::GetStructTypeFromName(const GStrIdx &nameIdx) { } } +uint32 FETypeManager::GetTypeIDFromMplClassName(const std::string &mplClassName) const { + auto const &it = classNameTypeIDMap.find(mplClassName); + if (it != classNameTypeIDMap.end()) { + return it->second; + } + return UINT32_MAX; // some type id not in the dex file, give UINT32_MAX +} + MIRType *FETypeManager::GetOrCreateTypeFromName(const std::string &name, FETypeFlag typeFlag, bool usePtr) { CHECK_FATAL(!name.empty(), "type name is empty"); PrimType pty = GetPrimType(name); @@ -249,7 +325,7 @@ MIRType *FETypeManager::GetOrCreateTypeFromName(const std::string &name, FETypeF case 'A': { uint32 dim = 0; bool isCreate = false; - std::string elemTypeName = GetBaseTypeName(name, dim, true); + const std::string &elemTypeName = GetBaseTypeName(name, dim, true); MIRType *elemType = GetMIRTypeForPrim(elemTypeName); if (elemType == nullptr) { elemType = GetOrCreateClassOrInterfaceType(elemTypeName, false, typeFlag, isCreate); @@ -306,30 +382,28 @@ void FETypeManager::AddClassToModule(const MIRStructType &structType) { module.AddClass(structType.GetTypeIndex()); } -FEStructElemInfo *FETypeManager::RegisterStructFieldInfo(const GStrIdx &fullNameIdx, MIRSrcLang argSrcLang, - bool isStatic) { - FEStructElemInfo *ptrInfo = GetStructElemInfo(fullNameIdx); +FEStructElemInfo *FETypeManager::RegisterStructFieldInfo( + const StructElemNameIdx &structElemNameIdx, MIRSrcLang argSrcLang, bool isStatic) { + std::lock_guard lk(feTypeManagerMtx); + FEStructElemInfo *ptrInfo = GetStructElemInfo(structElemNameIdx.full); if (ptrInfo != nullptr) { return ptrInfo; } - UniqueFEStructElemInfo info = std::make_unique(fullNameIdx, argSrcLang, isStatic); - ptrInfo = info.get(); - listStructElemInfo.push_back(std::move(info)); - CHECK_FATAL(mapStructElemInfo.insert(std::make_pair(fullNameIdx, ptrInfo)).second == true, + ptrInfo = mp->New(structElemNameIdx, argSrcLang, isStatic); + CHECK_FATAL(mapStructElemInfo.insert(std::make_pair(structElemNameIdx.full, ptrInfo)).second == true, "register struct elem info failed"); return ptrInfo; } -FEStructElemInfo *FETypeManager::RegisterStructMethodInfo(const GStrIdx &fullNameIdx, MIRSrcLang argSrcLang, - bool isStatic) { - FEStructElemInfo *ptrInfo = GetStructElemInfo(fullNameIdx); +FEStructElemInfo *FETypeManager::RegisterStructMethodInfo( + const StructElemNameIdx &structElemNameIdx, MIRSrcLang argSrcLang, bool isStatic) { + std::lock_guard lk(feTypeManagerMtx); + FEStructElemInfo *ptrInfo = GetStructElemInfo(structElemNameIdx.full); if (ptrInfo != nullptr) { return ptrInfo; } - UniqueFEStructElemInfo info = std::make_unique(fullNameIdx, argSrcLang, isStatic); - ptrInfo = info.get(); - listStructElemInfo.push_back(std::move(info)); - CHECK_FATAL(mapStructElemInfo.insert(std::make_pair(fullNameIdx, ptrInfo)).second == true, + ptrInfo = mp->New(structElemNameIdx, argSrcLang, isStatic); + CHECK_FATAL(mapStructElemInfo.insert(std::make_pair(structElemNameIdx.full, ptrInfo)).second == true, "register struct elem info failed"); return ptrInfo; } @@ -373,6 +447,7 @@ MIRFunction *FETypeManager::CreateFunction(const GStrIdx &nameIdx, const TyIdx & funcSymbol->SetNameStrIdx(nameIdx); bool added = GlobalTables::GetGsymTable().AddToStringSymbolMap(*funcSymbol); if (!added) { + funcSymbol = GlobalTables::GetGsymTable().GetSymbolFromStrIdx(nameIdx); mirFunc = funcSymbol->GetFunction(); if (mirFunc != nullptr) { return mirFunc; @@ -402,6 +477,7 @@ MIRFunction *FETypeManager::CreateFunction(const GStrIdx &nameIdx, const TyIdx & mirFunc->SetMIRFuncType(functype); mirFunc->SetReturnTyIdx(retTypeIdx); if (isStatic) { + mirFunc->SetAttr(FUNCATTR_static); CHECK_FATAL(nameStaticFuncMap.insert(std::make_pair(nameIdx, mirFunc)).second, "nameStaticFuncMap insert failed"); } else { CHECK_FATAL(nameFuncMap.insert(std::make_pair(nameIdx, mirFunc)).second, "nameFuncMap insert failed"); @@ -484,12 +560,15 @@ bool FETypeManager::IsStructType(const MIRType &type) { PrimType FETypeManager::GetPrimType(const std::string &name) { #define LOAD_ALGO_PRIMARY_TYPE -#define PRIMTYPE(P) \ - if (name.compare(#P) == 0) { \ - return PTY_##P; \ - } +#define PRIMTYPE(P) + static std::unordered_map typeMap = { #include "prim_types.def" + }; #undef PRIMTYPE + auto it = typeMap.find(name); + if (it != typeMap.end()) { + return it->second; + } return kPtyInvalid; } @@ -558,8 +637,22 @@ std::string FETypeManager::TypeAttrsToString(const TypeAttrs &attrs) { return ss.str(); } +void FETypeManager::MarkExternStructType() { + for (auto elem : structNameTypeMap) { + if (elem.second.second != FETypeFlag::kSrcInput && + elem.second.second != FETypeFlag::kSrcMplt && + elem.second.second != FETypeFlag::kSrcMpltSys && + elem.second.second != FETypeFlag::kSrcMpltApk) { + module.AddExternStructType(elem.second.first); + } + } +} + void FETypeManager::InitMCCFunctions() { InitFuncMCCGetOrInsertLiteral(); + if (FEOptions::GetInstance().IsAOT()) { + InitFuncMCCStaticField(); + } } void FETypeManager::InitFuncMCCGetOrInsertLiteral() { @@ -568,9 +661,45 @@ void FETypeManager::InitFuncMCCGetOrInsertLiteral() { MIRType *typeString = kFEIRTypeJavaString->GenerateMIRTypeAuto(kSrcLangJava); std::vector argsType; funcMCCGetOrInsertLiteral = CreateFunction(nameIdx, typeString->GetTypeIndex(), argsType, false, false); + funcMCCGetOrInsertLiteral->SetAttr(FUNCATTR_pure); + funcMCCGetOrInsertLiteral->SetAttr(FUNCATTR_nosideeffect); + funcMCCGetOrInsertLiteral->SetAttr(FUNCATTR_noprivate_defeffect); nameMCCFuncMap[nameIdx] = funcMCCGetOrInsertLiteral; } +void FETypeManager::InitFuncMCCStaticField() { + std::map> MCCIdxFuncMap = { + { FEUtils::GetMCCStaticFieldGetBoolIdx(), std::make_pair('Z', funcMCCStaticFieldGetBool) }, + { FEUtils::GetMCCStaticFieldGetByteIdx(), std::make_pair('B', funcMCCStaticFieldGetByte) }, + { FEUtils::GetMCCStaticFieldGetShortIdx(), std::make_pair('S', funcMCCStaticFieldGetShort) }, + { FEUtils::GetMCCStaticFieldGetCharIdx(), std::make_pair('C', funcMCCStaticFieldGetChar) }, + { FEUtils::GetMCCStaticFieldGetIntIdx(), std::make_pair('I', funcMCCStaticFieldGetInt) }, + { FEUtils::GetMCCStaticFieldGetLongIdx(), std::make_pair('J', funcMCCStaticFieldGetLong) }, + { FEUtils::GetMCCStaticFieldGetFloatIdx(), std::make_pair('F', funcMCCStaticFieldGetFloat) }, + { FEUtils::GetMCCStaticFieldGetDoubleIdx(), std::make_pair('D', funcMCCStaticFieldGetDouble) }, + { FEUtils::GetMCCStaticFieldGetObjectIdx(), std::make_pair('R', funcMCCStaticFieldGetObject) }, + { FEUtils::GetMCCStaticFieldSetBoolIdx(), std::make_pair('Z', funcMCCStaticFieldSetBool) }, + { FEUtils::GetMCCStaticFieldSetByteIdx(), std::make_pair('B', funcMCCStaticFieldSetByte) }, + { FEUtils::GetMCCStaticFieldSetShortIdx(), std::make_pair('S', funcMCCStaticFieldSetShort) }, + { FEUtils::GetMCCStaticFieldSetCharIdx(), std::make_pair('C', funcMCCStaticFieldSetChar) }, + { FEUtils::GetMCCStaticFieldSetIntIdx(), std::make_pair('I', funcMCCStaticFieldSetInt) }, + { FEUtils::GetMCCStaticFieldSetLongIdx(), std::make_pair('J', funcMCCStaticFieldSetLong) }, + { FEUtils::GetMCCStaticFieldSetFloatIdx(), std::make_pair('F', funcMCCStaticFieldSetFloat) }, + { FEUtils::GetMCCStaticFieldSetDoubleIdx(), std::make_pair('D', funcMCCStaticFieldSetDouble) }, + { FEUtils::GetMCCStaticFieldSetObjectIdx(), std::make_pair('R', funcMCCStaticFieldSetObject) }, + }; + + for (auto &idxFun : MCCIdxFuncMap) { + std::vector argsType; + MIRType *typeMCC = GetMIRTypeForPrim(idxFun.second.first); + idxFun.second.second = CreateFunction(idxFun.first, typeMCC->GetTypeIndex(), argsType, false, false); + idxFun.second.second->SetAttr(FUNCATTR_pure); + idxFun.second.second->SetAttr(FUNCATTR_nosideeffect); + idxFun.second.second->SetAttr(FUNCATTR_noprivate_defeffect); + nameMCCFuncMap[idxFun.first] = idxFun.second.second; + } +} + MIRFunction *FETypeManager::GetMCCFunction(const std::string &funcName) const { GStrIdx funcNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(funcName); return GetMCCFunction(funcNameIdx); diff --git a/src/mplfe/common/src/fe_utils.cpp b/src/mplfe/common/src/fe_utils.cpp index 4d04dcf3db226266fde78599404d647e862eaaee..7e4e3639530615dd8ffaa13da06fbcf6a5b0308d 100644 --- a/src/mplfe/common/src/fe_utils.cpp +++ b/src/mplfe/common/src/fe_utils.cpp @@ -16,9 +16,37 @@ #include #include "mpl_logging.h" #include "mir_type.h" - namespace maple { - // ---------- FEUtils ---------- +// ---------- FEUtils ---------- +const std::string FEUtils::kBoolean = "Z"; +const std::string FEUtils::kByte = "B"; +const std::string FEUtils::kShort = "S"; +const std::string FEUtils::kChar = "C"; +const std::string FEUtils::kInt = "I"; +const std::string FEUtils::kLong = "J"; +const std::string FEUtils::kFloat = "F"; +const std::string FEUtils::kDouble = "D"; +const std::string FEUtils::kVoid = "V"; +const std::string FEUtils::kMCCStaticFieldGetBool = "MCC_StaticFieldGetBool"; +const std::string FEUtils::kMCCStaticFieldGetByte = "MCC_StaticFieldGetByte"; +const std::string FEUtils::kMCCStaticFieldGetShort = "MCC_StaticFieldGetShort"; +const std::string FEUtils::kMCCStaticFieldGetChar = "MCC_StaticFieldGetChar"; +const std::string FEUtils::kMCCStaticFieldGetInt = "MCC_StaticFieldGetInt"; +const std::string FEUtils::kMCCStaticFieldGetLong = "MCC_StaticFieldGetLong"; +const std::string FEUtils::kMCCStaticFieldGetFloat = "MCC_StaticFieldGetFloat"; +const std::string FEUtils::kMCCStaticFieldGetDouble = "MCC_StaticFieldGetDouble"; +const std::string FEUtils::kMCCStaticFieldGetObject = "MCC_StaticFieldGetObject"; + +const std::string FEUtils::kMCCStaticFieldSetBool = "MCC_StaticFieldSetBool"; +const std::string FEUtils::kMCCStaticFieldSetByte = "MCC_StaticFieldSetByte"; +const std::string FEUtils::kMCCStaticFieldSetShort = "MCC_StaticFieldSetShort"; +const std::string FEUtils::kMCCStaticFieldSetChar = "MCC_StaticFieldSetChar"; +const std::string FEUtils::kMCCStaticFieldSetInt = "MCC_StaticFieldSetInt"; +const std::string FEUtils::kMCCStaticFieldSetLong = "MCC_StaticFieldSetLong"; +const std::string FEUtils::kMCCStaticFieldSetFloat = "MCC_StaticFieldSetFloat"; +const std::string FEUtils::kMCCStaticFieldSetDouble = "MCC_StaticFieldSetDouble"; +const std::string FEUtils::kMCCStaticFieldSetObject = "MCC_StaticFieldSetObject"; + std::vector FEUtils::Split(const std::string &str, char delim) { std::vector ans; std::stringstream ss; @@ -104,6 +132,53 @@ PrimType FEUtils::MergePrimType(PrimType primType1, PrimType primType2) { return PTY_unknown; } +uint8 FEUtils::GetDim(const std::string &typeName) { + uint8 dim = 0; + for (size_t i = 0; i < typeName.length(); ++i) { + if (typeName.at(i) == 'A') { + dim++; + } else { + break; + } + } + return dim; +} + +std::string FEUtils::GetBaseTypeName(const std::string &typeName) { + return typeName.substr(GetDim(typeName)); +} + +PrimType FEUtils::GetPrimType(const GStrIdx &typeNameIdx) { + if (typeNameIdx == GetBooleanIdx()) { + return PTY_u1; + } + if (typeNameIdx == GetByteIdx()) { + return PTY_i8; + } + if (typeNameIdx == GetShortIdx()) { + return PTY_i16; + } + if (typeNameIdx == GetCharIdx()) { + return PTY_u16; + } + if (typeNameIdx == GetIntIdx()) { + return PTY_i32; + } + if (typeNameIdx == GetLongIdx()) { + return PTY_i64; + } + if (typeNameIdx == GetFloatIdx()) { + return PTY_f32; + } + if (typeNameIdx == GetDoubleIdx()) { + return PTY_f64; + } + if (typeNameIdx == GetVoidIdx()) { + return PTY_void; + } + return PTY_ref; +} + // ---------- FELinkListNode ---------- FELinkListNode::FELinkListNode() : prev(nullptr), next(nullptr) {} diff --git a/src/mplfe/common/src/fe_utils_java.cpp b/src/mplfe/common/src/fe_utils_java.cpp index a7b73c1e669f428ffc11410f59434fdc00349703..ae872cd5ec10e9fcace9eefa9328093dcc20afde 100644 --- a/src/mplfe/common/src/fe_utils_java.cpp +++ b/src/mplfe/common/src/fe_utils_java.cpp @@ -16,10 +16,7 @@ #include "namemangler.h" namespace maple { -std::vector FEUtilJava::SolveMethodSignature(std::string signature, bool inMpl) { - if (inMpl) { - signature = namemangler::DecodeName(signature); - } +std::vector FEUtilJava::SolveMethodSignature(const std::string &signature) { std::vector ans; size_t pos1 = signature.find('('); size_t pos2 = signature.find(')'); @@ -28,10 +25,10 @@ std::vector FEUtilJava::SolveMethodSignature(std::string signature, } std::string paramTypeNames = signature.substr(pos1 + 1, pos2 - pos1 - 1); std::string retTypeName = signature.substr(pos2 + 1); - ans.push_back(inMpl ? namemangler::EncodeName(retTypeName) : retTypeName); + ans.push_back(retTypeName); while (paramTypeNames.length() > 0) { std::string typeName = SolveParamNameInJavaFormat(paramTypeNames); - ans.push_back(inMpl ? namemangler::EncodeName(typeName) : typeName); + ans.push_back(typeName); paramTypeNames = paramTypeNames.substr(typeName.length()); } return ans; diff --git a/src/mplfe/common/src/feir_builder.cpp b/src/mplfe/common/src/feir_builder.cpp index 40ae330f1c1490e36af24479e991f84bd881717a..f6943f517aac293f377f697cde9e1ca6f9f09c5e 100644 --- a/src/mplfe/common/src/feir_builder.cpp +++ b/src/mplfe/common/src/feir_builder.cpp @@ -18,14 +18,26 @@ #include "feir_var_reg.h" #include "feir_var_name.h" #include "fe_type_manager.h" +#include "feir_type_helper.h" namespace maple { +extern const char *GetPrimTypeName(PrimType primType); +extern uint32 GetPrimTypeSize(PrimType primType); + UniqueFEIRType FEIRBuilder::CreateType(PrimType basePty, const GStrIdx &baseNameIdx, uint32 dim) { UniqueFEIRType type = std::make_unique(basePty, baseNameIdx, dim); CHECK_NULL_FATAL(type); return type; } +UniqueFEIRType FEIRBuilder::CreateArrayElemType(const UniqueFEIRType &arrayType) { + std::string typeName = arrayType->GetTypeName(); + ASSERT(typeName.length() > 1 && typeName.at(0) == 'A', "Invalid array type: %s", typeName.c_str()); + std::unique_ptr type = std::make_unique(); + type->LoadFromJavaTypeName(typeName.substr(1), true); + return type; +} + UniqueFEIRType FEIRBuilder::CreateRefType(const GStrIdx &baseNameIdx, uint32 dim) { return CreateType(PTY_ref, baseNameIdx, dim); } @@ -83,6 +95,14 @@ UniqueFEIRExpr FEIRBuilder::CreateExprConstRefNull() { return std::make_unique(int64{ 0 }, PTY_ref); } +UniqueFEIRExpr FEIRBuilder::CreateExprConstI8(int8 val) { + return std::make_unique(int64{ val }, PTY_i8); +} + +UniqueFEIRExpr FEIRBuilder::CreateExprConstI16(int16 val) { + return std::make_unique(int64{ val }, PTY_i16); +} + UniqueFEIRExpr FEIRBuilder::CreateExprConstI32(int32 val) { return std::make_unique(int64{ val }, PTY_i32); } @@ -104,6 +124,10 @@ UniqueFEIRExpr FEIRBuilder::CreateExprMathUnary(Opcode op, UniqueFEIRVar var0) { return std::make_unique(op, std::move(opnd0)); } +UniqueFEIRExpr FEIRBuilder::CreateExprMathUnary(Opcode op, UniqueFEIRExpr expr) { + return std::make_unique(op, std::move(expr)); +} + UniqueFEIRExpr FEIRBuilder::CreateExprMathBinary(Opcode op, UniqueFEIRVar var0, UniqueFEIRVar var1) { UniqueFEIRExpr opnd0 = CreateExprDRead(std::move(var0)); UniqueFEIRExpr opnd1 = CreateExprDRead(std::move(var1)); @@ -119,8 +143,8 @@ UniqueFEIRExpr FEIRBuilder::CreateExprSExt(UniqueFEIRVar srcVar) { std::make_unique(std::move(srcVar))); } -UniqueFEIRExpr FEIRBuilder::CreateExprSExt(UniqueFEIRExpr srcExpr) { - return std::make_unique(OP_sext, PTY_i32, std::move(srcExpr)); +UniqueFEIRExpr FEIRBuilder::CreateExprSExt(UniqueFEIRExpr srcExpr, PrimType dstType) { + return std::make_unique(OP_sext, dstType, std::move(srcExpr)); } UniqueFEIRExpr FEIRBuilder::CreateExprZExt(UniqueFEIRVar srcVar) { @@ -128,8 +152,8 @@ UniqueFEIRExpr FEIRBuilder::CreateExprZExt(UniqueFEIRVar srcVar) { std::make_unique(std::move(srcVar))); } -UniqueFEIRExpr FEIRBuilder::CreateExprZExt(UniqueFEIRExpr srcExpr) { - return std::make_unique(OP_zext, PTY_i32, std::move(srcExpr)); +UniqueFEIRExpr FEIRBuilder::CreateExprZExt(UniqueFEIRExpr srcExpr, PrimType dstType) { + return std::make_unique(OP_zext, dstType, std::move(srcExpr)); } UniqueFEIRExpr FEIRBuilder::CreateExprCvtPrim(UniqueFEIRVar srcVar, PrimType dstType) { @@ -150,12 +174,24 @@ UniqueFEIRExpr FEIRBuilder::CreateExprJavaNewInstance(UniqueFEIRType type) { return expr; } +UniqueFEIRExpr FEIRBuilder::CreateExprJavaNewInstance(UniqueFEIRType type, uint32 argTypeID) { + UniqueFEIRExpr expr = std::make_unique(std::move(type), argTypeID); + CHECK_NULL_FATAL(expr); + return expr; +} + UniqueFEIRExpr FEIRBuilder::CreateExprJavaNewArray(UniqueFEIRType type, UniqueFEIRExpr exprSize) { UniqueFEIRExpr expr = std::make_unique(std::move(type), std::move(exprSize)); CHECK_NULL_FATAL(expr); return expr; } +UniqueFEIRExpr FEIRBuilder::CreateExprJavaNewArray(UniqueFEIRType type, UniqueFEIRExpr exprSize, uint32 typeID) { + UniqueFEIRExpr expr = std::make_unique(std::move(type), std::move(exprSize), typeID); + CHECK_NULL_FATAL(expr); + return expr; +} + UniqueFEIRExpr FEIRBuilder::CreateExprJavaArrayLength(UniqueFEIRExpr exprArray) { UniqueFEIRExpr expr = std::make_unique(std::move(exprArray)); CHECK_NULL_FATAL(expr); @@ -208,6 +244,15 @@ UniqueFEIRStmt FEIRBuilder::CreateStmtJavaCheckCast(UniqueFEIRVar dstVar, Unique return stmt; } +UniqueFEIRStmt FEIRBuilder::CreateStmtJavaCheckCast(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type, + uint32 argTypeID) { + UniqueFEIRExpr expr = CreateExprDRead(std::move(srcVar)); + UniqueFEIRStmt stmt = std::make_unique(std::move(dstVar), std::move(expr), std::move(type), + FEIRStmtJavaTypeCheck::CheckKind::kCheckCast, + argTypeID); + return stmt; +} + UniqueFEIRStmt FEIRBuilder::CreateStmtJavaInstanceOf(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type) { UniqueFEIRExpr expr = CreateExprDRead(std::move(srcVar)); UniqueFEIRStmt stmt = std::make_unique(std::move(dstVar), std::move(expr), std::move(type), @@ -215,26 +260,53 @@ UniqueFEIRStmt FEIRBuilder::CreateStmtJavaInstanceOf(UniqueFEIRVar dstVar, Uniqu return stmt; } +UniqueFEIRStmt FEIRBuilder::CreateStmtJavaInstanceOf(UniqueFEIRVar dstVar, UniqueFEIRVar srcVar, UniqueFEIRType type, + uint32 argTypeID) { + UniqueFEIRExpr expr = CreateExprDRead(std::move(srcVar)); + UniqueFEIRStmt stmt = std::make_unique(std::move(dstVar), std::move(expr), std::move(type), + FEIRStmtJavaTypeCheck::CheckKind::kInstanceOf, + argTypeID); + return stmt; +} + +UniqueFEIRStmt FEIRBuilder::CreateStmtJavaFillArrayData(UniqueFEIRVar srcVar, const int8 *arrayData, + uint32 size, const std::string &arrayName) { + UniqueFEIRExpr expr = CreateExprDRead(std::move(srcVar)); + UniqueFEIRStmt stmt = std::make_unique(std::move(expr), arrayData, size, arrayName); + return stmt; +} + std::list FEIRBuilder::CreateStmtArrayStore(UniqueFEIRVar varElem, UniqueFEIRVar varArray, - UniqueFEIRVar varIndex, PrimType elemPrimType) { + UniqueFEIRVar varIndex) { std::list ans; + UniqueFEIRType arrayType = varElem->GetType()->Clone(); + (void)arrayType->ArrayIncrDim(); UniqueFEIRExpr exprElem = CreateExprDRead(std::move(varElem)); UniqueFEIRExpr exprArray = CreateExprDRead(std::move(varArray)); UniqueFEIRExpr exprIndex = CreateExprDRead(std::move(varIndex)); - UniqueFEIRType arrayType = std::make_unique(elemPrimType); - (void)arrayType->ArrayIncrDim(); UniqueFEIRStmt stmt = std::make_unique(std::move(exprElem), std::move(exprArray), std::move(exprIndex), std::move(arrayType)); ans.push_back(std::move(stmt)); return ans; } +UniqueFEIRStmt FEIRBuilder::CreateStmtArrayStoreOneStmt(UniqueFEIRVar varElem, UniqueFEIRVar varArray, + UniqueFEIRExpr exprIndex) { + UniqueFEIRType arrayType = varElem->GetType()->Clone(); + (void)arrayType->ArrayIncrDim(); + UniqueFEIRExpr exprElem = CreateExprDRead(std::move(varElem)); + UniqueFEIRExpr exprArray = CreateExprDRead(std::move(varArray)); + UniqueFEIRStmt stmt = std::make_unique(std::move(exprElem), std::move(exprArray), + std::move(exprIndex), std::move(arrayType)); + return stmt; +} + std::list FEIRBuilder::CreateStmtArrayLoad(UniqueFEIRVar varElem, UniqueFEIRVar varArray, - UniqueFEIRVar varIndex, PrimType elemPrimType) { + UniqueFEIRVar varIndex) { std::list ans; UniqueFEIRExpr exprArray = CreateExprDRead(std::move(varArray)); UniqueFEIRExpr exprIndex = CreateExprDRead(std::move(varIndex)); - UniqueFEIRType arrayType = std::make_unique(elemPrimType); + UniqueFEIRType arrayType = varElem->GetType()->Clone(); (void)arrayType->ArrayIncrDim(); UniqueFEIRExpr expr = std::make_unique(std::move(exprArray), std::move(exprIndex), std::move(arrayType)); @@ -243,6 +315,48 @@ std::list FEIRBuilder::CreateStmtArrayLoad(UniqueFEIRVar varElem return ans; } +UniqueFEIRStmt FEIRBuilder::CreateStmtArrayLength(UniqueFEIRVar varLength, UniqueFEIRVar varArray) { + UniqueFEIRExpr exprArray = CreateExprDRead(std::move(varArray)); + UniqueFEIRExpr exprIntriOp = CreateExprJavaArrayLength(std::move(exprArray)); + UniqueFEIRStmt stmt = std::make_unique(std::move(varLength), std::move(exprIntriOp)); + return stmt; +} + +UniqueFEIRStmt FEIRBuilder::CreateStmtRetype(UniqueFEIRVar varDst, const UniqueFEIRVar &varSrc) { + // ref -> ref : retype + // primitive + // short -> long : cvt GetPrimTypeSize + // long -> short : JAVAMERGE + PrimType dstType = varDst->GetType()->GetPrimType(); + PrimType srcType = varSrc->GetType()->GetPrimType(); + uint32 srcPrmTypeSize = GetPrimTypeSize(varSrc->GetType()->GetPrimType()); + uint32 dstPrmTypeSize = GetPrimTypeSize(dstType); + UniqueFEIRExpr dreadExpr = std::make_unique(varSrc->Clone()); + if (dstType == PTY_ref && srcType == PTY_ref) { + std::unique_ptr ptrTy = FEIRTypeHelper::CreatePointerType(varDst->GetType()->Clone(), PTY_ref); + UniqueFEIRExpr expr = std::make_unique(std::move(ptrTy), OP_retype, std::move(dreadExpr)); + return FEIRBuilder::CreateStmtDAssign(std::move(varDst), std::move(expr), false); + } else if (srcPrmTypeSize < dstPrmTypeSize || (IsPrimitiveFloat(srcType) && IsPrimitiveInteger(dstType)) || + dstType == PTY_ref) { + UniqueFEIRExpr expr = std::make_unique(varDst->GetType()->Clone(), OP_cvt, std::move(dreadExpr)); + return FEIRBuilder::CreateStmtDAssign(std::move(varDst), std::move(expr), false); + } else if (((IsPrimitiveInteger(dstType) || IsPrimitiveFloat(dstType)) && + (IsPrimitiveInteger(srcType) || IsPrimitiveFloat(srcType)) && + IsPrimitiveInteger(srcType) && IsPrimitiveFloat(dstType) && + GetPrimTypeBitSize(srcType) <= GetPrimTypeBitSize(dstType)) || + (IsPrimitiveInteger(srcType) && IsPrimitiveInteger(dstType))) { + std::vector> exprs; + exprs.emplace_back(std::move(dreadExpr)); + UniqueFEIRExpr javaMerge = std::make_unique(varDst->GetType()->Clone(), exprs); + return std::make_unique(std::move(varDst), std::move(javaMerge)); + } else { + WARN(kLncWarn, "Unsafe convert %s to %s", GetPrimTypeName(srcType), GetPrimTypeName(dstType)); + UniqueFEIRExpr expr = std::make_unique(varDst->GetType()->Clone(), OP_cvt, std::move(dreadExpr)); + return FEIRBuilder::CreateStmtDAssign(std::move(varDst), std::move(expr), false); + } + return nullptr; // Cannot retype, maybe introduced by redundant phi. +} + UniqueFEIRStmt FEIRBuilder::CreateStmtComment(const std::string &comment) { UniqueFEIRStmt stmt = std::make_unique(comment); return stmt; diff --git a/src/mplfe/common/src/feir_dfg.cpp b/src/mplfe/common/src/feir_dfg.cpp index 7a319fe79137cac9388b50d5942c1c448a56c4e2..bec402d9fa9a514fac6bb927a1881bca4ac37e05 100644 --- a/src/mplfe/common/src/feir_dfg.cpp +++ b/src/mplfe/common/src/feir_dfg.cpp @@ -15,8 +15,7 @@ #include "feir_dfg.h" namespace maple { -void FEIRDFG::CalculateDefUseByUseDef(std::map> &mapDefUse, - const std::map> &mapUseDef) { +void FEIRDFG::CalculateDefUseByUseDef(FEIRDefUseChain &mapDefUse, const FEIRUseDefChain &mapUseDef) { mapDefUse.clear(); for (auto &it : mapUseDef) { for (UniqueFEIRVar *def : it.second) { @@ -27,8 +26,7 @@ void FEIRDFG::CalculateDefUseByUseDef(std::map> &mapUseDef, - const std::map> &mapDefUse) { +void FEIRDFG::CalculateUseDefByDefUse(FEIRUseDefChain &mapUseDef, const FEIRDefUseChain &mapDefUse) { mapUseDef.clear(); for (auto &it : mapDefUse) { for (UniqueFEIRVar *use : it.second) { diff --git a/src/mplfe/common/src/feir_stmt.cpp b/src/mplfe/common/src/feir_stmt.cpp index 79f2433e9241f27277dd44164c6313a67c0e5b58..d0c0596c8522db841bd5ec03c7bef694578310f0 100644 --- a/src/mplfe/common/src/feir_stmt.cpp +++ b/src/mplfe/common/src/feir_stmt.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. + * Copyright (c) [2020-2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. @@ -21,8 +21,26 @@ #include "feir_var_name.h" #include "fe_manager.h" #include "mplfe_env.h" +#include "feir_var_type_scatter.h" +#include "fe_options.h" +#include "bc_util.h" namespace maple { +std::string GetFEIRNodeKindDescription(FEIRNodeKind kindArg) { + switch (kindArg) { +#define FEIR_NODE_KIND(kind, description) \ + case k##kind: { \ + return description; \ + } +#include "feir_node_kind.def" +#undef FEIR_NODE_KIND + default: { + CHECK_FATAL(false, "Undefined FEIRNodeKind %u", static_cast(kindArg)); + return ""; + } + } +} + // ---------- FEIRStmt ---------- std::list FEIRStmt::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { return std::list(); @@ -63,6 +81,12 @@ bool FEIRStmt::ShouldHaveLOC() const { return (IsStmtInstImpl() || IsStmtInstComment()); } +std::string FEIRStmt::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtCheckPoint ---------- void FEIRStmtCheckPoint::Reset() { predCPs.clear(); @@ -94,17 +118,25 @@ void FEIRStmtCheckPoint::RegisterDFGNodes(const std::list &vars) } } -void FEIRStmtCheckPoint::AddPredCheckPoint(const UniqueFEIRStmt &stmtCheckPoint) { - if (stmtCheckPoint == nullptr || stmtCheckPoint->GetKind() != FEIRNodeKind::kStmtCheckPoint) { - CHECK_FATAL(false, "invalid input"); +void FEIRStmtCheckPoint::RegisterDFGNodeFromAllVisibleStmts() { + if (firstVisibleStmt == nullptr) { + return; + } + FELinkListNode *node = static_cast(firstVisibleStmt); + while (node != this) { + FEIRStmt *stmt = static_cast(node); + stmt->RegisterDFGNodes2CheckPoint(*this); + node = node->GetNext(); } - FEIRStmtCheckPoint *cp = static_cast(stmtCheckPoint.get()); - if (predCPs.find(cp) == predCPs.end()) { - CHECK_FATAL(predCPs.insert(cp).second, "pred checkpoints insert error"); +} + +void FEIRStmtCheckPoint::AddPredCheckPoint(FEIRStmtCheckPoint &stmtCheckPoint) { + if (predCPs.find(&stmtCheckPoint) == predCPs.end()) { + CHECK_FATAL(predCPs.insert(&stmtCheckPoint).second, "pred checkpoints insert error"); } } -std::set &FEIRStmtCheckPoint::CalcuDef(const UniqueFEIRVar &use) { +std::set &FEIRStmtCheckPoint::CalcuDef(UniqueFEIRVar &use) { CHECK_NULL_FATAL(use); auto itLocal = localUD.find(&use); // search localUD @@ -118,12 +150,12 @@ std::set &FEIRStmtCheckPoint::CalcuDef(const UniqueFEIRVar &use) } // search by DFS std::set visitSet; - std::set &target = cacheUD[FEIRDFGNode(use)]; - CalcuDefDFS(target, use, *this, visitSet); - if (target.size() == 0) { + std::set &result = cacheUD[FEIRDFGNode(use)]; + CalcuDefDFS(result, use, *this, visitSet); + if (result.size() == 0) { WARN(kLncWarn, "use var %s without def", use->GetNameRaw().c_str()); } - return target; + return result; } void FEIRStmtCheckPoint::CalcuDefDFS(std::set &result, const UniqueFEIRVar &use, @@ -136,14 +168,14 @@ void FEIRStmtCheckPoint::CalcuDefDFS(std::set &result, const Uni CHECK_FATAL(visitSet.insert(&cp).second, "visitSet insert failed"); auto itLast = cp.lastDef.find(FEIRDFGNode(use)); if (itLast != cp.lastDef.end()) { - CHECK_FATAL(result.insert(itLast->second).second, "result insert failed"); + CHECK_FATAL(result.insert(itLast->second).second, "def insert failed"); return; } // optimization by cacheUD auto itCache = cp.cacheUD.find(FEIRDFGNode(use)); if (itCache != cp.cacheUD.end()) { for (UniqueFEIRVar *def : itCache->second) { - CHECK_FATAL(result.insert(def).second, "result insert failed"); + CHECK_FATAL(result.insert(def).second, "def insert failed"); } if (itCache->second.size() > 0) { return; @@ -156,11 +188,57 @@ void FEIRStmtCheckPoint::CalcuDefDFS(std::set &result, const Uni } } +std::string FEIRStmtCheckPoint::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind) << " preds: [ "; + for (FEIRStmtCheckPoint *pred : predCPs) { + ss << pred->GetID() << ", "; + } + ss << " ]"; + return ss.str(); +} + +// ---------- FEIRStmtNary ---------- +FEIRStmtNary::FEIRStmtNary(Opcode opIn, std::list> argExprsIn) + : FEIRStmt(kFEIRStmtNary), op(opIn), argExprs(std::move(argExprsIn)) {} + +std::list FEIRStmtNary::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list stmts; + StmtNode *stmt = nullptr; + if (argExprs.size() > 1) { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (const auto &arg : argExprs) { + BaseNode *node = arg->GenMIRNode(mirBuilder); + args.push_back(node); + } + stmt = mirBuilder.CreateStmtNary(op, args); + } else if (argExprs.size() == 1) { + BaseNode *node = argExprs.front()->GenMIRNode(mirBuilder); + stmt = mirBuilder.CreateStmtNary(op, node); + } else { + CHECK_FATAL(false, "Invalid arg size for MIR StmtNary"); + } + stmts.emplace_back(stmt); + return stmts; +} + // ---------- FEStmtAssign ---------- FEIRStmtAssign::FEIRStmtAssign(FEIRNodeKind argKind, std::unique_ptr argVar) : FEIRStmt(argKind), hasException(false), - var(std::move(argVar)) { + var(std::move(argVar)) {} + +void FEIRStmtAssign::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + if (var != nullptr) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); + } +} + +std::string FEIRStmtAssign::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); } // ---------- FEStmtDAssign ---------- @@ -170,6 +248,37 @@ FEIRStmtDAssign::FEIRStmtDAssign(std::unique_ptr argVar, std::unique_pt SetExpr(std::move(argExpr)); } +void FEIRStmtDAssign::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + +bool FEIRStmtDAssign::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return expr->CalculateDefs4AllUses(checkPoint, udChain); +} + +void FEIRStmtDAssign::InitTrans4AllVarsImpl() { + switch (expr->GetKind()) { + case FEIRNodeKind::kExprDRead: { + FEIRExprDRead *dRead = static_cast(expr.get()); + UniqueFEIRVarTrans trans1 = std::make_unique(FEIRVarTransKind::kFEIRVarTransDirect, var); + dRead->SetTrans(std::move(trans1)); + var->SetTrans(dRead->CreateTransDirect()); + break; + } + case FEIRNodeKind::kExprArrayLoad: { + FEIRExprArrayLoad *arrayLoad = static_cast(expr.get()); + UniqueFEIRVarTrans trans1 = std::make_unique(FEIRVarTransKind::kFEIRVarTransArrayDimIncr, var); + arrayLoad->SetTrans(std::move(trans1)); + var->SetTrans(arrayLoad->CreateTransArrayDimDecr()); + break; + } + default: + break; + } +} + std::list FEIRStmtDAssign::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; ASSERT(var != nullptr, "dst var is nullptr"); @@ -181,6 +290,13 @@ std::list FEIRStmtDAssign::GenMIRStmtsImpl(MIRBuilder &mirBuilder) co return ans; } +std::string FEIRStmtDAssign::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + ss << " def : " << var->GetNameRaw() << ", uses : " << expr->DumpDotString() << std::endl; + return ss.str(); +} + // ---------- FEIRStmtJavaTypeCheck ---------- FEIRStmtJavaTypeCheck::FEIRStmtJavaTypeCheck(std::unique_ptr argVar, std::unique_ptr argExpr, std::unique_ptr argType, @@ -190,6 +306,26 @@ FEIRStmtJavaTypeCheck::FEIRStmtJavaTypeCheck(std::unique_ptr argVar, st expr(std::move(argExpr)), type(std::move(argType)) {} +FEIRStmtJavaTypeCheck::FEIRStmtJavaTypeCheck(std::unique_ptr argVar, std::unique_ptr argExpr, + std::unique_ptr argType, + FEIRStmtJavaTypeCheck::CheckKind argCheckKind, + uint32 argTypeID) + : FEIRStmtAssign(FEIRNodeKind::kStmtJavaTypeCheck, std::move(argVar)), + checkKind(argCheckKind), + typeID(argTypeID), + expr(std::move(argExpr)), + type(std::move(argType)) {} + +void FEIRStmtJavaTypeCheck::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + +bool FEIRStmtJavaTypeCheck::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return expr->CalculateDefs4AllUses(checkPoint, udChain); +} + std::list FEIRStmtJavaTypeCheck::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; CHECK_FATAL(expr->GetKind() == FEIRNodeKind::kExprDRead, "only support expr dread"); @@ -198,8 +334,8 @@ std::list FEIRStmtJavaTypeCheck::GenMIRStmtsImpl(MIRBuilder &mirBuild MIRType *mirType = type->GenerateMIRType(); MIRType *mirPtrType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*mirType, PTY_ref); MapleVector arguments(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + arguments.push_back(objNode); if (checkKind == kCheckCast) { - arguments.push_back(objNode); StmtNode *callStmt = mirBuilder.CreateStmtIntrinsicCallAssigned(INTRN_JAVA_CHECK_CAST, arguments, ret, mirPtrType->GetTypeIndex()); ans.push_back(callStmt); @@ -213,11 +349,23 @@ std::list FEIRStmtJavaTypeCheck::GenMIRStmtsImpl(MIRBuilder &mirBuild return ans; } +std::string FEIRStmtJavaTypeCheck::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + ss << "uses :" << expr->DumpDotString(); + return ss.str(); +} + // ---------- FEIRStmtJavaConstClass ---------- FEIRStmtJavaConstClass::FEIRStmtJavaConstClass(std::unique_ptr argVar, std::unique_ptr argType) : FEIRStmtAssign(FEIRNodeKind::kStmtJavaConstClass, std::move(argVar)), type(std::move(argType)) {} +void FEIRStmtJavaConstClass::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + std::list FEIRStmtJavaConstClass::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; MIRSymbol *varSym = var->GenerateLocalMIRSymbol(mirBuilder); @@ -235,6 +383,16 @@ FEIRStmtJavaConstString::FEIRStmtJavaConstString(std::unique_ptr argVar : FEIRStmtAssign(FEIRNodeKind::kStmtJavaConstString, std::move(argVar)), strIdx(argStrIdx) {} +FEIRStmtJavaConstString::FEIRStmtJavaConstString(std::unique_ptr argVar, const GStrIdx &argStrIdx, + uint32 argStringID) + : FEIRStmtAssign(FEIRNodeKind::kStmtJavaConstString, std::move(argVar)), + strIdx(argStrIdx), stringID(argStringID) {} + +void FEIRStmtJavaConstString::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + std::list FEIRStmtJavaConstString::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; const std::string &str = GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx); @@ -247,13 +405,17 @@ std::list FEIRStmtJavaConstString::GenMIRStmtsImpl(MIRBuilder &mirBui std::string localStrName = kLocalStringPrefix + std::to_string(static_cast(strIdx)); MIRType *typeString = FETypeManager::kFEIRTypeJavaString->GenerateMIRTypeAuto(kSrcLangJava); MIRSymbol *symbolLocal = mirBuilder.GetOrCreateLocalDecl(localStrName.c_str(), *typeString); - MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); - args.push_back(mirBuilder.CreateExprAddrof(0, *literalVal)); - StmtNode *stmtCreate = mirBuilder.CreateStmtCallAssigned( - FEManager::GetTypeManager().GetPuIdxForMCCGetOrInsertLiteral(), args, symbolLocal, OP_callassigned); - ans.push_back(stmtCreate); + if (!FEOptions::GetInstance().IsAOT()) { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + args.push_back(mirBuilder.CreateExprAddrof(0, *literalVal)); + StmtNode *stmtCreate = mirBuilder.CreateStmtCallAssigned( + FEManager::GetTypeManager().GetPuIdxForMCCGetOrInsertLiteral(), args, symbolLocal, OP_callassigned); + + ans.push_back(stmtCreate); + } literalValPtr = symbolLocal; } + (void)stringID; MIRSymbol *varDst = var->GenerateLocalMIRSymbol(mirBuilder); AddrofNode *node = mirBuilder.CreateDread(*literalValPtr, PTY_ptr); StmtNode *stmt = mirBuilder.CreateStmtDassign(*varDst, 0, node); @@ -261,6 +423,115 @@ std::list FEIRStmtJavaConstString::GenMIRStmtsImpl(MIRBuilder &mirBui return ans; } +// ---------- FEIRStmtJavaFillArrayData ---------- +FEIRStmtJavaFillArrayData::FEIRStmtJavaFillArrayData(std::unique_ptr arrayExprIn, const int8 *arrayDataIn, + uint32 sizeIn, const std::string &arrayNameIn) + : FEIRStmtAssign(FEIRNodeKind::kStmtJavaFillArrayData, nullptr), + arrayExpr(std::move(arrayExprIn)), + arrayData(arrayDataIn), + size(sizeIn), + arrayName(arrayNameIn) {} + +void FEIRStmtJavaFillArrayData::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + arrayExpr->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRStmtJavaFillArrayData::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return arrayExpr->CalculateDefs4AllUses(checkPoint, udChain); +} + +std::list FEIRStmtJavaFillArrayData::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + PrimType elemPrimType = ProcessArrayElemPrimType(); + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + BaseNode *nodeArray = arrayExpr->GenMIRNode(mirBuilder); + args.push_back(nodeArray); + MIRSymbol *elemDataVar = ProcessArrayElemData(mirBuilder, elemPrimType); + BaseNode *nodeAddrof = mirBuilder.CreateExprAddrof(0, *elemDataVar); + args.push_back(nodeAddrof); + uint64 elemPrimTypeSize = GetPrimTypeSize(elemPrimType); + uint64 val = elemPrimTypeSize * size; + BaseNode *nodebytes = mirBuilder.CreateIntConst(val, PTY_i32); + args.push_back(nodebytes); + StmtNode *stmt = mirBuilder.CreateStmtIntrinsicCallAssigned(INTRN_JAVA_ARRAY_FILL, args, nullptr); + ans.push_back(stmt); + return ans; +} + +PrimType FEIRStmtJavaFillArrayData::ProcessArrayElemPrimType() const { + const FEIRType &arrayType = arrayExpr->GetTypeRef(); + CHECK_FATAL(arrayType.IsArray(), "var should be array type"); + UniqueFEIRType elemType = arrayType.Clone(); + (void)elemType->ArrayDecrDim(); + PrimType elemPrimType = elemType->GetPrimType(); + return elemPrimType; +} + +MIRSymbol *FEIRStmtJavaFillArrayData::ProcessArrayElemData(MIRBuilder &mirBuilder, PrimType elemPrimType) const { + // specify size for const array + uint32 sizeIn = size; + MIRType *arrayTypeWithSize = GlobalTables::GetTypeTable().GetOrCreateArrayType( + *GlobalTables::GetTypeTable().GetPrimType(elemPrimType), 1, &sizeIn); + MIRSymbol *arrayVar = mirBuilder.GetOrCreateGlobalDecl(arrayName, *arrayTypeWithSize); + arrayVar->SetAttr(ATTR_readonly); + arrayVar->SetStorageClass(kScFstatic); + MIRAggConst *val = FillArrayElem(mirBuilder, elemPrimType, *arrayTypeWithSize, arrayData, size); + arrayVar->SetKonst(val); + return arrayVar; +} + +MIRAggConst *FEIRStmtJavaFillArrayData::FillArrayElem(MIRBuilder &mirBuilder, PrimType elemPrimType, + MIRType &arrayTypeWithSize, const int8 *arrayData, + uint32 size) const { + MemPool *mp = mirBuilder.GetMirModule().GetMemPool(); + MIRModule &module = mirBuilder.GetMirModule(); + MIRAggConst *val = module.GetMemPool()->New(module, arrayTypeWithSize); + MIRConst *cst = nullptr; + for (uint32 i = 0; i < size; ++i) { + MIRType &elemType = *GlobalTables::GetTypeTable().GetPrimType(elemPrimType); + switch (elemPrimType) { + case PTY_u1: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_i8: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_u8: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_i16: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_u16: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_i32: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_u32: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_i64: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_u64: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_f32: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + case PTY_f64: + cst = mp->New((reinterpret_cast(arrayData))[i], elemType); + break; + default: + CHECK_FATAL(false, "Unsupported primitive type"); + break; + } + val->PushBack(cst); + } + return val; +} + // ---------- FEIRStmtJavaMultiANewArray ---------- UniqueFEIRVar FEIRStmtJavaMultiANewArray::varSize = nullptr; UniqueFEIRVar FEIRStmtJavaMultiANewArray::varClass = nullptr; @@ -272,6 +543,22 @@ FEIRStmtJavaMultiANewArray::FEIRStmtJavaMultiANewArray(std::unique_ptr : FEIRStmtAssign(FEIRNodeKind::kStmtJavaMultiANewArray, std::move(argVar)), type(std::move(argType)) {} +void FEIRStmtJavaMultiANewArray::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + for (const UniqueFEIRExpr &expr : exprSizes) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); + } + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + +bool FEIRStmtJavaMultiANewArray::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + for (const UniqueFEIRExpr &expr : exprSizes) { + success = success && expr->CalculateDefs4AllUses(checkPoint, udChain); + } + return success; +} + void FEIRStmtJavaMultiANewArray::AddVarSize(std::unique_ptr argVarSize) { argVarSize->SetType(FETypeManager::kPrimFEIRTypeI32->Clone()); UniqueFEIRExpr expr = FEIRBuilder::CreateExprDRead(std::move(argVarSize)); @@ -353,14 +640,21 @@ FEStructMethodInfo &FEIRStmtJavaMultiANewArray::GetMethodInfoNewInstance() { if (methodInfoNewInstance != nullptr) { return *methodInfoNewInstance; } - std::string methodNameJava = "Ljava/lang/reflect/Array;|newInstance|(Ljava/lang/Class;[I)Ljava/lang/Object;"; - GStrIdx methodNameIdx = - GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(namemangler::EncodeName(methodNameJava)); - methodInfoNewInstance = static_cast( - FEManager::GetTypeManager().RegisterStructMethodInfo(methodNameIdx, kSrcLangJava, true)); + StructElemNameIdx structElemNameIdx(bc::BCUtil::GetMultiANewArrayClassIdx(), + bc::BCUtil::GetMultiANewArrayElemIdx(), + bc::BCUtil::GetMultiANewArrayTypeIdx(), + bc::BCUtil::GetMultiANewArrayFullIdx()); + methodInfoNewInstance = static_cast(FEManager::GetTypeManager().RegisterStructMethodInfo( + structElemNameIdx, kSrcLangJava, true)); return *methodInfoNewInstance; } +std::string FEIRStmtJavaMultiANewArray::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtUseOnly ---------- FEIRStmtUseOnly::FEIRStmtUseOnly(FEIRNodeKind argKind, Opcode argOp, std::unique_ptr argExpr) : FEIRStmt(argKind), @@ -373,6 +667,19 @@ FEIRStmtUseOnly::FEIRStmtUseOnly(FEIRNodeKind argKind, Opcode argOp, std::unique FEIRStmtUseOnly::FEIRStmtUseOnly(Opcode argOp, std::unique_ptr argExpr) : FEIRStmtUseOnly(FEIRNodeKind::kStmtUseOnly, argOp, std::move(argExpr)) {} +void FEIRStmtUseOnly::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + if (expr != nullptr) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); + } +} + +bool FEIRStmtUseOnly::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + if (expr != nullptr) { + return expr->CalculateDefs4AllUses(checkPoint, udChain); + } + return true; +} + std::list FEIRStmtUseOnly::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; ASSERT_NOT_NULL(expr); @@ -382,6 +689,15 @@ std::list FEIRStmtUseOnly::GenMIRStmtsImpl(MIRBuilder &mirBuilder) co return ans; } +std::string FEIRStmtUseOnly::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + if (expr != nullptr) { + ss << expr->DumpDotString(); + } + return ss.str(); +} + // ---------- FEIRStmtReturn ---------- FEIRStmtReturn::FEIRStmtReturn(std::unique_ptr argExpr) : FEIRStmtUseOnly(FEIRNodeKind::kStmtReturn, OP_return, std::move(argExpr)) {} @@ -417,6 +733,28 @@ std::list FEIRStmtGoto::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const return ans; } +std::string FEIRStmtGoto::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtGoto2 ---------- +FEIRStmtGoto2::FEIRStmtGoto2(uint32 qIdx0, uint32 qIdx1) + : FEIRStmt(FEIRNodeKind::kStmtGoto), labelIdxOuter(qIdx0), labelIdxInner(qIdx1) {} + +std::list FEIRStmtGoto2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list stmts; + GotoNode *gotoNode = mirBuilder.CreateStmtGoto( + OP_goto, FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, labelIdxOuter, labelIdxInner)); + stmts.push_back(gotoNode); + return stmts; +} + +std::pair FEIRStmtGoto2::GetLabelIdx() const { + return std::make_pair(labelIdxOuter, labelIdxInner); +} + // ---------- FEIRStmtCondGoto ---------- FEIRStmtCondGoto::FEIRStmtCondGoto(Opcode argOp, uint32 argLabelIdx, UniqueFEIRExpr argExpr) : FEIRStmtGoto(argLabelIdx), @@ -425,6 +763,14 @@ FEIRStmtCondGoto::FEIRStmtCondGoto(Opcode argOp, uint32 argLabelIdx, UniqueFEIRE SetExpr(std::move(argExpr)); } +void FEIRStmtCondGoto::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRStmtCondGoto::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return expr->CalculateDefs4AllUses(checkPoint, udChain); +} + std::list FEIRStmtCondGoto::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; BaseNode *condNode = expr->GenMIRNode(mirBuilder); @@ -434,6 +780,25 @@ std::list FEIRStmtCondGoto::GenMIRStmtsImpl(MIRBuilder &mirBuilder) c return ans; } +std::string FEIRStmtCondGoto::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtCondGoto2 ---------- +FEIRStmtCondGoto2::FEIRStmtCondGoto2(Opcode argOp, uint32 qIdx0, uint32 qIdx1, UniqueFEIRExpr argExpr) + : FEIRStmtGoto2(qIdx0, qIdx1), op(argOp), expr(std::move(argExpr)) {} + +std::list FEIRStmtCondGoto2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list stmts; + BaseNode *condNode = expr->GenMIRNode(mirBuilder); + CondGotoNode *gotoNode = mirBuilder.CreateStmtCondGoto( + condNode, op, FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, labelIdxOuter, labelIdxInner)); + stmts.push_back(gotoNode); + return stmts; +} + // ---------- FEIRStmtSwitch ---------- FEIRStmtSwitch::FEIRStmtSwitch(UniqueFEIRExpr argExpr) : FEIRStmt(FEIRNodeKind::kStmtSwitch), @@ -446,6 +811,14 @@ FEIRStmtSwitch::~FEIRStmtSwitch() { defaultTarget = nullptr; } +void FEIRStmtSwitch::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + expr->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRStmtSwitch::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return expr->CalculateDefs4AllUses(checkPoint, udChain); +} + std::list FEIRStmtSwitch::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; CaseVector switchTable(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); @@ -460,6 +833,45 @@ std::list FEIRStmtSwitch::GenMIRStmtsImpl(MIRBuilder &mirBuilder) con return ans; } +std::string FEIRStmtSwitch::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtSwitch2 ---------- +FEIRStmtSwitch2::FEIRStmtSwitch2(uint32 outerIdxIn, UniqueFEIRExpr argExpr) + : FEIRStmt(FEIRNodeKind::kStmtSwitch), + outerIdx(outerIdxIn), + defaultLabelIdx(0), + defaultTarget(nullptr) { + SetExpr(std::move(argExpr)); +} + +FEIRStmtSwitch2::~FEIRStmtSwitch2() { + defaultTarget = nullptr; +} + +std::list FEIRStmtSwitch2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + CaseVector switchTable(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (const std::pair &valueLabelPair : mapValueLabelIdx) { + switchTable.emplace_back(valueLabelPair.first, + FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, outerIdx, valueLabelPair.second)); + } + BaseNode *exprNode = expr->GenMIRNode(mirBuilder); + SwitchNode *switchNode = mirBuilder.CreateStmtSwitch(exprNode, + FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, outerIdx, defaultLabelIdx), switchTable); + ans.push_back(switchNode); + return ans; +} + +std::string FEIRStmtSwitch2::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtArrayStore ---------- FEIRStmtArrayStore::FEIRStmtArrayStore(UniqueFEIRExpr argExprElem, UniqueFEIRExpr argExprArray, UniqueFEIRExpr argExprIndex, UniqueFEIRType argTypeArray) @@ -469,21 +881,67 @@ FEIRStmtArrayStore::FEIRStmtArrayStore(UniqueFEIRExpr argExprElem, UniqueFEIRExp exprIndex(std::move(argExprIndex)), typeArray(std::move(argTypeArray)) {} -std::list FEIRStmtArrayStore::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { +void FEIRStmtArrayStore::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + exprArray->RegisterDFGNodes2CheckPoint(checkPoint); + exprIndex->RegisterDFGNodes2CheckPoint(checkPoint); + exprElem->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRStmtArrayStore::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + success = success && exprArray->CalculateDefs4AllUses(checkPoint, udChain); + success = success && exprIndex->CalculateDefs4AllUses(checkPoint, udChain); + success = success && exprElem->CalculateDefs4AllUses(checkPoint, udChain); + return success; +} + +void FEIRStmtArrayStore::InitTrans4AllVarsImpl() { CHECK_FATAL(exprArray->GetKind() == kExprDRead, "only support dread expr for exprArray"); CHECK_FATAL(exprIndex->GetKind() == kExprDRead, "only support dread expr for exprIndex"); + CHECK_FATAL(exprElem->GetKind() == kExprDRead, "only support dread expr for exprElem"); + FEIRExprDRead *exprArrayDRead = static_cast(exprArray.get()); + FEIRExprDRead *exprElemDRead = static_cast(exprElem.get()); + exprArrayDRead->SetTrans(exprElemDRead->CreateTransArrayDimIncr()); + exprElemDRead->SetTrans(exprArrayDRead->CreateTransArrayDimDecr()); +} + +std::list FEIRStmtArrayStore::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + CHECK_FATAL(exprArray->GetKind() == kExprDRead, "only support dread expr for exprArray"); + CHECK_FATAL((exprIndex->GetKind() == kExprDRead) || (exprIndex->GetKind() == kExprConst), "only support dread/const"\ + "expr for exprIndex"); + CHECK_FATAL(exprElem->GetKind() == kExprDRead, "only support dread expr for exprElem"); BaseNode *addrBase = exprArray->GenMIRNode(mirBuilder); BaseNode *indexBn = exprIndex->GenMIRNode(mirBuilder); - MIRType *ptrMIRArrayType = typeArray->GenerateMIRType(true); + MIRType *ptrMIRArrayType = typeArray->GenerateMIRType(false); BaseNode *arrayExpr = mirBuilder.CreateExprArray(*ptrMIRArrayType, addrBase, indexBn); UniqueFEIRType typeElem = typeArray->Clone(); - (void)typeElem->ArrayDecrDim(); - MIRType *ptrMIRElemType = typeElem->GenerateMIRType(true); + if ((exprIndex->GetKind() != kExprConst) || (!FEOptions::GetInstance().IsAOT())) { + (void)typeElem->ArrayDecrDim(); + } + MIRType *mIRElemType = typeElem->GenerateMIRType(true); BaseNode *elemBn = exprElem->GenMIRNode(mirBuilder); - IassignNode *stmt = mirBuilder.CreateStmtIassign(*ptrMIRElemType, 0, arrayExpr, elemBn); + IassignNode *stmt = nullptr; + if ((exprIndex->GetKind() != kExprConst) || (!FEOptions::GetInstance().IsAOT())) { + MIRType *ptrMIRElemType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*mIRElemType, PTY_ptr); + stmt = mirBuilder.CreateStmtIassign(*ptrMIRElemType, 0, arrayExpr, elemBn); + } else { + reinterpret_cast(arrayExpr)->SetBoundsCheck(false); + stmt = mirBuilder.CreateStmtIassign(*mIRElemType, 0, arrayExpr, elemBn); + } return std::list({ stmt }); } +std::string FEIRStmtArrayStore::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + ss << " def : {"; + ss << " exprArray : " << exprArray->DumpDotString(); + ss << " exprIndex : " << exprIndex->DumpDotString(); + ss << " exprElem kind : " << GetFEIRNodeKindDescription(exprElem->GetKind()) << " " << exprElem->DumpDotString(); + ss << " } "; + return ss.str(); +} + // ---------- FEIRStmtFieldStore ---------- FEIRStmtFieldStore::FEIRStmtFieldStore(UniqueFEIRVar argVarObj, UniqueFEIRVar argVarField, FEStructFieldInfo &argFieldInfo, bool argIsStatic) @@ -493,6 +951,45 @@ FEIRStmtFieldStore::FEIRStmtFieldStore(UniqueFEIRVar argVarObj, UniqueFEIRVar ar fieldInfo(argFieldInfo), isStatic(argIsStatic) {} +void FEIRStmtFieldStore::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + if (isStatic) { + RegisterDFGNodes2CheckPointForStatic(checkPoint); + } else { + RegisterDFGNodes2CheckPointForNonStatic(checkPoint); + } +} + +void FEIRStmtFieldStore::RegisterDFGNodes2CheckPointForStatic(FEIRStmtCheckPoint &checkPoint) { + checkPoint.RegisterDFGNode(varField); +} + +void FEIRStmtFieldStore::RegisterDFGNodes2CheckPointForNonStatic(FEIRStmtCheckPoint &checkPoint) { + checkPoint.RegisterDFGNode(varObj); + checkPoint.RegisterDFGNode(varField); +} + +bool FEIRStmtFieldStore::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + if (isStatic) { + return CalculateDefs4AllUsesForStatic(checkPoint, udChain); + } else { + return CalculateDefs4AllUsesForNonStatic(checkPoint, udChain); + } +} + +bool FEIRStmtFieldStore::CalculateDefs4AllUsesForStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + std::set &defs4VarField = checkPoint.CalcuDef(varField); + (void)udChain.insert(std::make_pair(&varField, defs4VarField)); + return (defs4VarField.size() > 0); +} + +bool FEIRStmtFieldStore::CalculateDefs4AllUsesForNonStatic(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + std::set &defs4VarObj = checkPoint.CalcuDef(varObj); + (void)udChain.insert(std::make_pair(&varObj, defs4VarObj)); + std::set &defs4VarField = checkPoint.CalcuDef(varField); + (void)udChain.insert(std::make_pair(&varField, defs4VarField)); + return ((defs4VarObj.size() > 0) && (defs4VarField.size() > 0)); +} + std::list FEIRStmtFieldStore::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { // prepare and find root fieldInfo.Prepare(mirBuilder, isStatic); @@ -503,13 +1000,62 @@ std::list FEIRStmtFieldStore::GenMIRStmtsImpl(MIRBuilder &mirBuilder) } } +uint32 FEIRStmtFieldStore::GetTypeIDForStatic() const { + const std::string &actualContainerName = fieldInfo.GetActualContainerName(); + uint32 typeID = FEManager::GetTypeManager().GetTypeIDFromMplClassName(actualContainerName); + return typeID; +} + std::list FEIRStmtFieldStore::GenMIRStmtsImplForStatic(MIRBuilder &mirBuilder) const { CHECK_FATAL(fieldInfo.GetFieldNameIdx() != 0, "invalid name idx"); + std::list mirStmts; UniqueFEIRVar varTarget = std::make_unique(fieldInfo.GetFieldNameIdx(), fieldInfo.GetType()->Clone()); varTarget->SetGlobal(true); + MIRSymbol *symSrc = varTarget->GenerateGlobalMIRSymbol(mirBuilder); UniqueFEIRExpr exprDRead = FEIRBuilder::CreateExprDRead(varField->Clone()); UniqueFEIRStmt stmtDAssign = FEIRBuilder::CreateStmtDAssign(std::move(varTarget), std::move(exprDRead)); - return stmtDAssign->GenMIRStmts(mirBuilder); + mirStmts = stmtDAssign->GenMIRStmts(mirBuilder); + TyIdx containerTyIdx = fieldInfo.GetActualContainerType()->GenerateMIRType()->GetTypeIndex(); + if (!mirBuilder.GetCurrentFunction()->IsClinit() || + mirBuilder.GetCurrentFunction()->GetClassTyIdx() != containerTyIdx) { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + + uint32 typeID = UINT32_MAX; + if (FEOptions::GetInstance().IsAOT()) { + typeID = GetTypeIDForStatic(); + if (typeID != UINT32_MAX) { + BaseNode *argNumExpr = mirBuilder.CreateIntConst(static_cast(typeID), PTY_i32); + args.push_back(argNumExpr); + } else { + const auto &pt = fieldInfo.GetType()->GetPrimType(); + std::map primTypeFuncNameIdxMap = { + { PTY_u1, FEUtils::GetMCCStaticFieldSetBoolIdx() }, + { PTY_i8, FEUtils::GetMCCStaticFieldSetByteIdx() }, + { PTY_i16, FEUtils::GetMCCStaticFieldSetShortIdx() }, + { PTY_u16, FEUtils::GetMCCStaticFieldSetCharIdx() }, + { PTY_i32, FEUtils::GetMCCStaticFieldSetIntIdx() }, + { PTY_i64, FEUtils::GetMCCStaticFieldSetLongIdx() }, + { PTY_f32, FEUtils::GetMCCStaticFieldSetFloatIdx() }, + { PTY_f64, FEUtils::GetMCCStaticFieldSetDoubleIdx() }, + { PTY_ref, FEUtils::GetMCCStaticFieldSetObjectIdx() }, + }; + const auto &itorFunc = primTypeFuncNameIdxMap.find(pt); + CHECK_FATAL(itorFunc != primTypeFuncNameIdxMap.end(), "java type not support %d", pt); + args.push_back(mirBuilder.CreateIntConst(static_cast(fieldInfo.GetFieldID()), PTY_i32)); + BaseNode *nodeSrc = mirBuilder.CreateExprDread(*symSrc); + args.push_back(nodeSrc); + StmtNode *stmtMCC = mirBuilder.CreateStmtCallAssigned( + FEManager::GetTypeManager().GetMCCFunction(itorFunc->second)->GetPuidx(), args, nullptr, OP_callassigned); + mirStmts.emplace_front(stmtMCC); + } + } + + if (!FEOptions::GetInstance().IsAOT() || typeID != UINT32_MAX) { + StmtNode *stmtClinitCheck = mirBuilder.CreateStmtIntrinsicCall(INTRN_JAVA_CLINIT_CHECK, args, containerTyIdx); + mirStmts.emplace_front(stmtClinitCheck); + } + } + return mirStmts; } std::list FEIRStmtFieldStore::GenMIRStmtsImplForNonStatic(MIRBuilder &mirBuilder) const { @@ -528,6 +1074,12 @@ std::list FEIRStmtFieldStore::GenMIRStmtsImplForNonStatic(MIRBuilder return ans; } +std::string FEIRStmtFieldStore::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtFieldLoad ---------- FEIRStmtFieldLoad::FEIRStmtFieldLoad(UniqueFEIRVar argVarObj, UniqueFEIRVar argVarField, FEStructFieldInfo &argFieldInfo, bool argIsStatic) @@ -536,6 +1088,36 @@ FEIRStmtFieldLoad::FEIRStmtFieldLoad(UniqueFEIRVar argVarObj, UniqueFEIRVar argV fieldInfo(argFieldInfo), isStatic(argIsStatic) {} +void FEIRStmtFieldLoad::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + if (isStatic) { + RegisterDFGNodes2CheckPointForStatic(checkPoint); + } else { + RegisterDFGNodes2CheckPointForNonStatic(checkPoint); + } +} + +bool FEIRStmtFieldLoad::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + if (!isStatic) { + std::set &defs = checkPoint.CalcuDef(varObj); + (void)udChain.insert(std::make_pair(&varObj, defs)); + if (defs.size() == 0) { + return false; + } + } + return true; +} + +void FEIRStmtFieldLoad::RegisterDFGNodes2CheckPointForStatic(FEIRStmtCheckPoint &checkPoint) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + +void FEIRStmtFieldLoad::RegisterDFGNodes2CheckPointForNonStatic(FEIRStmtCheckPoint &checkPoint) { + checkPoint.RegisterDFGNode(varObj); + var->SetDef(true); + checkPoint.RegisterDFGNode(var); +} + std::list FEIRStmtFieldLoad::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { // prepare and find root fieldInfo.Prepare(mirBuilder, isStatic); @@ -546,12 +1128,57 @@ std::list FEIRStmtFieldLoad::GenMIRStmtsImpl(MIRBuilder &mirBuilder) } } +uint32 FEIRStmtFieldLoad::GetTypeIDForStatic() const { + const std::string &actualContainerName = fieldInfo.GetActualContainerName(); + uint32 typeID = FEManager::GetTypeManager().GetTypeIDFromMplClassName(actualContainerName); + return typeID; +} + std::list FEIRStmtFieldLoad::GenMIRStmtsImplForStatic(MIRBuilder &mirBuilder) const { + std::list mirStmts; UniqueFEIRVar varTarget = std::make_unique(fieldInfo.GetFieldNameIdx(), fieldInfo.GetType()->Clone()); varTarget->SetGlobal(true); UniqueFEIRExpr exprDRead = FEIRBuilder::CreateExprDRead(std::move(varTarget)); UniqueFEIRStmt stmtDAssign = FEIRBuilder::CreateStmtDAssign(var->Clone(), std::move(exprDRead)); - return stmtDAssign->GenMIRStmts(mirBuilder); + mirStmts = stmtDAssign->GenMIRStmts(mirBuilder); + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + + uint32 typeID = UINT32_MAX; + if (FEOptions::GetInstance().IsAOT()) { + typeID = GetTypeIDForStatic(); + if (typeID != UINT32_MAX) { + BaseNode *argNumExpr = mirBuilder.CreateIntConst(static_cast(typeID), PTY_i32); + args.push_back(argNumExpr); + } else { + auto pt = fieldInfo.GetType()->GetPrimType(); + std::map primTypeFuncNameIdxMap = { + { PTY_u1, FEUtils::GetMCCStaticFieldGetBoolIdx() }, + { PTY_i8, FEUtils::GetMCCStaticFieldGetByteIdx() }, + { PTY_i16, FEUtils::GetMCCStaticFieldGetShortIdx() }, + { PTY_u16, FEUtils::GetMCCStaticFieldGetCharIdx() }, + { PTY_i32, FEUtils::GetMCCStaticFieldGetIntIdx() }, + { PTY_i64, FEUtils::GetMCCStaticFieldGetLongIdx() }, + { PTY_f32, FEUtils::GetMCCStaticFieldGetFloatIdx() }, + { PTY_f64, FEUtils::GetMCCStaticFieldGetDoubleIdx() }, + { PTY_ref, FEUtils::GetMCCStaticFieldGetObjectIdx() }, + }; + auto itorFunc = primTypeFuncNameIdxMap.find(pt); + CHECK_FATAL(itorFunc != primTypeFuncNameIdxMap.end(), "java type not support %d", pt); + args.push_back(mirBuilder.CreateIntConst(static_cast(fieldInfo.GetFieldID()), PTY_i32)); + StmtNode *stmtMCC = mirBuilder.CreateStmtCallAssigned( + FEManager::GetTypeManager().GetMCCFunction(itorFunc->second)->GetPuidx(), args, nullptr, OP_callassigned); + mirStmts.emplace_front(stmtMCC); + } + } + if (!FEOptions::GetInstance().IsAOT() || typeID != UINT32_MAX) { + TyIdx containerTyIdx = fieldInfo.GetActualContainerType()->GenerateMIRType()->GetTypeIndex(); + if (!mirBuilder.GetCurrentFunction()->IsClinit() || + mirBuilder.GetCurrentFunction()->GetClassTyIdx() != containerTyIdx) { + StmtNode *stmtClinitCheck = mirBuilder.CreateStmtIntrinsicCall(INTRN_JAVA_CLINIT_CHECK, args, containerTyIdx); + mirStmts.emplace_front(stmtClinitCheck); + } + } + return mirStmts; } std::list FEIRStmtFieldLoad::GenMIRStmtsImplForNonStatic(MIRBuilder &mirBuilder) const { @@ -571,6 +1198,12 @@ std::list FEIRStmtFieldLoad::GenMIRStmtsImplForNonStatic(MIRBuilder & return ans; } +std::string FEIRStmtFieldLoad::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtCallAssign ---------- std::map FEIRStmtCallAssign::mapOpAssignToOp = FEIRStmtCallAssign::InitMapOpAssignToOp(); std::map FEIRStmtCallAssign::mapOpToOpAssign = FEIRStmtCallAssign::InitMapOpToOpAssign(); @@ -600,7 +1233,32 @@ std::map FEIRStmtCallAssign::InitMapOpToOpAssign() { return ans; } +void FEIRStmtCallAssign::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + for (const UniqueFEIRExpr &exprArg : exprArgs) { + exprArg->RegisterDFGNodes2CheckPoint(checkPoint); + } + if (!methodInfo.IsReturnVoid() && (var != nullptr)) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); + } +} + +bool FEIRStmtCallAssign::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + for (const UniqueFEIRExpr &exprArg : exprArgs) { + success = success && exprArg->CalculateDefs4AllUses(checkPoint, udChain); + } + return success; +} + std::list FEIRStmtCallAssign::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + // If the struct is a class, we check it if external type directly. + // If the struct is a array type, we check its baseType if external type. + // FEUtils::GetBaseTypeName returns a class type itself or an arrayType's base type. + std::string baseStructName = FEUtils::GetBaseTypeName(methodInfo.GetStructName()); + bool isCreate = false; + (void)FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType( + baseStructName, false, FETypeFlag::kSrcExtern, isCreate); std::list ans; StmtNode *stmtCall = nullptr; // prepare and find root @@ -608,19 +1266,17 @@ std::list FEIRStmtCallAssign::GenMIRStmtsImpl(MIRBuilder &mirBuilder) if (methodInfo.IsJavaPolymorphicCall() || methodInfo.IsJavaDynamicCall()) { return GenMIRStmtsUseZeroReturn(mirBuilder); } - Opcode op = AdjustMIROp(); MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); for (const UniqueFEIRExpr &exprArg : exprArgs) { BaseNode *node = exprArg->GenMIRNode(mirBuilder); args.push_back(node); } PUIdx puIdx = methodInfo.GetPuIdx(); - if (methodInfo.IsReturnVoid()) { - stmtCall = mirBuilder.CreateStmtCall(puIdx, args, op); - } else { - MIRSymbol *retVarSym = var->GenerateLocalMIRSymbol(mirBuilder); - stmtCall = mirBuilder.CreateStmtCallAssigned(puIdx, args, retVarSym, op); + MIRSymbol *retVarSym = nullptr; + if (!methodInfo.IsReturnVoid() && var != nullptr) { + retVarSym = var->GenerateLocalMIRSymbol(mirBuilder); } + stmtCall = mirBuilder.CreateStmtCallAssigned(puIdx, args, retVarSym, mirOp); ans.push_back(stmtCall); return ans; } @@ -679,6 +1335,180 @@ Opcode FEIRStmtCallAssign::AdjustMIROp() const { return mirOp; } +std::string FEIRStmtCallAssign::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + if (var != nullptr) { + ss << " def : " << var->GetNameRaw() << ", "; + } + if (exprArgs.size() > 0) { + ss << " uses : "; + for (const UniqueFEIRExpr &exprArg : exprArgs) { + ss << exprArg->DumpDotString() << ", "; + } + } + return ss.str(); +} + +// ---------- FEIRStmtIntrinsicCallAssign ---------- +FEIRStmtIntrinsicCallAssign::FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, + UniqueFEIRVar argVarRet) + : FEIRStmtAssign(FEIRNodeKind::kStmtIntrinsicCallAssign, std::move(argVarRet)), + intrinsicId(id), + type(std::move(typeIn)) {} + +FEIRStmtIntrinsicCallAssign::FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, + UniqueFEIRVar argVarRet, + std::unique_ptr> exprListIn) + : FEIRStmtAssign(FEIRNodeKind::kStmtIntrinsicCallAssign, std::move(argVarRet)), + intrinsicId(id), + type(std::move(typeIn)), + exprList(std::move(exprListIn)) {} + +FEIRStmtIntrinsicCallAssign::FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, const std::string &funcNameIn, + const std::string &protoIN, + std::unique_ptr> argsIn) + : FEIRStmtAssign(FEIRNodeKind::kStmtIntrinsicCallAssign, nullptr), + intrinsicId(id), + funcName(funcNameIn), + proto(protoIN), + polyArgs(std::move(argsIn)) {} +FEIRStmtIntrinsicCallAssign::FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, const std::string &funcNameIn, + const std::string &protoIN, + std::unique_ptr> argsIn, + uint32 callerClassTypeIDIn, bool isInStaticFuncIn) + : FEIRStmtAssign(FEIRNodeKind::kStmtIntrinsicCallAssign, nullptr), + intrinsicId(id), + funcName(funcNameIn), + proto(protoIN), + polyArgs(std::move(argsIn)), + callerClassTypeID(callerClassTypeIDIn), + isInStaticFunc(isInStaticFuncIn) {} + +FEIRStmtIntrinsicCallAssign::FEIRStmtIntrinsicCallAssign(MIRIntrinsicID id, UniqueFEIRType typeIn, + UniqueFEIRVar argVarRet, uint32 typeIDIn) + : FEIRStmtAssign(FEIRNodeKind::kStmtIntrinsicCallAssign, std::move(argVarRet)), + intrinsicId(id), + type(std::move(typeIn)), + typeID(typeIDIn) {} + +std::string FEIRStmtIntrinsicCallAssign::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +void FEIRStmtIntrinsicCallAssign::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + if ((var != nullptr) && (var.get() != nullptr)) { + var->SetDef(true); + checkPoint.RegisterDFGNode(var); + } +} + +std::list FEIRStmtIntrinsicCallAssign::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + StmtNode *stmtCall = nullptr; + if (intrinsicId == INTRN_JAVA_CLINIT_CHECK) { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + if (FEOptions::GetInstance().IsAOT()) { + BaseNode *argNumExpr = mirBuilder.CreateIntConst(static_cast(typeID), PTY_i32); + args.push_back(argNumExpr); + } + stmtCall = + mirBuilder.CreateStmtIntrinsicCall(INTRN_JAVA_CLINIT_CHECK, args, type->GenerateMIRType()->GetTypeIndex()); + } else if (intrinsicId == INTRN_JAVA_FILL_NEW_ARRAY) { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + if (exprList != nullptr) { + for (const auto &expr : *exprList) { + BaseNode *node = expr->GenMIRNode(mirBuilder); + args.push_back(node); + } + } + MIRSymbol *retVarSym = nullptr; + if ((var != nullptr) && (var.get() != nullptr)) { + retVarSym = var->GenerateLocalMIRSymbol(mirBuilder); + } + stmtCall = mirBuilder.CreateStmtIntrinsicCallAssigned(INTRN_JAVA_FILL_NEW_ARRAY, args, retVarSym, + type->GenerateMIRType(true)->GetTypeIndex()); + } else if (intrinsicId == INTRN_JAVA_POLYMORPHIC_CALL) { + return GenMIRStmtsForInvokePolyMorphic(mirBuilder); + } + // other intrinsic call should be implemented + ans.emplace_back(stmtCall); + return ans; +} + +std::list FEIRStmtIntrinsicCallAssign::GenMIRStmtsForInvokePolyMorphic(MIRBuilder &mirBuilder) const { + std::list ans; + StmtNode *stmtCall = nullptr; + UniqueFEIRVar tmpVar; + bool needRetypeRet = false; + MIRSymbol *retVarSym = nullptr; + if ((var != nullptr) && (var.get() != nullptr)) { + PrimType ptyRet = var->GetTypeRef().GetPrimType(); + needRetypeRet = (ptyRet == PTY_f32 || ptyRet == PTY_f64); + tmpVar = var->Clone(); + if (ptyRet == PTY_f32) { + tmpVar->SetType(std::make_unique(PTY_i32, + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("I"))); + } else if (ptyRet == PTY_f64) { + tmpVar->SetType(std::make_unique(PTY_i64, + GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("J"))); + } + retVarSym = tmpVar->GenerateLocalMIRSymbol(mirBuilder); + } + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + ConstructArgsForInvokePolyMorphic(mirBuilder, args); + stmtCall = mirBuilder.CreateStmtIntrinsicCallAssigned(INTRN_JAVA_POLYMORPHIC_CALL, args, retVarSym); + ans.emplace_back(stmtCall); + if (needRetypeRet) { + UniqueFEIRStmt retypeStmt = FEIRBuilder::CreateStmtRetype(var->Clone(), std::move(tmpVar)); + std::list retypeMirStmts = retypeStmt->GenMIRStmts(mirBuilder); + for (auto elem : retypeMirStmts) { + ans.emplace_back(elem); + } + } + return ans; +} + +void FEIRStmtIntrinsicCallAssign::ConstructArgsForInvokePolyMorphic(MIRBuilder &mirBuilder, + MapleVector &intrnCallargs) const { + MIRSymbol *funcNameVal = FEManager::GetJavaStringManager().GetLiteralVar(funcName); + if (funcNameVal == nullptr) { + funcNameVal = FEManager::GetJavaStringManager().CreateLiteralVar(mirBuilder, funcName, false); + } + BaseNode *dreadExprFuncName = mirBuilder.CreateExprAddrof(0, *funcNameVal); + dreadExprFuncName->SetPrimType(PTY_ptr); + intrnCallargs.push_back(dreadExprFuncName); + + MIRSymbol *protoNameVal = FEManager::GetJavaStringManager().GetLiteralVar(proto); + if (protoNameVal == nullptr) { + protoNameVal = FEManager::GetJavaStringManager().CreateLiteralVar(mirBuilder, proto, false); + } + BaseNode *dreadExprProtoName = mirBuilder.CreateExprAddrof(0, *protoNameVal); + dreadExprProtoName->SetPrimType(PTY_ptr); + intrnCallargs.push_back(dreadExprProtoName); + + BaseNode *argNumExpr = mirBuilder.CreateIntConst(static_cast(polyArgs->size() - 1), PTY_i32); + intrnCallargs.push_back(argNumExpr); + + bool isAfterMethodHandle = true; + for (const auto &arg : *polyArgs) { + intrnCallargs.push_back(mirBuilder.CreateExprDread(*(arg->GenerateMIRSymbol(mirBuilder)))); + if (FEOptions::GetInstance().IsAOT() && isAfterMethodHandle) { + if (isInStaticFunc) { + intrnCallargs.push_back(mirBuilder.CreateIntConst(static_cast(callerClassTypeID), PTY_i32)); + } else { + GStrIdx thisNameIdx = GlobalTables::GetStrTable().GetStrIdxFromName("_this"); + std::unique_ptr varThisAsLocalVar = std::make_unique(thisNameIdx, + FEIRTypeDefault(PTY_ref).Clone()); + intrnCallargs.push_back(mirBuilder.CreateExprDread(*(varThisAsLocalVar->GenerateMIRSymbol(mirBuilder)))); + } + isAfterMethodHandle = false; + } + } +} + // ---------- FEIRExpr ---------- FEIRExpr::FEIRExpr(FEIRNodeKind argKind) : kind(argKind), @@ -696,10 +1526,6 @@ FEIRExpr::FEIRExpr(FEIRNodeKind argKind, std::unique_ptr argType) SetType(std::move(argType)); } -std::vector FEIRExpr::GetVarUsesImpl() const { - return std::vector(); -} - bool FEIRExpr::IsNestableImpl() const { return isNestable; } @@ -712,6 +1538,24 @@ bool FEIRExpr::HasExceptionImpl() const { return hasException; } +std::vector FEIRExpr::GetVarUsesImpl() const { + return std::vector(); +} + +std::string FEIRExpr::DumpDotString() const { + std::stringstream ss; + if (kind == FEIRNodeKind::kExprArrayLoad) { + ss << " kExprArrayLoad: "; + } + std::vector varUses = GetVarUses(); + ss << "[ "; + for (FEIRVar *use : varUses) { + ss << use->GetNameRaw() << ", "; + } + ss << "] "; + return ss.str(); +} + // ---------- FEIRExprConst ---------- FEIRExprConst::FEIRExprConst() : FEIRExpr(FEIRNodeKind::kExprConst) { @@ -725,6 +1569,7 @@ FEIRExprConst::FEIRExprConst(int64 val, PrimType argType) ASSERT(type != nullptr, "type is nullptr"); type->SetPrimType(argType); value.valueI64 = val; + CheckRawValue2SetZero(); } FEIRExprConst::FEIRExprConst(uint64 val, PrimType argType) @@ -732,6 +1577,7 @@ FEIRExprConst::FEIRExprConst(uint64 val, PrimType argType) ASSERT(type != nullptr, "type is nullptr"); type->SetPrimType(argType); value.valueU64 = val; + CheckRawValue2SetZero(); } FEIRExprConst::FEIRExprConst(float val) @@ -739,6 +1585,7 @@ FEIRExprConst::FEIRExprConst(float val) ASSERT(type != nullptr, "type is nullptr"); type->SetPrimType(PTY_f32); value.valueF32 = val; + CheckRawValue2SetZero(); } FEIRExprConst::FEIRExprConst(double val) @@ -746,6 +1593,7 @@ FEIRExprConst::FEIRExprConst(double val) ASSERT(type != nullptr, "type is nullptr"); type->SetPrimType(PTY_f64); value.valueF64 = val; + CheckRawValue2SetZero(); } std::unique_ptr FEIRExprConst::CloneImpl() const { @@ -754,6 +1602,7 @@ std::unique_ptr FEIRExprConst::CloneImpl() const { exprConst->value.raw = value.raw; ASSERT(type != nullptr, "type is nullptr"); exprConst->type->SetPrimType(type->GetPrimType()); + exprConst->CheckRawValue2SetZero(); return expr; } @@ -782,6 +1631,12 @@ BaseNode *FEIRExprConst::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { } } +void FEIRExprConst::CheckRawValue2SetZero() { + if (value.raw == 0) { + type->SetZero(true); + } +} + // ---------- FEIRExprDRead ---------- FEIRExprDRead::FEIRExprDRead(std::unique_ptr argVarSrc) : FEIRExpr(FEIRNodeKind::kExprDRead) { @@ -816,6 +1671,30 @@ std::vector FEIRExprDRead::GetVarUsesImpl() const { return std::vector({ varSrc.get() }); } +// ---------- FEIRExprRegRead ---------- +FEIRExprRegRead::FEIRExprRegRead(PrimType pty, int32 regNumIn) + : FEIRExpr(FEIRNodeKind::kExprRegRead), prmType(pty), regNum(regNumIn) {} + +std::unique_ptr FEIRExprRegRead::CloneImpl() const { + std::unique_ptr expr = std::make_unique(prmType, regNum); + return expr; +} + +BaseNode *FEIRExprRegRead::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { + RegreadNode *node = mirBuilder.CreateExprRegread(prmType, regNum); + return node; +} + +void FEIRExprDRead::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + checkPoint.RegisterDFGNode(varSrc); +} + +bool FEIRExprDRead::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + std::set defs = checkPoint.CalcuDef(varSrc); + (void)udChain.insert(std::make_pair(&varSrc, defs)); + return (defs.size() > 0); +} + // ---------- FEIRExprUnary ---------- std::map FEIRExprUnary::mapOpNestable = FEIRExprUnary::InitMapOpNestableForExprUnary(); @@ -859,6 +1738,14 @@ BaseNode *FEIRExprUnary::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { return expr; } +void FEIRExprUnary::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprUnary::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return opnd->CalculateDefs4AllUses(checkPoint, udChain); +} + std::vector FEIRExprUnary::GetVarUsesImpl() const { return opnd->GetVarUses(); } @@ -871,6 +1758,7 @@ void FEIRExprUnary::SetOpnd(std::unique_ptr argOpnd) { void FEIRExprUnary::SetExprTypeByOp() { switch (op) { case OP_neg: + case OP_bnot: type->SetPrimType(opnd->GetPrimType()); break; default: @@ -900,6 +1788,21 @@ BaseNode *FEIRExprTypeCvt::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { return (this->*(ptrFunc->second))(mirBuilder); } +void FEIRExprTypeCvt::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprTypeCvt::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return opnd->CalculateDefs4AllUses(checkPoint, udChain); +} + +Opcode FEIRExprTypeCvt::ChooseOpcodeByFromVarAndToVar(const FEIRVar &fromVar, const FEIRVar &toVar) { + if ((fromVar.GetType()->IsRef()) && (toVar.GetType()->IsRef())) { + return OP_retype; + } + return OP_retype; +} + BaseNode *FEIRExprTypeCvt::GenMIRNodeMode1(MIRBuilder &mirBuilder) const { // MIR: op () MIRType *mirTypeDst = @@ -920,7 +1823,7 @@ BaseNode *FEIRExprTypeCvt::GenMIRNodeMode2(MIRBuilder &mirBuilder) const { BaseNode *FEIRExprTypeCvt::GenMIRNodeMode3(MIRBuilder &mirBuilder) const { // MIR: retype () MIRType *mirTypeDst = GetTypeRef().GenerateMIRType(); - MIRType *mirTypeSrc = opnd->GetTypeRef().GenerateMIRType(); + MIRType *mirTypeSrc = opnd->GetTypeRef().GenerateMIRTypeAuto(); BaseNode *nodeOpnd = opnd->GenMIRNode(mirBuilder); BaseNode *expr = mirBuilder.CreateExprRetype(*mirTypeDst, *mirTypeSrc, nodeOpnd); return expr; @@ -977,6 +1880,14 @@ BaseNode *FEIRExprExtractBits::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { return (this->*(ptrFunc->second))(mirBuilder); } +void FEIRExprExtractBits::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprExtractBits::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return opnd->CalculateDefs4AllUses(checkPoint, udChain); +} + std::map FEIRExprExtractBits::InitMapOpNestableForExtractBits() { std::map ans; ans[OP_extractbits] = true; @@ -1003,7 +1914,7 @@ BaseNode *FEIRExprExtractBits::GenMIRNodeForExtrabits(MIRBuilder &mirBuilder) co uint8 widthSrc = FEUtils::GetWidth(primTypeSrc); CHECK_FATAL(widthDst >= bitSize, "dst width is not enough"); CHECK_FATAL(widthSrc >= bitOffset + bitSize, "src width is not enough"); - MIRType *mirTypeDst = GlobalTables::GetTypeTable().GetTypeFromTyIdx(TyIdx(static_cast(primTypeDst))); + MIRType *mirTypeDst = GetTypeRef().GenerateMIRTypeAuto(); BaseNode *nodeOpnd = opnd->GenMIRNode(mirBuilder); BaseNode *expr = mirBuilder.CreateExprExtractbits(op, *mirTypeDst, bitOffset, bitSize, nodeOpnd); return expr; @@ -1012,15 +1923,11 @@ BaseNode *FEIRExprExtractBits::GenMIRNodeForExtrabits(MIRBuilder &mirBuilder) co BaseNode *FEIRExprExtractBits::GenMIRNodeForExt(MIRBuilder &mirBuilder) const { ASSERT(opnd != nullptr, "nullptr check"); PrimType primTypeDst = GetTypeRef().GetPrimType(); - PrimType primTypeSrc = opnd->GetPrimType(); - CHECK_FATAL(FEUtils::IsInteger(primTypeSrc), "src type of sext/zext must integer"); CHECK_FATAL(FEUtils::IsInteger(primTypeDst), "dst type of sext/zext must integer"); uint8 widthDst = FEUtils::GetWidth(primTypeDst); - uint8 widthSrc = (bitSize == 0) ? FEUtils::GetWidth(primTypeSrc) : bitSize; - CHECK_FATAL(widthDst >= widthSrc, "width of dst must be not smaller than width of src"); - MIRType *mirTypeDst = GlobalTables::GetTypeTable().GetTypeFromTyIdx(TyIdx(static_cast(primTypeDst))); + MIRType *mirTypeDst = GetTypeRef().GenerateMIRTypeAuto(); BaseNode *nodeOpnd = opnd->GenMIRNode(mirBuilder); - BaseNode *expr = mirBuilder.CreateExprExtractbits(op, *mirTypeDst, 0, widthSrc, nodeOpnd); + BaseNode *expr = mirBuilder.CreateExprExtractbits(op, *mirTypeDst, 0, widthDst, nodeOpnd); return expr; } @@ -1056,6 +1963,18 @@ BaseNode *FEIRExprBinary::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { return (this->*(ptrFunc->second))(mirBuilder); } +void FEIRExprBinary::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + opnd0->RegisterDFGNodes2CheckPoint(checkPoint); + opnd1->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprBinary::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + success = success && opnd0->CalculateDefs4AllUses(checkPoint, udChain); + success = success && opnd1->CalculateDefs4AllUses(checkPoint, udChain); + return success; +} + std::vector FEIRExprBinary::GetVarUsesImpl() const { std::vector ans; for (FEIRVar *var : opnd0->GetVarUses()) { @@ -1178,6 +2097,7 @@ void FEIRExprBinary::SetExprTypeByOp() { break; // Compare case OP_cmp: + case OP_cmpl: case OP_cmpg: case OP_eq: case OP_ge: @@ -1218,7 +2138,10 @@ void FEIRExprBinary::SetExprTypeByOpLogic() { void FEIRExprBinary::SetExprTypeByOpCompare() { PrimType primTypeOpnd0 = opnd0->GetPrimType(); PrimType primTypeOpnd1 = opnd1->GetPrimType(); - CHECK_FATAL(primTypeOpnd0 == primTypeOpnd1, "primtype of opnds must be the same"); + CHECK_FATAL(primTypeOpnd0 == primTypeOpnd1 || + (opnd0->GetKind() == kExprConst && static_cast(opnd0.get())->GetValueRaw() == 0) || + (opnd1->GetKind() == kExprConst && static_cast(opnd1.get())->GetValueRaw() == 0), + "primtype of opnds must be the same"); type->SetPrimType(PTY_i32); } @@ -1248,6 +2171,20 @@ BaseNode *FEIRExprTernary::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { return expr; } +void FEIRExprTernary::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + opnd0->RegisterDFGNodes2CheckPoint(checkPoint); + opnd1->RegisterDFGNodes2CheckPoint(checkPoint); + opnd2->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprTernary::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + success = success && opnd0->CalculateDefs4AllUses(checkPoint, udChain); + success = success && opnd1->CalculateDefs4AllUses(checkPoint, udChain); + success = success && opnd2->CalculateDefs4AllUses(checkPoint, udChain); + return success; +} + std::vector FEIRExprTernary::GetVarUsesImpl() const { std::vector ans; for (FEIRVar *var : opnd0->GetVarUses()) { @@ -1309,6 +2246,20 @@ std::vector FEIRExprNary::GetVarUsesImpl() const { return ans; } +void FEIRExprNary::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + for (const std::unique_ptr &opnd : opnds) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); + } +} + +bool FEIRExprNary::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + for (const std::unique_ptr &opnd : opnds) { + success = success && opnd->CalculateDefs4AllUses(checkPoint, udChain); + } + return success; +} + void FEIRExprNary::AddOpnd(std::unique_ptr argOpnd) { CHECK_FATAL(argOpnd != nullptr, "input opnd is nullptr"); opnds.push_back(std::move(argOpnd)); @@ -1355,6 +2306,27 @@ FEIRExprIntrinsicop::FEIRExprIntrinsicop(std::unique_ptr exprType, MIR AddOpnds(argOpnds); } +FEIRExprIntrinsicop::FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, + std::unique_ptr argParamType, uint32 argTypeID) + : FEIRExprNary(OP_intrinsicopwithtype), + intrinsicID(argIntrinsicID), + typeID(argTypeID) { + kind = FEIRNodeKind::kExprIntrinsicop; + SetType(std::move(exprType)); + paramType = std::move(argParamType); +} + +FEIRExprIntrinsicop::FEIRExprIntrinsicop(std::unique_ptr exprType, MIRIntrinsicID argIntrinsicID, + std::unique_ptr argParamType, uint32 argTypeID, uint32 argArraySize) + : FEIRExprNary(OP_intrinsicopwithtype), + intrinsicID(argIntrinsicID), + typeID(argTypeID), + arraySize(argArraySize) { + kind = FEIRNodeKind::kExprIntrinsicop; + SetType(std::move(exprType)); + paramType = std::move(argParamType); +} + std::unique_ptr FEIRExprIntrinsicop::CloneImpl() const { if (op == OP_intrinsicop) { return std::make_unique(type->Clone(), intrinsicID, opnds); @@ -1365,7 +2337,31 @@ std::unique_ptr FEIRExprIntrinsicop::CloneImpl() const { } BaseNode *FEIRExprIntrinsicop::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { - return nullptr; + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (const auto &e : opnds) { + BaseNode *node = e->GenMIRNode(mirBuilder); + args.emplace_back(node); + } + (void)arraySize; + (void)typeID; + MIRType *ptrType = GlobalTables::GetTypeTable().GetOrCreatePointerType( + *(type->GenerateMIRType()), paramType->IsRef() ? PTY_ref : PTY_ptr); + BaseNode *expr = mirBuilder.CreateExprIntrinsicop(intrinsicID, op, *ptrType, args); + return expr; +} + +void FEIRExprIntrinsicop::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + for (const std::unique_ptr &opnd : opnds) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); + } +} + +bool FEIRExprIntrinsicop::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + for (const std::unique_ptr &opnd : opnds) { + success = success && opnd->CalculateDefs4AllUses(checkPoint, udChain); + } + return success; } bool FEIRExprIntrinsicop::IsNestableImpl() const { @@ -1376,12 +2372,57 @@ bool FEIRExprIntrinsicop::IsAddrofImpl() const { return false; } +// ---------- FEIRExprJavaMerge ---------------- +FEIRExprJavaMerge::FEIRExprJavaMerge(std::unique_ptr mergedTypeArg, + const std::vector> &argOpnds) + : FEIRExprNary(OP_intrinsicop) { + SetType(std::move(mergedTypeArg)); + AddOpnds(argOpnds); +} + +std::unique_ptr FEIRExprJavaMerge::CloneImpl() const { + return std::make_unique(type->Clone(), opnds); +} + +void FEIRExprJavaMerge::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + for (const std::unique_ptr &opnd : opnds) { + opnd->RegisterDFGNodes2CheckPoint(checkPoint); + } +} + +bool FEIRExprJavaMerge::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + for (const std::unique_ptr &opnd : opnds) { + success = success && opnd->CalculateDefs4AllUses(checkPoint, udChain); + } + return success; +} + +BaseNode *FEIRExprJavaMerge::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { + MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (const auto &e : opnds) { + BaseNode *node = e->GenMIRNode(mirBuilder); + args.emplace_back(node); + } + // (intrinsicop u1 JAVA_MERGE (dread i32 %Reg0_I)) + IntrinDesc *intrinDesc = &IntrinDesc::intrinTable[INTRN_JAVA_MERGE]; + MIRType *retType = intrinDesc->GetReturnType(); + BaseNode *intr = mirBuilder.CreateExprIntrinsicop(INTRN_JAVA_MERGE, op, *retType, args); + intr->SetPrimType(type->GetPrimType()); + return intr; +} + // ---------- FEIRExprJavaNewInstance ---------- FEIRExprJavaNewInstance::FEIRExprJavaNewInstance(UniqueFEIRType argType) : FEIRExpr(FEIRNodeKind::kExprJavaNewInstance) { SetType(std::move(argType)); } +FEIRExprJavaNewInstance::FEIRExprJavaNewInstance(UniqueFEIRType argType, uint32 argTypeID) + : FEIRExpr(FEIRNodeKind::kExprJavaNewInstance), typeID(argTypeID) { + SetType(std::move(argType)); +} + std::unique_ptr FEIRExprJavaNewInstance::CloneImpl() const { std::unique_ptr expr = std::make_unique(type->Clone()); CHECK_NULL_FATAL(expr); @@ -1390,8 +2431,10 @@ std::unique_ptr FEIRExprJavaNewInstance::CloneImpl() const { BaseNode *FEIRExprJavaNewInstance::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { MIRType *mirType = type->GenerateMIRType(kSrcLangJava, false); + BaseNode *expr = nullptr; + (void)typeID; MIRType *ptrType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*mirType, PTY_ref); - BaseNode *expr = mirBuilder.CreateExprGCMalloc(OP_gcmalloc, *ptrType, *mirType); + expr = mirBuilder.CreateExprGCMalloc(OP_gcmalloc, *ptrType, *mirType); CHECK_NULL_FATAL(expr); return expr; } @@ -1403,21 +2446,46 @@ FEIRExprJavaNewArray::FEIRExprJavaNewArray(UniqueFEIRType argArrayType, UniqueFE SetExprSize(std::move(argExprSize)); } +FEIRExprJavaNewArray::FEIRExprJavaNewArray(UniqueFEIRType argArrayType, UniqueFEIRExpr argExprSize, uint32 argTypeID) + : FEIRExpr(FEIRNodeKind::kExprJavaNewArray), typeID(argTypeID) { + SetArrayType(std::move(argArrayType)); + SetExprSize(std::move(argExprSize)); +} + std::unique_ptr FEIRExprJavaNewArray::CloneImpl() const { std::unique_ptr expr = std::make_unique(arrayType->Clone(), exprSize->Clone()); CHECK_NULL_FATAL(expr); return expr; } +std::vector FEIRExprJavaNewArray::GetVarUsesImpl() const { + return exprSize->GetVarUses(); +} + BaseNode *FEIRExprJavaNewArray::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { + UniqueFEIRType elemType = FEIRBuilder::CreateArrayElemType(arrayType); + MIRType *elemMirType = elemType->GenerateMIRType(kSrcLangJava, false); + if (!elemMirType->IsScalarType()) { + elemMirType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*elemMirType, PTY_ptr); + } + MIRType *jarrayType = GlobalTables::GetTypeTable().GetOrCreateJarrayType(*elemMirType); + (void)typeID; MIRType *mirType = arrayType->GenerateMIRType(kSrcLangJava, false); MIRType *ptrType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*mirType, PTY_ref); BaseNode *sizeNode = exprSize->GenMIRNode(mirBuilder); - BaseNode *expr = mirBuilder.CreateExprJarrayMalloc(OP_gcmallocjarray, *ptrType, *mirType, sizeNode); + BaseNode *expr = mirBuilder.CreateExprJarrayMalloc(OP_gcmallocjarray, *ptrType, *jarrayType, sizeNode); CHECK_NULL_FATAL(expr); return expr; } +void FEIRExprJavaNewArray::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + exprSize->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprJavaNewArray::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return exprSize->CalculateDefs4AllUses(checkPoint, udChain); +} + // ---------- FEIRExprJavaArrayLength ---------- FEIRExprJavaArrayLength::FEIRExprJavaArrayLength(UniqueFEIRExpr argExprArray) : FEIRExpr(FEIRNodeKind::kExprJavaArrayLength) { @@ -1430,6 +2498,10 @@ std::unique_ptr FEIRExprJavaArrayLength::CloneImpl() const { return expr; } +std::vector FEIRExprJavaArrayLength::GetVarUsesImpl() const { + return exprArray->GetVarUses(); +} + BaseNode *FEIRExprJavaArrayLength::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { BaseNode *arrayNode = exprArray->GenMIRNode(mirBuilder); MapleVector args(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); @@ -1438,6 +2510,14 @@ BaseNode *FEIRExprJavaArrayLength::GenMIRNodeImpl(MIRBuilder &mirBuilder) const return mirBuilder.CreateExprIntrinsicop(INTRN_JAVA_ARRAY_LENGTH, OP_intrinsicop, *retType, args); } +void FEIRExprJavaArrayLength::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + exprArray->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprJavaArrayLength::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + return exprArray->CalculateDefs4AllUses(checkPoint, udChain); +} + // ---------- FEIRExprArrayLoad ---------- FEIRExprArrayLoad::FEIRExprArrayLoad(UniqueFEIRExpr argExprArray, UniqueFEIRExpr argExprIndex, UniqueFEIRType argTypeArray) @@ -1457,16 +2537,41 @@ BaseNode *FEIRExprArrayLoad::GenMIRNodeImpl(MIRBuilder &mirBuilder) const { CHECK_FATAL(exprIndex->GetKind() == kExprDRead, "only support dread expr for exprIndex"); BaseNode *addrBase = exprArray->GenMIRNode(mirBuilder); BaseNode *indexBn = exprIndex->GenMIRNode(mirBuilder); - MIRType *ptrMIRArrayType = typeArray->GenerateMIRType(true); + MIRType *ptrMIRArrayType = typeArray->GenerateMIRType(false); + BaseNode *arrayExpr = mirBuilder.CreateExprArray(*ptrMIRArrayType, addrBase, indexBn); UniqueFEIRType typeElem = typeArray->Clone(); (void)typeElem->ArrayDecrDim(); - MIRType *ptrMIRElemType = typeElem->GenerateMIRType(true); - MIRType *mirElemType = typeElem->GenerateMIRType(false); + + MIRType *mirElemType = typeElem->GenerateMIRType(true); + MIRType *ptrMIRElemType = GlobalTables::GetTypeTable().GetOrCreatePointerType(*mirElemType, PTY_ptr); BaseNode *elemBn = mirBuilder.CreateExprIread(*mirElemType, *ptrMIRElemType, 0, arrayExpr); return elemBn; } +std::vector FEIRExprArrayLoad::GetVarUsesImpl() const { + std::vector ans; + for (FEIRVar *var : exprArray->GetVarUses()) { + ans.push_back(var); + } + for (FEIRVar *var : exprIndex->GetVarUses()) { + ans.push_back(var); + } + return ans; +} + +void FEIRExprArrayLoad::RegisterDFGNodes2CheckPointImpl(FEIRStmtCheckPoint &checkPoint) { + exprArray->RegisterDFGNodes2CheckPoint(checkPoint); + exprIndex->RegisterDFGNodes2CheckPoint(checkPoint); +} + +bool FEIRExprArrayLoad::CalculateDefs4AllUsesImpl(FEIRStmtCheckPoint &checkPoint, FEIRUseDefChain &udChain) { + bool success = true; + success = success && exprArray->CalculateDefs4AllUses(checkPoint, udChain); + success = success && exprIndex->CalculateDefs4AllUses(checkPoint, udChain); + return success; +} + // ---------- FEIRStmtPesudoLabel ---------- FEIRStmtPesudoLabel::FEIRStmtPesudoLabel(uint32 argLabelIdx) : FEIRStmt(kStmtPesudoLabel), @@ -1487,16 +2592,47 @@ void FEIRStmtPesudoLabel::GenerateLabelIdx(MIRBuilder &mirBuilder) { mirLabelIdx = mirBuilder.GetOrCreateMIRLabel(ss.str()); } +std::string FEIRStmtPesudoLabel::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtPesudoLabel2 ---------- +LabelIdx FEIRStmtPesudoLabel2::GenMirLabelIdx(MIRBuilder &mirBuilder, uint32 qIdx0, uint32 qIdx1) { + std::string label = "L" + std::to_string(qIdx0) + "_" + std::to_string(qIdx1); + return mirBuilder.GetOrCreateMIRLabel(label); +} + +std::pair FEIRStmtPesudoLabel2::GetLabelIdx() const { + return std::make_pair(labelIdxOuter, labelIdxInner); +} + +std::list FEIRStmtPesudoLabel2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + StmtNode *stmtLabel = mirBuilder.CreateStmtLabel(GenMirLabelIdx(mirBuilder, labelIdxOuter, labelIdxInner)); + ans.push_back(stmtLabel); + return ans; +} + // ---------- FEIRStmtPesudoLOC ---------- FEIRStmtPesudoLOC::FEIRStmtPesudoLOC(uint32 argSrcFileIdx, uint32 argLineNumber) : FEIRStmt(kStmtPesudoLOC), srcFileIdx(argSrcFileIdx), - lineNumber(argLineNumber) {} + lineNumber(argLineNumber) { + isAuxPre = true; +} std::list FEIRStmtPesudoLOC::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { return std::list(); } +std::string FEIRStmtPesudoLOC::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtPesudoJavaTry ---------- FEIRStmtPesudoJavaTry::FEIRStmtPesudoJavaTry() : FEIRStmt(kStmtPesudoJavaTry) {} @@ -1512,9 +2648,38 @@ std::list FEIRStmtPesudoJavaTry::GenMIRStmtsImpl(MIRBuilder &mirBuild return ans; } +std::string FEIRStmtPesudoJavaTry::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtPesudoJavaTry2 ---------- +FEIRStmtPesudoJavaTry2::FEIRStmtPesudoJavaTry2(uint32 outerIdxIn) + : FEIRStmt(kStmtPesudoJavaTry), outerIdx(outerIdxIn) {} + +std::list FEIRStmtPesudoJavaTry2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + MapleVector vec(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (uint32 target : catchLabelIdxVec) { + vec.push_back(FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, outerIdx, target)); + } + StmtNode *stmtTry = mirBuilder.CreateStmtTry(vec); + ans.push_back(stmtTry); + return ans; +} + +std::string FEIRStmtPesudoJavaTry2::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtPesudoEndTry ---------- FEIRStmtPesudoEndTry::FEIRStmtPesudoEndTry() - : FEIRStmt(kStmtPesudoEndTry) {} + : FEIRStmt(kStmtPesudoEndTry) { + isAuxPost = true; +} std::list FEIRStmtPesudoEndTry::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; @@ -1525,6 +2690,12 @@ std::list FEIRStmtPesudoEndTry::GenMIRStmtsImpl(MIRBuilder &mirBuilde return ans; } +std::string FEIRStmtPesudoEndTry::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtPesudoCatch ---------- FEIRStmtPesudoCatch::FEIRStmtPesudoCatch(uint32 argLabelIdx) : FEIRStmtPesudoLabel(argLabelIdx) {} @@ -1548,13 +2719,58 @@ void FEIRStmtPesudoCatch::AddCatchTypeNameIdx(GStrIdx typeNameIdx) { catchTypes.push_back(std::move(type)); } +std::string FEIRStmtPesudoCatch::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + +// ---------- FEIRStmtPesudoCatch2 ---------- +FEIRStmtPesudoCatch2::FEIRStmtPesudoCatch2(uint32 qIdx0, uint32 qIdx1) + : FEIRStmtPesudoLabel2(qIdx0, qIdx1) {} + +std::list FEIRStmtPesudoCatch2::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { + std::list ans; + StmtNode *stmtLabel = mirBuilder.CreateStmtLabel( + FEIRStmtPesudoLabel2::GenMirLabelIdx(mirBuilder, GetLabelIdx().first, GetLabelIdx().second)); + ans.push_back(stmtLabel); + MapleVector vec(mirBuilder.GetCurrentFuncCodeMpAllocator()->Adapter()); + for (const UniqueFEIRType &type : catchTypes) { + MIRType *mirType = type->GenerateMIRType(kSrcLangJava, true); + vec.push_back(mirType->GetTypeIndex()); + } + StmtNode *stmtCatch = mirBuilder.CreateStmtCatch(vec); + ans.push_back(stmtCatch); + return ans; +} + +void FEIRStmtPesudoCatch2::AddCatchTypeNameIdx(GStrIdx typeNameIdx) { + UniqueFEIRType type; + if (typeNameIdx == FEUtils::GetVoidIdx()) { + type = std::make_unique(std::make_unique(PTY_void, typeNameIdx)); + } else { + type = std::make_unique(PTY_ref, typeNameIdx); + } + catchTypes.push_back(std::move(type)); +} + +std::string FEIRStmtPesudoCatch2::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtPesudoComment ---------- FEIRStmtPesudoComment::FEIRStmtPesudoComment(FEIRNodeKind argKind) - : FEIRStmt(argKind) {} + : FEIRStmt(argKind) { + isAuxPre = true; +} FEIRStmtPesudoComment::FEIRStmtPesudoComment(const std::string &argContent) : FEIRStmt(kStmtPesudoComment), - content(argContent) {} + content(argContent) { + isAuxPre = true; +} std::list FEIRStmtPesudoComment::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; @@ -1563,12 +2779,26 @@ std::list FEIRStmtPesudoComment::GenMIRStmtsImpl(MIRBuilder &mirBuild return ans; } +std::string FEIRStmtPesudoComment::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} + // ---------- FEIRStmtPesudoCommentForInst ---------- FEIRStmtPesudoCommentForInst::FEIRStmtPesudoCommentForInst() - : FEIRStmtPesudoComment(kStmtPesudoCommentForInst) {} + : FEIRStmtPesudoComment(kStmtPesudoCommentForInst) { + isAuxPre = true; +} std::list FEIRStmtPesudoCommentForInst::GenMIRStmtsImpl(MIRBuilder &mirBuilder) const { std::list ans; return ans; } + +std::string FEIRStmtPesudoCommentForInst::DumpDotStringImpl() const { + std::stringstream ss; + ss << " " << id << ": " << GetFEIRNodeKindDescription(kind); + return ss.str(); +} } // namespace maple diff --git a/src/mplfe/common/src/feir_type.cpp b/src/mplfe/common/src/feir_type.cpp index 0d469d4a91c3c45cff9e0178bb0257c0334edc93..20e1c0958fd4b496bbcef1a7d9272683c13f5076 100644 --- a/src/mplfe/common/src/feir_type.cpp +++ b/src/mplfe/common/src/feir_type.cpp @@ -18,6 +18,7 @@ #include "mpl_logging.h" #include "fe_manager.h" #include "fe_config_parallel.h" +#include "fe_utils.h" namespace maple { // ---------- FEIRType ---------- @@ -69,7 +70,8 @@ MIRType *FEIRType::GenerateMIRTypeAuto(MIRSrcLang argSrcLang) const { CHECK_FATAL(false, "unsupported language"); return nullptr; } - return GenerateMIRType(std::get<0>(it->second), std::get<1>(it->second)); + PrimType pTy = GetPrimType(); + return GenerateMIRType(std::get<0>(it->second), pTy == PTY_begin ? std::get<1>(it->second) : pTy); } // ---------- FEIRTypeDefault ---------- @@ -80,7 +82,16 @@ FEIRTypeDefault::FEIRTypeDefault(PrimType argPrimType) : FEIRTypeDefault(argPrimType, GStrIdx(0), 0) {} FEIRTypeDefault::FEIRTypeDefault(PrimType argPrimType, const GStrIdx &argTypeNameIdx) - : FEIRTypeDefault(argPrimType, argTypeNameIdx, 0) {} + : FEIRTypeDefault(argPrimType, argTypeNameIdx, 0) { + std::string typeName = GlobalTables::GetStrTable().GetStringFromStrIdx(argTypeNameIdx); + uint8 typeDim = FEUtils::GetDim(typeName); + if (typeDim != 0) { + dim = typeDim; + typeName = typeName.substr(dim); + typeNameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(typeName); + primType = FEUtils::GetPrimType(typeNameIdx); + } +} FEIRTypeDefault::FEIRTypeDefault(PrimType argPrimType, const GStrIdx &argTypeNameIdx, TypeDim argDim) : FEIRType(kFEIRTypeDefault), @@ -165,7 +176,6 @@ void FEIRTypeDefault::SetPrimTypeImpl(PrimType pt) { } void FEIRTypeDefault::LoadFromJavaTypeName(const std::string &typeName, bool inMpl) { - MPLFE_PARALLEL_FORBIDDEN(); uint32 dimLocal = 0; std::string baseName = FETypeManager::GetBaseTypeName(typeName, dimLocal, inMpl); CHECK_FATAL(dimLocal <= FEConstants::kDimMax, "invalid array type %s (dim is too big)", typeName.c_str()); @@ -392,6 +402,6 @@ PrimType FEIRTypePointer::GetPrimTypeImpl() const { } void FEIRTypePointer::SetPrimTypeImpl(PrimType pt) { - CHECK_FATAL(false, "should not run here"); + CHECK_FATAL(false, "PrimType %d should not run here", pt); } } // namespace maple diff --git a/src/mplfe/common/src/feir_type_helper.cpp b/src/mplfe/common/src/feir_type_helper.cpp index ca19fc27097b343718c54e35b2f83e8e411c87ce..d6b7570c812e2e9e53c4c20f3438d1f8885dcd34 100644 --- a/src/mplfe/common/src/feir_type_helper.cpp +++ b/src/mplfe/common/src/feir_type_helper.cpp @@ -25,7 +25,7 @@ UniqueFEIRType FEIRTypeHelper::CreateTypeByPrimType(PrimType primType, TypeDim d } } -UniqueFEIRType FEIRTypeHelper::CreateTypeByJavaName(const std::string typeName, bool inMpl, bool usePtr) { +UniqueFEIRType FEIRTypeHelper::CreateTypeByJavaName(const std::string &typeName, bool inMpl, bool usePtr) { uint32 dim = 0; std::string baseName = FETypeManager::GetBaseTypeName(typeName, dim, inMpl); CHECK_FATAL(dim <= FEConstants::kDimMax, "invalid array type %s (dim is too big)", typeName.c_str()); diff --git a/src/mplfe/common/src/feir_type_infer.cpp b/src/mplfe/common/src/feir_type_infer.cpp index 27bc4012386be84e97d9c7046440b99a7c7f5b61..14e19c79264dacbb960480d4bf94dabe07d58d47 100644 --- a/src/mplfe/common/src/feir_type_infer.cpp +++ b/src/mplfe/common/src/feir_type_infer.cpp @@ -144,8 +144,7 @@ bool FEIRTypeMergeHelper::MergeType(UniqueFEIRType &typeDst, const UniqueFEIRTyp } // ---------- FEIRTypeInfer ---------- -FEIRTypeInfer::FEIRTypeInfer(MIRSrcLang argSrcLang, - const std::map> &argMapDefUse) +FEIRTypeInfer::FEIRTypeInfer(MIRSrcLang argSrcLang, const FEIRDefUseChain &argMapDefUse) : srcLang(argSrcLang), mapDefUse(argMapDefUse) { LoadTypeDefault(); @@ -171,7 +170,7 @@ void FEIRTypeInfer::Reset() { UniqueFEIRType FEIRTypeInfer::GetTypeForVarUse(const UniqueFEIRVar &varUse) { CHECK_NULL_FATAL(varUse); - if (varUse->GetType()->IsPreciseRefType()) { + if (varUse->GetType()->IsPrecise()) { return varUse->GetType()->Clone(); } if (varUse->GetTrans().get() == nullptr) { @@ -257,7 +256,7 @@ void FEIRTypeInfer::ProcessVarDef(UniqueFEIRVar &varDef) { std::unique_ptr varNew = std::make_unique(static_cast(varDef->Clone())); FEIRVarTypeScatter *ptrVarNew = varNew.get(); - varDef->SetType(varDef->GetType()->Clone()); + ptrVarNew->SetType(varDef->GetType()->Clone()); for (const FEIRTypeKey &typeKey : useTypes) { ptrVarNew->AddScatterType(typeKey.GetType()); } @@ -278,4 +277,22 @@ UniqueFEIRType FEIRTypeInfer::GetTypeByTransForVarUse(const UniqueFEIRVar &varUs return defType; } } + +Opcode FEIRTypeCvtHelper::ChooseCvtOpcodeByFromTypeAndToType(const FEIRType &fromType, const FEIRType &toType) { + if (IsRetypeable(fromType, toType)) { + return OP_retype; + } else if (IsIntCvt2Ref(fromType, toType)) { + return OP_cvt; + } else { + return OP_undef; + } +} + +bool FEIRTypeCvtHelper::IsRetypeable(const FEIRType &fromType, const FEIRType &toType) { + return (fromType.GetPrimType() == toType.GetPrimType()); +} + +bool FEIRTypeCvtHelper::IsIntCvt2Ref(const FEIRType &fromType, const FEIRType &toType) { + return (IsPrimitiveInteger(fromType.GetPrimType()) && toType.IsPreciseRefType()); +} } // namespace maple diff --git a/src/mplfe/common/src/feir_var.cpp b/src/mplfe/common/src/feir_var.cpp index 842f076d40b2467d978c26124dee0dbcccc6f112..8d27b1256b9e6f0e0260456c0421356926be525d 100644 --- a/src/mplfe/common/src/feir_var.cpp +++ b/src/mplfe/common/src/feir_var.cpp @@ -96,7 +96,40 @@ MIRSymbol *FEIRVar::GenerateGlobalMIRSymbolImpl(MIRBuilder &builder) const { MPLFE_PARALLEL_FORBIDDEN(); MIRType *mirType = type->GenerateMIRTypeAuto(); std::string name = GetName(*mirType); - return builder.GetOrCreateGlobalDecl(name, *mirType); + GStrIdx nameIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name); + MIRSymbol *gSymbol = builder.GetOrCreateGlobalDecl(name, *mirType); + if (gSymbol->GetAttrs().GetAttrFlag() != 0) { + return gSymbol; + } + // Set global var attr once + std::size_t pos = name.find("_7C"); + if (pos != std::string::npos) { + std::string containerName = name.substr(0, pos); + GStrIdx strIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(containerName); + TyIdx containerTypeIdx = GlobalTables::GetTypeNameTable().GetTyIdxFromGStrIdx(strIdx); + if (containerTypeIdx != TyIdx(0)) { + MIRType *containerType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(containerTypeIdx); + if (containerType->IsStructType()) { + // for external class + MIRStructType *mirContainer = static_cast(containerType); + if (!mirContainer->IsLocal()) { + gSymbol->SetStorageClass(kScExtern); + } + // for not defined field use + if (gSymbol->GetAttrs().GetAttrFlag() == 0) { + auto t = TypeAttrs(); + t.SetAttr(ATTR_static); + gSymbol->AddAttrs(t); + } + for (auto &field : mirContainer->GetStaticFields()) { + if (field.first == nameIdx) { + gSymbol->AddAttrs(field.second.second.ConvertToTypeAttrs()); + } + } + } + } + } + return gSymbol; } MIRSymbol *FEIRVar::GenerateLocalMIRSymbolImpl(MIRBuilder &builder) const { diff --git a/src/mplfe/common/src/feir_var_reg.cpp b/src/mplfe/common/src/feir_var_reg.cpp index 1fa46538d1f21a52b957433565d29fbb0aeb425e..1aa55cbc710598b14fe4413c7f805a0aec9bf9bf 100644 --- a/src/mplfe/common/src/feir_var_reg.cpp +++ b/src/mplfe/common/src/feir_var_reg.cpp @@ -19,18 +19,26 @@ namespace maple { std::string FEIRVarReg::GetNameImpl(const MIRType &mirType) const { - std::stringstream ss; - ss << "Reg" << regNum << "_"; + thread_local static std::stringstream ss(""); + ss.str(""); + ss << "Reg"; + ss << regNum; + ss << "_"; if (type->IsPreciseRefType()) { ss << "R" << mirType.GetTypeIndex().GetIdx(); } else { - ss << GetPrimTypeName(type->GetPrimType()); + if (type->GetSrcLang() == kSrcLangJava) { + ss << GetPrimTypeJavaName(type->GetPrimType()); + } else { + ss << GetPrimTypeName(type->GetPrimType()); + } } return ss.str(); } std::string FEIRVarReg::GetNameRawImpl() const { - std::stringstream ss; + thread_local static std::stringstream ss(""); + ss.str(""); ss << "Reg" << regNum; return ss.str(); } @@ -52,4 +60,35 @@ bool FEIRVarReg::EqualsToImpl(const std::unique_ptr &var) const { size_t FEIRVarReg::HashImpl() const { return std::hash{}(regNum); } + +// ========== FEIRVarAccumulator ========== +std::string FEIRVarAccumulator::GetNameImpl(const MIRType &mirType) const { + thread_local static std::stringstream ss(""); + ss.str(""); + ss << "Reg"; + ss << "_Accumulator"; + ss << "_"; + if (type->IsPreciseRefType()) { + ss << "R" << mirType.GetTypeIndex().GetIdx(); + } else { + if (type->GetSrcLang() == kSrcLangJava) { + ss << GetPrimTypeJavaName(type->GetPrimType()); + } else { + ss << GetPrimTypeName(type->GetPrimType()); + } + } + return ss.str(); +} + +std::string FEIRVarAccumulator::GetNameRawImpl() const { + thread_local static std::stringstream ss(""); + ss.str(""); + ss << "Reg_Accumulator"; + return ss.str(); +} + +std::unique_ptr FEIRVarAccumulator::CloneImpl() const { + std::unique_ptr var = std::make_unique(regNum, type->Clone()); + return var; +} } // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/feir_var_type_scatter.cpp b/src/mplfe/common/src/feir_var_type_scatter.cpp index 0ff7e46759a3c041fdd090e950b3dce2aaa083b6..083bb721df3d8074bbbc050643653fc39aad77ab 100644 --- a/src/mplfe/common/src/feir_var_type_scatter.cpp +++ b/src/mplfe/common/src/feir_var_type_scatter.cpp @@ -57,4 +57,26 @@ bool FEIRVarTypeScatter::EqualsToImpl(const std::unique_ptr &argVar) co size_t FEIRVarTypeScatter::HashImpl() const { return 0; } + +MIRSymbol *FEIRVarTypeScatter::GenerateGlobalMIRSymbolImpl(MIRBuilder &builder) const { + MPLFE_PARALLEL_FORBIDDEN(); + MIRType *mirType = var->GetType()->GenerateMIRTypeAuto(); + std::string name = GetName(*mirType); + return builder.GetOrCreateGlobalDecl(name, *mirType); +} + +MIRSymbol *FEIRVarTypeScatter::GenerateLocalMIRSymbolImpl(MIRBuilder &builder) const { + MPLFE_PARALLEL_FORBIDDEN(); + MIRType *mirType = var->GetType()->GenerateMIRTypeAuto(); + std::string name = GetName(*mirType); + return builder.GetOrCreateLocalDecl(name, *mirType); +} + +MIRSymbol *FEIRVarTypeScatter::GenerateMIRSymbolImpl(MIRBuilder &builder) const { + if (isGlobal) { + return GenerateGlobalMIRSymbol(builder); + } else { + return GenerateLocalMIRSymbol(builder); + } +} } // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/general_bb.cpp b/src/mplfe/common/src/general_bb.cpp index bd303be3442007ecda50a0dcb21cc2f05eb43462..f1295fe76822aa6f858ab35a56d6ffa9ceb39e94 100644 --- a/src/mplfe/common/src/general_bb.cpp +++ b/src/mplfe/common/src/general_bb.cpp @@ -33,34 +33,31 @@ GeneralBB::~GeneralBB() { stmtNoAuxTail = nullptr; } -void GeneralBB::AppendStmt(const GeneralStmt *stmt) { - if (stmt == nullptr) { - return; - } +void GeneralBB::AppendStmt(GeneralStmt &stmt) { if (stmtHead == nullptr) { - stmtHead = stmt; + stmtHead = &stmt; } - stmtTail = stmt; - if (stmt->IsAux() == false) { + stmtTail = &stmt; + if (stmt.IsAux() == false) { if (stmtNoAuxHead == nullptr) { - stmtNoAuxHead = stmt; + stmtNoAuxHead = &stmt; } - stmtNoAuxTail = stmt; + stmtNoAuxTail = &stmt; } } -void GeneralBB::AddStmtAuxPre(const GeneralStmt *stmt) { - if (stmt == nullptr || stmt->IsAuxPre() == false) { +void GeneralBB::AddStmtAuxPre(GeneralStmt &stmt) { + if (stmt.IsAuxPre() == false) { return; } - stmtHead = stmt; + stmtHead = &stmt; } -void GeneralBB::AddStmtAuxPost(const GeneralStmt *stmt) { - if (stmt == nullptr || stmt->IsAuxPost() == false) { +void GeneralBB::AddStmtAuxPost(GeneralStmt &stmt) { + if (stmt.IsAuxPost() == false) { return; } - stmtTail = stmt; + stmtTail = &stmt; } bool GeneralBB::IsPredBB(uint32 bbID) { diff --git a/src/mplfe/common/src/general_cfg.cpp b/src/mplfe/common/src/general_cfg.cpp index 272c9a2e6ba7929c62a1606e80edac22f0d442e0..0af5a53751d6d865f607133f3c7740ba9089f15c 100644 --- a/src/mplfe/common/src/general_cfg.cpp +++ b/src/mplfe/common/src/general_cfg.cpp @@ -32,10 +32,10 @@ void GeneralCFG::BuildBB() { } void GeneralCFG::BuildBasicBB() { - const FELinkListNode *nodeStmt = stmtHead.GetNext(); + FELinkListNode *nodeStmt = stmtHead.GetNext(); GeneralBB *currBB = nullptr; while (nodeStmt != nullptr) { - const GeneralStmt *stmt = static_cast(nodeStmt); + GeneralStmt *stmt = static_cast(nodeStmt); if (stmt->GetGeneralStmtKind() == kStmtDummyEnd) { break; } @@ -46,7 +46,7 @@ void GeneralCFG::BuildBasicBB() { bbTail->InsertBefore(currBB); } CHECK_FATAL(currBB != nullptr, "nullptr check of currBB"); - currBB->AppendStmt(stmt); + currBB->AppendStmt(*stmt); // check end of BB if (stmt->IsFallThru() == false || stmt->GetGeneralStmtKind() == GeneralStmtKind::kStmtMultiOut) { currBB = nullptr; @@ -68,7 +68,7 @@ void GeneralCFG::AppendAuxStmt() { break; } if (stmt->IsAuxPre()) { - bb->AddStmtAuxPre(stmt); + bb->AddStmtAuxPre(*stmt); } else { break; } @@ -82,7 +82,7 @@ void GeneralCFG::AppendAuxStmt() { break; } if (stmt->IsAuxPost()) { - bb->AddStmtAuxPost(stmt); + bb->AddStmtAuxPost(*stmt); } else { break; } @@ -117,8 +117,8 @@ bool GeneralCFG::BuildCFG() { while (nodeBB != nullptr && nodeBB != bbTail.get()) { GeneralBB *bb = static_cast(nodeBB); if (firstBB) { - bb->AddPredBB(bbHead.get()); - bbHead->AddSuccBB(bb); + bb->AddPredBB(*(bbHead.get())); + bbHead->AddSuccBB(*bb); firstBB = false; } const GeneralStmt *locStmtTail = bb->GetStmtNoAuxTail(); @@ -130,16 +130,16 @@ bool GeneralCFG::BuildCFG() { return false; } GeneralBB *bbNext = static_cast(nodeBBNext); - bb->AddSuccBB(bbNext); - bbNext->AddPredBB(bb); + bb->AddSuccBB(*bbNext); + bbNext->AddPredBB(*bb); } if (locStmtTail->GetGeneralStmtKind() == GeneralStmtKind::kStmtMultiOut) { for (GeneralStmt *stmt : locStmtTail->GetSuccs()) { auto itBB = mapTargetStmtBB.find(stmt); CHECK_FATAL(itBB != mapTargetStmtBB.end(), "Target BB is not found"); GeneralBB *bbNext = itBB->second; - bb->AddSuccBB(bbNext); - bbNext->AddPredBB(bb); + bb->AddSuccBB(*bbNext); + bbNext->AddPredBB(*bb); } } nodeBB = nodeBB->GetNext(); diff --git a/src/mplfe/common/src/general_stmt.cpp b/src/mplfe/common/src/general_stmt.cpp index 4f65c46a7a56fccb54b8526ff09e5348de822a09..9024e6a783df09a36656e1cb60ead34c40e9f36f 100644 --- a/src/mplfe/common/src/general_stmt.cpp +++ b/src/mplfe/common/src/general_stmt.cpp @@ -19,11 +19,11 @@ namespace maple { // ---------- GeneralStmt ---------- GeneralStmt::GeneralStmt() - : genKind(kStmtDefault), isFallThru(true), isAuxPre(false), isAuxPost(false), id(0) { + : genKind(kStmtDefault), isFallThru(true), isAuxPre(false), isAuxPost(false), isThrowable(false), id(0) { } GeneralStmt::GeneralStmt(GeneralStmtKind argGenKind) - : genKind(argGenKind), isFallThru(true), isAuxPre(false), isAuxPost(false), id(0) { + : genKind(argGenKind), isFallThru(true), isAuxPre(false), isAuxPost(false), isThrowable(false), id(0) { } void GeneralStmt::DumpImpl(const std::string &prefix) const { @@ -56,4 +56,8 @@ std::string GeneralStmt::GetStmtKindNameImpl() const { bool GeneralStmt::IsStmtInstImpl() const { return false; } + +bool GeneralStmt::IsBranchImpl() const { + return false; +} } // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/mplfe.cpp b/src/mplfe/common/src/mplfe.cpp index 921b286737995c2e7839116b6a8bcd9bf6563479..fc4e71ee6a5898170434aaaa92bb0fd73e95864b 100644 --- a/src/mplfe/common/src/mplfe.cpp +++ b/src/mplfe/common/src/mplfe.cpp @@ -12,14 +12,7 @@ * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ -#include "mpl_logging.h" -#include "mplfe_options.h" #include "mplfe_compiler.h" -#include "jbc_compiler_component.h" -#include "fe_errno.h" -#include "mpl_timer.h" -#include "mplfe_env.h" -#include "fe_manager.h" using namespace maple; int main(int argc, char **argv) { @@ -32,31 +25,10 @@ int main(int argc, char **argv) { MPLFEEnv::GetInstance().Init(); MIRModule module; MPLFECompiler compiler(module); - bool success = true; - compiler.Init(); - compiler.CheckInput(); - compiler.SetupOutputPathAndName(); - success = success && compiler.LoadMplt(); - if (FEOptions::GetInstance().GetInputClassFiles().size() != 0 || - FEOptions::GetInstance().GetInputJarFiles().size() != 0) { - std::unique_ptr jbcCompilerComp = std::make_unique(module); - compiler.RegisterCompilerComponent(std::move(jbcCompilerComp)); - } - compiler.InitFromOptions(); - compiler.ParseInputs(); - compiler.PreProcessDecls(); - compiler.ProcessDecls(); - FEManager::GetTypeManager().InitMCCFunctions(); - compiler.PreProcessWithFunctions(); - compiler.ProcessFunctions(); - CHECK_FATAL(success, "Compile Error"); - compiler.ExportMpltFile(); - compiler.ExportMplFile(); - MPLFEEnv::GetInstance().Finish(); + compiler.Run(); timer.Stop(); if (FEOptions::GetInstance().IsDumpTime()) { - INFO(kLncInfo, "mplfe time: %.2lfs", timer.ElapsedMilliseconds() / 1000.0); + INFO(kLncInfo, "mplfe time: %.2lfms", timer.ElapsedMilliseconds() / 1.0); } - compiler.Release(); return static_cast(FEErrno::kNoError); -} \ No newline at end of file +} diff --git a/src/mplfe/common/src/mplfe_compiler.cpp b/src/mplfe/common/src/mplfe_compiler.cpp index c3df826d2526d81ac2ec24eee31b627dcaadf6ec..9813ec8ccb0e527c46a6b77fe0dd9acc2eaa9493 100644 --- a/src/mplfe/common/src/mplfe_compiler.cpp +++ b/src/mplfe/common/src/mplfe_compiler.cpp @@ -32,12 +32,60 @@ void MPLFECompiler::Init() { FEManager::Init(module); FEStructMethodInfo::InitJavaPolymorphicWhiteList(); module.SetFlavor(maple::kFeProduced); + // The default language is Java. + module.SetSrcLang(maple::kSrcLangJava); + module.GetImportFiles().clear(); } void MPLFECompiler::Release() { FEManager::Release(); - memPoolCtrler.DeleteMemPool(mp); - mp = nullptr; + if (mp != nullptr) { + delete mp; + mp = nullptr; + } +} + +void MPLFECompiler::Run() { + bool success = true; + Init(); + CheckInput(); + success = success && LoadMplt(); + SetupOutputPathAndName(); + if (FEOptions::GetInstance().HasJBC()) { + FEOptions::GetInstance().SetTypeInferKind(FEOptions::TypeInferKind::kNo); + std::unique_ptr jbcCompilerComp = std::make_unique(module); + RegisterCompilerComponent(std::move(jbcCompilerComp)); + } + if (FEOptions::GetInstance().GetInputDexFiles().size() != 0) { + bc::ArkAnnotationProcessor::Process(); + std::unique_ptr bcCompilerComp = + std::make_unique>(module); + RegisterCompilerComponent(std::move(bcCompilerComp)); + } + ParseInputs(); + if (!FEOptions::GetInstance().GetXBootClassPath().empty()) { + LoadOnDemandTypes(); + } + FEManager::GetJavaStringManager().GenStringMetaClassVar(); + PreProcessDecls(); + ProcessDecls(); + ProcessPragmas(); + if (!FEOptions::GetInstance().IsGenMpltOnly()) { + FEManager::GetTypeManager().InitMCCFunctions(); + PreProcessWithFunctions(); + FETypeHierarchy::GetInstance().InitByGlobalTable(); + ProcessFunctions(); + } + FEManager::GetManager().ReleaseStructElemMempool(); + CHECK_FATAL(success, "Compile Error"); + if (!FEOptions::GetInstance().IsNoMplFile()) { + ExportMpltFile(); + if (!FEOptions::GetInstance().IsGenMpltOnly()) { + ExportMplFile(); + } + } + MPLFEEnv::GetInstance().Finish(); + Release(); } void MPLFECompiler::CheckInput() { @@ -62,6 +110,15 @@ void MPLFECompiler::CheckInput() { } } + // check input dex files + const std::vector &inputDexNames = FEOptions::GetInstance().GetInputDexFiles(); + if (!inputDexNames.empty()) { + nInput += inputDexNames.size(); + if (firstInputName.empty()) { + firstInputName = inputDexNames[0]; + } + } + CHECK_FATAL(nInput > 0, "Error occurs: no inputs. exit."); } @@ -73,12 +130,12 @@ void MPLFECompiler::SetupOutputPathAndName() { outputName = outputName0; } else { // use default - outputName = FEFileType::GetName(firstInputName, false); + outputName = FEFileType::GetName(firstInputName, true); outputPath = FEFileType::GetPath(firstInputName); } const std::string &outputPath0 = FEOptions::GetInstance().GetOutputPath(); if (!outputPath0.empty()) { - outputPath = outputPath0; + outputPath = outputPath0[outputPath0.size() - 1] == '/' ? outputPath0 : (outputPath0 + "/"); } FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "OutputPath: %s", outputPath.c_str()); FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "OutputName: %s", outputName.c_str()); @@ -86,10 +143,28 @@ void MPLFECompiler::SetupOutputPathAndName() { if (outputPath.empty()) { outName = outputName; } else { - outName = outputPath + "/" + outputName; + outName = outputPath + outputName; } FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "OutputFullName: %s", outName.c_str()); module.SetFileName(outName); + // mapleall need outName with type, but mplt file no need + size_t lastDot = outName.find_last_of("."); + std::string outNameWithoutType; + if (lastDot == std::string::npos) { + outNameWithoutType = outName; + } else { + outNameWithoutType = outName.substr(0, lastDot); + } + std::string mpltName = outNameWithoutType + ".mplt"; + GStrIdx strIdx = module.GetMIRBuilder()->GetOrCreateStringIndex(mpltName); + module.GetImportFiles().push_back(strIdx); +} + +inline void MPLFECompiler::InsertImportInMpl(const std::list &mplt) const { + for (const std::string &fileName : mplt) { + GStrIdx strIdx = module.GetMIRBuilder()->GetOrCreateStringIndex(fileName); + module.GetImportFiles().push_back(strIdx); + } } bool MPLFECompiler::LoadMplt() { @@ -99,13 +174,16 @@ bool MPLFECompiler::LoadMplt() { const std::list &mpltsFromSys = FEOptions::GetInstance().GetInputMpltFilesFromSys(); success = success && FEManager::GetTypeManager().LoadMplts(mpltsFromSys, FETypeFlag::kSrcMpltSys, "Load mplt from sys"); + InsertImportInMpl(mpltsFromSys); + // load mplt + const std::list &mplts = FEOptions::GetInstance().GetInputMpltFiles(); + success = success && FEManager::GetTypeManager().LoadMplts(mplts, FETypeFlag::kSrcMplt, "Load mplt"); + InsertImportInMpl(mplts); // load mplt from apk const std::list &mpltsFromApk = FEOptions::GetInstance().GetInputMpltFilesFromApk(); success = success && FEManager::GetTypeManager().LoadMplts(mpltsFromApk, FETypeFlag::kSrcMpltApk, "Load mplt from apk"); - // load mplt - const std::list &mplts = FEOptions::GetInstance().GetInputMpltFiles(); - success = success && FEManager::GetTypeManager().LoadMplts(mplts, FETypeFlag::kSrcMplt, "Load mplt"); + InsertImportInMpl(mpltsFromApk); return success; } @@ -128,14 +206,6 @@ void MPLFECompiler::RegisterCompilerComponent(std::unique_ptr &comp : components) { - ASSERT(comp != nullptr, "nullptr check"); - bool success = comp->InitFromOptions(); - CHECK_FATAL(success, "Error occurs in MPLFECompiler::InitFromOptions(). exit."); - } -} - void MPLFECompiler::ParseInputs() { FETimer timer; timer.StartAndDump("MPLFECompiler::ParseInputs()"); @@ -147,9 +217,21 @@ void MPLFECompiler::ParseInputs() { timer.StopAndDumpTimeMS("MPLFECompiler::ParseInputs()"); } +void MPLFECompiler::LoadOnDemandTypes() { + FETimer timer; + timer.StartAndDump("MPLFECompiler::LoadOnDemandTypes()"); + for (const std::unique_ptr &comp : components) { + CHECK_NULL_FATAL(comp); + bool success = comp->LoadOnDemandType(); + CHECK_FATAL(success, "Error occurs in MPLFECompiler::LoadOnDemandTypes(). exit."); + } + timer.StopAndDumpTimeMS("MPLFECompiler::LoadOnDemandTypes()"); +} + void MPLFECompiler::PreProcessDecls() { FETimer timer; timer.StartAndDump("MPLFECompiler::PreProcessDecls()"); + (void)GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("_this"); for (const std::unique_ptr &comp : components) { ASSERT(comp != nullptr, "nullptr check"); bool success = comp->PreProcessDecl(); @@ -169,9 +251,20 @@ void MPLFECompiler::ProcessDecls() { timer.StopAndDumpTimeMS("MPLFECompiler::ProcessDecl()"); } +void MPLFECompiler::ProcessPragmas() { + FETimer timer; + timer.StartAndDump("MPLFECompiler::ProcessPragmas()"); + for (const std::unique_ptr &comp : components) { + ASSERT_NOT_NULL(comp); + comp->ProcessPragma(); + } + timer.StopAndDumpTimeMS("MPLFECompiler::ProcessPragmas()"); +} + void MPLFECompiler::PreProcessWithFunctions() { FETimer timer; timer.StartAndDump("MPLFECompiler::PreProcessWithFunctions()"); + (void)GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("_this"); for (const std::unique_ptr &comp : components) { ASSERT(comp != nullptr, "nullptr check"); bool success = comp->PreProcessWithFunction(); @@ -187,20 +280,53 @@ void MPLFECompiler::ProcessFunctions() { uint32 funcSize = 0; for (const std::unique_ptr &comp : components) { ASSERT(comp != nullptr, "nullptr check"); + funcSize += comp->GetFunctionsSize(); uint32 nthreads = FEOptions::GetInstance().GetNThreads(); if (comp->Parallelable() && nthreads > 0) { FEConfigParallel::GetInstance().EnableParallel(); success = comp->ProcessFunctionParallel(nthreads) && success; + FEConfigParallel::GetInstance().DisableParallel(); } else { success = comp->ProcessFunctionSerial() && success; } - funcSize += comp->GetFunctionsSize(); + if (!success) { + const std::set &failedFEFunctions = comp->GetCompileFailedFEFunctions(); + compileFailedFEFunctions.insert(failedFEFunctions.begin(), failedFEFunctions.end()); + } if (FEOptions::GetInstance().IsDumpPhaseTime()) { comp->DumpPhaseTimeTotal(); } + comp->ReleaseMemPool(); } + FEManager::GetTypeManager().MarkExternStructType(); module.SetNumFuncs(funcSize); + FindMinCompileFailedFEFunctions(); timer.StopAndDumpTimeMS("MPLFECompiler::ProcessFunctions()"); CHECK_FATAL(success, "ProcessFunction error"); } -} // namespace maple \ No newline at end of file + +void MPLFECompiler::FindMinCompileFailedFEFunctions() { + if (compileFailedFEFunctions.size() == 0) { + return; + } + FEFunction *minCompileFailedFEFunction = nullptr; + uint32 minFailedStmtCount = 0; + for (FEFunction *feFunc : compileFailedFEFunctions) { + if (minCompileFailedFEFunction == nullptr) { + minCompileFailedFEFunction = feFunc; + minFailedStmtCount = minCompileFailedFEFunction->GetStmtCount(); + } + uint32 stmtCount = feFunc->GetStmtCount(); + if (stmtCount < minFailedStmtCount) { + minCompileFailedFEFunction = feFunc; + minFailedStmtCount = stmtCount; + } + } + if (minCompileFailedFEFunction != nullptr) { + INFO(kLncWarn, "function compile failed!!! the min function is :"); + INFO(kLncWarn, minCompileFailedFEFunction->GetDescription().c_str()); + minCompileFailedFEFunction->OutputUseDefChain(); + minCompileFailedFEFunction->OutputDefUseChain(); + } +} +} // namespace maple diff --git a/src/mplfe/common/src/mplfe_compiler_component.cpp b/src/mplfe/common/src/mplfe_compiler_component.cpp index 85f3cbba64412225bb6fa848160e05aba938e421..f77c60c205ac2c1ae0b930d1ec225a0aa4cfc808 100644 --- a/src/mplfe/common/src/mplfe_compiler_component.cpp +++ b/src/mplfe/common/src/mplfe_compiler_component.cpp @@ -20,24 +20,28 @@ namespace maple { // ---------- FEFunctionProcessTask ---------- -FEFunctionProcessTask::FEFunctionProcessTask(FEFunction &argFunction) +FEFunctionProcessTask::FEFunctionProcessTask(std::unique_ptr &argFunction) : function(argFunction) {} int FEFunctionProcessTask::RunImpl(MplTaskParam *param) { - function.Process(); - return 0; + bool success = function->Process(); + if (success) { + return 1; + } else { + return 0; + } } int FEFunctionProcessTask::FinishImpl(MplTaskParam *param) { - function.Finish(); + function->Finish(); + FEFunction *funPtr = function.release(); + delete funPtr; return 0; } // ---------- FEFunctionProcessSchedular ---------- -void FEFunctionProcessSchedular::AddFunctionProcessTask(const std::unique_ptr &function) { - FEFunction *ptrFunc = function.get(); - CHECK_NULL_FATAL(ptrFunc); - std::unique_ptr task = std::make_unique(*ptrFunc); +void FEFunctionProcessSchedular::AddFunctionProcessTask(std::unique_ptr &function) { + std::unique_ptr task = std::make_unique(function); AddTask(task.get()); tasks.push_back(std::move(task)); } @@ -61,14 +65,19 @@ bool MPLFECompilerComponent::ProcessFunctionSerialImpl() { ss << GetComponentName() << "::ProcessFunctionSerial()"; FETimer timer; timer.StartAndDump(ss.str()); + bool success = true; FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process %s =====", ss.str().c_str()); - for (const std::unique_ptr &function : functions) { - ASSERT(function != nullptr, "nullptr check"); - function->Process(); - function->Finish(); + for (auto it = functions.begin(); it != functions.end();) { + bool processResult = (*it)->Process(); + if (!processResult) { + (void)compileFailedFEFunctions.insert((*it).get()); + } + success = success && processResult; + (*it)->Finish(); + it = functions.erase(it); } timer.StopAndDumpTimeMS(ss.str()); - return true; + return success; } bool MPLFECompilerComponent::ProcessFunctionParallelImpl(uint32 nthreads) { @@ -79,7 +88,7 @@ bool MPLFECompilerComponent::ProcessFunctionParallelImpl(uint32 nthreads) { FE_INFO_LEVEL(FEOptions::kDumpLevelInfo, "===== Process %s =====", ss.str().c_str()); FEFunctionProcessSchedular schedular(ss.str()); schedular.Init(); - for (const std::unique_ptr &function : functions) { + for (std::unique_ptr &function : functions) { schedular.AddFunctionProcessTask(function); } schedular.SetDumpTime(FEOptions::GetInstance().IsDumpThreadTime()); @@ -100,4 +109,4 @@ void MPLFECompilerComponent::DumpPhaseTimeTotalImpl() const { CHECK_NULL_FATAL(phaseResultTotal); phaseResultTotal->DumpMS(); } -} // namespace maple +} // namespace maple \ No newline at end of file diff --git a/src/mplfe/common/src/mplfe_env.cpp b/src/mplfe/common/src/mplfe_env.cpp index ec5a269c0d9825022af9aa46947d80d819aa1500..1f7f3abe6eb75caf9a8ad82c3904248277683866 100644 --- a/src/mplfe/common/src/mplfe_env.cpp +++ b/src/mplfe/common/src/mplfe_env.cpp @@ -31,7 +31,7 @@ void MPLFEEnv::Finish() { } uint32 MPLFEEnv::NewSrcFileIdx(const GStrIdx &nameIdx) { - size_t idx = srcFileIdxNameMap.size(); + size_t idx = srcFileIdxNameMap.size() + 1; // 1: already occupied by VtableImpl.mpl CHECK_FATAL(idx < UINT32_MAX, "idx is out of range"); srcFileIdxNameMap[idx] = nameIdx; return static_cast(idx); diff --git a/src/mplfe/common/src/mplfe_options.cpp b/src/mplfe/common/src/mplfe_options.cpp index 2a71cf11aaf843c305d7e02cd0b757b44255a327..3cb3142552fa5eea8b784e64ae146988c693a10b 100644 --- a/src/mplfe/common/src/mplfe_options.cpp +++ b/src/mplfe/common/src/mplfe_options.cpp @@ -29,18 +29,21 @@ enum OptionIndex : uint32 { // input control options kMpltSys, kMpltApk, - kMplt, kInClass, kInJar, + kInDex, // output control options kOutputPath, kOutputName, kGenMpltOnly, kGenAsciiMplt, kDumpInstComment, + kNoMplFile, // debug info control options kDumpLevel, kDumpTime, + kDumpComment, + kDumpLOC, kDumpPhaseTime, kDumpPhaseTimeDetail, // java bytecode compile options @@ -57,148 +60,198 @@ enum OptionIndex : uint32 { // multi-thread control options kNThreads, kDumpThreadTime, - kReleaseAfterEmit, + // type-infer + kTypeInfer, + // On Demand Type Creation + kXBootClassPath, + kClassLoaderContext, + kInputFile, + kCollectDepTypes, + kDepSameNamePolicy, }; -const mapleOption::Descriptor kUsage[] = { - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, +const Descriptor kUsage[] = { + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========================================\n" " Usage: mplfe [ options ] input1 input2 input3\n" " options:", "mplfe", {} }, - { static_cast(kMplfeHelp), 0, "h", "help", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kMplfeHelp, 0, "h", "help", + kBuildTypeAll, kArgCheckPolicyNone, " -h, --help : print usage and exit", "mplfe", {} }, - { static_cast(kVersion), 0, "v", "version", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kVersion, 0, "v", "version", + kBuildTypeAll, kArgCheckPolicyNone, " -v, --version : print version and exit", "mplfe", {} }, // input control options - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========== Input Control Options ==========", "mplfe", {} }, - { static_cast(kMpltSys), 0, "", "mplt-sys", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kMpltSys, 0, "", "mplt-sys", + kBuildTypeAll, kArgCheckPolicyRequired, " -mplt-sys sys1.mplt,sys2.mplt\n" " : input sys mplt files", "mplfe", {} }, - { static_cast(kMpltApk), 0, "", "mplt-apk", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kMpltApk, 0, "", "mplt-apk", + kBuildTypeAll, kArgCheckPolicyRequired, " -mplt-apk apk1.mplt,apk2.mplt\n" " : input apk mplt files", "mplfe", {} }, - { static_cast(kMplt), 0, "", "mplt", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kInMplt, 0, "", "mplt", + kBuildTypeAll, kArgCheckPolicyRequired, " -mplt lib1.mplt,lib2.mplt\n" " : input mplt files", "mplfe", {} }, - { static_cast(kInClass), 0, "", "in-class", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kInClass, 0, "", "in-class", + kBuildTypeAll, kArgCheckPolicyRequired, " --in-class file1.jar,file2.jar\n" " : input class files", "mplfe", {} }, - { static_cast(kInJar), 0, "", "in-jar", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kInJar, 0, "", "in-jar", + kBuildTypeAll, kArgCheckPolicyRequired, " --in-jar file1.jar,file2.jar\n" " : input jar files", "mplfe", {} }, + { kInDex, 0, "", "in-dex", + kBuildTypeAll, kArgCheckPolicyRequired, + " --in-dex file1.dex,file2.dex\n" + " : input dex files", "mplfe", {} }, // output control options - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========== Output Control Options ==========", "mplfe", {} }, - { static_cast(kOutputPath), 0, "p", "output", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kOutputPath, 0, "p", "output", + kBuildTypeAll, kArgCheckPolicyRequired, " -p, --output : output path", "mplfe", {} }, - { static_cast(kOutputName), 0, "o", "output-name", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kOutputName, 0, "o", "output-name", + kBuildTypeAll, kArgCheckPolicyRequired, " -o, --output-name : output name", "mplfe", {} }, - { static_cast(kGenMpltOnly), 0, "t", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kGenMpltOnly, 0, "t", "", + kBuildTypeAll, kArgCheckPolicyNone, " -t : generate mplt only", "mplfe", {} }, - { static_cast(kGenAsciiMplt), 0, "", "asciimplt", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kGenAsciiMplt, 0, "", "asciimplt", + kBuildTypeAll, kArgCheckPolicyNone, " --asciimplt : generate mplt in ascii format", "mplfe", {} }, - { static_cast(kDumpInstComment), 0, "", "dump-inst-comment", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpInstComment, 0, "", "dump-inst-comment", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-inst-comment : dump instruction comment", "mplfe", {} }, + { kNoMplFile, 0, "", "no-mpl-file", + kBuildTypeAll, kArgCheckPolicyNone, + " --no-mpl-file : disable dump mpl file", "mplfe", {} }, // debug info control options - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========== Debug Info Control Options ==========", "mplfe", {} }, - { static_cast(kDumpLevel), 0, "d", "dump-level", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNumeric, + { kDumpLevel, 0, "d", "dump-level", + kBuildTypeAll, kArgCheckPolicyNumeric, " -d, --dump-level xx : debug info dump level\n" " [0] disable\n" " [1] dump simple info\n" " [2] dump detail info\n" " [3] dump debug info", "mplfe", {} }, - { static_cast(kDumpTime), 0, "", "dump-time", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpTime, 0, "", "dump-time", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-time : dump time", "mplfe", {} }, - { static_cast(kDumpPhaseTime), 0, "", "dump-phase-time", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpComment, 0, "", "dump-comment", + kBuildTypeAll, kArgCheckPolicyNone, + " --dump-comment : gen comment stmt", "mplfe", {} }, + { kDumpLOC, 0, "", "dump-LOC", + kBuildTypeAll, kArgCheckPolicyNone, + " --dump-LOC : gen LOC", "mplfe", {} }, + { kDumpPhaseTime, 0, "", "dump-phase-time", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-phase-time : dump total phase time", "mplfe", {} }, - { static_cast(kDumpPhaseTimeDetail), 0, "", "dump-phase-time-detail", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpPhaseTimeDetail, 0, "", "dump-phase-time-detail", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-phase-time-detail" " : dump phase time for each method", "mplfe", {} }, // java bytecode compile options - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========== Java Bytecode Compile Options ==========", "mplfe", {} }, - { static_cast(kJavaStaticFieldName), 0, "", "java-staticfield-name", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kJavaStaticFieldName, 0, "", "java-staticfield-name", + kBuildTypeAll, kArgCheckPolicyRequired, " --java-staticfield-name\n" " : java static field name mode\n" " [notype] all static fields have no types in names\n" " [alltype] all static fields have types in names\n" " [smart] only static fields in field-proguard class have types in names\n", "mplfe", {} }, - { static_cast(kJBCInfoUsePathName), 0, "", "jbc-info-use-pathname", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kJBCInfoUsePathName, 0, "", "jbc-info-use-pathname", + kBuildTypeAll, kArgCheckPolicyNone, " --jbc-info-use-pathname\n" " : use JBC pathname in file info", "mplfe", {} }, - { static_cast(kDumpJBCStmt), 0, "", "dump-jbc-stmt", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpJBCStmt, 0, "", "dump-jbc-stmt", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-jbc-stmt : dump JBC Stmt", "mplfe", {} }, - { static_cast(kDumpJBCBB), 0, "", "dump-jbc-bb", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpJBCBB, 0, "", "dump-jbc-bb", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-jbc-bb : dump JBC BB", "mplfe", {} }, - { static_cast(kDumpJBCAll), 0, "", "dump-jbc-all", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpJBCAll, 0, "", "dump-jbc-all", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-jbc-all : dump all JBC function", "mplfe", {} }, - { static_cast(kDumpJBCErrorOnly), 0, "", "dump-jbc-error-only", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpJBCErrorOnly, 0, "", "dump-jbc-error-only", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-jbc-error-only\n" " : dump JBC functions with errors", "mplfe", {} }, - { static_cast(kDumpJBCFuncName), 0, "", "dump-jbc-funcname", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kDumpJBCFuncName, 0, "", "dump-jbc-funcname", + kBuildTypeAll, kArgCheckPolicyRequired, " --dump-jbc-funcname=name1,name2,...\n" " : dump JBC functions with specified names\n" " : name format: ClassName;|MethodName|Signature", "mplfe", {} }, // general stmt/bb/cfg debug options - { static_cast(kDumpGenCFGGraph), 0, "", "dump-general-cfg-graph", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kDumpGenCFGGraph, 0, "", "dump-general-cfg-graph", + kBuildTypeAll, kArgCheckPolicyRequired, " --dump-general-cfg-graph=graph.dot\n" " : dump General CFG into graphviz dot file", "mplfe", {} }, - { static_cast(kEmitJBCLocalVarInfo), 0, "", "emit-jbc-localvar-info", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kEmitJBCLocalVarInfo, 0, "", "emit-jbc-localvar-info", + kBuildTypeAll, kArgCheckPolicyNone, " --emit-jbc-localvar-info\n" " : emit jbc's LocalVar Info in mpl using comments", "mplfe", {} }, // multi-thread control - { static_cast(kUnknown), 0, "", "", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyUnknown, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, "========== Multi-Thread Control Options ==========", "mplfe", {} }, - { static_cast(kNThreads), 0, "", "np", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyRequired, + { kNThreads, 0, "", "np", + kBuildTypeAll, kArgCheckPolicyRequired, " --np num : number of threads", "mplfe", {} }, - { static_cast(kDumpThreadTime), 0, "", "dump-thread-time", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, + { kDumpThreadTime, 0, "", "dump-thread-time", + kBuildTypeAll, kArgCheckPolicyNone, " --dump-thread-time : dump thread time in mpl schedular", "mplfe", {} }, - { static_cast(kReleaseAfterEmit), 0, "", "release-after-emit", - mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, - " --release-after-emit : release temp memory after emit", "mplfe", {} }, - { 0, 0, "", "", mapleOption::kBuildTypeAll, mapleOption::kArgCheckPolicyNone, "", "mplfe", {} } + // type-infer + { kTypeInfer, 0, "", "type-infer", + kBuildTypeAll, kArgCheckPolicyNone, + " --type-infer : enable type infer", "mplfe", {} }, + // On Demand Type Creation + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyUnknown, + "========== On Demand Type Creation ==========", "mplfe", {} }, + { kXBootClassPath, 0, "", "Xbootclasspath", + kBuildTypeAll, kArgCheckPolicyRequired, + " -Xbootclasspath=bootclasspath\n"\ + " : boot class path list\n"\ + " : boot class path list", "mplfe", {} }, + { kClassLoaderContext, 0, "", "classloadercontext", + kBuildTypeAll, kArgCheckPolicyRequired, + " -classloadercontext=pcl\n"\ + " : class loader context \n"\ + " : path class loader", "mplfe", {} }, + { kInputFile, 0, "", "inputfile", + kBuildTypeAll, kArgCheckPolicyRequired, + " -classloadercontext=pcl\n"\ + " : class loader context \n"\ + " : path class loader", "mplfe", {} }, + { kCollectDepTypes, 0, "", "dep", + kBuildTypeAll, kArgCheckPolicyRequired, + " -dep=all or func\n"\ + " : [all] collect all dependent types\n"\ + " : [func] collect dependent types in function", "mplfe", {} }, + { kDepSameNamePolicy, 0, "", "depsamename", + kBuildTypeAll, kArgCheckPolicyRequired, + " -DepSameNamePolicy=sys or src\n"\ + " : [sys] load type from sys when on-demand load same name type\n"\ + " : [src] load type from src when on-demand load same name type", "mplfe", {} }, + { kUnknown, 0, "", "", + kBuildTypeAll, kArgCheckPolicyNone, + "", "mplfe", {} } }; -MPLFEOptions MPLFEOptions::options; - MPLFEOptions::MPLFEOptions() { CreateUsages(kUsage); Init(); @@ -211,77 +264,95 @@ void MPLFEOptions::Init() { } bool MPLFEOptions::InitFactory() { - RegisterFactoryFunction(static_cast(kMplfeHelp), + RegisterFactoryFunction(kMplfeHelp, &MPLFEOptions::ProcessHelp); - RegisterFactoryFunction(static_cast(kVersion), + RegisterFactoryFunction(kVersion, &MPLFEOptions::ProcessVersion); // input control options - RegisterFactoryFunction(static_cast(kMpltSys), + RegisterFactoryFunction(kMpltSys, &MPLFEOptions::ProcessInputMpltFromSys); - RegisterFactoryFunction(static_cast(kMpltApk), + RegisterFactoryFunction(kMpltApk, &MPLFEOptions::ProcessInputMpltFromApk); - RegisterFactoryFunction(static_cast(kMplt), + RegisterFactoryFunction(kInMplt, &MPLFEOptions::ProcessInputMplt); - RegisterFactoryFunction(static_cast(kInClass), + RegisterFactoryFunction(kInClass, &MPLFEOptions::ProcessInClass); - RegisterFactoryFunction(static_cast(kInJar), + RegisterFactoryFunction(kInJar, &MPLFEOptions::ProcessInJar); + RegisterFactoryFunction(kInDex, + &MPLFEOptions::ProcessInDex); // output control options - RegisterFactoryFunction(static_cast(kOutputPath), + RegisterFactoryFunction(kOutputPath, &MPLFEOptions::ProcessOutputPath); - RegisterFactoryFunction(static_cast(kOutputName), + RegisterFactoryFunction(kOutputName, &MPLFEOptions::ProcessOutputName); - RegisterFactoryFunction(static_cast(kGenMpltOnly), + RegisterFactoryFunction(kGenMpltOnly, &MPLFEOptions::ProcessGenMpltOnly); - RegisterFactoryFunction(static_cast(kGenAsciiMplt), + RegisterFactoryFunction(kGenAsciiMplt, &MPLFEOptions::ProcessGenAsciiMplt); - RegisterFactoryFunction(static_cast(kDumpInstComment), + RegisterFactoryFunction(kDumpInstComment, &MPLFEOptions::ProcessDumpInstComment); + RegisterFactoryFunction(kNoMplFile, + &MPLFEOptions::ProcessNoMplFile); // debug info control options - RegisterFactoryFunction(static_cast(kDumpLevel), + RegisterFactoryFunction(kDumpLevel, &MPLFEOptions::ProcessDumpLevel); - RegisterFactoryFunction(static_cast(kDumpTime), + RegisterFactoryFunction(kDumpTime, &MPLFEOptions::ProcessDumpTime); - RegisterFactoryFunction(static_cast(kDumpPhaseTime), + RegisterFactoryFunction(kDumpComment, + &MPLFEOptions::ProcessDumpComment); + RegisterFactoryFunction(kDumpLOC, + &MPLFEOptions::ProcessDumpLOC); + RegisterFactoryFunction(kDumpPhaseTime, &MPLFEOptions::ProcessDumpPhaseTime); - RegisterFactoryFunction(static_cast(kDumpPhaseTimeDetail), + RegisterFactoryFunction(kDumpPhaseTimeDetail, &MPLFEOptions::ProcessDumpPhaseTimeDetail); // java bytecode compile options - RegisterFactoryFunction(static_cast(kJavaStaticFieldName), + RegisterFactoryFunction(kJavaStaticFieldName, &MPLFEOptions::ProcessModeForJavaStaticFieldName); - RegisterFactoryFunction(static_cast(kJBCInfoUsePathName), + RegisterFactoryFunction(kJBCInfoUsePathName, &MPLFEOptions::ProcessJBCInfoUsePathName); - RegisterFactoryFunction(static_cast(kDumpJBCStmt), + RegisterFactoryFunction(kDumpJBCStmt, &MPLFEOptions::ProcessDumpJBCStmt); - RegisterFactoryFunction(static_cast(kDumpJBCBB), + RegisterFactoryFunction(kDumpJBCBB, &MPLFEOptions::ProcessDumpJBCBB); - RegisterFactoryFunction(static_cast(kDumpJBCErrorOnly), + RegisterFactoryFunction(kDumpJBCErrorOnly, &MPLFEOptions::ProcessDumpJBCErrorOnly); - RegisterFactoryFunction(static_cast(kDumpJBCFuncName), + RegisterFactoryFunction(kDumpJBCFuncName, &MPLFEOptions::ProcessDumpJBCFuncName); - RegisterFactoryFunction(static_cast(kEmitJBCLocalVarInfo), + RegisterFactoryFunction(kEmitJBCLocalVarInfo, &MPLFEOptions::ProcessEmitJBCLocalVarInfo); // general stmt/bb/cfg debug options - RegisterFactoryFunction(static_cast(kDumpGenCFGGraph), + RegisterFactoryFunction(kDumpGenCFGGraph, &MPLFEOptions::ProcessDumpGeneralCFGGraph); // multi-thread control options - RegisterFactoryFunction(static_cast(kNThreads), + RegisterFactoryFunction(kNThreads, &MPLFEOptions::ProcessNThreads); - RegisterFactoryFunction(static_cast(kDumpThreadTime), + RegisterFactoryFunction(kDumpThreadTime, &MPLFEOptions::ProcessDumpThreadTime); - RegisterFactoryFunction(static_cast(kReleaseAfterEmit), - &MPLFEOptions::ProcessReleaseAfterEmit); + + // On Demand Type Creation + RegisterFactoryFunction(kXBootClassPath, + &MPLFEOptions::ProcessXbootclasspath); + RegisterFactoryFunction(kClassLoaderContext, + &MPLFEOptions::ProcessClassLoaderContext); + RegisterFactoryFunction(kInputFile, + &MPLFEOptions::ProcessCompilefile); + RegisterFactoryFunction(kCollectDepTypes, + &MPLFEOptions::ProcessCollectDepTypes); + RegisterFactoryFunction(kDepSameNamePolicy, + &MPLFEOptions::ProcessDepSameNamePolicy); return true; } -bool MPLFEOptions::SolveOptions(const std::vector &opts, bool isDebug) { - for (const mapleOption::Option &opt : opts) { +bool MPLFEOptions::SolveOptions(const std::vector