Search code examples
swiftcompiler-optimizationassertionscompiler-options

Which assertions are retained with wholemodule optimization mode?


All explanations of Swift assertions I can find explain that assert* gets thrown out with -O but precondition* are kept unless -Ounchecked is set.

However, we now have whole-module optimization -wmo as new default for release builds.

Are precondition* assertions retained when whole-module optimization is enabled?


Solution

  • Consider this small program:

    func f(_ i: Int) -> Int {
        assert(i > 0, "needed positive number")
        return i
    }
    
    print(f(0))
    

    Compiling it with xcrun swiftc [opt] and running the result gives:

    • -Onone: assertion error
    • -Onone -wmo: assertion error
    • -O: prints 0
    • -O -wmo: prints 0

    And in comparison:

    func f(_ i: Int) -> Int {
        precondition(i > 0, "needed positive number")
        return i
    }
    
    print(f(0))
    
    • -Onone: precondition error
    • -Onone -wmo: precondition error
    • -O: Illegal instruction: 4
    • -O -wmo: Illegal instruction: 4

    I can't quite explain the last two results, but it seems clear that whole-module optimization does not influence how assertions are handled; only the optimization level matters.


    This is on

    Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1)
    Target: x86_64-apple-macosx10.9