source: src/main.cc @ 7cc2c8d

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 7cc2c8d was 3fe34ae, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Added bootloader.cf which contains the main that wraps the user main

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