Are there extensions to let optimizers assume const-ref parameters will stay const?

前端 未结 2 1186
旧巷少年郎
旧巷少年郎 2021-02-14 03:58

Related to my former question: Are compilers not allowed to assume const-ref parameters will stay const?

My new question is: Is there compiler-specific, non-standard ext

2条回答
  •  日久生厌
    2021-02-14 04:54

    I do not know of non-standard ways to permit the compiler to assume immutability, but if I read the standard correctly, I think there is a standard way to do so (adapted from your other question):

    void f(const int&);
    
    struct ImmutableInt {
        // it is UB to change val, because it is itself const
        // not just a const reference
        const int val;    
    };
    
    void g3(const ImmutableInt & i) {
        if (i.val == 42) f(i.val);
        if (i.val == 42) f(i.val); // the compiler could assume i.val has not changed
    }
    

    The problem is, currently the compilers I checked do not make use of this knowledge to actually omit reloading the value.

    I do not think there are any fundamental problems with this, because clang uses similar and more complicated reasoning about the virtual table pointer to achieve devirtualization. This reasoning is somewhat more complicated because the vptr will change during construction and is therefore not entirely const. The llvm metadata used for this is called invariant.group, but I do not know if you can set it yourself in C++.

提交回复
热议问题