[LLVMdev] Failure to optimize ? operator

Brent Walker brenthwalker at gmail.com
Tue Dec 13 05:59:28 PST 2011


The following seemingly identical functions, get compiled to quite
different machine code.  The first is correctly optimized (the
computation of var y is nicely moved into the else branch of the "if"
statement), which the second one is not (the full computation of var y
is always done).  The output was produced using the demo page on
llvm's web site (optimization level LTO).

Can someone shed some light on this strange behavior?

Thanks,
Brent

===============================================================
int f1(int x) {
  int y = 5*x*x*x+2*x*x+3*x+1;

  if (x > 0)
    return 0;
  else
     return y;
}

int f2(int x) {
  int y = 5*x*x*x+2*x*x+3*x+1;

  return x > 0 ? 0 : y;
}

================================================================
Output from llvm disassembler targeting LLVM assembly

; ModuleID = '/tmp/webcompile/_11262_0.bc'
target datalayout =
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
target triple = "x86_64-unknown-linux-gnu"

define i32 @f1(i32 %x) nounwind readnone {
; <label>:0
  %1 = icmp sgt i32 %x, 0
  br i1 %1, label %7, label %2

; <label>:2                                       ; preds = %0
  %3 = mul i32 %x, 5
  %tmp = add i32 %3, 2
  %tmp1 = mul i32 %tmp, %x
  %4 = add i32 %tmp1, 3
  %5 = mul i32 %4, %x
  %6 = add nsw i32 %5, 1
  br label %7

; <label>:7                                       ; preds = %2, %0
  %.0 = phi i32 [ %6, %2 ], [ 0, %0 ]
  ret i32 %.0
}

define i32 @f2(i32 %x) nounwind readnone {
  %1 = mul i32 %x, 5
  %tmp = add i32 %1, 2
  %tmp1 = mul i32 %tmp, %x
  %2 = add i32 %tmp1, 3
  %3 = mul i32 %2, %x
  %4 = add nsw i32 %3, 1
  %5 = icmp sgt i32 %x, 0
  %6 = select i1 %5, i32 0, i32 %4
  ret i32 %6
}
===================================================



More information about the llvm-dev mailing list