source: src/main.cc @ 0270824

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

Replace user main with custom main, prototype

  • Property mode set to 100644
File size: 14.5 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        parsep = false,
69        resolvep = false,                                                                       // used in AlternativeFinder
70        symtabp = false,
71        treep = false,
72        tuplep = false,
73        validp = false,
74        errorp = false,
75        codegenp = false;
76
77static void parse_cmdline( int argc, char *argv[], const char *& filename );
78static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
79static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
80
81std::unique_ptr<FunctionDecl> translation_unit_main_signature = nullptr;
82
83static void backtrace( int start ) {                                    // skip first N stack frames
84        enum { Frames = 50 };
85        void * array[Frames];
86        int size = ::backtrace( array, Frames );
87        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
88
89        *index( messages[0], '(' ) = '\0';                                      // find executable name
90        cerr << "Stack back trace for: " << messages[0] << endl;
91
92        // skip last 2 stack frames after main
93        for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
94                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
95                for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
96                        if ( *p == '(' ) {
97                                mangled_name = p;
98                        } else if ( *p == '+' ) {
99                                offset_begin = p;
100                        } else if ( *p == ')' ) {
101                                offset_end = p;
102                                break;
103                        } // if
104                } // for
105
106                // if line contains symbol, attempt to demangle
107                int frameNo = i - start;
108                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
109                        *mangled_name++ = '\0';                                         // delimit strings
110                        *offset_begin++ = '\0';
111                        *offset_end++ = '\0';
112
113                        int status;
114                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
115                        // bug in __cxa_demangle for single-character lower-case non-mangled names
116                        if ( status == 0 ) {                                            // demangling successful ?
117                                cerr << "(" << frameNo << ") " << messages[i] << " : "
118                                         << real_name << "+" << offset_begin << offset_end << endl;
119                        } else {                                                                        // otherwise, output mangled name
120                                cerr << "(" << frameNo << ") " << messages[i] << " : "
121                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
122                        } // if
123
124                        free( real_name );
125                } else {                                                                                // otherwise, print the whole line
126                        cerr << "(" << frameNo << ") " << messages[i] << endl;
127                } // if
128        } // for
129
130        free( messages );
131} // backtrace
132
133void sigSegvBusHandler( int sig_num ) {
134        cerr << "*CFA runtime error* program cfa-cpp terminated with "
135                 <<     (sig_num == SIGSEGV ? "segment fault" : "bus error")
136                 << "." << endl;
137        backtrace( 2 );                                                                         // skip first 2 stack frames
138        exit( EXIT_FAILURE );
139} // sigSegvBusHandler
140
141void sigAbortHandler( int sig_num ) {
142        backtrace( 6 );                                                                         // skip first 6 stack frames
143        signal( SIGABRT, SIG_DFL);                                                      // reset default signal handler
144    raise( SIGABRT );                                                                   // reraise SIGABRT
145} // sigAbortHandler
146
147
148int main( int argc, char * argv[] ) {
149        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
150        ostream *output = & cout;
151        const char *filename = nullptr;
152        list< Declaration * > translationUnit;
153
154        signal( SIGSEGV, sigSegvBusHandler );
155        signal( SIGBUS, sigSegvBusHandler );
156        signal( SIGABRT, sigAbortHandler );
157
158        parse_cmdline( argc, argv, filename );                          // process command-line arguments
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                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
178                        output = new ofstream( argv[ optind ] );
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                // add the assignment statement after the initialization of a type parameter
219                OPTPRINT( "validate" )
220                SymTab::validate( translationUnit, symtabp );
221                if ( symtabp ) {
222                        deleteAll( translationUnit );
223                        return 0;
224                } // if
225
226                if ( expraltp ) {
227                        ResolvExpr::AlternativePrinter printer( cout );
228                        acceptAll( translationUnit, printer );
229                        return 0;
230                } // if
231
232                if ( validp ) {
233                        dump( translationUnit );
234                        return 0;
235                } // if
236
237                OPTPRINT( "mutate" )
238                ControlStruct::mutate( translationUnit );
239                OPTPRINT( "fixNames" )
240                CodeGen::fixNames( translationUnit );
241                OPTPRINT( "tweakInit" )
242                InitTweak::genInit( translationUnit );
243                OPTPRINT( "expandMemberTuples" );
244                Tuples::expandMemberTuples( translationUnit );
245                if ( libcfap ) {
246                        // generate the bodies of cfa library functions
247                        LibCfa::makeLibCfa( translationUnit );
248                } // if
249
250                if ( bresolvep ) {
251                        dump( translationUnit );
252                        return 0;
253                } // if
254
255                OPTPRINT( "resolve" )
256                ResolvExpr::resolve( translationUnit );
257                if ( exprp ) {
258                        dump( translationUnit );
259                        return 0;
260                } // if
261
262                // fix ObjectDecl - replaces ConstructorInit nodes
263                OPTPRINT( "fixInit" )
264                InitTweak::fix( translationUnit, filename, libcfap || treep );
265                if ( ctorinitp ) {
266                        dump ( translationUnit );
267                        return 0;
268                } // if
269
270                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
271                Tuples::expandUniqueExpr( translationUnit );
272
273                OPTPRINT( "convertSpecializations" ) // needs to happen before tuple types are expanded
274                GenPoly::convertSpecializations( translationUnit );
275
276                OPTPRINT( "expandTuples" ); // xxx - is this the right place for this?
277                Tuples::expandTuples( translationUnit );
278                if ( tuplep ) {
279                        dump( translationUnit );
280                        return 0;
281                }
282
283                OPTPRINT("instantiateGenerics")
284                GenPoly::instantiateGeneric( translationUnit );
285                OPTPRINT( "copyParams" );
286                GenPoly::copyParams( translationUnit );
287                OPTPRINT( "convertLvalue" )
288                GenPoly::convertLvalue( translationUnit );
289
290                if ( bboxp ) {
291                        dump( translationUnit );
292                        return 0;
293                } // if
294                OPTPRINT( "box" )
295                GenPoly::box( translationUnit );
296
297                // print tree right before code generation
298                if ( codegenp ) {
299                        dump( translationUnit );
300                        return 0;
301                } // if
302
303                CodeGen::generate( translationUnit, *output, ! noprotop );
304
305                if( translation_unit_main_signature ) {
306                        *output << "int main(int argc, char** argv) { return ";
307
308                        *output << translation_unit_main_signature->get_scopedMangleName() << "(";
309                        if(translation_unit_main_signature->get_functionType()->get_parameters().size() != 0){
310                                *output << "argc, argv";
311                        }
312                        *output << ");";
313
314                        *output << " }\n";
315                }
316
317                if ( output != &cout ) {
318                        delete output;
319                } // if
320        } catch ( SemanticError &e ) {
321                if ( errorp ) {
322                        cerr << "---AST at error:---" << endl;
323                        dump( translationUnit, cerr );
324                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
325                } // if
326                e.print( cerr );
327                if ( output != &cout ) {
328                        delete output;
329                } // if
330                return 1;
331        } catch ( UnimplementedError &e ) {
332                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
333                if ( output != &cout ) {
334                        delete output;
335                } // if
336                return 1;
337        } catch ( CompilerError &e ) {
338                cerr << "Compiler Error: " << e.get_what() << endl;
339                cerr << "(please report bugs to " << endl;
340                if ( output != &cout ) {
341                        delete output;
342                } // if
343                return 1;
344        } // try
345
346        deleteAll( translationUnit );
347        return 0;
348} // main
349
350void parse_cmdline( int argc, char * argv[], const char *& filename ) {
351        enum { Ast, Bbox, Bresolver, CtorInitFix, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
352
353        static struct option long_opts[] = {
354                { "ast", no_argument, 0, Ast },
355                { "before-box", no_argument, 0, Bbox },
356                { "before-resolver", no_argument, 0, Bresolver },
357                { "ctorinitfix", no_argument, 0, CtorInitFix },
358                { "expr", no_argument, 0, Expr },
359                { "expralt", no_argument, 0, ExprAlt },
360                { "grammar", no_argument, 0, Grammar },
361                { "libcfa", no_argument, 0, LibCFA },
362                { "no-preamble", no_argument, 0, Nopreamble },
363                { "parse", no_argument, 0, Parse },
364                { "no-prototypes", no_argument, 0, Prototypes },
365                { "resolver", no_argument, 0, Resolver },
366                { "symbol", no_argument, 0, Symbol },
367                { "tree", no_argument, 0, Tree },
368                { "tuple-expansion", no_argument, 0, TupleExpansion },
369                { "validate", no_argument, 0, Validate },
370                { 0, 0, 0, 0 }
371        }; // long_opts
372        int long_index;
373
374        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
375
376        int c;
377        while ( (c = getopt_long( argc, argv, "abBcefglnpqrstTvyzD:F:", long_opts, &long_index )) != -1 ) {
378                switch ( c ) {
379                  case Ast:
380                  case 'a':                                                                             // dump AST
381                        astp = true;
382                        break;
383                  case Bresolver:
384                  case 'b':                                                                             // print before resolver steps
385                        bresolvep = true;
386                        break;
387                  case 'B':                                                                             // print before box steps
388                        bboxp = true;
389                        break;
390                  case CtorInitFix:
391                  case 'c':
392                        ctorinitp = true;
393                        break;
394                  case Expr:
395                  case 'e':                                                                             // dump AST after expression analysis
396                        exprp = true;
397                        break;
398                  case ExprAlt:
399                  case 'f':                                                                             // print alternatives for expressions
400                        expraltp = true;
401                        break;
402                  case Grammar:
403                  case 'g':                                                                             // bison debugging info (grammar rules)
404                        yydebug = true;
405                        break;
406                  case LibCFA:
407                  case 'l':                                                                             // generate libcfa.c
408                        libcfap = true;
409                        break;
410                  case Nopreamble:
411                  case 'n':                                                                             // do not read preamble
412                        nopreludep = true;
413                        break;
414                  case Prototypes:
415                  case 'p':                                                                             // generate prototypes for preamble functions
416                        noprotop = true;
417                        break;
418                  case Parse:
419                  case 'q':                                                                             // dump parse tree
420                        parsep = true;
421                        break;
422                  case Resolver:
423                  case 'r':                                                                             // print resolver steps
424                        resolvep = true;
425                        break;
426                  case Symbol:
427                  case 's':                                                                             // print symbol table events
428                        symtabp = true;
429                        break;
430                  case Tree:
431                  case 't':                                                                             // build in tree
432                        treep = true;
433                        break;
434                  case TupleExpansion:
435                  case 'T':                                                                             // print after tuple expansion
436                        tuplep = true;
437                        break;
438                  case 'v':                                                                             // dump AST after decl validation pass
439                        validp = true;
440                        break;
441                  case 'y':
442                        errorp = true;
443                        break;
444                  case 'z':
445                        codegenp = true;
446                        break;
447                  case 'D':                                                                             // ignore -Dxxx
448                        break;
449                  case 'F':                                                                             // source file-name without suffix
450                        filename = optarg;
451                        break;
452                  case '?':
453                        assertf( false, "Unknown option: '%c'\n", (char)optopt );
454                  default:
455                        abort();
456                } // switch
457        } // while
458} // parse_cmdline
459
460static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
461        extern int yyparse( void );
462        extern FILE * yyin;
463        extern int yylineno;
464
465        ::linkage = linkage;                                                            // set globals
466        yyin = input;
467        yylineno = 1;
468        typedefTable.enterScope();
469        int parseStatus = yyparse();
470
471        fclose( input );
472        if ( shouldExit || parseStatus != 0 ) {
473                exit( parseStatus );
474        } // if
475} // parse
476
477static bool notPrelude( Declaration * decl ) {
478        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
479} // notPrelude
480
481static void dump( list< Declaration * > & translationUnit, ostream & out ) {
482        list< Declaration * > decls;
483
484        if ( noprotop ) {
485                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
486        } else {
487                decls = translationUnit;
488        } // if
489
490        printAll( decls, out );
491        deleteAll( translationUnit );
492} // dump
493
494// Local Variables: //
495// tab-width: 4 //
496// mode: c++ //
497// compile-command: "make install" //
498// End:  //
Note: See TracBrowser for help on using the repository browser.