source: src/main.cc@ bd06384

new-env with_gc
Last change on this file since bd06384 was bd06384, checked in by Aaron Moss <a3moss@…>, 8 years ago

Add static roots to GC; fix some static GC_Objects

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