source: src/main.cc @ 805c167

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 805c167 was e39241b, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

allow codegen as an alternative to AST dump after any pass with the -z option

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