[LLVMdev] Re: how to code a loop in llvm assembly

Oscar Fuentes oscarfv at telefonica.net
Fri Apr 14 22:47:00 PDT 2006

Simon Burton <simon at arrowtheory.com> writes:

> Hi,
> I've read over the "LLVM Language Reference Manual"
> a few times, and writing some ll code, but i'm stuck at
> a very basic point. How to decrement a counter variable ?
> int %count(int %n) {
> EntryBlock:
>   %cond = seteq int %n, 0
>   br bool %cond, label %Exit, label %Next
> Next:
> ; how to decrement n ?
>   %new_n = sub int %n, 1
>   br label %EntryBlock
> Exit:
>   ret int 0
> }
> I guess I could malloc a variable and use store/load. Is that the right way ?
> Also the above code is invalid:
> Entry block to function must not have predecessors!
> label %EntryBlock
> Broken module found, compilation aborted!

You need a phi node.

A good way to learn how to write LLVM assembler is to use the online
demo available at http://llvm.org/demo/ You feed a C/C++/Stacker
program and you get the equivalent LLVM code. In this case, something
like this C code is necessary:

int foo(int n, int x) {
  while(n > x) --n;
  return n;

The extra stuff is for circumventing the optimizer. If you write

int foo(int n) {
  while(n) --n;
  return 0;

the optimizer will reduce it to a ret int 0, which teach us nothing.

An option for disabing optimizations would be very helpful for

BTW, Simon, is there a reason for writing LLVM assembler and not
generating LLVM code directly? The later is simpler and relieves you
from some nasty burdens. It doesn't require you to generate SSA
conformant code, for instance. Relating to your present problem, it is
"natural" to code a loop without resorting to phi nodes.


More information about the llvm-dev mailing list