source: src/ControlStruct/MultiLevelExit.cpp@ 190a833

Last change on this file since 190a833 was 16ba4897, checked in by Andrew Beach <ajbeach@…>, 12 months ago

Replaced SemanticErrorException::isEmpty with ...::throwIfNonEmpty. This is how it was used in every context and it saves a bit of text (if not two lines) at every use. I considered putting this function in the header for better inlining, but this should have at least the same preformance as the last version.

  • Property mode set to 100644
File size: 24.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// MultiLevelExit.cpp -- Replaces CFA's local control flow with C's versions.
8//
9// Author : Andrew Beach
10// Created On : Mon Nov 1 13:48:00 2021
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Dec 14 17:34:12 2023
13// Update Count : 39
14//
15
16#include "MultiLevelExit.hpp"
17
18#include <set>
19
20#include "AST/Pass.hpp"
21#include "AST/Stmt.hpp"
22#include "LabelGenerator.hpp"
23
24using namespace std;
25using namespace ast;
26
27namespace ControlStruct {
28
29namespace {
30
31/// The return context is used to remember if returns are allowed and if
32/// not, why not. It is the nearest local control flow blocking construct.
33enum ReturnContext {
34 MayReturn,
35 InTryWithHandler,
36 InResumeHandler,
37 InFinally,
38};
39
40class Entry {
41 public:
42 const Stmt * stmt;
43 private:
44 // Organized like a manual ADT. Avoids creating a bunch of dead data.
45 struct Target {
46 Label label;
47 bool used = false;
48 Target( const Label & label ) : label( label ) {}
49 Target() : label( CodeLocation(), "" ) {}
50 };
51 Target firstTarget;
52 Target secondTarget;
53
54 enum Kind {
55 ForStmtK, WhileDoStmtK, CompoundStmtK, IfStmtK, CaseClauseK, SwitchStmtK, TryStmtK
56 } kind;
57
58 bool fallDefaultValid = true;
59
60 static Label & useTarget( Target & target ) {
61 target.used = true;
62 return target.label;
63 }
64 public:
65 Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
66 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
67 Entry( const WhileDoStmt * stmt, Label breakExit, Label contExit ) :
68 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileDoStmtK ) {}
69 Entry( const CompoundStmt *stmt, Label breakExit ) :
70 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
71 Entry( const IfStmt *stmt, Label breakExit ) :
72 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
73 Entry( const CaseClause *, const CompoundStmt *stmt, Label fallExit ) :
74 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseClauseK ) {}
75 Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
76 stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
77 Entry( const TryStmt *stmt, Label breakExit ) :
78 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
79
80 // Check if this entry can be the target of the given type of control flow.
81 bool isContTarget() const { return kind <= WhileDoStmtK; }
82 bool isBreakTarget() const { return kind != CaseClauseK; }
83 bool isFallTarget() const { return kind == CaseClauseK; }
84 bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
85
86 // Check if this entry can be the target of an unlabelled break.
87 bool isUnlabelledBreakTarget() const { return kind <= WhileDoStmtK || kind == SwitchStmtK; }
88
89 // These routines set a target as being "used" by a BranchStmt
90 Label useContExit() { assert( kind <= WhileDoStmtK ); return useTarget(secondTarget); }
91 Label useBreakExit() { assert( kind != CaseClauseK ); return useTarget(firstTarget); }
92 Label useFallExit() { assert( kind == CaseClauseK ); return useTarget(firstTarget); }
93 Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
94
95 // These routines check if a specific label for a statement is used by a BranchStmt
96 bool isContUsed() const { assert( kind <= WhileDoStmtK ); return secondTarget.used; }
97 bool isBreakUsed() const { assert( kind != CaseClauseK ); return firstTarget.used; }
98 bool isFallUsed() const { assert( kind == CaseClauseK ); return firstTarget.used; }
99 bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
100 void seenDefault() { fallDefaultValid = false; }
101 bool isFallDefaultValid() const { return fallDefaultValid; }
102};
103
104// Helper predicates used in find_if calls (it doesn't take methods):
105bool isBreakTarget( const Entry & entry ) {
106 return entry.isBreakTarget();
107}
108
109bool isContinueTarget( const Entry & entry ) {
110 return entry.isContTarget();
111}
112
113bool isFallthroughTarget( const Entry & entry ) {
114 return entry.isFallTarget();
115}
116
117bool isFallthroughDefaultTarget( const Entry & entry ) {
118 return entry.isFallDefaultTarget();
119}
120
121bool isUnlabelledBreakTarget( const Entry & entry ) {
122 return entry.isUnlabelledBreakTarget();
123}
124
125struct MultiLevelExitCore final :
126 public WithVisitorRef<MultiLevelExitCore>,
127 public WithShortCircuiting, public WithGuards {
128 MultiLevelExitCore( const LabelToStmt & lt );
129
130 void previsit( const FunctionDecl * );
131
132 const CompoundStmt * previsit( const CompoundStmt * );
133 const BranchStmt * postvisit( const BranchStmt * );
134 void previsit( const WhileDoStmt * );
135 const WhileDoStmt * postvisit( const WhileDoStmt * );
136 void previsit( const ForStmt * );
137 const ForStmt * postvisit( const ForStmt * );
138 const CaseClause * previsit( const CaseClause * );
139 void previsit( const IfStmt * );
140 const IfStmt * postvisit( const IfStmt * );
141 void previsit( const SwitchStmt * );
142 const SwitchStmt * postvisit( const SwitchStmt * );
143 void previsit( const ReturnStmt * );
144 void previsit( const TryStmt * );
145 void postvisit( const TryStmt * );
146 void previsit( const CatchClause * );
147 void previsit( const FinallyClause * );
148
149 const Stmt * mutateLoop( const Stmt * body, Entry& );
150
151 const LabelToStmt & target_table;
152 set<Label> fallthrough_labels;
153 vector<Entry> enclosing_control_structures;
154 Label break_label;
155 ReturnContext ret_context;
156
157 template<typename LoopNode>
158 void prehandleLoopStmt( const LoopNode * loopStmt );
159 template<typename LoopNode>
160 const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
161
162 list<ptr<Stmt>> fixBlock(
163 const list<ptr<Stmt>> & kids, bool caseClause );
164
165 void enterSealedContext( ReturnContext );
166
167 template<typename UnaryPredicate>
168 auto findEnclosingControlStructure( UnaryPredicate pred ) {
169 return find_if( enclosing_control_structures.rbegin(),
170 enclosing_control_structures.rend(), pred );
171 }
172};
173
174NullStmt * labelledNullStmt( const CodeLocation & cl, const Label & label ) {
175 return new NullStmt( cl, vector<Label>{ label } );
176}
177
178MultiLevelExitCore::MultiLevelExitCore( const LabelToStmt & lt ) :
179 target_table( lt ), break_label( CodeLocation(), "" ),
180 ret_context( ReturnContext::MayReturn )
181{}
182
183void MultiLevelExitCore::previsit( const FunctionDecl * ) {
184 visit_children = false;
185}
186
187const CompoundStmt * MultiLevelExitCore::previsit(
188 const CompoundStmt * stmt ) {
189 visit_children = false;
190
191 // if the stmt is labelled then generate a label to check in postvisit if the label is used
192 bool isLabeled = ! stmt->labels.empty();
193 if ( isLabeled ) {
194 Label breakLabel = newLabel( "blockBreak", stmt );
195 enclosing_control_structures.emplace_back( stmt, breakLabel );
196 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
197 }
198
199 auto mutStmt = mutate( stmt );
200 // A child statement may set the break label.
201 mutStmt->kids = fixBlock( stmt->kids, false );
202
203 if ( isLabeled ) {
204 assert( ! enclosing_control_structures.empty() );
205 Entry & entry = enclosing_control_structures.back();
206 if ( ! entry.useBreakExit().empty() ) {
207 break_label = entry.useBreakExit();
208 }
209 }
210 return mutStmt;
211}
212
213size_t getUnusedIndex( const Stmt * stmt, const Label & originalTarget ) {
214 const size_t size = stmt->labels.size();
215
216 // If the label is empty, do not add unused attribute.
217 if ( originalTarget.empty() ) return size;
218
219 // Search for a label that matches the originalTarget.
220 for ( size_t i = 0 ; i < size ; ++i ) {
221 const Label & label = stmt->labels[i];
222 if ( label == originalTarget ) {
223 for ( const Attribute * attr : label.attributes ) {
224 if ( attr->name == "unused" ) return size;
225 }
226 return i;
227 }
228 }
229 assertf( false, "CFA internal error: could not find label '%s' on statement %s",
230 originalTarget.name.c_str(), toString( stmt ).c_str() );
231}
232
233const Stmt * addUnused( const Stmt * stmt, const Label & originalTarget ) {
234 size_t i = getUnusedIndex( stmt, originalTarget );
235 if ( i == stmt->labels.size() ) {
236 return stmt;
237 }
238 Stmt * mutStmt = mutate( stmt );
239 mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
240 return mutStmt;
241}
242
243// This routine updates targets on enclosing control structures to indicate which
244// label is used by the BranchStmt that is passed
245const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
246 vector<Entry>::reverse_iterator targetEntry =
247 enclosing_control_structures.rend();
248
249 // Labels on different stmts require different approaches to access
250 switch ( stmt->kind ) {
251 case BranchStmt::Goto:
252 return stmt;
253 case BranchStmt::Continue:
254 case BranchStmt::Break: {
255 bool isContinue = stmt->kind == BranchStmt::Continue;
256 // Handle unlabeled continue.
257 if ( isContinue && stmt->target.empty() ) {
258 targetEntry = findEnclosingControlStructure( isContinueTarget );
259 if ( targetEntry == enclosing_control_structures.rend() ) {
260 SemanticError( stmt->location,
261 "\"continue\" outside a loop" );
262 }
263 // Handle unlabeled break.
264 } else if ( stmt->target.empty() ) {
265 targetEntry = findEnclosingControlStructure( isUnlabelledBreakTarget );
266 if ( targetEntry == enclosing_control_structures.rend() ) {
267 SemanticError( stmt->location,
268 "\"break\" outside a loop or \"switch\"" );
269 }
270 // Handle labeled break and continue.
271 } else {
272 // Lookup label in table to find attached control structure.
273 targetEntry = findEnclosingControlStructure(
274 [ targetStmt = target_table.at(stmt->target) ](auto entry){
275 return entry.stmt == targetStmt;
276 } );
277 // Ensure that selected target is valid.
278 if ( targetEntry == enclosing_control_structures.rend()
279 || ( isContinue ? !isContinueTarget( *targetEntry ) : !isBreakTarget( *targetEntry ) ) ) {
280 SemanticError( stmt->location, toString( (isContinue ? "\"continue\"" : "\"break\""),
281 " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
282 stmt->originalTarget ) );
283 }
284 }
285 break;
286 }
287 // handle fallthrough in case/switch stmts
288 case BranchStmt::FallThrough: {
289 targetEntry = findEnclosingControlStructure( isFallthroughTarget );
290 // Check that target is valid.
291 if ( targetEntry == enclosing_control_structures.rend() ) {
292 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
293 }
294 if ( ! stmt->target.empty() ) {
295 // Labelled fallthrough: target must be a valid fallthough label.
296 if ( ! fallthrough_labels.count( stmt->target ) ) {
297 SemanticError( stmt->location, toString( "\"fallthrough\" target must be a later case statement: ",
298 stmt->originalTarget ) );
299 }
300 return new BranchStmt( stmt->location, BranchStmt::Goto, stmt->originalTarget );
301 }
302 break;
303 }
304 case BranchStmt::FallThroughDefault: {
305 targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
306
307 // Check if in switch or choose statement.
308 if ( targetEntry == enclosing_control_structures.rend() ) {
309 SemanticError( stmt->location, "\"fallthrough\" must be enclosed in a \"switch\" or \"choose\"" );
310 }
311
312 // Check if switch or choose has default clause.
313 auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
314 bool foundDefault = false;
315 for ( auto caseStmt : switchStmt->cases ) {
316 if ( caseStmt->isDefault() ) {
317 foundDefault = true;
318 break;
319 }
320 }
321 if ( ! foundDefault ) {
322 SemanticError( stmt->location, "\"fallthrough default\" must be enclosed in a \"switch\" or \"choose\""
323 "control structure with a \"default\" clause" );
324 }
325 break;
326 }
327 default:
328 assert( false );
329 }
330
331 // Branch error checks: get the appropriate label name, which is always replaced.
332 Label exitLabel( CodeLocation(), "" );
333 switch ( stmt->kind ) {
334 case BranchStmt::Break:
335 assert( ! targetEntry->useBreakExit().empty() );
336 exitLabel = targetEntry->useBreakExit();
337 break;
338 case BranchStmt::Continue:
339 assert( ! targetEntry->useContExit().empty() );
340 exitLabel = targetEntry->useContExit();
341 break;
342 case BranchStmt::FallThrough:
343 assert( ! targetEntry->useFallExit().empty() );
344 exitLabel = targetEntry->useFallExit();
345 break;
346 case BranchStmt::FallThroughDefault:
347 assert( ! targetEntry->useFallDefaultExit().empty() );
348 exitLabel = targetEntry->useFallDefaultExit();
349 // Check that fallthrough default comes before the default clause.
350 if ( ! targetEntry->isFallDefaultValid() ) {
351 SemanticError( stmt->location, "\"fallthrough default\" must precede the \"default\" clause" );
352 }
353 break;
354 default:
355 assert(0);
356 }
357 assert( !exitLabel.empty() );
358
359 // Add unused attribute to silence warnings.
360 targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
361
362 // Replace with goto to make later passes more uniform.
363 return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
364}
365
366void MultiLevelExitCore::previsit( const WhileDoStmt * stmt ) {
367 return prehandleLoopStmt( stmt );
368}
369
370const WhileDoStmt * MultiLevelExitCore::postvisit( const WhileDoStmt * stmt ) {
371 return posthandleLoopStmt( stmt );
372}
373
374void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
375 return prehandleLoopStmt( stmt );
376}
377
378const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
379 return posthandleLoopStmt( stmt );
380}
381
382// Mimic what the built-in push_front would do anyways. It is O(n).
383void push_front( vector<ptr<Stmt>> & vec, const Stmt * element ) {
384 vec.emplace_back( nullptr );
385 for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
386 vec[ i ] = std::move( vec[ i - 1 ] );
387 }
388 vec[ 0 ] = element;
389}
390
391const CaseClause * MultiLevelExitCore::previsit( const CaseClause * stmt ) {
392 visit_children = false;
393
394 // If default, mark seen.
395 if ( stmt->isDefault() ) {
396 assert( ! enclosing_control_structures.empty() );
397 enclosing_control_structures.back().seenDefault();
398 }
399
400 // The cond may not exist, but if it does update it now.
401 visitor->maybe_accept( stmt, &CaseClause::cond );
402
403 // Just save the mutated node for simplicity.
404 CaseClause * mutStmt = mutate( stmt );
405
406 Label fallLabel = newLabel( "fallThrough", stmt->location );
407 if ( ! mutStmt->stmts.empty() ) {
408 // These should already be in a block.
409 auto first = mutStmt->stmts.front().get_and_mutate();
410 auto block = strict_dynamic_cast<CompoundStmt *>( first );
411
412 // Ensure that the stack isn't corrupted by exceptions in fixBlock.
413 auto guard = makeFuncGuard(
414 [&](){ enclosing_control_structures.emplace_back( mutStmt, block, fallLabel ); },
415 [this](){ enclosing_control_structures.pop_back(); }
416 );
417
418 block->kids = fixBlock( block->kids, true );
419
420 // Add fallthrough label if necessary.
421 assert( ! enclosing_control_structures.empty() );
422 Entry & entry = enclosing_control_structures.back();
423 if ( entry.isFallUsed() ) {
424 mutStmt->stmts.push_back( labelledNullStmt( block->location, entry.useFallExit() ) );
425 }
426 }
427 assert( ! enclosing_control_structures.empty() );
428 Entry & entry = enclosing_control_structures.back();
429 assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
430 "CFA internal error: control structure enclosing a case clause must be a switch, but is: %s",
431 toString( entry.stmt ).c_str() );
432 if ( mutStmt->isDefault() ) {
433 if ( entry.isFallDefaultUsed() ) {
434 // Add fallthrough default label if necessary.
435 push_front( mutStmt->stmts, labelledNullStmt( stmt->location, entry.useFallDefaultExit() ) );
436 }
437 }
438 return mutStmt;
439}
440
441void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
442 bool labeledBlock = ! stmt->labels.empty();
443 if ( labeledBlock ) {
444 Label breakLabel = newLabel( "blockBreak", stmt );
445 enclosing_control_structures.emplace_back( stmt, breakLabel );
446 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
447 }
448}
449
450const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
451 bool labeledBlock = ! stmt->labels.empty();
452 if ( labeledBlock ) {
453 auto this_label = enclosing_control_structures.back().useBreakExit();
454 if ( ! this_label.empty() ) {
455 break_label = this_label;
456 }
457 }
458 return stmt;
459}
460
461static bool isDefaultCase( const ptr<CaseClause> & caseClause ) {
462 return caseClause->isDefault();
463}
464
465void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
466 Label label = newLabel( "switchBreak", stmt );
467 auto it = find_if( stmt->cases.rbegin(), stmt->cases.rend(), isDefaultCase );
468
469 const CaseClause * defaultCase = it != stmt->cases.rend() ? (*it) : nullptr;
470 Label defaultLabel = defaultCase ? newLabel( "fallThroughDefault", defaultCase->location ) : Label( stmt->location, "" );
471 enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
472 GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
473
474 // Collect valid labels for fallthrough. It starts with all labels at this level, then remove as each is seen during
475 // traversal.
476 for ( const CaseClause * caseStmt : stmt->cases ) {
477 if ( caseStmt->stmts.empty() ) continue;
478 auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
479 for ( const Stmt * stmt : block->kids ) {
480 for ( const Label & l : stmt->labels ) {
481 fallthrough_labels.insert( l );
482 }
483 }
484 }
485}
486
487const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
488 assert( ! enclosing_control_structures.empty() );
489 Entry & entry = enclosing_control_structures.back();
490 assert( entry.stmt == stmt );
491
492 // Only run to generate the break label.
493 if ( entry.isBreakUsed() ) {
494 // To keep the switch statements uniform (all direct children of a SwitchStmt should be CastStmts), append the
495 // exit label and break to the last case, create a default case if no cases.
496 SwitchStmt * mutStmt = mutate( stmt );
497 if ( mutStmt->cases.empty() ) {
498 mutStmt->cases.push_back( new CaseClause( mutStmt->location, nullptr, {} ) );
499 }
500
501 auto mutCase = mutStmt->cases.back().get_and_mutate();
502
503 Label label( mutCase->location, "breakLabel" );
504 auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
505 branch->labels.push_back( entry.useBreakExit() );
506 mutCase->stmts.push_back( branch );
507
508 return mutStmt;
509 }
510 return stmt;
511}
512
513void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
514 char const * context;
515 switch ( ret_context ) {
516 case ReturnContext::MayReturn:
517 return;
518 case ReturnContext::InTryWithHandler:
519 context = "try statement with a catch clause";
520 break;
521 case ReturnContext::InResumeHandler:
522 context = "catchResume clause";
523 break;
524 case ReturnContext::InFinally:
525 context = "finally clause";
526 break;
527 default:
528 assert(0);
529 }
530 SemanticError( stmt->location, "\"return\" may not appear in a %s", context );
531}
532
533bool hasTerminate( const TryStmt * stmt ) {
534 for ( auto clause : stmt->handlers ) {
535 if ( ast::Terminate == clause->kind ) return true;
536 }
537 return false;
538}
539
540void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
541 visit_children = false;
542
543 bool isLabeled = ! stmt->labels.empty();
544 if ( isLabeled ) {
545 Label breakLabel = newLabel( "blockBreak", stmt );
546 enclosing_control_structures.emplace_back( stmt, breakLabel );
547 GuardAction([this](){ enclosing_control_structures.pop_back(); } );
548 }
549
550 // Try statements/try blocks are only sealed with a termination handler.
551 if ( hasTerminate( stmt ) ) {
552 // This is just enterSealedContext except scoped to the block.
553 // And that is because the state must change for a single field.
554 ValueGuard< ReturnContext > guard0( ret_context );
555 ret_context = ReturnContext::InTryWithHandler;
556 auto guard = makeFuncGuard( [](){}, [this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
557 enclosing_control_structures = vector<Entry>();
558 visitor->maybe_accept( stmt, &TryStmt::body );
559 } else {
560 visitor->maybe_accept( stmt, &TryStmt::body );
561 }
562
563 visitor->maybe_accept( stmt, &TryStmt::handlers );
564 visitor->maybe_accept( stmt, &TryStmt::finally );
565}
566
567void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
568 bool isLabeled = ! stmt->labels.empty();
569 if ( isLabeled ) {
570 auto this_label = enclosing_control_structures.back().useBreakExit();
571 if ( ! this_label.empty() ) {
572 break_label = this_label;
573 }
574 }
575}
576
577void MultiLevelExitCore::previsit( const CatchClause * clause ) {
578 if ( ast::Resume == clause->kind ) {
579 enterSealedContext( ReturnContext::InResumeHandler );
580 }
581}
582
583void MultiLevelExitCore::previsit( const FinallyClause * ) {
584 enterSealedContext( ReturnContext::InFinally );
585}
586
587const Stmt * MultiLevelExitCore::mutateLoop(
588 const Stmt * body, Entry & entry ) {
589 if ( entry.isBreakUsed() ) {
590 break_label = entry.useBreakExit();
591 }
592
593 // if continue is used insert a continue label into the back of the body of the loop
594 if ( entry.isContUsed() ) {
595 // {
596 // body
597 // ContinueLabel: ;
598 // }
599 return new CompoundStmt( body->location, {
600 body,
601 labelledNullStmt( body->location, entry.useContExit() ),
602 } );
603 }
604
605 return body;
606}
607
608template<typename LoopNode>
609void MultiLevelExitCore::prehandleLoopStmt( const LoopNode * loopStmt ) {
610 // Create temporary labels and mark the enclosing loop before traversal.
611 // The labels will be folded in if they are used.
612 Label breakLabel = newLabel( "loopBreak", loopStmt );
613 Label contLabel = newLabel( "loopContinue", loopStmt );
614 enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
615
616 GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
617
618 // Because of fixBlock, this should be empty now (and must be).
619 assert( nullptr == loopStmt->else_ );
620}
621
622template<typename LoopNode>
623const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
624 assert( ! enclosing_control_structures.empty() );
625 Entry & entry = enclosing_control_structures.back();
626 assert( entry.stmt == loopStmt );
627
628 // Now check if the labels are used and add them if so.
629 return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
630}
631
632list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
633 const list<ptr<Stmt>> & kids, bool is_case_clause ) {
634 // Unfortunately cannot use automatic error collection.
635 SemanticErrorException errors;
636
637 list<ptr<Stmt>> ret;
638
639 // Manually visit each child.
640 for ( const ptr<Stmt> & kid : kids ) {
641 if ( is_case_clause ) {
642 // Once a label is seen, it's no longer a valid for fallthrough.
643 for ( const Label & l : kid->labels ) {
644 fallthrough_labels.erase( l );
645 }
646 }
647
648 ptr<Stmt> else_stmt = nullptr;
649 const Stmt * to_visit;
650 // check if loop node and if so add else clause if it exists
651 if ( auto ptr = kid.as<WhileDoStmt>() ; ptr && ptr->else_ ) {
652 else_stmt = ptr->else_;
653 to_visit = mutate_field( ptr, &WhileDoStmt::else_, nullptr );
654 } else if ( auto ptr = kid.as<ForStmt>() ; ptr && ptr->else_ ) {
655 else_stmt = ptr->else_;
656 to_visit = mutate_field( ptr, &ForStmt::else_, nullptr );
657 } else {
658 to_visit = kid.get();
659 }
660
661 // This is the main (safe) visit of the child node.
662 try {
663 ret.push_back( to_visit->accept( *visitor ) );
664 } catch ( SemanticErrorException & e ) {
665 errors.append( e );
666 }
667
668 // The following sections handle visiting loop else clause and makes
669 // sure breaking from a loop body does not execute that clause.
670 Label local_break_label = std::move( break_label );
671 break_label = Label( CodeLocation(), "" );
672
673 if ( else_stmt ) try {
674 ret.push_back( else_stmt->accept( *visitor ) );
675 } catch ( SemanticErrorException & e ) {
676 errors.append( e );
677 }
678
679 if ( !break_label.empty() ) {
680 ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
681 break_label = Label( CodeLocation(), "" );
682 }
683
684 // This handles a break from the body or non-loop statement.
685 if ( !local_break_label.empty() ) {
686 ret.push_back( labelledNullStmt( ret.back()->location, local_break_label ) );
687 }
688 }
689
690 errors.throwIfNonEmpty();
691 return ret;
692}
693
694void MultiLevelExitCore::enterSealedContext( ReturnContext enter_context ) {
695 GuardAction([this, old = std::move(enclosing_control_structures)](){ enclosing_control_structures = std::move(old); });
696 enclosing_control_structures = vector<Entry>();
697 GuardValue( ret_context ) = enter_context;
698}
699
700} // namespace
701
702const CompoundStmt * multiLevelExitUpdate(
703 const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
704 // Must start in the body, so FunctionDecls can be a stopping point.
705 Pass<MultiLevelExitCore> visitor( labelTable );
706 return stmt->accept( visitor );
707}
708
709} // namespace ControlStruct
710
711// Local Variables: //
712// tab-width: 4 //
713// mode: c++ //
714// compile-command: "make install" //
715// End: //
Note: See TracBrowser for help on using the repository browser.