source: src/main.cc @ f32e53e

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

Fix build for 16.04

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