Skip to content

Instantly share code, notes, and snippets.

@arosh
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arosh/ba91d3d76e199429c50e to your computer and use it in GitHub Desktop.
Save arosh/ba91d3d76e199429c50e to your computer and use it in GitHub Desktop.
fibonacci

環境

$ clang++ -version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

コンパイルオプション

$ clang++ -std=c++11 -O2 -S (source.cpp)

forループ版

ソースコード

int f(const int n) {
  int a = 0;
  int b = 1;
  for(int i = 0; i != n; ++i) {
    int c = a + b;
    a = b;
    b = c;
  }
  return a;
}

出力

	.section	__TEXT,__text,regular,pure_instructions
	.globl	__Z1fi
	.align	4, 0x90
__Z1fi:                                 ## @_Z1fi
	.cfi_startproc
## BB#0:
	pushq	%rbp
Ltmp2:
	.cfi_def_cfa_offset 16
Ltmp3:
	.cfi_offset %rbp, -16
	movq	%rsp, %rbp
Ltmp4:
	.cfi_def_cfa_register %rbp
	xorl	%ecx, %ecx
	testl	%edi, %edi
	je	LBB0_1
## BB#2:
	movl	$1, %edx
	.align	4, 0x90
LBB0_3:                                 ## %.lr.ph
                                        ## =>This Inner Loop Header: Depth=1
	movl	%edx, %eax
	movl	%ecx, %edx
	addl	%eax, %edx
	decl	%edi
	movl	%eax, %ecx
	jne	LBB0_3
## BB#4:                                ## %._crit_edge
	popq	%rbp
	retq
LBB0_1:
	xorl	%eax, %eax
	popq	%rbp
	retq
	.cfi_endproc


.subsections_via_symbols

rangeクラス版

namespace {
struct range {
  struct iter {
    int m_value;
    inline iter(const int value) : m_value(value) { }
    inline int operator*() const { return m_value; }
    inline bool operator!=(const iter & rhs) { return m_value != rhs.m_value; }
    inline void operator++() { ++m_value; }
  };
  const iter m_stop;
  inline range(const int stop) : m_stop(stop) { }
  inline iter begin() const { return iter(0); };
  inline iter end()   const { return m_stop; }
};
};

int f(const int n) {
  int a = 0;
  int b = 1;
  for(const int i : range(n)) {
    int c = a + b;
    a = b;
    b = c;
  }
  return a;
}

出力

	.section	__TEXT,__text,regular,pure_instructions
	.globl	__Z1fi
	.align	4, 0x90
__Z1fi:                                 ## @_Z1fi
	.cfi_startproc
## BB#0:
	pushq	%rbp
Ltmp2:
	.cfi_def_cfa_offset 16
Ltmp3:
	.cfi_offset %rbp, -16
	movq	%rsp, %rbp
Ltmp4:
	.cfi_def_cfa_register %rbp
	xorl	%ecx, %ecx
	testl	%edi, %edi
	je	LBB0_1
## BB#2:
	movl	$1, %edx
	.align	4, 0x90
LBB0_3:                                 ## %.lr.ph
                                        ## =>This Inner Loop Header: Depth=1
	movl	%edx, %eax
	movl	%ecx, %edx
	addl	%eax, %edx
	decl	%edi
	movl	%eax, %ecx
	jne	LBB0_3
## BB#4:                                ## %._crit_edge
	popq	%rbp
	retq
LBB0_1:
	xorl	%eax, %eax
	popq	%rbp
	retq
	.cfi_endproc


.subsections_via_symbols

結果

完全に一致

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