source: src/main.cc@ 6fd1955

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 6fd1955 was 3c0d4cd, checked in by tdelisle <tdelisle@…>, 7 years ago

Fixed/implemented % of parent printing in timing sections

  • Property mode set to 100644
File size: 20.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 : Sat Feb 16 09:14:04 2019
13// Update Count : 500
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 "CompilationState.h"
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/ResolvProtoDump.h" // for dumpAsResolvProto
37#include "CodeTools/TrackLoc.h" // for fillLocations
38#include "Common/CompilerError.h" // for CompilerError
39#include "Common/Stats.h"
40#include "Common/PassVisitor.h"
41#include "Common/SemanticError.h" // for SemanticError
42#include "Common/UnimplementedError.h" // for UnimplementedError
43#include "Common/utility.h" // for deleteAll, filter, printAll
44#include "Concurrency/Waitfor.h" // for generateWaitfor
45#include "ControlStruct/ExceptTranslate.h" // for translateEHM
46#include "ControlStruct/Mutate.h" // for mutate
47#include "GenPoly/Box.h" // for box
48#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
49#include "GenPoly/Lvalue.h" // for convertLvalue
50#include "GenPoly/Specialize.h" // for convertSpecializations
51#include "InitTweak/FixInit.h" // for fix
52#include "InitTweak/GenInit.h" // for genInit
53#include "MakeLibCfa.h" // for makeLibCfa
54#include "Parser/LinkageSpec.h" // for Spec, Cforall, Intrinsic
55#include "Parser/ParseNode.h" // for DeclarationNode, buildList
56#include "Parser/TypedefTable.h" // for TypedefTable
57#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
58#include "ResolvExpr/Resolver.h" // for resolve
59#include "SymTab/Validate.h" // for validate
60#include "SynTree/Declaration.h" // for Declaration
61#include "SynTree/Visitor.h" // for acceptAll
62#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
63#include "Virtual/ExpandCasts.h" // for expandCasts
64
65using namespace std;
66
67
68void NewPass(const char * const name) {
69 Stats::Heap::newPass(name);
70 using namespace Stats::Counters;
71 static auto pass_visitor_group = build<CounterGroup>("Pass Visitor");
72 auto pass = build<CounterGroup>(name, pass_visitor_group);
73 pass_visitor_stats.depth = 0;
74 pass_visitor_stats.avg = build<AverageCounter<double>>("Average Depth", pass);
75 pass_visitor_stats.max = build<MaxCounter<double>>("Max Depth", pass);
76}
77
78#define PASS(name, pass) \
79 if ( errorp ) { cerr << name << endl; } \
80 NewPass(name); \
81 Stats::Time::StartBlock(name); \
82 pass; \
83 Stats::Time::StopBlock();
84
85LinkageSpec::Spec linkage = LinkageSpec::Cforall;
86TypedefTable typedefTable;
87DeclarationNode * parseTree = nullptr; // program parse tree
88
89std::string PreludeDirector = "";
90
91static void parse_cmdline( int argc, char *argv[], const char *& filename );
92static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
93static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
94
95static void backtrace( int start ) { // skip first N stack frames
96 enum { Frames = 50 };
97 void * array[Frames];
98 int size = ::backtrace( array, Frames );
99 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
100
101 *index( messages[0], '(' ) = '\0'; // find executable name
102 cerr << "Stack back trace for: " << messages[0] << endl;
103
104 // skip last 2 stack frames after main
105 for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
106 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
107 for ( char *p = messages[i]; *p; ++p ) { // find parantheses and +offset
108 if ( *p == '(' ) {
109 mangled_name = p;
110 } else if ( *p == '+' ) {
111 offset_begin = p;
112 } else if ( *p == ')' ) {
113 offset_end = p;
114 break;
115 } // if
116 } // for
117
118 // if line contains symbol, attempt to demangle
119 int frameNo = i - start;
120 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
121 *mangled_name++ = '\0'; // delimit strings
122 *offset_begin++ = '\0';
123 *offset_end++ = '\0';
124
125 int status;
126 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
127 // bug in __cxa_demangle for single-character lower-case non-mangled names
128 if ( status == 0 ) { // demangling successful ?
129 cerr << "(" << frameNo << ") " << messages[i] << " : "
130 << real_name << "+" << offset_begin << offset_end << endl;
131 } else { // otherwise, output mangled name
132 cerr << "(" << frameNo << ") " << messages[i] << " : "
133 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
134 } // if
135
136 free( real_name );
137 } else { // otherwise, print the whole line
138 cerr << "(" << frameNo << ") " << messages[i] << endl;
139 } // if
140 } // for
141
142 free( messages );
143} // backtrace
144
145void sigSegvBusHandler( int sig_num ) {
146 cerr << "*CFA runtime error* program cfa-cpp terminated with "
147 << (sig_num == SIGSEGV ? "segment fault" : "bus error")
148 << "." << endl;
149 backtrace( 2 ); // skip first 2 stack frames
150 //_exit( EXIT_FAILURE );
151 abort();
152} // sigSegvBusHandler
153
154void sigAbortHandler( __attribute__((unused)) int sig_num ) {
155 backtrace( 6 ); // skip first 6 stack frames
156 signal( SIGABRT, SIG_DFL); // reset default signal handler
157 raise( SIGABRT ); // reraise SIGABRT
158} // sigAbortHandler
159
160
161int main( int argc, char * argv[] ) {
162 FILE * input; // use FILE rather than istream because yyin is FILE
163 ostream * output = & cout;
164 const char * filename = nullptr;
165 list< Declaration * > translationUnit;
166
167 signal( SIGSEGV, sigSegvBusHandler );
168 signal( SIGBUS, sigSegvBusHandler );
169 signal( SIGABRT, sigAbortHandler );
170
171 // std::cout << "main" << std::endl;
172 // for ( int i = 0; i < argc; i += 1 ) {
173 // std::cout << '\t' << argv[i] << std::endl;
174 // } // for
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.cfa";
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 Stats::Time::StartGlobal();
197 NewPass("Parse");
198 Stats::Time::StartBlock("Parse");
199
200 // read in the builtins, extras, and the prelude
201 if ( ! nopreludep ) { // include gcc builtins
202 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
203
204 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
205
206 // Read to gcc builtins, if not generating the cfa library
207 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
208 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
209 parse( gcc_builtins, LinkageSpec::Compiler );
210
211 // read the extra prelude in, if not generating the cfa library
212 FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
213 assertf( extras, "cannot open extras.cf\n" );
214 parse( extras, LinkageSpec::BuiltinC );
215
216 if ( ! libcfap ) {
217 // read the prelude in, if not generating the cfa library
218 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
219 assertf( prelude, "cannot open prelude.cfa\n" );
220 parse( prelude, LinkageSpec::Intrinsic );
221
222 // Read to cfa builtins, if not generating the cfa library
223 FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
224 assertf( builtins, "cannot open builtins.cf\n" );
225 parse( builtins, LinkageSpec::BuiltinCFA );
226 } // if
227 } // if
228
229 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
230
231 if ( parsep ) {
232 parseTree->printList( cout );
233 delete parseTree;
234 return 0;
235 } // if
236
237 buildList( parseTree, translationUnit );
238 delete parseTree;
239 parseTree = nullptr;
240
241 if ( astp ) {
242 dump( translationUnit );
243 return 0;
244 } // if
245
246 // Temporary: fill locations after parsing so that every node has a location, for early error messages.
247 // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
248 // works okay for now.
249 CodeTools::fillLocations( translationUnit );
250 Stats::Time::StopBlock();
251
252 // add the assignment statement after the initialization of a type parameter
253 PASS( "Validate", SymTab::validate( translationUnit, symtabp ) );
254 if ( symtabp ) {
255 deleteAll( translationUnit );
256 return 0;
257 } // if
258
259 if ( expraltp ) {
260 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
261 acceptAll( translationUnit, printer );
262 return 0;
263 } // if
264
265 if ( validp ) {
266 dump( translationUnit );
267 return 0;
268 } // if
269
270 PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
271 PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
272 PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
273 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
274 if ( libcfap ) {
275 // generate the bodies of cfa library functions
276 LibCfa::makeLibCfa( translationUnit );
277 } // if
278
279 if ( declstatsp ) {
280 CodeTools::printDeclStats( translationUnit );
281 deleteAll( translationUnit );
282 return 0;
283 }
284
285 if ( bresolvep ) {
286 dump( translationUnit );
287 return 0;
288 } // if
289
290 CodeTools::fillLocations( translationUnit );
291
292 if ( resolvprotop ) {
293 CodeTools::dumpAsResolvProto( translationUnit );
294 return 0;
295 }
296
297 PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
298 if ( exprp ) {
299 dump( translationUnit );
300 return 0;
301 } // if
302
303 // fix ObjectDecl - replaces ConstructorInit nodes
304 PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
305 if ( ctorinitp ) {
306 dump ( translationUnit );
307 return 0;
308 } // if
309
310 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( translationUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent 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
311
312 PASS( "Translate EHM" , ControlStruct::translateEHM( translationUnit ) );
313
314 PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
315
316 PASS( "Convert Specializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
317
318 PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
319
320 if ( tuplep ) {
321 dump( translationUnit );
322 return 0;
323 }
324
325 PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
326
327 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
328 if ( genericsp ) {
329 dump( translationUnit );
330 return 0;
331 }
332 PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
333
334
335 if ( bboxp ) {
336 dump( translationUnit );
337 return 0;
338 } // if
339 PASS( "Box", GenPoly::box( translationUnit ) );
340
341 if ( bcodegenp ) {
342 dump( translationUnit );
343 return 0;
344 }
345
346 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
347 output = new ofstream( argv[ optind ] );
348 } // if
349
350 CodeTools::fillLocations( translationUnit );
351 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );
352
353 CodeGen::FixMain::fix( *output, (PreludeDirector + "/bootloader.c").c_str() );
354 if ( output != &cout ) {
355 delete output;
356 } // if
357 } catch ( SemanticErrorException &e ) {
358 if ( errorp ) {
359 cerr << "---AST at error:---" << endl;
360 dump( translationUnit, cerr );
361 cerr << endl << "---End of AST, begin error message:---\n" << endl;
362 } // if
363 e.print();
364 if ( output != &cout ) {
365 delete output;
366 } // if
367 return 1;
368 } catch ( UnimplementedError &e ) {
369 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
370 if ( output != &cout ) {
371 delete output;
372 } // if
373 return 1;
374 } catch ( CompilerError &e ) {
375 cerr << "Compiler Error: " << e.get_what() << endl;
376 cerr << "(please report bugs to [REDACTED])" << endl;
377 if ( output != &cout ) {
378 delete output;
379 } // if
380 return 1;
381 } catch(...) {
382 std::exception_ptr eptr = std::current_exception();
383 try {
384 if (eptr) {
385 std::rethrow_exception(eptr);
386 }
387 else {
388 std::cerr << "Exception Uncaught and Unkown" << std::endl;
389 }
390 } catch(const std::exception& e) {
391 std::cerr << "Uncaught Exception \"" << e.what() << "\"\n";
392 }
393 return 1;
394 }// try
395
396 deleteAll( translationUnit );
397 Stats::print();
398
399 return 0;
400} // main
401
402void parse_cmdline( int argc, char * argv[], const char *& filename ) {
403 enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, PreludeDir, Prototypes, Resolver, ResolvProto, Stats, Symbol, Tree, TupleExpansion, Validate};
404
405 static struct option long_opts[] = {
406 { "ast", no_argument, 0, Ast },
407 { "before-box", no_argument, 0, Bbox },
408 { "before-resolver", no_argument, 0, Bresolver },
409 { "ctorinitfix", no_argument, 0, CtorInitFix },
410 { "decl-stats", no_argument, 0, DeclStats },
411 { "expr", no_argument, 0, Expr },
412 { "expralt", no_argument, 0, ExprAlt },
413 { "grammar", no_argument, 0, Grammar },
414 { "libcfa", no_argument, 0, LibCFA },
415 { "line-marks", no_argument, 0, Linemarks },
416 { "no-line-marks", no_argument, 0, Nolinemarks },
417 { "no-preamble", no_argument, 0, Nopreamble },
418 { "parse", no_argument, 0, Parse },
419 { "prelude-dir", required_argument, 0, PreludeDir },
420 { "no-prototypes", no_argument, 0, Prototypes },
421 { "resolver", no_argument, 0, Resolver },
422 { "resolv-proto", no_argument, 0, ResolvProto },
423 { "stats", required_argument, 0, Stats },
424 { "symbol", no_argument, 0, Symbol },
425 { "tree", no_argument, 0, Tree },
426 { "tuple-expansion", no_argument, 0, TupleExpansion },
427 { "validate", no_argument, 0, Validate },
428 { 0, 0, 0, 0 }
429 }; // long_opts
430 int long_index;
431
432 opterr = 0; // (global) prevent getopt from printing error messages
433
434 bool Wsuppress = false, Werror = false;
435 int c;
436 while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrRstTvwW:yzZD:F:", long_opts, &long_index )) != -1 ) {
437 switch ( c ) {
438 case Ast:
439 case 'a': // dump AST
440 astp = true;
441 break;
442 case Bresolver:
443 case 'b': // print before resolver steps
444 bresolvep = true;
445 break;
446 case 'B': // print before box steps
447 bboxp = true;
448 break;
449 case CtorInitFix:
450 case 'c': // print after constructors and destructors are replaced
451 ctorinitp = true;
452 break;
453 case 'C': // print before code generation
454 bcodegenp = true;
455 break;
456 case DeclStats:
457 case 'd':
458 declstatsp = true;
459 break;
460 case Expr:
461 case 'e': // dump AST after expression analysis
462 exprp = true;
463 break;
464 case ExprAlt:
465 case 'f': // print alternatives for expressions
466 expraltp = true;
467 break;
468 case Grammar:
469 case 'g': // bison debugging info (grammar rules)
470 yydebug = true;
471 break;
472 case 'G': // dump AST after instantiate generics
473 genericsp = true;
474 break;
475 case LibCFA:
476 case 'l': // generate libcfa.c
477 libcfap = true;
478 break;
479 case Linemarks:
480 case 'L': // print lines marks
481 linemarks = true;
482 break;
483 case Nopreamble:
484 case 'n': // do not read preamble
485 nopreludep = true;
486 break;
487 case Nolinemarks:
488 case 'N': // suppress line marks
489 linemarks = false;
490 break;
491 case Prototypes:
492 case 'p': // generate prototypes for preamble functions
493 noprotop = true;
494 break;
495 case PreludeDir:
496 PreludeDirector = optarg;
497 break;
498 case 'm': // don't replace the main
499 nomainp = true;
500 break;
501 case Parse:
502 case 'q': // dump parse tree
503 parsep = true;
504 break;
505 case Resolver:
506 case 'r': // print resolver steps
507 resolvep = true;
508 break;
509 case 'R': // dump resolv-proto instance
510 resolvprotop = true;
511 break;
512 case Stats:
513 Stats::parse_params(optarg);
514 break;
515 case Symbol:
516 case 's': // print symbol table events
517 symtabp = true;
518 break;
519 case Tree:
520 case 't': // build in tree
521 treep = true;
522 break;
523 case TupleExpansion:
524 case 'T': // print after tuple expansion
525 tuplep = true;
526 break;
527 case 'v': // dump AST after decl validation pass
528 validp = true;
529 break;
530 case 'w':
531 Wsuppress = true;
532 break;
533 case 'W':
534 if ( strcmp( optarg, "all" ) == 0 ) {
535 SemanticWarning_EnableAll();
536 } else if ( strcmp( optarg, "error" ) == 0 ) {
537 Werror = true;
538 } else {
539 char * warning = optarg;
540 Severity s;
541 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
542 warning += 3;
543 s = Severity::Suppress;
544 } else {
545 s = Severity::Warn;
546 } // if
547 SemanticWarning_Set( warning, s );
548 } // if
549 break;
550 case 'y': // dump AST on error
551 errorp = true;
552 break;
553 case 'z': // dump as codegen rather than AST
554 codegenp = true;
555 break;
556 case 'Z': // prettyprint during codegen (i.e. print unmangled names, etc.)
557 prettycodegenp = true;
558 break;
559 case 'D': // ignore -Dxxx
560 break;
561 case 'F': // source file-name without suffix
562 filename = optarg;
563 break;
564 case '?':
565 if ( optopt ) { // short option ?
566 assertf( false, "Unknown option: -%c\n", (char)optopt );
567 } else {
568 assertf( false, "Unknown option: %s\n", argv[optind - 1] );
569 } // if
570 #if defined(__GNUC__) && __GNUC__ >= 7
571 __attribute__((fallthrough));
572 #endif
573 default:
574 abort();
575 } // switch
576 } // while
577
578 if ( Werror ) {
579 SemanticWarning_WarningAsError();
580 } // if
581 if ( Wsuppress ) {
582 SemanticWarning_SuppressAll();
583 } // if
584 // for ( const auto w : WarningFormats ) {
585 // cout << w.name << ' ' << (int)w.severity << endl;
586 // } // for
587} // parse_cmdline
588
589static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
590 extern int yyparse( void );
591 extern FILE * yyin;
592 extern int yylineno;
593
594 ::linkage = linkage; // set globals
595 yyin = input;
596 yylineno = 1;
597 int parseStatus = yyparse();
598
599 fclose( input );
600 if ( shouldExit || parseStatus != 0 ) {
601 exit( parseStatus );
602 } // if
603} // parse
604
605static bool notPrelude( Declaration * decl ) {
606 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
607} // notPrelude
608
609static void dump( list< Declaration * > & translationUnit, ostream & out ) {
610 list< Declaration * > decls;
611
612 if ( noprotop ) {
613 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
614 } else {
615 decls = translationUnit;
616 } // if
617
618 // depending on commandline options, either generate code or dump the AST
619 if ( codegenp ) {
620 CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
621 } else {
622 printAll( decls, out );
623 }
624 deleteAll( translationUnit );
625} // dump
626
627// Local Variables: //
628// tab-width: 4 //
629// mode: c++ //
630// compile-command: "make install" //
631// End: //
Note: See TracBrowser for help on using the repository browser.