effect of goto on C++ compiler optimization

后端 未结 4 2315
执笔经年
执笔经年 2021-02-18 21:26

What are the performance benefits or penalties of using goto with a modern C++ compiler?

I am writing a C++ code generator and use of

4条回答
  •  遥遥无期
    2021-02-18 21:55

    How do you think that loops are represented, at the assembly level ?

    Using jump instructions to labels...

    Many compilers will actually use jumps even in their Intermediate Representation:

    int loop(int* i) {
      int result = 0;
      while(*i) {
        result += *i;
      }
      return result;
    }
    
    int jump(int* i) {
      int result = 0;
      while (true) {
        if (not *i) { goto end; }
        result += *i;
      }
    
    end:
      return result;
    }
    

    Yields in LLVM:

    define i32 @_Z4loopPi(i32* nocapture %i) nounwind uwtable readonly {
      %1 = load i32* %i, align 4, !tbaa !0
      %2 = icmp eq i32 %1, 0
      br i1 %2, label %3, label %.lr.ph..lr.ph.split_crit_edge
    
    .lr.ph..lr.ph.split_crit_edge:                    ; preds = %.lr.ph..lr.ph.split_crit_edge, %0
      br label %.lr.ph..lr.ph.split_crit_edge
    
    ; 

    Where br is the branch instruction (a conditional jump).

    All optimizations are performed on this structure. So, goto is the bread and butter of optimizers.

提交回复
热议问题