source: src/main.cc @ 623c16a

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since 623c16a was 44bca7f, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

first attempt at warning control

  • Property mode set to 100644
File size: 19.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 May  2 14:59:02 2018
13// Update Count     : 490
14//
15
16#include <cxxabi.h>                         // for __cxa_demangle
17#include <execinfo.h>                       // for backtrace, backtrace_symbols
18#include <getopt.h>                         // for no_argument, optind, geto...
19#include <signal.h>                         // for signal, SIGABRT, SIGSEGV
20#include <cassert>                          // for assertf
21#include <cstdio>                           // for fopen, FILE, fclose, stdin
22#include <cstdlib>                          // for exit, free, abort, EXIT_F...
23#include <cstring>                          // for index
24#include <fstream>                          // for ofstream
25#include <iostream>                         // for operator<<, basic_ostream
26#include <iterator>                         // for back_inserter
27#include <list>                             // for list
28#include <string>                           // for char_traits, operator<<
29
30#include "../config.h"                      // for CFA_LIBDIR
31#include "CodeGen/FixMain.h"                // for FixMain
32#include "CodeGen/FixNames.h"               // for fixNames
33#include "CodeGen/Generate.h"               // for generate
34#include "CodeTools/DeclStats.h"            // for printDeclStats
35#include "CodeTools/TrackLoc.h"             // for fillLocations
36#include "Common/PassVisitor.h"
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/InstantiateGeneric.h"     // for instantiateGeneric
46#include "GenPoly/Lvalue.h"                 // for convertLvalue
47#include "GenPoly/Specialize.h"             // for convertSpecializations
48#include "InitTweak/FixInit.h"              // for fix
49#include "InitTweak/GenInit.h"              // for genInit
50#include "MakeLibCfa.h"                     // for makeLibCfa
51#include "Parser/LinkageSpec.h"             // for Spec, Cforall, Intrinsic
52#include "Parser/ParseNode.h"               // for DeclarationNode, buildList
53#include "Parser/TypedefTable.h"            // for TypedefTable
54#include "ResolvExpr/AlternativePrinter.h"  // for AlternativePrinter
55#include "ResolvExpr/Resolver.h"            // for resolve
56#include "SymTab/Validate.h"                // for validate
57#include "SynTree/Declaration.h"            // for Declaration
58#include "SynTree/Visitor.h"                // for acceptAll
59#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
60#include "Virtual/ExpandCasts.h"            // for expandCasts
61
62using namespace std;
63
64#define OPTPRINT(x) if ( errorp ) cerr << x << endl;
65
66
67LinkageSpec::Spec linkage = LinkageSpec::Cforall;
68TypedefTable typedefTable;
69DeclarationNode * parseTree = nullptr;                                  // program parse tree
70
71extern int yydebug;                                                                             // set for -g flag (Grammar)
72bool
73        astp = false,
74        bresolvep = false,
75        bboxp = false,
76        bcodegenp = false,
77        ctorinitp = false,
78        declstatsp = false,
79        exprp = false,
80        expraltp = false,
81        genericsp = 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        linemarks = 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        // std::cout << "main" << std::endl;
177        // for ( int i = 0; i < argc; i += 1 ) {
178        //      std::cout << '\t' << argv[i] << std::endl;
179        // } // for
180
181        parse_cmdline( argc, argv, filename );                          // process command-line arguments
182        CodeGen::FixMain::setReplaceMain( !nomainp );
183
184        try {
185                // choose to read the program from a file or stdin
186                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
187                        input = fopen( argv[ optind ], "r" );
188                        assertf( input, "cannot open %s\n", argv[ optind ] );
189                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
190                        if ( filename == nullptr ) filename = argv[ optind ];
191                        // prelude filename comes in differently
192                        if ( libcfap ) filename = "prelude.cf";
193                        optind += 1;
194                } else {                                                                                // no input file name
195                        input = stdin;
196                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
197                        // a fake name along
198                        if ( filename == nullptr ) filename = "stdin";
199                } // if
200
201                // read in the builtins, extras, and the prelude
202                if ( ! nopreludep ) {                                                   // include gcc builtins
203                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
204
205                        // Read to gcc builtins, if not generating the cfa library
206                        FILE * gcc_builtins = fopen( libcfap | treep ? "../prelude/gcc-builtins.cf" : CFA_LIBDIR "/gcc-builtins.cf", "r" );
207                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
208                        parse( gcc_builtins, LinkageSpec::Compiler );
209
210                        // read the extra prelude in, if not generating the cfa library
211                        FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
212                        assertf( extras, "cannot open extras.cf\n" );
213                        parse( extras, LinkageSpec::BuiltinC );
214
215                        if ( ! libcfap ) {
216                                // read the prelude in, if not generating the cfa library
217                                FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
218                                assertf( prelude, "cannot open prelude.cf\n" );
219                                parse( prelude, LinkageSpec::Intrinsic );
220
221                                // Read to cfa builtins, if not generating the cfa library
222                                FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
223                                assertf( builtins, "cannot open builtins.cf\n" );
224                                parse( builtins, LinkageSpec::BuiltinCFA );
225                        } // if
226                } // if
227
228                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
229
230                if ( parsep ) {
231                        parseTree->printList( cout );
232                        delete parseTree;
233                        return 0;
234                } // if
235
236                buildList( parseTree, translationUnit );
237                delete parseTree;
238                parseTree = nullptr;
239
240                if ( astp ) {
241                        dump( translationUnit );
242                        return 0;
243                } // if
244
245                // add the assignment statement after the initialization of a type parameter
246                OPTPRINT( "validate" )
247                SymTab::validate( translationUnit, symtabp );
248                if ( symtabp ) {
249                        deleteAll( translationUnit );
250                        return 0;
251                } // if
252
253                if ( expraltp ) {
254                        PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
255                        acceptAll( translationUnit, printer );
256                        return 0;
257                } // if
258
259                if ( validp ) {
260                        dump( translationUnit );
261                        return 0;
262                } // if
263
264                OPTPRINT( "mutate" )
265                ControlStruct::mutate( translationUnit );
266                OPTPRINT( "fixNames" )
267                CodeGen::fixNames( translationUnit );
268                OPTPRINT( "genInit" )
269                InitTweak::genInit( translationUnit );
270                OPTPRINT( "expandMemberTuples" );
271                Tuples::expandMemberTuples( translationUnit );
272                if ( libcfap ) {
273                        // generate the bodies of cfa library functions
274                        LibCfa::makeLibCfa( translationUnit );
275                } // if
276
277                if ( declstatsp ) {
278                        CodeTools::printDeclStats( translationUnit );
279                        deleteAll( translationUnit );
280                        return 0;
281                }
282
283                if ( bresolvep ) {
284                        dump( translationUnit );
285                        return 0;
286                } // if
287
288                CodeTools::fillLocations( translationUnit );
289
290                OPTPRINT( "resolve" )
291                ResolvExpr::resolve( translationUnit );
292                if ( exprp ) {
293                        dump( translationUnit );
294                        return 0;
295                } // if
296
297                // fix ObjectDecl - replaces ConstructorInit nodes
298                OPTPRINT( "fixInit" )
299                InitTweak::fix( translationUnit, filename, libcfap || treep );
300                if ( ctorinitp ) {
301                        dump ( translationUnit );
302                        return 0;
303                } // if
304
305                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
306                Tuples::expandUniqueExpr( translationUnit );
307
308                OPTPRINT( "translateEHM" );
309                ControlStruct::translateEHM( translationUnit );
310
311                OPTPRINT( "generateWaitfor" );
312                Concurrency::generateWaitFor( translationUnit );
313
314                OPTPRINT( "convertSpecializations" ) // needs to happen before tuple types are expanded
315                GenPoly::convertSpecializations( translationUnit );
316
317                OPTPRINT( "expandTuples" ); // xxx - is this the right place for this?
318                Tuples::expandTuples( translationUnit );
319                if ( tuplep ) {
320                        dump( translationUnit );
321                        return 0;
322                }
323
324                OPTPRINT( "virtual expandCasts" ) // Must come after translateEHM
325                Virtual::expandCasts( translationUnit );
326
327                OPTPRINT("instantiateGenerics")
328                GenPoly::instantiateGeneric( translationUnit );
329                if ( genericsp ) {
330                        dump( translationUnit );
331                        return 0;
332                }
333                OPTPRINT( "convertLvalue" )
334                GenPoly::convertLvalue( translationUnit );
335
336
337                if ( bboxp ) {
338                        dump( translationUnit );
339                        return 0;
340                } // if
341                OPTPRINT( "box" )
342                GenPoly::box( translationUnit );
343
344                if ( bcodegenp ) {
345                        dump( translationUnit );
346                        return 0;
347                }
348
349                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
350                        output = new ofstream( argv[ optind ] );
351                } // if
352
353                CodeTools::fillLocations( translationUnit );
354                OPTPRINT( "codegen" )
355                CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks );
356
357                CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
358                OPTPRINT( "end" )
359
360                if ( output != &cout ) {
361                        delete output;
362                } // if
363        } catch ( SemanticErrorException &e ) {
364                if ( errorp ) {
365                        cerr << "---AST at error:---" << endl;
366                        dump( translationUnit, cerr );
367                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
368                } // if
369                e.print();
370                if ( output != &cout ) {
371                        delete output;
372                } // if
373                return 1;
374        } catch ( UnimplementedError &e ) {
375                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
376                if ( output != &cout ) {
377                        delete output;
378                } // if
379                return 1;
380        } catch ( CompilerError &e ) {
381                cerr << "Compiler Error: " << e.get_what() << endl;
382                cerr << "(please report bugs to [REDACTED])" << endl;
383                if ( output != &cout ) {
384                        delete output;
385                } // if
386                return 1;
387        } // try
388
389        deleteAll( translationUnit );
390        return 0;
391} // main
392
393void parse_cmdline( int argc, char * argv[], const char *& filename ) {
394        enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
395
396        static struct option long_opts[] = {
397                { "ast", no_argument, 0, Ast },
398                { "before-box", no_argument, 0, Bbox },
399                { "before-resolver", no_argument, 0, Bresolver },
400                { "ctorinitfix", no_argument, 0, CtorInitFix },
401                { "decl-stats", no_argument, 0, DeclStats },
402                { "expr", no_argument, 0, Expr },
403                { "expralt", no_argument, 0, ExprAlt },
404                { "grammar", no_argument, 0, Grammar },
405                { "libcfa", no_argument, 0, LibCFA },
406                { "line-marks", no_argument, 0, Linemarks },
407                { "no-line-marks", no_argument, 0, Nolinemarks },
408                { "no-preamble", no_argument, 0, Nopreamble },
409                { "parse", no_argument, 0, Parse },
410                { "no-prototypes", no_argument, 0, Prototypes },
411                { "resolver", no_argument, 0, Resolver },
412                { "symbol", no_argument, 0, Symbol },
413                { "tree", no_argument, 0, Tree },
414                { "tuple-expansion", no_argument, 0, TupleExpansion },
415                { "validate", no_argument, 0, Validate },
416                { 0, 0, 0, 0 }
417        }; // long_opts
418        int long_index;
419
420        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
421
422        bool Werror = false;
423        int c;
424        while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrstTvwW:yzZD:F:", long_opts, &long_index )) != -1 ) {
425                switch ( c ) {
426                  case Ast:
427                  case 'a':                                                                             // dump AST
428                        astp = true;
429                        break;
430                  case Bresolver:
431                  case 'b':                                                                             // print before resolver steps
432                        bresolvep = true;
433                        break;
434                  case 'B':                                                                             // print before box steps
435                        bboxp = true;
436                        break;
437                  case CtorInitFix:
438                  case 'c':                                                                             // print after constructors and destructors are replaced
439                        ctorinitp = true;
440                        break;
441                  case 'C':                                                                             // print before code generation
442                        bcodegenp = true;
443                        break;
444                  case DeclStats:
445                  case 'd':
446                    declstatsp = true;
447                        break;
448                  case Expr:
449                  case 'e':                                                                             // dump AST after expression analysis
450                        exprp = true;
451                        break;
452                  case ExprAlt:
453                  case 'f':                                                                             // print alternatives for expressions
454                        expraltp = true;
455                        break;
456                  case Grammar:
457                  case 'g':                                                                             // bison debugging info (grammar rules)
458                        yydebug = true;
459                        break;
460                  case 'G':                                                                             // dump AST after instantiate generics
461                        genericsp = true;
462                        break;
463                  case LibCFA:
464                  case 'l':                                                                             // generate libcfa.c
465                        libcfap = true;
466                        break;
467                  case Linemarks:
468                  case 'L':                                                                             // print lines marks
469                        linemarks = true;
470                        break;
471                  case Nopreamble:
472                  case 'n':                                                                             // do not read preamble
473                        nopreludep = true;
474                        break;
475                  case Nolinemarks:
476                  case 'N':                                                                             // suppress line marks
477                        linemarks = false;
478                        break;
479                  case Prototypes:
480                  case 'p':                                                                             // generate prototypes for preamble functions
481                        noprotop = true;
482                        break;
483                  case 'm':                                                                             // don't replace the main
484                        nomainp = true;
485                        break;
486                  case Parse:
487                  case 'q':                                                                             // dump parse tree
488                        parsep = true;
489                        break;
490                  case Resolver:
491                  case 'r':                                                                             // print resolver steps
492                        resolvep = true;
493                        break;
494                  case Symbol:
495                  case 's':                                                                             // print symbol table events
496                        symtabp = true;
497                        break;
498                  case Tree:
499                  case 't':                                                                             // build in tree
500                        treep = true;
501                        break;
502                  case TupleExpansion:
503                  case 'T':                                                                             // print after tuple expansion
504                        tuplep = true;
505                        break;
506                  case 'v':                                                                             // dump AST after decl validation pass
507                        validp = true;
508                        break;
509                  case 'w':
510                        for ( auto & w : WarningFormats ) {
511                                w.severity = Severity::Suppress;
512                        } // for
513                        break;
514                  case 'W':
515                        if ( strcmp( optarg, "all" ) == 0 ) {
516                                for ( auto & w : WarningFormats ) {
517                                        if ( w.severity == Severity::Suppress ) w.severity = Severity::Warn;
518                                } // for
519                        } else if ( strcmp( optarg, "error" ) == 0 ) {
520                                Werror = true;
521                        } else {
522                                char * warning = optarg;
523                                Severity s;
524                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
525                                        warning += 3;
526                                        s = Severity::Suppress;
527                                } else {
528                                        s = Severity::Warn;
529                                } // if
530                                for ( auto  & w : WarningFormats ) {
531                                        if ( strcmp( warning, w.name ) == 0 ) { // replace the argument for cfa-cpp
532                                                w.severity = s;
533                                                break;
534                                        } // if
535                                } // for
536                        } // if
537                        break;
538                  case 'y':                                                                             // dump AST on error
539                        errorp = true;
540                        break;
541                  case 'z':                                                                             // dump as codegen rather than AST
542                        codegenp = true;
543                        break;
544                        case 'Z':                                                                       // prettyprint during codegen (i.e. print unmangled names, etc.)
545                        prettycodegenp = true;
546                        break;
547                  case 'D':                                                                             // ignore -Dxxx
548                        break;
549                  case 'F':                                                                             // source file-name without suffix
550                        filename = optarg;
551                        break;
552                  case '?':
553                        if ( optopt ) {                                                         // short option ?
554                                assertf( false, "Unknown option: -%c\n", (char)optopt );
555                        } else {
556                                assertf( false, "Unknown option: %s\n", argv[optind - 1] );
557                        } // if
558                        #if __GNUC__ < 7
559                        #else
560                                __attribute__((fallthrough));
561                        #endif
562                  default:
563                        abort();
564                } // switch
565        } // while
566
567        if ( Werror ) {
568                for ( auto & w : WarningFormats ) {
569                        if ( w.severity == Severity::Warn ) w.severity = Severity::Error;
570                } // for
571        } // if
572        // for ( const auto w : WarningFormats ) {
573        //      cout << w.name << ' ' << (int)w.severity << endl;
574        // } // for
575} // parse_cmdline
576
577static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
578        extern int yyparse( void );
579        extern FILE * yyin;
580        extern int yylineno;
581
582        ::linkage = linkage;                                                            // set globals
583        yyin = input;
584        yylineno = 1;
585        typedefTable.enterScope();
586        int parseStatus = yyparse();
587
588        fclose( input );
589        if ( shouldExit || parseStatus != 0 ) {
590                exit( parseStatus );
591        } // if
592} // parse
593
594static bool notPrelude( Declaration * decl ) {
595        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
596} // notPrelude
597
598static void dump( list< Declaration * > & translationUnit, ostream & out ) {
599        list< Declaration * > decls;
600
601        if ( noprotop ) {
602                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
603        } else {
604                decls = translationUnit;
605        } // if
606
607        // depending on commandline options, either generate code or dump the AST
608        if ( codegenp ) {
609                CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
610        } else {
611                printAll( decls, out );
612        }
613        deleteAll( translationUnit );
614} // dump
615
616// Local Variables: //
617// tab-width: 4 //
618// mode: c++ //
619// compile-command: "make install" //
620// End:  //
Note: See TracBrowser for help on using the repository browser.