Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Last active June 4, 2019 03:13
Show Gist options
  • Save kaityo256/95276045de818bb899c1ea0b03f41f8c to your computer and use it in GitHub Desktop.
Save kaityo256/95276045de818bb899c1ea0b03f41f8c to your computer and use it in GitHub Desktop.
Constant folding and loop unrolling
n = ARGV[0].to_i
s = (1..n).to_a.map { |i| i.to_s }.join(",")
s = "{" + s + "}"
puts <<"EOS"
#include <cstdio>
const int N = #{n};
const int a[] = #{s};
int func(int b[N]) {
int sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i] * b[i];
}
return sum;
}
int main() {
int b[] = #{s};
printf("%d\\n", func(b));
}
EOS
@kaityo256
Copy link
Author

$ ruby dump.rb 10 > test.cpp  
$ clang++ -O3 test.cpp -S
_main:                                  ## @main
        .cfi_startproc
## %bb.0:
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset %rbp, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register %rbp
        leaq    L_.str(%rip), %rdi
        movl    $385, %esi              ## imm = 0x181
        xorl    %eax, %eax
        callq   _printf
        xorl    %eax, %eax
        popq    %rbp
        retq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment