source: src/ControlStruct/MultiLevelExit.cpp @ 567c775

Last change on this file since 567c775 was 0a6d2045, checked in by Andrew Beach <ajbeach@…>, 7 months ago

You can how use local control flow out of 'catch' clauses. Added a test to show that it works.

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