Skip to content

Add a br_unless instruction. - #481

Closed
sunfishcode wants to merge 1 commit into
masterfrom
br_unless
Closed

sunfishcode wants to merge 1 commit into
masterfrom
br_unless

Conversation

@sunfishcode

Copy link
Copy Markdown
Member

This is the same as br_if, but with an inverted condition.

This is useful for low-level tools that wish to invert a branch condition in place, for example to rearrange basic blocks while being otherwise minimally invasive. Having both br_if and br_unless means that this is possible just by rewriting the opcode. If course, it is possible to invert a condition explicitly without this, although in many cases it requires inserting new AST nodes.

@jfbastien

Copy link
Copy Markdown
Member

I'm not sure I like this: compilers can have their own IR where this is easy but I don't think we necessarily want WebAssembly to have it. IMO the format isn't designed to support low-level tools: these have to understand the WebAssembly format already so having an internal representation and a writer isn't that onerous.

Similarly, LLVM has comparisons for eq/ne/... and it has true/false comparisons. I see this change as analogous to adding true/false comparisons: useful for low-level tools, but IMO wrong abstraction level for WebAssembly's opcodes.

WDYT?

@kripken

kripken commented Nov 25, 2015

Copy link
Copy Markdown
Member

It seems that for consistency, if we have br_if and br_unless, we should also have if and unless (where unless is like if, but executes the code if the condition is false)? I'm not sure I like that.

Since we do have the negations of the relational ops (both == and !=, etc.), in which cases is another node actually needed? Just for the case of the br_if receiving a direct i32, I suppose, instead of a comparison result? If that's very common perhaps it could justify this.

@sunfishcode

Copy link
Copy Markdown
Member Author

We don't have the negations of all the floating-point comparisons (currently). And since we don't have a bool type, the condition is an i32, which means the value will sometimes come from a get_local, so the code for reversing the condition will have to know multiple tricks, and still have to insert new instructions in some cases.

It's also worth mentioning that this change closely echos constructs present in many ISAs, which commonly have both "branch on zero" and "branch on non-zero" instructions. They give compilers full flexibility to put blocks in whatever order they like (eg. to optimize for fall-through paths) without having to weigh the benefits against inserting new instructions.

I wouldn't necessarily be opposed to adding an unless instruction, which would be to if what br_unless if to br_if.

@kripken

kripken commented Nov 26, 2015

Copy link
Copy Markdown
Member

Fair points. But I feel that the motivation here could equally support adding the missing floating-point comparisons, plus adding i32.not. That's just one new instruction instead of br_unless and unless, and i32.not could be useful for more things too.

But again, if br_unless/unless would be very common, then maybe avoiding the extra not would justify adding them.

In asm2wasm, btw, I could in some cases work around the lack of i32.not/br_unless by branching to a different label. But I agree that's annoying.

@sunfishcode

Copy link
Copy Markdown
Member Author

@kripken In my prototyping of this feature, br_unless is quite common. For example, in a CFG diamond, LLVM CodeGen chooses which block gets to be the fallthrough from the conditional branch by consulting profiling information if available, or static heuristics otherwise. The result is that conditions are quite often reversed. br_unless makes it very natural to perform these kinds of low-level block ordering optimizations since we don't have to worry about the tradeoffs of inserting nots while doing so.

@kripken

kripken commented Nov 28, 2015

Copy link
Copy Markdown
Member

Interesting. Is it easy to see which proportion of those would actually require a not?

@ghost

ghost commented Nov 28, 2015

Copy link
Copy Markdown

@kripken It may well help with the text source code to have separate opcodes here. If a canonicalization of the br and test occurs there would be an information loss.

@sunfishcode

Copy link
Copy Markdown
Member Author

I got an in-person lgtm from @jfbastien for this proposal.

@jfbastien

Copy link
Copy Markdown
Member

Virtual lgtm as well. @sunfishcode showed me the different code that gets emitted by LLVM with/without this feature and it's much cleaner to have both.

@kripken

kripken commented Dec 4, 2015

Copy link
Copy Markdown
Member

I did some measurements for this, on bananabread converted with binaryen. I looked at a random 20 out of 3,225 br_ifs. 90% could be flipped (< to >=, etc.), while 2 were direct checks of a getlocal, which could only be trivially flipped if we had br_unless.

@ghost

ghost commented Jan 8, 2016

Copy link
Copy Markdown

@kripken Any change of opinion here?

@kripken

kripken commented Jan 8, 2016

Copy link
Copy Markdown
Member

