From ed00fd3b8624d49899af3abd9f5c2bcdcca926c9 Mon Sep 17 00:00:00 2001 From: anastasosmoho Date: Thu, 10 Sep 2026 16:32:05 +0000 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2=20=C2=AB?= =?UTF-8?q?/=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Mihaylova228.md | 289 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 Mihaylova228.md diff --git a/Mihaylova228.md b/Mihaylova228.md new file mode 100644 index 0000000..428d95a --- /dev/null +++ b/Mihaylova228.md @@ -0,0 +1,289 @@ +Михайлова Практическая 228 группа +Отчет по 1 практическому заданию +Подготовка к заданию: +1. Откройте godbolt.org (https://godbolt.org/). +2. В левой панели выберите язык: C. +3. В правой панели добавьте два компилятора (кнопка + Add new...): +x86-64 GCC 14.1 (или последняя доступная версия) +x86-64 Clang 18.1 (или последняя доступная версия) +4. Для обоих компиляторов в Compiler options введите: +-O2 -masm=intel -fno-verbose-asm +5. Снимите галочки с Directives и Comments в фильтрах (Filter...), чтобы видеть только "чистый" ассемблер. +Ход работы: +1. Задание 1. Заставь компилятор использовать idiv" +Напишите на C функцию, которая делит переменную на другую переменную (не константу). Убедитесь в Godbolt, что появилась инструкция idiv (или sdiv в ARM) и инструкция подготовки cqo (или sdiv с расширением). +long math_ops(long a, long b) +{ + return a/b; +} + +Далее заходим в инструкция idiv (или sdiv в ARM) и инструкция подготовки cqo (или sdiv с расширением). +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .p2align 4 + .globl math_ops + .type math_ops, @function +math_ops: +.LFB0: + .file 1 "/app/example.c" + .loc 1 2 1 view -0 + .cfi_startproc + .loc 1 3 5 view .LVU1 + .loc 1 2 1 is_stmt 0 view .LVU2 + mov rax, rdi + .loc 1 3 13 view .LVU3 + cqo + idiv rsi вот онииии + .loc 1 4 1 view .LVU4 + ret + .cfi_endproc +2. Задание 2. "Побитовая магия" +Напишите функцию, которая меняет местами старший и младший байты в 16-битном числе (например, 0x1234 -> 0x3412). Используйте только побитовые операции (&, |, <<, >>). +unsigned short swap_bytes(unsigned short a) +{ + return (a >> 8)|(a << 8); + +} + +Смотрим, сгенерирует ли компилятор инструкцию rol/ror (rotate) или оставит сдвиги. +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .p2align 4 + .globl swap_bytes + .type swap_bytes, @function +swap_bytes: +.LFB0: + .file 1 "/app/example.c" + .loc 1 2 1 view -0 + .cfi_startproc + .loc 1 3 5 view .LVU1 + .loc 1 3 20 is_stmt 0 view .LVU2 + mov eax, edi + rol ax, 8 + .loc 1 5 1 view .LVU3 + ret + .cfi_endproc +3. Задание 3. "ARM64 взгляд" +Переключите один из компиляторов в Godbolt на ARM64 GCC. Посмотрите на ту же функцию деления. Найдите инструкцию sdiv. Обратите внимание, насколько "чище" и линейнее код ARM64 по сравнению с x86-64 из-за отсутствия скрытых регистров. +long math_ops(long a, long b) +{ + return a/b; +} + + +.arch armv8-a + .file "example.c" +// GNU C23 (GCC) version 16.1.0 (aarch64-unknown-linux-gnu) +// compiled by GNU C version 16.0.1 20260421 (experimental), GMP version 6.3.0, MPFR version 4.2.2, MPC version 1.3.1, isl version isl-0.19-GMP + +// GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +// options passed: -mlittle-endian -mabi=lp64 -g + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .align 2 + .global math_ops + .type math_ops, %function +math_ops: +.LFB0: + .file 1 "/app/example.c" + .loc 1 2 1 + .cfi_startproc + sub sp, sp, #16 //,, + .cfi_def_cfa_offset 16 + str x0, [sp, 8] // a, a + str x1, [sp] // b, b +// /app/example.c:3: return a/b; + .loc 1 3 13 + ldr x1, [sp, 8] // tmp103, a + ldr x0, [sp] // tmp104, b + sdiv x0, x1, x0 // _3, tmp103, tmp104 +// /app/example.c:4: } + .loc 1 4 1 + add sp, sp, 16 //,, +4. Задание 4. Исследование lea: Найдите в интернете, почему инструкция lea может выполнять сложение и умножение одновременно, но не может выполнять вычитание или деление. Напишите в Godbolt пример, где компилятор использует lea для умножения на 3, 5 и 9. +long mult_3(long x) { return x * 3; } +long mult_5(long x) { return x * 5; } +long mult_9(long x) { return x * 9; } +mult_3: +.LFB0: + .file 1 "/app/example.c" + .loc 1 1 21 + .cfi_startproc + sub sp, sp, #16 //,, + .cfi_def_cfa_offset 16 + str x0, [sp, 8] // x, x +// /app/example.c:1: long mult_3(long x) { return x * 3; } + .loc 1 1 32 + ldr x1, [sp, 8] // tmp103, x + mov x0, x1 // tmp104, tmp103 + lsl x0, x0, 1 // tmp104, tmp104, + add x0, x0, x1 // _2, tmp104, tmp103 +// /app/example.c:1: long mult_3(long x) { return x * 3; } + .loc 1 1 37 + add sp, sp, 16 //,, + .cfi_def_cfa_offset 0 + ret + .cfi_endproc +.LFE0: + .size mult_3, .-mult_3 + .align 2 + .global mult_5 + .type mult_5, %function +mult_5: +.LFB1: + .loc 1 2 21 + .cfi_startproc + sub sp, sp, #16 //,, + .cfi_def_cfa_offset 16 + str x0, [sp, 8] // x, x +// /app/example.c:2: long mult_5(long x) { return x * 5; } + .loc 1 2 32 + ldr x1, [sp, 8] // tmp103, x + mov x0, x1 // tmp104, tmp103 + lsl x0, x0, 2 // tmp104, tmp104, + add x0, x0, x1 // _2, tmp104, tmp103 +// /app/example.c:2: long mult_5(long x) { return x * 5; } + .loc 1 2 37 + add sp, sp, 16 //,, + .cfi_def_cfa_offset 0 + ret + .cfi_endproc +.LFE1: + .size mult_5, .-mult_5 + .align 2 + .global mult_9 + .type mult_9, %function +mult_9: +.LFB2: + .loc 1 3 21 + .cfi_startproc + sub sp, sp, #16 //,, + .cfi_def_cfa_offset 16 + str x0, [sp, 8] // x, x +// /app/example.c:3: long mult_9(long x) { return x * 9; } + .loc 1 3 32 + ldr x1, [sp, 8] // tmp103, x + mov x0, x1 // tmp104, tmp103 + lsl x0, x0, 3 // tmp104, tmp104, + add x0, x0, x1 // _2, tmp104, tmp103 +// /app/example.c:3: long mult_9(long x) { return x * 9; } + .loc 1 3 37 + add sp, sp, 16 //,, + .cfi_def_cfa_offset 0 + ret + .cfi_endproc +Задание 5. Сравнение оптимизаций: Возьмите функцию вычисления факториала (циклом, не рекурсией). Скомпилируйте её с -O0, -O1, -O2, -O3. Сохраните 4 ссылки на Godbolt. Опишите, на каком уровне оптимизации цикл превращается в формулу или полностью разворачивается (unrolling). +long factorial(int n) +{ + long res = 1; + for (int i = 1; i <= n; ++i) + { + res *= i; + } + return res; +} + + +Скомпилируйте её с -O0 +-O0 -masm=intel -fno-verbose-asm +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .globl factorial + .type factorial, @function +factorial: +.LFB0: + .file 1 "/app/example.c" + .loc 1 1 23 + .cfi_startproc + push rbp + .cfi_def_cfa_offset 16 + .cfi_offset 6, -16 + mov rbp, rsp + .cfi_def_cfa_register 6 + mov DWORD PTR [rbp-20], edi + .loc 1 2 10 + mov QWORD PTR [rbp-8], 1 +-O1, +-O1 -masm=intel -fno-verbose-asm +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .globl factorial + .type factorial, @function +factorial: +.LVL0: +.LFB0: + .file 1 "/app/example.c" + .loc 1 1 23 view -0 + .cfi_startproc + .loc 1 2 5 view .LVU1 + .loc 1 3 5 view .LVU2 +.LBB2: + .loc 1 3 10 view .LVU3 + .loc 1 3 23 discriminator 1 view .LVU4 + test edi, edi + jle .L4 + lea ecx, [rdi+1] + mov eax, 1 +-O2 +-O2 -masm=intel -fno-verbose-asm +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .p2align 4 + .globl factorial + .type factorial, @function +factorial: +.LVL0: +.LFB0: + .file 1 "/app/example.c" + .loc 1 1 23 view -0 + .cfi_startproc + .loc 1 2 5 view .LVU1 + .loc 1 3 5 view .LVU2 +.LBB2: + .loc 1 3 10 view .LVU3 + .loc 1 3 23 discriminator 1 view .LVU4 + test edi, edi + jle .L4 + lea esi, [rdi+1] + and edi, 1 +-O3 +-O3 -masm=intel -fno-verbose-asm +.file "example.c" + .intel_syntax noprefix + .text +.Ltext0: + .file 0 "/app" "/app/example.c" + .p2align 4 + .globl factorial + .type factorial, @function +factorial: +.LVL0: +.LFB0: + .file 1 "/app/example.c" + .loc 1 1 23 view -0 + .cfi_startproc + .loc 1 2 5 view .LVU1 + .loc 1 3 5 view .LVU2 +.LBB2: + .loc 1 3 10 view .LVU3 + .loc 1 3 23 discriminator 1 view .LVU4 + test edi, edi + jle .L4 + lea esi, [rdi+1] + and edi, 1