source: src/main.cc@ 1cb7fab2

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
Last change on this file since 1cb7fab2 was 1cb7fab2, checked in by tdelisle <tdelisle@…>, 7 years ago

Added better support for enabling/disabling/compiling-out statistics

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