source: src/main.cc @ 1a59641

new-env
Last change on this file since 1a59641 was 28f3a19, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge branch 'master' into with_gc

  • Property mode set to 100644
File size: 19.9 KB
Line 
1
2//
3// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
4//
5// The contents of this file are covered under the licence agreement in the
6// file "LICENCE" distributed with Cforall.
7//
8// main.cc --
9//
10// Author           : Richard C. Bilson
11// Created On       : Fri May 15 23:12:02 2015
12// Last Modified By : Peter A. Buhr
13// Last Modified On : Wed Jun  6 15:51:47 2018
14// Update Count     : 498
15//
16
17#include <cxxabi.h>                         // for __cxa_demangle
18#include <execinfo.h>                       // for backtrace, backtrace_symbols
19#include <getopt.h>                         // for no_argument, optind, geto...
20#include <signal.h>                         // for signal, SIGABRT, SIGSEGV
21#include <cassert>                          // for assertf
22#include <cstdio>                           // for fopen, FILE, fclose, stdin
23#include <cstdlib>                          // for exit, free, abort, EXIT_F...
24#include <cstring>                          // for index
25#include <fstream>                          // for ofstream
26#include <iostream>                         // for operator<<, basic_ostream
27#include <iterator>                         // for back_inserter
28#include <list>                             // for list
29#include <string>                           // for char_traits, operator<<
30
31#include "../config.h"                      // for CFA_LIBDIR
32#include "CodeGen/FixMain.h"                // for FixMain
33#include "CodeGen/FixNames.h"               // for fixNames
34#include "CodeGen/Generate.h"               // for generate
35#include "CodeTools/DeclStats.h"            // for printDeclStats
36#include "CodeTools/TrackLoc.h"             // for fillLocations
37#include "Common/CompilerError.h"           // for CompilerError
38#include "Common/GC.h"                      // for GC
39#include "Common/Heap.h"
40#include "Common/PassVisitor.h"
41#include "Common/SemanticError.h"           // for SemanticError
42#include "Common/UnimplementedError.h"      // for UnimplementedError
43#include "Common/utility.h"                 // for deleteAll, filter, printAll
44#include "Concurrency/Waitfor.h"            // for generateWaitfor
45#include "ControlStruct/ExceptTranslate.h"  // for translateEHM
46#include "ControlStruct/Mutate.h"           // for mutate
47#include "GenPoly/Box.h"                    // for box
48#include "GenPoly/InstantiateGeneric.h"     // for instantiateGeneric
49#include "GenPoly/Lvalue.h"                 // for convertLvalue
50#include "GenPoly/Specialize.h"             // for convertSpecializations
51#include "InitTweak/FixInit.h"              // for fix
52#include "InitTweak/GenInit.h"              // for genInit
53#include "MakeLibCfa.h"                     // for makeLibCfa
54#include "Parser/LinkageSpec.h"             // for Spec, Cforall, Intrinsic
55#include "Parser/ParseNode.h"               // for DeclarationNode, buildList
56#include "Parser/TypedefTable.h"            // for TypedefTable
57#include "ResolvExpr/AlternativePrinter.h"  // for AlternativePrinter
58#include "ResolvExpr/Resolver.h"            // for resolve
59#include "SymTab/Validate.h"                // for validate
60#include "SynTree/Declaration.h"            // for Declaration
61#include "SynTree/GcTracer.h"               // for GC << TranslationUnit
62#include "SynTree/Visitor.h"                // for acceptAll
63#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
64#include "Virtual/ExpandCasts.h"            // for expandCasts
65
66using namespace std;
67
68#define PASS(name, pass)                   \
69        if ( errorp ) { cerr << name << endl; } \
70        HeapStats::newPass(name);               \
71        pass;
72
73LinkageSpec::Spec linkage = LinkageSpec::Cforall;
74TypedefTable typedefTable;
75DeclarationNode * parseTree = nullptr;                                  // program parse tree
76
77extern int yydebug;                                                                             // set for -g flag (Grammar)
78bool
79        astp = false,
80        bresolvep = false,
81        bboxp = false,
82        bcodegenp = false,
83        ctorinitp = false,
84        declstatsp = false,
85        exprp = false,
86        expraltp = false,
87        genericsp = false,
88        libcfap = false,
89        nopreludep = false,
90        noprotop = false,
91        nomainp = false,
92        parsep = false,
93        resolvep = false,                                                                       // used in AlternativeFinder
94        symtabp = false,
95        treep = false,
96        tuplep = false,
97        validp = false,
98        errorp = false,
99        codegenp = false,
100        prettycodegenp = false,
101        linemarks = false;
102
103static void parse_cmdline( int argc, char *argv[], const char *& filename );
104static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
105static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
106
107static void backtrace( int start ) {                                    // skip first N stack frames
108        enum { Frames = 50 };
109        void * array[Frames];
110        int size = ::backtrace( array, Frames );
111        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
112
113        *index( messages[0], '(' ) = '\0';                                      // find executable name
114        cerr << "Stack back trace for: " << messages[0] << endl;
115
116        // skip last 2 stack frames after main
117        for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
118                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
119                for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
120                        if ( *p == '(' ) {
121                                mangled_name = p;
122                        } else if ( *p == '+' ) {
123                                offset_begin = p;
124                        } else if ( *p == ')' ) {
125                                offset_end = p;
126                                break;
127                        } // if
128                } // for
129
130                // if line contains symbol, attempt to demangle
131                int frameNo = i - start;
132                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
133                        *mangled_name++ = '\0';                                         // delimit strings
134                        *offset_begin++ = '\0';
135                        *offset_end++ = '\0';
136
137                        int status;
138                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
139                        // bug in __cxa_demangle for single-character lower-case non-mangled names
140                        if ( status == 0 ) {                                            // demangling successful ?
141                                cerr << "(" << frameNo << ") " << messages[i] << " : "
142                                         << real_name << "+" << offset_begin << offset_end << endl;
143                        } else {                                                                        // otherwise, output mangled name
144                                cerr << "(" << frameNo << ") " << messages[i] << " : "
145                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
146                        } // if
147
148                        free( real_name );
149                } else {                                                                                // otherwise, print the whole line
150                        cerr << "(" << frameNo << ") " << messages[i] << endl;
151                } // if
152        } // for
153
154        free( messages );
155} // backtrace
156
157void sigSegvBusHandler( int sig_num ) {
158        cerr << "*CFA runtime error* program cfa-cpp terminated with "
159                 <<     (sig_num == SIGSEGV ? "segment fault" : "bus error")
160                 << "." << endl;
161        backtrace( 2 );                                                                         // skip first 2 stack frames
162        //_exit( EXIT_FAILURE );
163        abort();
164} // sigSegvBusHandler
165
166void sigAbortHandler( __attribute__((unused)) int sig_num ) {
167        backtrace( 6 );                                                                         // skip first 6 stack frames
168        signal( SIGABRT, SIG_DFL);                                                      // reset default signal handler
169    raise( SIGABRT );                                                                   // reraise SIGABRT
170} // sigAbortHandler
171
172
173int main( int argc, char * argv[] ) {
174        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
175        ostream *output = & cout;
176        const char *filename = nullptr;
177        list< Declaration * > translationUnit;
178
179        signal( SIGSEGV, sigSegvBusHandler );
180        signal( SIGBUS, sigSegvBusHandler );
181        signal( SIGABRT, sigAbortHandler );
182
183        parse_cmdline( argc, argv, filename );                          // process command-line arguments
184        CodeGen::FixMain::setReplaceMain( !nomainp );
185
186        try {
187                // choose to read the program from a file or stdin
188                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
189                        input = fopen( argv[ optind ], "r" );
190                        assertf( input, "cannot open %s\n", argv[ optind ] );
191                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
192                        if ( filename == nullptr ) filename = argv[ optind ];
193                        // prelude filename comes in differently
194                        if ( libcfap ) filename = "prelude.cf";
195                        optind += 1;
196                } else {                                                                                // no input file name
197                        input = stdin;
198                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
199                        // a fake name along
200                        if ( filename == nullptr ) filename = "stdin";
201                } // if
202
203                // read in the builtins, extras, and the prelude
204                if ( ! nopreludep ) {                                                   // include gcc builtins
205                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
206
207                        // Read to gcc builtins, if not generating the cfa library
208                        FILE * gcc_builtins = fopen( libcfap | treep ? "../prelude/gcc-builtins.cf" : CFA_LIBDIR "/gcc-builtins.cf", "r" );
209                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
210                        parse( gcc_builtins, LinkageSpec::Compiler );
211
212                        // read the extra prelude in, if not generating the cfa library
213                        FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
214                        assertf( extras, "cannot open extras.cf\n" );
215                        parse( extras, LinkageSpec::BuiltinC );
216
217                        if ( ! libcfap ) {
218                                // read the prelude in, if not generating the cfa library
219                                FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
220                                assertf( prelude, "cannot open prelude.cf\n" );
221                                parse( prelude, LinkageSpec::Intrinsic );
222
223                                // Read to cfa builtins, if not generating the cfa library
224                                FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
225                                assertf( builtins, "cannot open builtins.cf\n" );
226                                parse( builtins, LinkageSpec::BuiltinCFA );
227                        } // if
228                } // if
229
230                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
231
232                if ( parsep ) {
233                        parseTree->printList( cout );
234                        delete parseTree;
235                        return 0;
236                } // if
237
238                buildList( parseTree, translationUnit );
239                delete parseTree;
240                parseTree = nullptr;
241                collect( translationUnit );
242
243                if ( astp ) {
244                        dump( translationUnit );
245                        return 0;
246                } // if
247
248                // add the assignment statement after the initialization of a type parameter
249                PASS( "validate", SymTab::validate( translationUnit, symtabp ) );
250                if ( symtabp ) return 0;
251                collect( translationUnit );
252
253                if ( expraltp ) {
254                        PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
255                        acceptAll( translationUnit, printer );
256                        return 0;
257                } // if
258
259                if ( validp ) {
260                        dump( translationUnit );
261                        return 0;
262                } // if
263
264                PASS( "fixLabels", ControlStruct::fixLabels( translationUnit ) );
265                PASS( "fixNames", CodeGen::fixNames( translationUnit ) );
266                PASS( "genInit", InitTweak::genInit( translationUnit ) );
267                PASS( "expandMemberTuples" , Tuples::expandMemberTuples( translationUnit ) );
268                collect( translationUnit );
269                if ( libcfap ) {
270                        // generate the bodies of cfa library functions
271                        LibCfa::makeLibCfa( translationUnit );
272                } // if
273
274                if ( declstatsp ) {
275                        CodeTools::printDeclStats( translationUnit );
276                        return 0;
277                }
278
279                if ( bresolvep ) {
280                        dump( translationUnit );
281                        return 0;
282                } // if
283
284                CodeTools::fillLocations( translationUnit );
285
286                PASS( "resolve", ResolvExpr::resolve( translationUnit ) );
287                collect( translationUnit );
288                if ( exprp ) {
289                        dump( translationUnit );
290                        return 0;
291                } // if
292
293                // fix ObjectDecl - replaces ConstructorInit nodes
294                PASS( "fixInit", InitTweak::fix( translationUnit, filename, libcfap || treep ) );
295                collect( translationUnit );
296                if ( ctorinitp ) {
297                        dump ( translationUnit );
298                        return 0;
299                } // if
300
301                PASS( "expandUniqueExpr", Tuples::expandUniqueExpr( translationUnit ) ); // 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
302
303                PASS( "translateEHM" , ControlStruct::translateEHM( translationUnit ) );
304
305                PASS( "generateWaitfor" , Concurrency::generateWaitFor( translationUnit ) );
306
307                PASS( "convertSpecializations",  GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
308
309                PASS( "expandTuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
310                collect( translationUnit );
311                if ( tuplep ) {
312                        dump( translationUnit );
313                        return 0;
314                }
315
316                PASS( "virtual expandCasts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
317
318                PASS( "instantiateGenerics", GenPoly::instantiateGeneric( translationUnit ) );
319                collect( translationUnit );
320                if ( genericsp ) {
321                        dump( translationUnit );
322                        return 0;
323                }
324                PASS( "convertLvalue", GenPoly::convertLvalue( translationUnit ) );
325                collect( translationUnit );
326                if ( bboxp ) {
327                        dump( translationUnit );
328                        return 0;
329                } // if
330                PASS( "box", GenPoly::box( translationUnit ) );
331                collect( translationUnit );
332                if ( bcodegenp ) {
333                        dump( translationUnit );
334                        return 0;
335                }
336
337                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
338                        output = new ofstream( argv[ optind ] );
339                } // if
340
341                CodeTools::fillLocations( translationUnit );
342                PASS( "codegen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );
343
344                CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
345                if ( output != &cout ) {
346                        delete output;
347                } // if
348        } catch ( SemanticErrorException &e ) {
349                if ( errorp ) {
350                        cerr << "---AST at error:---" << endl;
351                        dump( translationUnit, cerr );
352                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
353                } // if
354                e.print();
355                if ( output != &cout ) {
356                        delete output;
357                } // if
358                return 1;
359        } catch ( UnimplementedError &e ) {
360                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
361                if ( output != &cout ) {
362                        delete output;
363                } // if
364                return 1;
365        } catch ( CompilerError &e ) {
366                cerr << "Compiler Error: " << e.get_what() << endl;
367                cerr << "(please report bugs to [REDACTED])" << endl;
368                if ( output != &cout ) {
369                        delete output;
370                } // if
371                return 1;
372        } catch(...) {
373                std::exception_ptr eptr = std::current_exception();
374                try {
375                        if (eptr) {
376                                std::rethrow_exception(eptr);
377                        }
378                        else {
379                                std::cerr << "Exception Uncaught and Unkown" << std::endl;
380                        }
381                } catch(const std::exception& e) {
382                        std::cerr << "Unaught Exception \"" << e.what() << "\"\n";
383                }
384                return 1;
385        }// try
386
387        if(!libcfap && !treep) HeapStats::printStats();
388        return 0;
389} // main
390
391void parse_cmdline( int argc, char * argv[], const char *& filename ) {
392        enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
393
394        static struct option long_opts[] = {
395                { "ast", no_argument, 0, Ast },
396                { "before-box", no_argument, 0, Bbox },
397                { "before-resolver", no_argument, 0, Bresolver },
398                { "ctorinitfix", no_argument, 0, CtorInitFix },
399                { "decl-stats", no_argument, 0, DeclStats },
400                { "expr", no_argument, 0, Expr },
401                { "expralt", no_argument, 0, ExprAlt },
402                { "grammar", no_argument, 0, Grammar },
403                { "libcfa", no_argument, 0, LibCFA },
404                { "line-marks", no_argument, 0, Linemarks },
405                { "no-line-marks", no_argument, 0, Nolinemarks },
406                { "no-preamble", no_argument, 0, Nopreamble },
407                { "parse", no_argument, 0, Parse },
408                { "no-prototypes", no_argument, 0, Prototypes },
409                { "resolver", no_argument, 0, Resolver },
410                { "symbol", no_argument, 0, Symbol },
411                { "tree", no_argument, 0, Tree },
412                { "tuple-expansion", no_argument, 0, TupleExpansion },
413                { "validate", no_argument, 0, Validate },
414                { 0, 0, 0, 0 }
415        }; // long_opts
416        int long_index;
417
418        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
419
420        bool Wsuppress = false, Werror = false;
421        int c;
422        while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrstTvwW:yzZD:F:", long_opts, &long_index )) != -1 ) {
423                switch ( c ) {
424                  case Ast:
425                  case 'a':                                                                             // dump AST
426                        astp = true;
427                        break;
428                  case Bresolver:
429                  case 'b':                                                                             // print before resolver steps
430                        bresolvep = true;
431                        break;
432                  case 'B':                                                                             // print before box steps
433                        bboxp = true;
434                        break;
435                  case CtorInitFix:
436                  case 'c':                                                                             // print after constructors and destructors are replaced
437                        ctorinitp = true;
438                        break;
439                  case 'C':                                                                             // print before code generation
440                        bcodegenp = true;
441                        break;
442                  case DeclStats:
443                  case 'd':
444                    declstatsp = true;
445                        break;
446                  case Expr:
447                  case 'e':                                                                             // dump AST after expression analysis
448                        exprp = true;
449                        break;
450                  case ExprAlt:
451                  case 'f':                                                                             // print alternatives for expressions
452                        expraltp = true;
453                        break;
454                  case Grammar:
455                  case 'g':                                                                             // bison debugging info (grammar rules)
456                        yydebug = true;
457                        break;
458                  case 'G':                                                                             // dump AST after instantiate generics
459                        genericsp = true;
460                        break;
461                  case LibCFA:
462                  case 'l':                                                                             // generate libcfa.c
463                        libcfap = true;
464                        break;
465                  case Linemarks:
466                  case 'L':                                                                             // print lines marks
467                        linemarks = true;
468                        break;
469                  case Nopreamble:
470                  case 'n':                                                                             // do not read preamble
471                        nopreludep = true;
472                        break;
473                  case Nolinemarks:
474                  case 'N':                                                                             // suppress line marks
475                        linemarks = false;
476                        break;
477                  case Prototypes:
478                  case 'p':                                                                             // generate prototypes for preamble functions
479                        noprotop = true;
480                        break;
481                  case 'm':                                                                             // don't replace the main
482                        nomainp = true;
483                        break;
484                  case Parse:
485                  case 'q':                                                                             // dump parse tree
486                        parsep = true;
487                        break;
488                  case Resolver:
489                  case 'r':                                                                             // print resolver steps
490                        resolvep = true;
491                        break;
492                  case Symbol:
493                  case 's':                                                                             // print symbol table events
494                        symtabp = true;
495                        break;
496                  case Tree:
497                  case 't':                                                                             // build in tree
498                        treep = true;
499                        break;
500                  case TupleExpansion:
501                  case 'T':                                                                             // print after tuple expansion
502                        tuplep = true;
503                        break;
504                  case 'v':                                                                             // dump AST after decl validation pass
505                        validp = true;
506                        break;
507                  case 'w':
508                        Wsuppress = true;
509                        break;
510                  case 'W':
511                        if ( strcmp( optarg, "all" ) == 0 ) {
512                                SemanticWarning_EnableAll();
513                        } else if ( strcmp( optarg, "error" ) == 0 ) {
514                                Werror = true;
515                        } else {
516                                char * warning = optarg;
517                                Severity s;
518                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
519                                        warning += 3;
520                                        s = Severity::Suppress;
521                                } else {
522                                        s = Severity::Warn;
523                                } // if
524                                SemanticWarning_Set( warning, s );
525                        } // if
526                        break;
527                  case 'y':                                                                             // dump AST on error
528                        errorp = true;
529                        break;
530                  case 'z':                                                                             // dump as codegen rather than AST
531                        codegenp = true;
532                        break;
533                        case 'Z':                                                                       // prettyprint during codegen (i.e. print unmangled names, etc.)
534                        prettycodegenp = true;
535                        break;
536                  case 'D':                                                                             // ignore -Dxxx
537                        break;
538                  case 'F':                                                                             // source file-name without suffix
539                        filename = optarg;
540                        break;
541                  case '?':
542                        if ( optopt ) {                                                         // short option ?
543                                assertf( false, "Unknown option: -%c\n", (char)optopt );
544                        } else {
545                                assertf( false, "Unknown option: %s\n", argv[optind - 1] );
546                        } // if
547                        #if defined(__GNUC__) && __GNUC__ >= 7
548                                __attribute__((fallthrough));
549                        #endif
550                  default:
551                        abort();
552                } // switch
553        } // while
554
555        if ( Werror ) {
556                SemanticWarning_WarningAsError();
557        } // if
558        if ( Wsuppress ) {
559                SemanticWarning_SuppressAll();
560        } // if
561        // for ( const auto w : WarningFormats ) {
562        //      cout << w.name << ' ' << (int)w.severity << endl;
563        // } // for
564} // parse_cmdline
565
566static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
567        extern int yyparse( void );
568        extern FILE * yyin;
569        extern int yylineno;
570
571        ::linkage = linkage;                                                            // set globals
572        yyin = input;
573        yylineno = 1;
574        int parseStatus = yyparse();
575
576        fclose( input );
577        if ( shouldExit || parseStatus != 0 ) {
578                exit( parseStatus );
579        } // if
580} // parse
581
582static bool notPrelude( Declaration * decl ) {
583        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
584} // notPrelude
585
586static void dump( list< Declaration * > & translationUnit, ostream & out ) {
587        list< Declaration * > decls;
588
589        if ( noprotop ) {
590                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
591        } else {
592                decls = translationUnit;
593        } // if
594
595        // depending on commandline options, either generate code or dump the AST
596        if ( codegenp ) {
597                CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
598        } else {
599                printAll( decls, out );
600        }
601} // dump
602
603// Local Variables: //
604// tab-width: 4 //
605// mode: c++ //
606// compile-command: "make install" //
607// End:  //
Note: See TracBrowser for help on using the repository browser.