I agree this has reasonable motivations. My only real concern here is consistency with the rest of the spec. Maybe the simplest solution to keep that consistency is, as discussed above, to add both br_unless and unless (a reversed if), so that we maintain a parallel to br_if and if. How does that sound, @sunfishcode?

@titzer

titzer commented Jan 8, 2016

Copy link
Copy Markdown

IMO an "unless" instruction is not necessary, since one can simply express this with if(!cond) nop else expr

@ghost

ghost commented Jan 8, 2016

Copy link
Copy Markdown

@titzer The if operation is defined to return no values whereas if_else returns a value. I recall a discussion about a nop in an if_else branch but it might not have been resolved and might not be valid if the other branch returns values so would need (if (!cond) (nop) (block expr (nop))).

Neither br_unless or unless are necessary. The opening message in this PR mentions this and requests br_unless as a convenience to the producer. I see the unless pattern in asm2wasm generated code, and adding one opcode for this and using it decreases the v8 encoded binary size by 3 bytes per instance, and the brotli compressed size decreased too with a suitable number of the opcode.

Just wanted to test the consensus on this one again - would like it from a source-code point of view too.

@ghost

ghost commented Jan 8, 2016

Copy link
Copy Markdown

@titzer Sorry, looking at the type issue I see it's not a problem and your proposal would work, at a savings of 2 bytes per instance. I thinks it's just requested as a convenience.

@kripken

kripken commented Jan 8, 2016

Copy link
Copy Markdown
Member

@titzer: technically yes, however

  1. Your exact argument can also work against br_unless. In other words, both br_unless and unless are not strictly necessary, but both are nice to have.
  2. The spec seems odd with if, br_if, br_unless, since if and br_if are clearly parallel - both in name and in function - yet we would be missing a parallel for br_unless.
  3. The construct you mention depends on nop remaining in the spec, which some people want to remove; depending on it here would add a constraint.

@titzer

titzer commented Jan 11, 2016

Copy link
Copy Markdown

@kripken

  1. Agree. At this point both br_unless and unless are encoder conveniences, since no one has yet built a simple JIT for which we seem to be designing.
  2. Agree. I'm not sure what mode we are in here. Are we in encoding convenience mode or simplification mode? We've got outstanding proposals that go in both directions.
  3. nop is also used for the value to expression "no value" for the value-producing br_if and br, and that's not just a binary format issue.

@sunfishcode

Copy link
Copy Markdown
Member Author

@titzer Following up on #554 (comment) and offline discussions, would you mind taking another look at this PR?

@rossberg

Copy link
Copy Markdown
Member

With agreement on not, do we really need this?

@titzer

titzer commented Feb 25, 2016

Copy link
Copy Markdown

I won't fight strongly against br_unless; it won't be much work to support it.

@lukewagner

Copy link
Copy Markdown
Member

I like br_unless since it reflects the underlying machine and avoids adding the need to pattern match in a dumb compiler to fold the negation into the condition code check. I expect this is fairly common so it might also give a small layer 0 size boost; it'd nice to measure this with the current binary encoding.

@kripken

kripken commented Feb 26, 2016

Copy link
Copy Markdown
Member

Same rationale works for unless, plus it maintains symmetry and consistency. So let's add both, as suggested above?

@titzer

titzer commented Feb 26, 2016

Copy link
Copy Markdown

unless would only be useful in the 1-arm if case, since in the 2-arm if
case, you can simply swap the true and false cases. IMO that makes unless
less attractive.

On Fri, Feb 26, 2016 at 12:15 PM, Alon Zakai [email protected]
wrote:

Same rationale works for unless, plus it maintains symmetry and
consistency. So let's add both, as suggested above?

—
Reply to this email directly or view it on GitHub
#481 (comment).

@kripken

kripken commented Feb 26, 2016

Copy link
Copy Markdown
Member

Agreed, that reduces the usefulness a little, but 1-arm cases are over 50% in my measurements. So this would still be quite useful, in addition to maintaining consistency in the spec.

@ghost

ghost commented Feb 26, 2016

Copy link
Copy Markdown

I believe my results also support the utility of unless. The results below are for the zlib benchmark, compiler with the llvm backend and then the br_if's translated to if and if_else for some familiar patterns, and finally a translation of if to unless. Note that unless has a higher frequency than if_else.

block                            819     2.62
br_if                            685     2.19
if                               551     1.77
br                               387     1.24
unless                           141     0.45
if_else                           88     0.28

@qwertie

qwertie commented Feb 28, 2016

Copy link
Copy Markdown

