@@ -226,17 +226,51 @@ struct RemoveUnusedBrs : public WalkerPass<PostWalker<RemoveUnusedBrs>> {
226226 // we need the ifTrue to break, so it cannot reach the code we want to move
227227 if (ExpressionAnalyzer::obviouslyDoesNotFlowOut (iff->ifTrue )) {
228228 iff->ifFalse = builder.stealSlice (block, i + 1 , list.size ());
229+ iff->finalize ();
230+ block->finalize ();
229231 return true ;
230232 }
231233 } else {
232234 // this is already an if-else. if one side is a dead end, we can append to the other, if
233235 // there is no returned value to concern us
234236 assert (!isConcreteWasmType (iff->type )); // can't be, since in the middle of a block
237+
238+ // ensures the first node is a block, if it isn't already, and merges in the second,
239+ // either as a single element or, if a block, by appending to the first block. this
240+ // keeps the order of operations in place, that is, the appended element will be
241+ // executed after the first node's elements
242+ auto blockifyMerge = [&](Expression* any, Expression* append) -> Block* {
243+ Block* block = nullptr ;
244+ if (any) block = any->dynCast <Block>();
245+ // if the first isn't a block, or it's a block with a name (so we might
246+ // branch to the end, and so can't append to it, we might skip that code!)
247+ // then make a new block
248+ if (!block || block->name .is ()) {
249+ block = builder.makeBlock (any);
250+ } else {
251+ assert (!isConcreteWasmType (block->type ));
252+ }
253+ auto * other = append->dynCast <Block>();
254+ if (!other) {
255+ block->list .push_back (append);
256+ } else {
257+ for (auto * item : other->list ) {
258+ block->list .push_back (item);
259+ }
260+ }
261+ block->finalize ();
262+ return block;
263+ };
264+
235265 if (ExpressionAnalyzer::obviouslyDoesNotFlowOut (iff->ifTrue )) {
236- iff->ifFalse = builder.blockifyMerge (iff->ifFalse , builder.stealSlice (block, i + 1 , list.size ()));
266+ iff->ifFalse = blockifyMerge (iff->ifFalse , builder.stealSlice (block, i + 1 , list.size ()));
267+ iff->finalize ();
268+ block->finalize ();
237269 return true ;
238270 } else if (ExpressionAnalyzer::obviouslyDoesNotFlowOut (iff->ifFalse )) {
239- iff->ifTrue = builder.blockifyMerge (iff->ifTrue , builder.stealSlice (block, i + 1 , list.size ()));
271+ iff->ifTrue = blockifyMerge (iff->ifTrue , builder.stealSlice (block, i + 1 , list.size ()));
272+ iff->finalize ();
273+ block->finalize ();
240274 return true ;
241275 }
242276 }
0 commit comments