source: src/main.cc @ f43146e4

Last change on this file since f43146e4 was f43146e4, checked in by Andrew Beach <ajbeach@…>, 8 months ago

Updated some stats/counters to trigger off the new AST. Others will just have to be updated/re-added later because the support code to run them is missing and I don't know what stats we might need in the future.

  • Property mode set to 100644
File size: 28.7 KB
RevLine 
[b87a5ed]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//
[71f4e4f]7// main.cc --
[b87a5ed]8//
[3e96559]9// Author           : Peter Buhr and Rob Schluntz
[b87a5ed]10// Created On       : Fri May 15 23:12:02 2015
[372b6d3]11// Last Modified By : Peter A. Buhr
[12f671e]12// Last Modified On : Thu Sep 28 22:28:45 2023
13// Update Count     : 687
[b87a5ed]14//
15
[bf2438c]16#include <cxxabi.h>                         // for __cxa_demangle
17#include <execinfo.h>                       // for backtrace, backtrace_symbols
18#include <getopt.h>                         // for no_argument, optind, geto...
[08fc48f]19#include <cassert>                          // for assertf
[bf2438c]20#include <cstdio>                           // for fopen, FILE, fclose, stdin
21#include <cstdlib>                          // for exit, free, abort, EXIT_F...
[bffcd66]22#include <csignal>                          // for signal, SIGABRT, SIGSEGV
[bf2438c]23#include <cstring>                          // for index
[be9288a]24#include <fstream>                          // for ofstream
[bf2438c]25#include <iostream>                         // for operator<<, basic_ostream
[62ce290]26#include <iomanip>
[bf2438c]27#include <iterator>                         // for back_inserter
28#include <list>                             // for list
[08fc48f]29#include <string>                           // for char_traits, operator<<
[e6955b1]30
[9ea38de]31#include "AST/Convert.hpp"
[bccd70a]32#include "AST/Pass.hpp"                     // for pass_visitor_stats
33#include "AST/TranslationUnit.hpp"          // for TranslationUnit
[52f9804]34#include "AST/Util.hpp"                     // for checkInvariants
[7f38b67a]35#include "CompilationState.h"
[bf2438c]36#include "../config.h"                      // for CFA_LIBDIR
37#include "CodeGen/FixMain.h"                // for FixMain
38#include "CodeGen/FixNames.h"               // for fixNames
39#include "CodeGen/Generate.h"               // for generate
[aff7e86]40#include "CodeGen/LinkOnce.h"               // for translateLinkOnce
[bf2438c]41#include "CodeTools/TrackLoc.h"             // for fillLocations
[f57faf6f]42#include "Common/CodeLocationTools.hpp"     // for forceFillCodeLocations
[55cbff8]43#include "Common/DeclStats.hpp"             // for printDeclStats
44#include "Common/ResolvProtoDump.hpp"       // for dumpAsResolverProto
[09366b8]45#include "Common/Stats.h"                   // for Stats
[bf2438c]46#include "Common/utility.h"                 // for deleteAll, filter, printAll
[3dd8f42]47#include "Concurrency/Actors.hpp"           // for implementActors
[eb779d5]48#include "Concurrency/Corun.hpp"            // for implementCorun
[2cf3b87]49#include "Concurrency/Keywords.h"           // for implementMutex, implement...
[9f5ecf5]50#include "Concurrency/Waitfor.h"            // for generateWaitfor
[c86b08d]51#include "Concurrency/Waituntil.hpp"        // for generateWaitUntil
[0c730d9]52#include "ControlStruct/ExceptDecl.h"       // for translateExcept
[09366b8]53#include "ControlStruct/ExceptTranslate.h"  // for translateThrows, translat...
[b8ab91a]54#include "ControlStruct/FixLabels.hpp"      // for fixLabels
[a488783]55#include "ControlStruct/HoistControlDecls.hpp" //  hoistControlDecls
[bf2438c]56#include "GenPoly/Box.h"                    // for box
57#include "GenPoly/InstantiateGeneric.h"     // for instantiateGeneric
58#include "GenPoly/Lvalue.h"                 // for convertLvalue
59#include "GenPoly/Specialize.h"             // for convertSpecializations
60#include "InitTweak/FixInit.h"              // for fix
61#include "InitTweak/GenInit.h"              // for genInit
62#include "MakeLibCfa.h"                     // for makeLibCfa
[cbd1ba8]63#include "Parser/RunParser.hpp"             // for buildList, dumpParseTree,...
[1622af5]64#include "ResolvExpr/CandidatePrinter.hpp"  // for printCandidates
[d3652df]65#include "ResolvExpr/EraseWith.hpp"         // for eraseWith
[bf2438c]66#include "ResolvExpr/Resolver.h"            // for resolve
[bffcd66]67#include "SynTree/LinkageSpec.h"            // for Spec, Cforall, Intrinsic
[bf2438c]68#include "SynTree/Declaration.h"            // for Declaration
69#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
[a488783]70#include "Validate/Autogen.hpp"             // for autogenerateRoutines
[298fe57]71#include "Validate/CompoundLiteral.hpp"     // for handleCompoundLiterals
72#include "Validate/EliminateTypedef.hpp"    // for eliminateTypedef
[1931bb01]73#include "Validate/EnumAndPointerDecay.hpp" // for decayEnumsAndPointers
[ce36b55]74#include "Validate/FindSpecialDecls.h"      // for findGlobalDecls
[298fe57]75#include "Validate/FixQualifiedTypes.hpp"   // for fixQualifiedTypes
[1931bb01]76#include "Validate/FixReturnTypes.hpp"      // for fixReturnTypes
[9490621]77#include "Validate/ForallPointerDecay.hpp"  // for decayForallPointers
[298fe57]78#include "Validate/GenericParameter.hpp"    // for fillGenericParameters, tr...
79#include "Validate/HoistStruct.hpp"         // for hoistStruct
[1931bb01]80#include "Validate/HoistTypeDecls.hpp"      // for hoistTypeDecls
[ce36b55]81#include "Validate/InitializerLength.hpp"   // for setLengthFromInitializer
82#include "Validate/LabelAddressFixer.hpp"   // for fixLabelAddresses
[72e76fd]83#include "Validate/LinkReferenceToTypes.hpp" // for linkReferenceToTypes
[1931bb01]84#include "Validate/ReplaceTypedef.hpp"      // for replaceTypedef
[4ec9513]85#include "Validate/ReturnCheck.hpp"         // for checkReturnStatements
[1931bb01]86#include "Validate/VerifyCtorDtorAssign.hpp" // for verifyCtorDtorAssign
[a5f0529]87#include "Virtual/ExpandCasts.h"            // for expandCasts
[3830c84]88#include "Virtual/VirtualDtor.hpp"           // for implementVirtDtors
[51b7345]89
[2c38b15]90using namespace std;
91
[3e96559]92static void NewPass( const char * const name ) {
93        Stats::Heap::newPass( name );
[1cb7fab2]94        using namespace Stats::Counters;
[b8665e3]95        {
[f43146e4]96                static auto group = build<CounterGroup>( "Pass Visitor Template" );
[3e96559]97                auto pass = build<CounterGroup>( name, group );
[f43146e4]98                ast::pass_visitor_stats.depth = 0;
99                ast::pass_visitor_stats.avg = build<AverageCounter<double>>( "Average Depth", pass );
100                ast::pass_visitor_stats.max = build<MaxCounter<double>>( "Max Depth", pass );
[b8665e3]101        }
102        {
[3e96559]103                static auto group = build<CounterGroup>( "Syntax Node" );
104                auto pass = build<CounterGroup>( name, group );
105                BaseSyntaxNode::new_nodes = build<SimpleCounter>( "Allocs", pass );
[b8665e3]106        }
[675716e]107}
108
[52f9804]109// Helpers for checkInvariant:
110void checkInvariants( std::list< Declaration * > & ) {}
111using ast::checkInvariants;
112
113#define PASS( name, pass, unit, ... )       \
[ecaeac6e]114        if ( errorp ) { cerr << name << endl; } \
[675716e]115        NewPass(name);                          \
[4f97937]116        Stats::Time::StartBlock(name);          \
[52f9804]117        pass(unit,##__VA_ARGS__);               \
118        Stats::Time::StopBlock();               \
119        if ( invariant ) {                      \
120                checkInvariants(unit);              \
121        }
122
123#define DUMP( cond, unit )                  \
124        if ( cond ) {                           \
125                dump(unit);                         \
126                return EXIT_SUCCESS;                \
127        }
[0da3e2c]128
[ef22ad6]129static bool waiting_for_gdb = false;                                    // flag to set cfa-cpp to wait for gdb on start
[dee1f89]130
[bffcd66]131static string PreludeDirector = "";
[4dcaed2]132
[77d601f]133static void parse_cmdline( int argc, char * argv[] );
[e6955b1]134static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
[e499381]135static void dump( ast::TranslationUnit && transUnit, ostream & out = cout );
[e6955b1]136
[0afffee]137static void backtrace( int start ) {                                    // skip first N stack frames
[74330e7]138        enum { Frames = 50, };                                                          // maximum number of stack frames
[e6955b1]139        void * array[Frames];
[74330e7]140        size_t size = ::backtrace( array, Frames );
[0afffee]141        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
142
143        *index( messages[0], '(' ) = '\0';                                      // find executable name
144        cerr << "Stack back trace for: " << messages[0] << endl;
[e6955b1]145
[b542bfb]146        // skip last 2 stack frames after main
[74330e7]147        for ( unsigned int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
[e6955b1]148                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
[7006ba5]149
150                for ( char * p = messages[i]; *p; p += 1 ) {    // find parantheses and +offset
[0afffee]151                        if ( *p == '(' ) {
[46f6134]152                                mangled_name = p;
[0afffee]153                        } else if ( *p == '+' ) {
[e6955b1]154                                offset_begin = p;
[0afffee]155                        } else if ( *p == ')' ) {
[e6955b1]156                                offset_end = p;
157                                break;
158                        } // if
159                } // for
160
161                // if line contains symbol, attempt to demangle
[b542bfb]162                int frameNo = i - start;
[e6955b1]163                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
[0afffee]164                        *mangled_name++ = '\0';                                         // delimit strings
[e6955b1]165                        *offset_begin++ = '\0';
166                        *offset_end++ = '\0';
167
[0afffee]168                        int status;
[e6955b1]169                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
[0afffee]170                        // bug in __cxa_demangle for single-character lower-case non-mangled names
[e6955b1]171                        if ( status == 0 ) {                                            // demangling successful ?
[b542bfb]172                                cerr << "(" << frameNo << ") " << messages[i] << " : "
[e6955b1]173                                         << real_name << "+" << offset_begin << offset_end << endl;
174                        } else {                                                                        // otherwise, output mangled name
[b542bfb]175                                cerr << "(" << frameNo << ") " << messages[i] << " : "
[0afffee]176                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
[e6955b1]177                        } // if
[0afffee]178
[e6955b1]179                        free( real_name );
180                } else {                                                                                // otherwise, print the whole line
[b542bfb]181                        cerr << "(" << frameNo << ") " << messages[i] << endl;
[e6955b1]182                } // if
183        } // for
[b542bfb]184
[e6955b1]185        free( messages );
[b542bfb]186} // backtrace
187
[bffcd66]188#define SIGPARMS int sig __attribute__(( unused )), siginfo_t * sfp __attribute__(( unused )), ucontext_t * cxt __attribute__(( unused ))
189
[1f68d5d]190static void _Signal(struct sigaction & act, int sig, int flags ) {
[bffcd66]191        act.sa_flags = flags;
192
193        if ( sigaction( sig, &act, nullptr ) == -1 ) {
[77d601f]194            cerr << "*cfa-cpp compilation error* problem installing signal handler, error(" << errno << ") " << strerror( errno ) << endl;
[bffcd66]195            _exit( EXIT_FAILURE );
196        } // if
[1f68d5d]197}
198
199static void Signal( int sig, void (* handler)(SIGPARMS), int flags ) {
200        struct sigaction act;
201        act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
202        _Signal(act, sig, flags);
203} // Signal
204
205static void Signal( int sig, void (* handler)(int), int flags ) {
206        struct sigaction act;
207        act.sa_handler = handler;
208        _Signal(act, sig, flags);
[bffcd66]209} // Signal
210
211static void sigSegvBusHandler( SIGPARMS ) {
212        if ( sfp->si_addr == nullptr ) {
213                cerr << "Null pointer (nullptr) dereference." << endl;
214        } else {
215                cerr << (sig == SIGSEGV ? "Segment fault" : "Bus error") << " at memory location " << sfp->si_addr << "." << endl
216                         << "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript." << endl;
217        } // if
[b542bfb]218        backtrace( 2 );                                                                         // skip first 2 stack frames
[3e96559]219        abort();                                                                                        // cause core dump for debugging
[e6955b1]220} // sigSegvBusHandler
[0da3e2c]221
[74330e7]222static void sigFpeHandler( SIGPARMS ) {
223        const char * msg;
224
225        switch ( sfp->si_code ) {
226          case FPE_INTDIV: case FPE_FLTDIV: msg = "divide by zero"; break;
227          case FPE_FLTOVF: msg = "overflow"; break;
228          case FPE_FLTUND: msg = "underflow"; break;
229          case FPE_FLTRES: msg = "inexact result"; break;
230          case FPE_FLTINV: msg = "invalid operation"; break;
231          default: msg = "unknown";
232        } // choose
233        cerr << "Computation error " << msg << " at location " << sfp->si_addr << endl
234                 << "Possible cause is constant-expression evaluation invalid." << endl;
235        backtrace( 2 );                                                                         // skip first 2 stack frames
236        abort();                                                                                        // cause core dump for debugging
237} // sigFpeHandler
238
[bffcd66]239static void sigAbortHandler( SIGPARMS ) {
[b542bfb]240        backtrace( 6 );                                                                         // skip first 6 stack frames
[1f68d5d]241        Signal( SIGABRT, SIG_DFL, SA_SIGINFO ); // reset default signal handler
[9be45a2]242        raise( SIGABRT );                                                                       // reraise SIGABRT
[b542bfb]243} // sigAbortHandler
244
[cbaee0d]245int main( int argc, char * argv[] ) {
[3b8e52c]246        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
[d08beee]247        ostream * output = & cout;
[e6955b1]248        list< Declaration * > translationUnit;
[64b3cda]249        ast::TranslationUnit transUnit;
[e6955b1]250
[bffcd66]251        Signal( SIGSEGV, sigSegvBusHandler, SA_SIGINFO );
252        Signal( SIGBUS, sigSegvBusHandler, SA_SIGINFO );
[74330e7]253        Signal( SIGFPE, sigFpeHandler, SA_SIGINFO );
[bffcd66]254        Signal( SIGABRT, sigAbortHandler, SA_SIGINFO );
[b87a5ed]255
[bffcd66]256        // cout << "main" << endl;
[44bca7f]257        // for ( int i = 0; i < argc; i += 1 ) {
[bffcd66]258        //      cout << '\t' << argv[i] << endl;
[44bca7f]259        // } // for
260
[e0bd0f9]261        parse_cmdline( argc, argv );                                            // process command-line arguments
[13de47bc]262        CodeGen::FixMain::setReplaceMain( !nomainp );
[b87a5ed]263
[ef22ad6]264        if ( waiting_for_gdb ) {
[bffcd66]265                cerr << "Waiting for gdb" << endl;
266                cerr << "run :" << endl;
267                cerr << "  gdb attach " << getpid() << endl;
[dee1f89]268                raise(SIGSTOP);
[ef22ad6]269        } // if
[dee1f89]270
[b87a5ed]271        try {
[81419b5]272                // choose to read the program from a file or stdin
[3b8e52c]273                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
[b87a5ed]274                        input = fopen( argv[ optind ], "r" );
[e0bd0f9]275                        assertf( input, "cannot open %s because %s\n", argv[ optind ], strerror( errno ) );
[b87a5ed]276                        optind += 1;
[3b8e52c]277                } else {                                                                                // no input file name
[b87a5ed]278                        input = stdin;
279                } // if
280
[79eaeb7]281                Stats::Time::StartGlobal();
[3c0d4cd]282                NewPass("Parse");
283                Stats::Time::StartBlock("Parse");
[675716e]284
[159c62e]285                // read in the builtins, extras, and the prelude
[de62360d]286                if ( ! nopreludep ) {                                                   // include gcc builtins
[faf8857]287                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
[807ce84]288
[37fe352]289                        assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
[4dcaed2]290
[807ce84]291                        // Read to gcc builtins, if not generating the cfa library
[37fe352]292                        FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
[6ce3ae9]293                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
[f2f595d7]294                        parse( gcc_builtins, ast::Linkage::Compiler );
[81419b5]295
[159c62e]296                        // read the extra prelude in, if not generating the cfa library
[37fe352]297                        FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
[3b8e52c]298                        assertf( extras, "cannot open extras.cf\n" );
[f2f595d7]299                        parse( extras, ast::Linkage::BuiltinC );
[159c62e]300
[81419b5]301                        if ( ! libcfap ) {
[faf8857]302                                // read the prelude in, if not generating the cfa library
[e523b07]303                                FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
304                                assertf( prelude, "cannot open prelude.cfa\n" );
[f2f595d7]305                                parse( prelude, ast::Linkage::Intrinsic );
[fa4805f]306
307                                // Read to cfa builtins, if not generating the cfa library
[37fe352]308                                FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
[fa4805f]309                                assertf( builtins, "cannot open builtins.cf\n" );
[f2f595d7]310                                parse( builtins, ast::Linkage::BuiltinCFA );
[b87a5ed]311                        } // if
312                } // if
[81419b5]313
[f2f595d7]314                parse( input, libcfap ? ast::Linkage::Intrinsic : ast::Linkage::Cforall, yydebug );
[71f4e4f]315
[64b3cda]316                transUnit = buildUnit();
[b87a5ed]317
[52f9804]318                DUMP( astp, std::move( transUnit ) );
[b87a5ed]319
[3c0d4cd]320                Stats::Time::StopBlock();
[036dd5f]321
[52f9804]322                PASS( "Hoist Type Decls", Validate::hoistTypeDecls, transUnit );
323
324                PASS( "Translate Exception Declarations", ControlStruct::translateExcept, transUnit );
325                DUMP( exdeclp, std::move( transUnit ) );
326                PASS( "Verify Ctor, Dtor & Assign", Validate::verifyCtorDtorAssign, transUnit );
327                PASS( "Replace Typedefs", Validate::replaceTypedef, transUnit );
328                PASS( "Fix Return Types", Validate::fixReturnTypes, transUnit );
329                PASS( "Enum and Pointer Decay", Validate::decayEnumsAndPointers, transUnit );
330
331                PASS( "Link Reference To Types", Validate::linkReferenceToTypes, transUnit );
332
[14c0f7b]333                PASS( "Forall Pointer Decay", Validate::decayForallPointers, transUnit );
[52f9804]334                PASS( "Fix Qualified Types", Validate::fixQualifiedTypes, transUnit );
335                PASS( "Eliminate Typedef", Validate::eliminateTypedef, transUnit );
[2c38b15]336                PASS( "Hoist Struct", Validate::hoistStruct, transUnit );
[52f9804]337                PASS( "Validate Generic Parameters", Validate::fillGenericParameters, transUnit );
338                PASS( "Translate Dimensions", Validate::translateDimensionParameters, transUnit );
339                PASS( "Check Function Returns", Validate::checkReturnStatements, transUnit );
340                PASS( "Fix Return Statements", InitTweak::fixReturnStatements, transUnit );
341                PASS( "Implement Concurrent Keywords", Concurrency::implementKeywords, transUnit );
[14c0f7b]342                PASS( "Fix Unique Ids", Validate::fixUniqueIds, transUnit );
[cf3da24]343                PASS( "Implement Corun", Concurrency::implementCorun, transUnit );
[52f9804]344                PASS( "Hoist Control Declarations", ControlStruct::hoistControlDecls, transUnit );
345
346                PASS( "Generate Autogen Routines", Validate::autogenerateRoutines, transUnit );
347
348                PASS( "Implement Actors", Concurrency::implementActors, transUnit );
349                PASS( "Implement Virtual Destructors", Virtual::implementVirtDtors, transUnit );
350                PASS( "Implement Mutex", Concurrency::implementMutex, transUnit );
351                PASS( "Implement Thread Start", Concurrency::implementThreadStarter, transUnit );
352                PASS( "Compound Literal", Validate::handleCompoundLiterals, transUnit );
353                PASS( "Set Length From Initializer", Validate::setLengthFromInitializer, transUnit );
354                PASS( "Find Global Decls", Validate::findGlobalDecls, transUnit );
355                PASS( "Fix Label Address", Validate::fixLabelAddresses, transUnit );
[09366b8]356
357                if ( symtabp ) {
358                        return EXIT_SUCCESS;
359                } // if
[ccbc65c]360
[09366b8]361                if ( expraltp ) {
362                        ResolvExpr::printCandidates( transUnit );
363                        return EXIT_SUCCESS;
364                } // if
[3606fe4]365
[52f9804]366                DUMP( validp, std::move( transUnit ) );
[6a896b0]367
[52f9804]368                PASS( "Translate Throws", ControlStruct::translateThrows, transUnit );
369                PASS( "Fix Labels", ControlStruct::fixLabels, transUnit );
[14c0f7b]370                PASS( "Implement Waituntil", Concurrency::generateWaitUntil, transUnit  );
[52f9804]371                PASS( "Fix Names", CodeGen::fixNames, transUnit );
372                PASS( "Gen Init", InitTweak::genInit, transUnit );
373                PASS( "Expand Member Tuples" , Tuples::expandMemberTuples, transUnit );
[ce36b55]374
[09366b8]375                if ( libcfap ) {
376                        // Generate the bodies of cfa library functions.
377                        LibCfa::makeLibCfa( transUnit );
378                } // if
[1622af5]379
[09366b8]380                if ( declstatsp ) {
381                        printDeclStats( transUnit );
382                        return EXIT_SUCCESS;
383                } // if
[1622af5]384
[52f9804]385                DUMP( bresolvep, std::move( transUnit ) );
[1622af5]386
[09366b8]387                if ( resolvprotop ) {
388                        dumpAsResolverProto( transUnit );
389                        return EXIT_SUCCESS;
390                } // if
[9f5a19fa]391
[52f9804]392                PASS( "Resolve", ResolvExpr::resolve, transUnit );
393                DUMP( exprp, std::move( transUnit ) );
[68fe946e]394
[52f9804]395                PASS( "Fix Init", InitTweak::fix, transUnit, buildingLibrary() );
[d3652df]396                PASS( "Erase With", ResolvExpr::eraseWith, transUnit );
[68fe946e]397
[09366b8]398                // fix ObjectDecl - replaces ConstructorInit nodes
[52f9804]399                DUMP( ctorinitp, std::move( transUnit ) );
[68fe946e]400
[09366b8]401                // Currently not working due to unresolved issues with UniqueExpr
[52f9804]402                PASS( "Expand Unique Expr", Tuples::expandUniqueExpr, transUnit ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent passes don't need to worry about double-visiting a unique expr - needs to go after InitTweak::fix so that copy constructed return declarations are reused
[68fe946e]403
[52f9804]404                PASS( "Translate Tries", ControlStruct::translateTries, transUnit );
405                PASS( "Gen Waitfor", Concurrency::generateWaitFor, transUnit );
[4615ac8]406
[09366b8]407                // Needs to happen before tuple types are expanded.
[52f9804]408                PASS( "Convert Specializations",  GenPoly::convertSpecializations, transUnit );
[81419b5]409
[52f9804]410                PASS( "Expand Tuples", Tuples::expandTuples, transUnit );
411                DUMP( tuplep, std::move( transUnit ) );
[626dbc10]412
[09366b8]413                // Must come after Translate Tries.
[52f9804]414                PASS( "Virtual Expand Casts", Virtual::expandCasts, transUnit );
[141b786]415
[52f9804]416                PASS( "Instantiate Generics", GenPoly::instantiateGeneric, transUnit );
417                DUMP( genericsp, std::move( transUnit ) );
[b4f8808]418
[52f9804]419                PASS( "Convert L-Value", GenPoly::convertLvalue, transUnit );
[1ee0a4da]420                DUMP( bboxp, std::move( transUnit ) );
421                PASS( "Box", GenPoly::box, transUnit );
[3cbe320]422                PASS( "Link-Once", CodeGen::translateLinkOnce, transUnit );
[7fffb1b]423
[aff7e86]424                // Code has been lowered to C, now we can start generation.
425
[8941b6b]426                DUMP( bcodegenp, std::move( transUnit ) );
[8905f56]427
[13de47bc]428                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
429                        output = new ofstream( argv[ optind ] );
430                } // if
[0270824]431
[8941b6b]432                PASS( "Code Gen", CodeGen::generate, transUnit, *output, !genproto, prettycodegenp, true, linemarks, false );
433
[bef4f1a]434                CodeGen::FixMain::fix( transUnit, *output,
[8e48fca4]435                                (PreludeDirector + "/bootloader.c").c_str() );
[e6955b1]436                if ( output != &cout ) {
[b87a5ed]437                        delete output;
438                } // if
[77d601f]439        } catch ( SemanticErrorException & e ) {
[b87a5ed]440                if ( errorp ) {
[e6955b1]441                        cerr << "---AST at error:---" << endl;
[64b3cda]442                        // We check which section the errors came from without looking at
443                        // transUnit because std::move means it could look like anything.
444                        if ( !translationUnit.empty() ) {
445                                dump( translationUnit, cerr );
446                        } else {
447                                dump( std::move( transUnit ), cerr );
448                        }
[e6955b1]449                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
[926af74]450                } // if
[d55d7a6]451                e.print();
[e6955b1]452                if ( output != &cout ) {
[b87a5ed]453                        delete output;
454                } // if
[3e96559]455                return EXIT_FAILURE;
[77d601f]456        } catch ( std::bad_alloc & ) {
457                cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
458                backtrace( 1 );
459                abort();
[3e96559]460        } catch ( ... ) {
[bffcd66]461                exception_ptr eptr = current_exception();
[4990812]462                try {
463                        if (eptr) {
[bffcd66]464                                rethrow_exception(eptr);
[3e96559]465                        } else {
[77d601f]466                                cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
[3e96559]467                        } // if
[77d601f]468                } catch( const exception & e ) {
469                        cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
[3e96559]470                } // try
471                return EXIT_FAILURE;
472        } // try
[b87a5ed]473
[39786813]474        deleteAll( translationUnit );
[1cb7fab2]475        Stats::print();
[3e96559]476        return EXIT_SUCCESS;
[d9a0e76]477} // main
[51b7345]478
[0da3e2c]479
[372b6d3]480static const char optstring[] = ":c:ghilLmNnpdP:S:twW:D:";
[3e96559]481
[62ce290]482enum { PreludeDir = 128 };
[3e96559]483static struct option long_opts[] = {
[1a69a90]484        { "colors", required_argument, nullptr, 'c' },
485        { "gdb", no_argument, nullptr, 'g' },
[3e96559]486        { "help", no_argument, nullptr, 'h' },
[372b6d3]487        { "invariant", no_argument, nullptr, 'i' },
[3e96559]488        { "libcfa", no_argument, nullptr, 'l' },
[62ce290]489        { "linemarks", no_argument, nullptr, 'L' },
[372b6d3]490        { "no-main", no_argument, nullptr, 'm' },
[62ce290]491        { "no-linemarks", no_argument, nullptr, 'N' },
492        { "no-prelude", no_argument, nullptr, 'n' },
[3e96559]493        { "prototypes", no_argument, nullptr, 'p' },
[7215000]494        { "deterministic-out", no_argument, nullptr, 'd' },
[62ce290]495        { "print", required_argument, nullptr, 'P' },
496        { "prelude-dir", required_argument, nullptr, PreludeDir },
497        { "statistics", required_argument, nullptr, 'S' },
[3e96559]498        { "tree", no_argument, nullptr, 't' },
499        { "", no_argument, nullptr, 0 },                                        // -w
500        { "", no_argument, nullptr, 0 },                                        // -W
501        { "", no_argument, nullptr, 0 },                                        // -D
502        { nullptr, 0, nullptr, 0 }
503}; // long_opts
504
505static const char * description[] = {
[aa88cb9a]506        "diagnostic color: never, always, auto",                        // -c
[3e9de01]507        "wait for gdb to attach",                                                       // -g
[aa88cb9a]508        "print translator help message",                                        // -h
[372b6d3]509        "invariant checking during AST passes",                         // -i
[3e9de01]510        "generate libcfa.c",                                                            // -l
511        "generate line marks",                                                          // -L
512        "do not replace main",                                                          // -m
513        "do not generate line marks",                                           // -N
514        "do not read prelude",                                                          // -n
[aa88cb9a]515        "do not generate prelude prototypes => prelude not printed", // -p
[3e9de01]516        "only print deterministic output",                  // -d
517        "print",                                                                                        // -P
[62ce290]518        "<directory> prelude directory for debug/nodebug",      // no flag
[aa88cb9a]519        "<option-list> enable profiling information: counters, heap, time, all, none", // -S
[3e9de01]520        "building cfa standard lib",                                            // -t
521        "",                                                                                                     // -w
522        "",                                                                                                     // -W
523        "",                                                                                                     // -D
[3e96559]524}; // description
525
[0c0f548]526static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
[62ce290]527
528static struct Printopts {
529        const char * name;
530        int & flag;
531        int val;
532        const char * descript;
533} printopts[] = {
[0e464f6]534        { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
535        { "asterr", errorp, true, "print AST on error" },
[12f671e]536        { "declstats", declstatsp, true, "print code property statistics" },
537        { "parse", yydebug, true, "print yacc (parsing) debug information" },
[62ce290]538        { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
539        { "rproto", resolvprotop, true, "resolver-proto instance" },
[0e464f6]540        { "rsteps", resolvep, true, "print resolver steps" },
[5f917740]541        // AST dumps
[0e464f6]542        { "ast", astp, true, "print AST after parsing" },
[5f917740]543        { "excpdecl", exdeclp, true, "print AST after translating exception decls" },
[0e464f6]544        { "symevt", symtabp, true, "print AST after symbol table events" },
[5f917740]545        { "expralt", expraltp, true, "print AST after expressions alternatives" },
546        { "valdecl", validp, true, "print AST after declaration validation pass" },
547        { "bresolver", bresolvep, true, "print AST before resolver step" },
548        { "expranly", exprp, true, "print AST after expression analysis" },
[0e464f6]549        { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
550        { "tuple", tuplep, true, "print AST after tuple expansion" },
[5f917740]551        { "instgen", genericsp, true, "print AST after instantiate generics" },
552        { "bbox", bboxp, true, "print AST before box pass" },
553        { "bcodegen", bcodegenp, true, "print AST before code generation" },
[62ce290]554};
555enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
556
[77d601f]557static void usage( char * argv[] ) {
[e0bd0f9]558    cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
[3e96559]559        int i = 0, j = 1;                                                                       // j skips starting colon
560        for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
561                if ( long_opts[i].name[0] != '\0' ) {                   // hidden option, internal usage only
[62ce290]562                        if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
563                                cout << "  -" << optstring[j] << ",";
564                        } else {                                                                        // no flag
565                                j -= 1;                                                                 // compensate
566                                cout << "     ";
567                        } // if
568                        cout << " --" << left << setw(12) << long_opts[i].name << "  ";
569                        if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
570                                cout << "one of: " << endl;
571                                for ( int i = 0; i < printoptsSize; i += 1 ) {
572                                        cout << setw(10) << " " << left << setw(10) << printopts[i].name << "  " << printopts[i].descript << endl;
573                                } // for
574                        } else {
575                                cout << description[i] << endl;
576                        } // if
[3e96559]577                } // if
[62ce290]578                if ( optstring[j + 1] == ':' ) j += 1;
[3e96559]579        } // for
580        if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
581    exit( EXIT_FAILURE );
582} // usage
583
[e0bd0f9]584static void parse_cmdline( int argc, char * argv[] ) {
[0da3e2c]585        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
586
[c5e5109]587        bool Wsuppress = false, Werror = false;
[0da3e2c]588        int c;
[3e96559]589        while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
[0da3e2c]590                switch ( c ) {
[1a69a90]591                  case 'c':                                                                             // diagnostic colors
592                        if ( strcmp( optarg, "always" ) == 0 ) {
593                                ErrorHelpers::colors = ErrorHelpers::Colors::Always;
594                        } else if ( strcmp( optarg, "never" ) == 0 ) {
595                                ErrorHelpers::colors = ErrorHelpers::Colors::Never;
596                        } else if ( strcmp( optarg, "auto" ) == 0 ) {
597                                ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
598                        } // if
599                        break;
[3e96559]600                  case 'h':                                                                             // help message
601                        usage( argv );                                                          // no return
[53d3ab4b]602                        break;
[372b6d3]603                  case 'i':                                                                             // invariant checking
604                        invariant = true;
605                        break;
[3e96559]606                  case 'l':                                                                             // generate libcfa.c
[0da3e2c]607                        libcfap = true;
608                        break;
[62ce290]609                  case 'L':                                                                             // generate line marks
[6de43b6]610                        linemarks = true;
[c850687]611                        break;
[3e96559]612                  case 'm':                                                                             // do not replace main
613                        nomainp = true;
[0da3e2c]614                        break;
[62ce290]615                  case 'N':                                                                             // do not generate line marks
[6de43b6]616                        linemarks = false;
[c59bde6]617                        break;
[62ce290]618                  case 'n':                                                                             // do not read prelude
[3e96559]619                        nopreludep = true;
[0da3e2c]620                        break;
[62ce290]621                  case 'p':                                                                             // generate prototypes for prelude functions
622                        genproto = true;
[0da3e2c]623                        break;
[7215000]624                  case 'd':                                     // don't print non-deterministic output
[a77257be]625                        deterministic_output = true;
626                        break;
[62ce290]627                  case 'P':                                                                             // print options
628                        for ( int i = 0;; i += 1 ) {
629                                if ( i == printoptsSize ) {
630                                        cout << "Unknown --print option " << optarg << endl;
631                                        goto Default;
632                                } // if
633                                if ( strcmp( optarg, printopts[i].name ) == 0 ) {
634                                        printopts[i].flag = printopts[i].val;
635                                        break;
636                                } // if
637                        } // for
[0da3e2c]638                        break;
[62ce290]639                  case PreludeDir:                                                              // prelude directory for debug/nodebug, hidden
640                        PreludeDirector = optarg;
[3b3491b]641                        break;
[3e96559]642                  case 'S':                                                                             // enable profiling information, argument comma separated list of names
643                        Stats::parse_params( optarg );
[ebcc940]644                        break;
[dee1f89]645                  case 't':                                                                             // building cfa stdlib
[0da3e2c]646                        treep = true;
647                        break;
[dee1f89]648                  case 'g':                                                                             // wait for gdb
649                        waiting_for_gdb = true;
650                        break;
[3e96559]651                  case 'w':                                                                             // suppress all warnings, hidden
[c5e5109]652                        Wsuppress = true;
[44bca7f]653                        break;
[3e96559]654                  case 'W':                                                                             // coordinate gcc -W with CFA, hidden
[44bca7f]655                        if ( strcmp( optarg, "all" ) == 0 ) {
[68e9ace]656                                SemanticWarning_EnableAll();
[44bca7f]657                        } else if ( strcmp( optarg, "error" ) == 0 ) {
658                                Werror = true;
659                        } else {
660                                char * warning = optarg;
661                                Severity s;
662                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
663                                        warning += 3;
664                                        s = Severity::Suppress;
665                                } else {
666                                        s = Severity::Warn;
667                                } // if
[68e9ace]668                                SemanticWarning_Set( warning, s );
[44bca7f]669                        } // if
670                        break;
[3e96559]671                  case 'D':                                                                             // ignore -Dxxx, forwarded by cpp, hidden
[0da3e2c]672                        break;
[3e96559]673                  case '?':                                                                             // unknown option
674                        if ( optopt ) {                                                         // short option ?
675                                cout << "Unknown option -" << (char)optopt << endl;
676                        } else {
677                                cout << "Unknown option " << argv[optind - 1] << endl;
678                        } // if
679                        goto Default;
680                  case ':':                                                                             // missing option
[ae47a23]681                        if ( optopt ) {                                                         // short option ?
[3e96559]682                                cout << "Missing option for -" << (char)optopt << endl;
[ae47a23]683                        } else {
[3e96559]684                                cout << "Missing option for " << argv[optind - 1] << endl;
[ae47a23]685                        } // if
[3e96559]686                        goto Default;
687                  Default:
688                  default:
689                        usage( argv );                                                          // no return
[0da3e2c]690                } // switch
691        } // while
[44bca7f]692
693        if ( Werror ) {
[68e9ace]694                SemanticWarning_WarningAsError();
[44bca7f]695        } // if
[c5e5109]696        if ( Wsuppress ) {
697                SemanticWarning_SuppressAll();
698        } // if
[44bca7f]699        // for ( const auto w : WarningFormats ) {
700        //      cout << w.name << ' ' << (int)w.severity << endl;
701        // } // for
[0da3e2c]702} // parse_cmdline
703
[1ab4ce2]704static bool notPrelude( Declaration * decl ) {
705        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
[0da3e2c]706} // notPrelude
[1ab4ce2]707
[e6955b1]708static void dump( list< Declaration * > & translationUnit, ostream & out ) {
709        list< Declaration * > decls;
[926af74]710
[62ce290]711        if ( genproto ) {
[e6955b1]712                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
[1ab4ce2]713        } else {
714                decls = translationUnit;
[926af74]715        } // if
[1ab4ce2]716
[e39241b]717        // depending on commandline options, either generate code or dump the AST
718        if ( codegenp ) {
[62ce290]719                CodeGen::generate( decls, out, ! genproto, prettycodegenp );
[e39241b]720        } else {
721                printAll( decls, out );
[3e96559]722        } // if
[7f5566b]723        deleteAll( translationUnit );
[0da3e2c]724} // dump
[1ab4ce2]725
[e499381]726static void dump( ast::TranslationUnit && transUnit, ostream & out ) {
[09f34a84]727        std::list< Declaration * > translationUnit = convert( std::move( transUnit ) );
[e499381]728        dump( translationUnit, out );
729}
730
[51b7345]731// Local Variables: //
[b87a5ed]732// tab-width: 4 //
733// mode: c++ //
734// compile-command: "make install" //
[51b7345]735// End:  //
Note: See TracBrowser for help on using the repository browser.