source: src/main.cc@ 675716e

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

Instrumented PassVisitor to print average/max depth

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