source: src/main.cc @ 7358f65

ADTast-experimental
Last change on this file since 7358f65 was 6e1e2d0, checked in by caparsons <caparson@…>, 14 months ago

resolved merge conflicts

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