source: src/main.cc @ 9f0b975

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 9f0b975 was af98d27, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

ifdef out attribute fallthrough for older gccs

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