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
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
[400b8be]11// Last Modified By : Andrew Beach
[553f032f]12// Last Modified On : Fri Sep  8 17:04:00 2023
13// Update Count     : 36
[b8ab91a]14//
15
16#include "MultiLevelExit.hpp"
17
18#include "AST/Pass.hpp"
19#include "AST/Stmt.hpp"
[66daee4]20#include "LabelGeneratorNew.hpp"
[b8ab91a]21
22#include <set>
[66daee4]23using namespace std;
24using namespace ast;
[b8ab91a]25
26namespace ControlStruct {
[4a40fca7]27
28namespace {
29
[553f032f]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
[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,
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 ) ) ) {
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() ) {
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: ",
[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() ) {
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:
[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() ) {
[66daee4]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::InTerminateHandler:
514                context = "catch clause";
515                break;
516        case ReturnContext::InFinally:
517                context = "finally clause";
518                break;
519        default:
520                assert(0);
[b8ab91a]521        }
[553f032f]522        SemanticError( stmt->location, toString( "'return' may not appear in a ", context ) );
[b8ab91a]523}
524
[66daee4]525void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
[2f52b18]526        bool isLabeled = ! stmt->labels.empty();
[b8ab91a]527        if ( isLabeled ) {
[66daee4]528                Label breakLabel = newLabel( "blockBreak", stmt );
[b8ab91a]529                enclosing_control_structures.emplace_back( stmt, breakLabel );
530                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
531        }
[553f032f]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        }
[b8ab91a]539}
540
[66daee4]541void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
[2f52b18]542        bool isLabeled = ! stmt->labels.empty();
[b8ab91a]543        if ( isLabeled ) {
544                auto this_label = enclosing_control_structures.back().useBreakExit();
[2f52b18]545                if ( ! this_label.empty() ) {
[b8ab91a]546                        break_label = this_label;
547                }
548        }
549}
550
[553f032f]551void MultiLevelExitCore::previsit( const CatchClause * clause ) {
552        ReturnContext context = ( ast::Terminate == clause->kind )
553                ? ReturnContext::InTerminateHandler : ReturnContext::InResumeHandler;
554        enterSealedContext( context );
555}
556
[400b8be]557void MultiLevelExitCore::previsit( const FinallyClause * ) {
[553f032f]558        enterSealedContext( ReturnContext::InFinally );
[b8ab91a]559}
560
[66daee4]561const Stmt * MultiLevelExitCore::mutateLoop(
562        const Stmt * body, Entry & entry ) {
[b8ab91a]563        if ( entry.isBreakUsed() ) {
564                break_label = entry.useBreakExit();
565        }
566
[3e5db5b4]567        // if continue is used insert a continue label into the back of the body of the loop
[b8ab91a]568        if ( entry.isContUsed() ) {
[3e5db5b4]569                // {
570                //  body
[4a40fca7]571                //  ContinueLabel: ;
[3e5db5b4]572                // }
[4a40fca7]573                return new CompoundStmt( body->location, {
574                        body,
575                        labelledNullStmt( body->location, entry.useContExit() ),
576                } );
[b8ab91a]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.
[66daee4]586        Label breakLabel = newLabel( "loopBreak", loopStmt );
587        Label contLabel = newLabel( "loopContinue", loopStmt );
[b8ab91a]588        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
[3e5db5b4]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
[b8ab91a]593        GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
594}
595
596template<typename LoopNode>
597const LoopNode * MultiLevelExitCore::posthandleLoopStmt( const LoopNode * loopStmt ) {
[2f52b18]598        assert( ! enclosing_control_structures.empty() );
[b8ab91a]599        Entry & entry = enclosing_control_structures.back();
600        assert( entry.stmt == loopStmt );
601
[66daee4]602        // Now check if the labels are used and add them if so.
[2f52b18]603        return mutate_field( loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
[3e5db5b4]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
[b8ab91a]607}
608
[66daee4]609list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
610        const list<ptr<Stmt>> & kids, bool is_case_clause ) {
611        // Unfortunately cannot use automatic error collection.
[b8ab91a]612        SemanticErrorException errors;
613
[66daee4]614        list<ptr<Stmt>> ret;
[b8ab91a]615
616        // Manually visit each child.
[66daee4]617        for ( const ptr<Stmt> & kid : kids ) {
[b8ab91a]618                if ( is_case_clause ) {
619                        // Once a label is seen, it's no longer a valid for fallthrough.
[66daee4]620                        for ( const Label & l : kid->labels ) {
[b8ab91a]621                                fallthrough_labels.erase( l );
622                        }
623                }
624
[f75e25b]625                ptr<Stmt> else_stmt = nullptr;
[0577df2]626                const Stmt * loop_kid = nullptr;
[f75e25b]627                // check if loop node and if so add else clause if it exists
[0577df2]628                const WhileDoStmt * whilePtr = kid.as<WhileDoStmt>();
629                if ( whilePtr && whilePtr->else_ ) {
[f75e25b]630                        else_stmt = whilePtr->else_;
[0577df2]631                        loop_kid = mutate_field( whilePtr, &WhileDoStmt::else_, nullptr );
[f75e25b]632                }
[0577df2]633                const ForStmt * forPtr = kid.as<ForStmt>();
634                if ( forPtr && forPtr->else_ ) {
[f75e25b]635                        else_stmt = forPtr->else_;
[0577df2]636                        loop_kid = mutate_field( forPtr, &ForStmt::else_, nullptr );
[f75e25b]637                }
638
[b8ab91a]639                try {
[f75e25b]640                        if (else_stmt) ret.push_back( loop_kid->accept( *visitor ) );
641                        else ret.push_back( kid->accept( *visitor ) );
[b8ab91a]642                } catch ( SemanticErrorException & e ) {
643                        errors.append( e );
644                }
645
[f75e25b]646                if (else_stmt) ret.push_back(else_stmt);
[7ad47df]647
[2f52b18]648                if ( ! break_label.empty() ) {
649                        ret.push_back( labelledNullStmt( ret.back()->location, break_label ) );
[66daee4]650                        break_label = Label( CodeLocation(), "" );
[b8ab91a]651                }
652        }
653
[2f52b18]654        if ( ! errors.isEmpty() ) {
[b8ab91a]655                throw errors;
656        }
657        return ret;
658}
659
[553f032f]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
[4a40fca7]666} // namespace
667
[66daee4]668const CompoundStmt * multiLevelExitUpdate(
[4a40fca7]669                const CompoundStmt * stmt, const LabelToStmt & labelTable ) {
[b8ab91a]670        // Must start in the body, so FunctionDecls can be a stopping point.
[66daee4]671        Pass<MultiLevelExitCore> visitor( labelTable );
[4a40fca7]672        return stmt->accept( visitor );
[b8ab91a]673}
[4a40fca7]674
[b8ab91a]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.