source: src/main.cc @ 59239b8

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 59239b8 was 13de47bc, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Proper bootloader boilerplate implemented

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