source: src/main.cc @ e3e16bc

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

Skeleton for waitfor language support

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