0
点赞
收藏
分享

微信扫一扫

用 clang 编译成 IR 汇编 和 目标机器汇编语言文件

年迈的代码机器 2022-05-04 阅读 78
linuxcmake
$ clang -emit-llvm -c sum.c -o sum.bc
$ clang -emit-llvm  -S -c sum.c -o sum.ll
$ clang  -S  sum.c -o sum.asm

一,C源文件

sum.c

int sum(int x, int y){
        return x+y;
}

二,LLVM IR 汇编

//$ cat sum.ll
; ModuleID = 'sum.c'
source_filename = "sum.c"
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32 @sum(i32, i32) #0 {
  %3 = alloca i32, align 4
  %4 = alloca i32, align 4
  store i32 %0, i32* %3, align 4
  store i32 %1, i32* %4, align 4
  %5 = load i32, i32* %3, align 4
  %6 = load i32, i32* %4, align 4
  %7 = add nsw i32 %5, %6
  ret i32 %7
}

attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"wchar_size", i32 4}
!1 = !{!"clang version 7.0.0 (tags/RELEASE_700/final)"}

IR 的语言规范比较复杂,除了可以看LLVM的官方文档外,也可以参考编译器虎书《现代编译原理 C语言描述》第19章:静态单赋值形式

三,目标机器汇编语言 x86

//$ cat sum.asm
        .text
        .file   "sum.c"
        .globl  sum                     # -- Begin function sum
        .p2align        4, 0x90
        .type   sum,@function
sum:                                    # @sum
        .cfi_startproc
# %bb.0:
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset %rbp, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register %rbp
        movl    %edi, -4(%rbp)
        movl    %esi, -8(%rbp)
        movl    -4(%rbp), %esi
        addl    -8(%rbp), %esi
        movl    %esi, %eax
        popq    %rbp
        .cfi_def_cfa %rsp, 8
        retq
.Lfunc_end0:
        .size   sum, .Lfunc_end0-sum
        .cfi_endproc
                                        # -- End function

        .ident  "clang version 7.0.0 (tags/RELEASE_700/final)"
        .section        ".note.GNU-stack","",@progbits
        .addrsig
        .addrsig_sym sum

其中目标机器的汇编语言格式,是llvm特定的规范组织而成的文件。这样可以由llvm中的工具llvm-mc 来处理机器汇编语言文件,翻译成 机器语言的目标文件。

规范说明文档:

LLVM Extensions — LLVM 15.0.0git documentationhttps://llvm.org/docs/Extensions.html

举报

相关推荐

0 条评论