source: src/main.cc @ 4a161be

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 4a161be was 53d3ab4b, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Add G flag for debug dump after InstantiateGeneric?

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