source: src/main.cc @ 2bfc6b2

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2bfc6b2 was 9aa9126, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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