Just a thought. I think I read somewhere that (x86) when the branch target buffer is missing a cache entry for a conditional branch, it assumes the branch will not be taken and moreover the btb is left unmodified if the prediction is correct (that's a good thing, as it leaves more cache space for other branches). I've taken advantage of this when writing code like

if cond:
   f()
   return
else:
  g()
  return

What I do is, I put the most likely branch first. But if my compiler swaps "if" and "else" branches, this optimization is defeated. Therefore if we only pick one, I'd rather have a i32.eqz than an "unless" instruction, unless there is a matching "unless_else" with two branches.

@pizlonator

Copy link
Copy Markdown
Contributor

The compiler is extremely likely to flip the order of those basic blocks. The compilers that I'm familiar with will forget and then rebuild the order of blocks based on some tried-and-true heuristics.

-Filip

On Feb 27, 2016, at 6:25 PM, David Piepgrass [email protected] wrote:

Just a thought. I think I read somewhere that (x86) when the branch target buffer is missing a cache entry for a conditional branch, it assumes the branch will not be taken and moreover the btb is left unmodified if the prediction is correct. I've taken advantage of this when writing code like

if cond:
f()
return
else:
g()
return
What I do is, I put the most likely branch first. But if my compiler swaps "if" and "else" branches, this optimization is defeated. Therefore if we only pick one, I'd rather have a i32.eqz than an "unless" instruction, unless there is a matching "unless_else" with two branches.

—
Reply to this email directly or view it on GitHub.

@ghost

ghost commented Feb 28, 2016

Copy link
Copy Markdown

Looking at the comments there does appear to be consensus to add br_unless, or no significant objections except requests to also add an unless operator to balance it but perhaps it is fair to split that out into a separate PR see #565 and allow this to land.

@pizlonator

Copy link
Copy Markdown
Contributor

I'm not opposed to it.

-Filip

On Feb 28, 2016, at 12:14 AM, JSStats [email protected] wrote:

Looking at the comments there does appear to be consensus to add br_unless, or no significant objections except requests to also add an unless operator to balance it but perhaps it is fair to split that out into a separate PR see #565 and allow this to land.

—
Reply to this email directly or view it on GitHub.

@kripken

kripken commented Feb 28, 2016

Copy link
Copy Markdown
Member

I strongly disagree, we should not split out br_unless.

if is a direct parallel to br_if, and all arguments in favor of adding an unless version to one also apply to the other. Literally. Therefore we should add unless to neither or to both, in order to keep the spec symmetrical, consistent, and unsurprising.

Furthermore, the parallel is not just conceptual, but also practical - binaryen for example has optimizations that can convert between ifs and br_ifs, so if we have an unless version of just one then we have an odd limitation there.

I am in favor of adding both, since I think a reasonable argument has been made in this pull.

@sunfishcode

Copy link
Copy Markdown
Member Author

I don't have a strong opinion about unless, so unless someone has strong opinions against it, I'll add it to this PR, once if and if_else are merged (WebAssembly/spec#257, and we'll need a corresponding design PR too).

@ghost

ghost commented Feb 29, 2016

Copy link
Copy Markdown

@sunfishcode If there is consensus to add both br_unless and unless then can we please do it now rather than waiting on future PR's - take the opportunity.

@rossberg

Copy link
Copy Markdown
Member

To be honest, I'm not fond of br_unless, and I'm even less fond of unless. There are many other special branch instructions that are directly supported by CPUs and which we could introduce along similar lines, but I don't think creating a zoo here is an improvement. IMO br_unless is taking us on that slippery slope. The motivation in the original comment also seems rather hypothetical.

Can we perhaps wait until after we gained some experience with the MVP before we broaden the operator set in this direction? I don't think there is pressure to do it now.

@ghost

ghost commented Feb 29, 2016

Copy link
Copy Markdown

@rossberg-chromium They are just convenience operators, and not necessary, but there is evidence that they are both common patterns. What other 'special branch instructions that are directly supported by CPUs' do you suggest are in the same class of being so frequent?

It seems only a small step and not the start of adding endless convenience control flow operators. There might be some other patterns to consider such as and (sequential if_else) but it's not endless.

There is a chunk of code in the llvm backend to do this inversion as cleanly as possible, and I see a need for this when converting between br_if and if style, so it does not seem 'hypothetical'. They are common patterns.

There seems to otherwise be consensus. What results from the MVP 'experience' do you need to make a decision? Can we measure this for you now?

This is the same as br_if except with an inverted condition.
@sunfishcode

Copy link
Copy Markdown
Member Author

This idea did not achieve consensus.

@lukewagner
lukewagner deleted the br_unless branch September 7, 2016 18:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants