source: src/ControlStruct/MultiLevelExit.cpp @ 37ceccb

Last change on this file since 37ceccb was 553f032f, checked in by Andrew Beach <ajbeach@…>, 10 months ago

Insert additional checks so that impossible, or just unimplemented, local control flow raises an error in CFA.

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