Skip to content

Commit 2658f30

Browse files
author
icgmilk
committed
Replace MACROS with hashmap
Introduced 'MACROS_MAP' to replace the original 'MACROS' structure, and refactored related logic with hashmap utilities. Previously, 'find_macro' used linear search with a time complexity of O(n). By replacing it with a hashmap, the average lookup time is reduced to O(1).
1 parent 7163605 commit 2658f30

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

src/globals.c

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,12 @@ bool preproc_match;
2626
*/
2727
int macro_return_idx;
2828

29-
/* Global objects */
30-
31-
macro_t *MACROS;
32-
int macros_idx = 0;
33-
3429
/* FUNC_MAP is used to integrate function storing and boost lookup
3530
* performance, currently it uses FNV-1a hash function to hash function
3631
* name.
3732
*/
33+
34+
hashmap_t *MACROS_MAP;
3835
hashmap_t *FUNC_MAP;
3936
hashmap_t *ALIASES_MAP;
4037
hashmap_t *CONSTANTS_MAP;
@@ -557,28 +554,34 @@ bool remove_alias(char *alias)
557554

558555
macro_t *add_macro(char *name)
559556
{
560-
macro_t *ma = &MACROS[macros_idx++];
561-
strcpy(ma->name, name);
557+
macro_t *ma = hashmap_get(MACROS_MAP, name);
558+
if (!ma) {
559+
ma = malloc(sizeof(macro_t));
560+
if (!ma) {
561+
printf("Failed to allocate macro_t\n");
562+
return NULL;
563+
}
564+
strcpy(ma->name, name);
565+
hashmap_put(MACROS_MAP, name, ma);
566+
}
562567
ma->disabled = false;
563568
return ma;
564569
}
565570

566571
macro_t *find_macro(char *name)
567572
{
568-
for (int i = 0; i < macros_idx; i++) {
569-
if (!MACROS[i].disabled && !strcmp(name, MACROS[i].name))
570-
return &MACROS[i];
571-
}
573+
macro_t *ma = hashmap_get(MACROS_MAP, name);
574+
if (ma && !ma->disabled)
575+
return ma;
572576
return NULL;
573577
}
574578

575579
bool remove_macro(char *name)
576580
{
577-
for (int i = 0; i < macros_idx; i++) {
578-
if (!MACROS[i].disabled && !strcmp(name, MACROS[i].name)) {
579-
MACROS[i].disabled = true;
580-
return true;
581-
}
581+
macro_t *ma = hashmap_get(MACROS_MAP, name);
582+
if (ma && !ma->disabled) {
583+
ma->disabled = true;
584+
return true;
582585
}
583586
return false;
584587
}
@@ -974,7 +977,7 @@ void global_init(void)
974977
{
975978
elf_code_start = ELF_START + elf_header_len;
976979

977-
MACROS = malloc(MAX_ALIASES * sizeof(macro_t));
980+
MACROS_MAP = hashmap_create(MAX_ALIASES);
978981
TYPES = malloc(MAX_TYPES * sizeof(type_t));
979982
BLOCK_ARENA = arena_init(DEFAULT_ARENA_SIZE);
980983
INSN_ARENA = arena_init(DEFAULT_ARENA_SIZE);
@@ -996,7 +999,7 @@ void global_init(void)
996999

9971000
void global_release(void)
9981001
{
999-
free(MACROS);
1002+
hashmap_free(MACROS_MAP);
10001003
free(TYPES);
10011004
arena_free(BLOCK_ARENA);
10021005
arena_free(INSN_ARENA);

0 commit comments

Comments
 (0)