Search code examples
compiler-constructionllvmllvm-clang

The structure of a branch instruction


I am currently building a static analyzer for 'llvm-ir' and working on branch instructions. The 'condition' of a branch instruction seems to be either a result of a compare instruction, or a result of some logical operations of a compare instruction, which looks like

 %cmp1377 = icmp sgt i32 %length, 0
 br i1 %cmp1377, label %for.cond14.preheader.lr.ph, label %for.cond.cleanup

or probably like

%cmp2 = icmp slt i32 %rem, %div1
%cmp3 = icmp slt i32 %div, %div1
%or.cond = or i1 %cmp2, %cmp3
br i1 %or.cond, label %if.then9, label %lor.lhs.false4

But I'm not sure whether if LLVM-IR only uses compared values or it might also just use raw integer values. Is there any documentation that I can find how it constructs the condition of the branch instructions?


Solution

  • Condition for br instruction can be any value of type i1, no matter it comes from a comparison, logical operation or load from a global variable.

    It is possible for clang to generate either of such instructions. For example, for code:

    int f1(bool* a){
      if ( *a ){
        return 12;
      }else{
        return 15;
      }
    }
    

    It generates the following llvm-ir:

    define i32 @f(bool*)(i8* %a) #0 {
      %1 = alloca i32, align 4
      %2 = alloca i8*, align 8
      store i8* %a, i8** %2, align 8
      %3 = load i8*, i8** %2, align 8
      %4 = load i8, i8* %3, align 1
      %5 = trunc i8 %4 to i1                  ;;condition value
      br i1 %5, label %6, label %7            ;;br instruction
    
    ; <label>:6                                      
      store i32 12, i32* %1
      br label %8
    
    ; <label>:7                                      
      store i32 15, i32* %1
      br label %8
    
    ; <label>:8                                       
      %9 = load i32, i32* %1
      ret i32 %9
    }