source: src/main.cc@ 6e3eaa57

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum with_gc
Last change on this file since 6e3eaa57 was b368dd8, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

Merge branch 'master' of plg2:software/cfa/cfa-cc

  • Property mode set to 100644
File size: 19.8 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 30 17:53:14 2018
13// Update Count : 496
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/CompilerError.h" // for CompilerError
37#include "Common/Heap.h"
38#include "Common/PassVisitor.h"
39#include "Common/SemanticError.h" // for SemanticError
40#include "Common/UnimplementedError.h" // for UnimplementedError
41#include "Common/utility.h" // for deleteAll, filter, printAll
42#include "Concurrency/Waitfor.h" // for generateWaitfor
43#include "ControlStruct/ExceptTranslate.h" // for translateEHM
44#include "ControlStruct/Mutate.h" // for mutate
45#include "GenPoly/Box.h" // for box
46#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
47#include "GenPoly/Lvalue.h" // for convertLvalue
48#include "GenPoly/Specialize.h" // for convertSpecializations
49#include "InitTweak/FixInit.h" // for fix
50#include "InitTweak/GenInit.h" // for genInit
51#include "MakeLibCfa.h" // for makeLibCfa
52#include "Parser/LinkageSpec.h" // for Spec, Cforall, Intrinsic
53#include "Parser/ParseNode.h" // for DeclarationNode, buildList
54#include "Parser/TypedefTable.h" // for TypedefTable
55#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
56#include "ResolvExpr/Resolver.h" // for resolve
57#include "SymTab/Validate.h" // for validate
58#include "SynTree/Declaration.h" // for Declaration
59#include "SynTree/Visitor.h" // for acceptAll
60#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
61#include "Virtual/ExpandCasts.h" // for expandCasts
62
63using namespace std;
64
65#define PASS(name, pass) \
66 if ( errorp ) { cerr << name << endl; } \
67 HeapStats::newPass(name); \
68 pass;
69
70LinkageSpec::Spec linkage = LinkageSpec::Cforall;
71TypedefTable typedefTable;
72DeclarationNode * parseTree = nullptr; // program parse tree
73
74extern int yydebug; // set for -g flag (Grammar)
75bool
76 astp = false,
77 bresolvep = false,
78 bboxp = false,
79 bcodegenp = false,
80 ctorinitp = false,
81 declstatsp = false,
82 exprp = false,
83 expraltp = false,
84 genericsp = false,
85 libcfap = false,
86 nopreludep = false,
87 noprotop = false,
88 nomainp = false,
89 parsep = false,
90 resolvep = false, // used in AlternativeFinder
91 symtabp = false,
92 treep = false,
93 tuplep = false,
94 validp = false,
95 errorp = false,
96 codegenp = false,
97 prettycodegenp = false,
98 linemarks = false;
99
100static void parse_cmdline( int argc, char *argv[], const char *& filename );
101static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
102static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
103
104static void backtrace( int start ) { // skip first N stack frames
105 enum { Frames = 50 };
106 void * array[Frames];
107 int size = ::backtrace( array, Frames );
108 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
109
110 *index( messages[0], '(' ) = '\0'; // find executable name
111 cerr << "Stack back trace for: " << messages[0] << endl;
112
113 // skip last 2 stack frames after main
114 for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
115 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
116 for ( char *p = messages[i]; *p; ++p ) { // find parantheses and +offset
117 if ( *p == '(' ) {
118 mangled_name = p;
119 } else if ( *p == '+' ) {
120 offset_begin = p;
121 } else if ( *p == ')' ) {
122 offset_end = p;
123 break;
124 } // if
125 } // for
126
127 // if line contains symbol, attempt to demangle
128 int frameNo = i - start;
129 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
130 *mangled_name++ = '\0'; // delimit strings
131 *offset_begin++ = '\0';
132 *offset_end++ = '\0';
133
134 int status;
135 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
136 // bug in __cxa_demangle for single-character lower-case non-mangled names
137 if ( status == 0 ) { // demangling successful ?
138 cerr << "(" << frameNo << ") " << messages[i] << " : "
139 << real_name << "+" << offset_begin << offset_end << endl;
140 } else { // otherwise, output mangled name
141 cerr << "(" << frameNo << ") " << messages[i] << " : "
142 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
143 } // if
144
145 free( real_name );
146 } else { // otherwise, print the whole line
147 cerr << "(" << frameNo << ") " << messages[i] << endl;
148 } // if
149 } // for
150
151 free( messages );
152} // backtrace
153
154void sigSegvBusHandler( int sig_num ) {
155 cerr << "*CFA runtime error* program cfa-cpp terminated with "
156 << (sig_num == SIGSEGV ? "segment fault" : "bus error")
157 << "." << endl;
158 backtrace( 2 ); // skip first 2 stack frames
159 exit( EXIT_FAILURE );
160} // sigSegvBusHandler
161
162void sigAbortHandler( __attribute__((unused)) int sig_num ) {
163 backtrace( 6 ); // skip first 6 stack frames
164 signal( SIGABRT, SIG_DFL); // reset default signal handler
165 raise( SIGABRT ); // reraise SIGABRT
166} // sigAbortHandler
167
168
169int main( int argc, char * argv[] ) {
170 FILE * input; // use FILE rather than istream because yyin is FILE
171 ostream *output = & cout;
172 const char *filename = nullptr;
173 list< Declaration * > translationUnit;
174
175 signal( SIGSEGV, sigSegvBusHandler );
176 signal( SIGBUS, sigSegvBusHandler );
177 signal( SIGABRT, sigAbortHandler );
178
179 // std::cout << "main" << std::endl;
180 // for ( int i = 0; i < argc; i += 1 ) {
181 // std::cout << '\t' << argv[i] << std::endl;
182 // } // for
183
184 parse_cmdline( argc, argv, filename ); // process command-line arguments
185 CodeGen::FixMain::setReplaceMain( !nomainp );
186
187 try {
188 // choose to read the program from a file or stdin
189 if ( optind < argc ) { // any commands after the flags ? => input file name
190 input = fopen( argv[ optind ], "r" );
191 assertf( input, "cannot open %s\n", argv[ optind ] );
192 // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
193 if ( filename == nullptr ) filename = argv[ optind ];
194 // prelude filename comes in differently
195 if ( libcfap ) filename = "prelude.cf";
196 optind += 1;
197 } else { // no input file name
198 input = stdin;
199 // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
200 // a fake name along
201 if ( filename == nullptr ) filename = "stdin";
202 } // if
203
204 // read in the builtins, extras, and the prelude
205 if ( ! nopreludep ) { // include gcc builtins
206 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
207
208 // Read to gcc builtins, if not generating the cfa library
209 FILE * gcc_builtins = fopen( libcfap | treep ? "../prelude/gcc-builtins.cf" : CFA_LIBDIR "/gcc-builtins.cf", "r" );
210 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
211 parse( gcc_builtins, LinkageSpec::Compiler );
212
213 // read the extra prelude in, if not generating the cfa library
214 FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
215 assertf( extras, "cannot open extras.cf\n" );
216 parse( extras, LinkageSpec::BuiltinC );
217
218 if ( ! libcfap ) {
219 // read the prelude in, if not generating the cfa library
220 FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
221 assertf( prelude, "cannot open prelude.cf\n" );
222 parse( prelude, LinkageSpec::Intrinsic );
223
224 // Read to cfa builtins, if not generating the cfa library
225 FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
226 assertf( builtins, "cannot open builtins.cf\n" );
227 parse( builtins, LinkageSpec::BuiltinCFA );
228 } // if
229 } // if
230
231 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
232
233 if ( parsep ) {
234 parseTree->printList( cout );
235 delete parseTree;
236 return 0;
237 } // if
238
239 buildList( parseTree, translationUnit );
240 delete parseTree;
241 parseTree = nullptr;
242
243 if ( astp ) {
244 dump( translationUnit );
245 return 0;
246 } // if
247
248 // add the assignment statement after the initialization of a type parameter
249 PASS( "validate", SymTab::validate( translationUnit, symtabp ) );
250 if ( symtabp ) {
251 deleteAll( translationUnit );
252 return 0;
253 } // if
254
255 if ( expraltp ) {
256 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
257 acceptAll( translationUnit, printer );
258 return 0;
259 } // if
260
261 if ( validp ) {
262 dump( translationUnit );
263 return 0;
264 } // if
265
266 PASS( "fixLabels", ControlStruct::fixLabels( translationUnit ) );
267 PASS( "fixNames", CodeGen::fixNames( translationUnit ) );
268 PASS( "genInit", InitTweak::genInit( translationUnit ) );
269 PASS( "expandMemberTuples" , Tuples::expandMemberTuples( translationUnit ) );
270 if ( libcfap ) {
271 // generate the bodies of cfa library functions
272 LibCfa::makeLibCfa( translationUnit );
273 } // if
274
275 if ( declstatsp ) {
276 CodeTools::printDeclStats( translationUnit );
277 deleteAll( translationUnit );
278 return 0;
279 }
280
281 if ( bresolvep ) {
282 dump( translationUnit );
283 return 0;
284 } // if
285
286 CodeTools::fillLocations( translationUnit );
287
288 PASS( "resolve", ResolvExpr::resolve( translationUnit ) );
289 if ( exprp ) {
290 dump( translationUnit );
291 return 0;
292 } // if
293
294 // fix ObjectDecl - replaces ConstructorInit nodes
295 PASS( "fixInit", InitTweak::fix( translationUnit, filename, libcfap || treep ) );
296 if ( ctorinitp ) {
297 dump ( translationUnit );
298 return 0;
299 } // if
300
301 PASS( "expandUniqueExpr", 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
302
303 PASS( "translateEHM" , ControlStruct::translateEHM( translationUnit ) );
304
305 PASS( "generateWaitfor" , Concurrency::generateWaitFor( translationUnit ) );
306
307 PASS( "convertSpecializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
308
309 PASS( "expandTuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
310
311 if ( tuplep ) {
312 dump( translationUnit );
313 return 0;
314 }
315
316 PASS( "virtual expandCasts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
317
318 PASS( "instantiateGenerics", GenPoly::instantiateGeneric( translationUnit ) );
319 if ( genericsp ) {
320 dump( translationUnit );
321 return 0;
322 }
323 PASS( "convertLvalue", GenPoly::convertLvalue( translationUnit ) );
324
325
326 if ( bboxp ) {
327 dump( translationUnit );
328 return 0;
329 } // if
330 PASS( "box", GenPoly::box( translationUnit ) );
331
332 if ( bcodegenp ) {
333 dump( translationUnit );
334 return 0;
335 }
336
337 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
338 output = new ofstream( argv[ optind ] );
339 } // if
340
341 CodeTools::fillLocations( translationUnit );
342 PASS( "codegen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );
343
344 CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
345 if ( output != &cout ) {
346 delete output;
347 } // if
348 } catch ( SemanticErrorException &e ) {
349 if ( errorp ) {
350 cerr << "---AST at error:---" << endl;
351 dump( translationUnit, cerr );
352 cerr << endl << "---End of AST, begin error message:---\n" << endl;
353 } // if
354 e.print();
355 if ( output != &cout ) {
356 delete output;
357 } // if
358 return 1;
359 } catch ( UnimplementedError &e ) {
360 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
361 if ( output != &cout ) {
362 delete output;
363 } // if
364 return 1;
365 } catch ( CompilerError &e ) {
366 cerr << "Compiler Error: " << e.get_what() << endl;
367 cerr << "(please report bugs to [REDACTED])" << endl;
368 if ( output != &cout ) {
369 delete output;
370 } // if
371 return 1;
372 } catch(...) {
373 std::exception_ptr eptr = std::current_exception();
374 try {
375 if (eptr) {
376 std::rethrow_exception(eptr);
377 }
378 else {
379 std::cerr << "Exception Uncaught and Unkown" << std::endl;
380 }
381 } catch(const std::exception& e) {
382 std::cerr << "Unaught Exception \"" << e.what() << "\"\n";
383 }
384 return 1;
385 }// try
386
387 deleteAll( translationUnit );
388 if(!libcfap && !treep) HeapStats::printStats();
389 return 0;
390} // main
391
392void parse_cmdline( int argc, char * argv[], const char *& filename ) {
393 enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
394
395 static struct option long_opts[] = {
396 { "ast", no_argument, 0, Ast },
397 { "before-box", no_argument, 0, Bbox },
398 { "before-resolver", no_argument, 0, Bresolver },
399 { "ctorinitfix", no_argument, 0, CtorInitFix },
400 { "decl-stats", no_argument, 0, DeclStats },
401 { "expr", no_argument, 0, Expr },
402 { "expralt", no_argument, 0, ExprAlt },
403 { "grammar", no_argument, 0, Grammar },
404 { "libcfa", no_argument, 0, LibCFA },
405 { "line-marks", no_argument, 0, Linemarks },
406 { "no-line-marks", no_argument, 0, Nolinemarks },
407 { "no-preamble", no_argument, 0, Nopreamble },
408 { "parse", no_argument, 0, Parse },
409 { "no-prototypes", no_argument, 0, Prototypes },
410 { "resolver", no_argument, 0, Resolver },
411 { "symbol", no_argument, 0, Symbol },
412 { "tree", no_argument, 0, Tree },
413 { "tuple-expansion", no_argument, 0, TupleExpansion },
414 { "validate", no_argument, 0, Validate },
415 { 0, 0, 0, 0 }
416 }; // long_opts
417 int long_index;
418
419 opterr = 0; // (global) prevent getopt from printing error messages
420
421 bool Wsuppress = false, Werror = false;
422 int c;
423 while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrstTvwW:yzZD: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 'w':
509 Wsuppress = true;
510 break;
511 case 'W':
512 if ( strcmp( optarg, "all" ) == 0 ) {
513 SemanticWarning_EnableAll();
514 } else if ( strcmp( optarg, "error" ) == 0 ) {
515 Werror = true;
516 } else {
517 char * warning = optarg;
518 Severity s;
519 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
520 warning += 3;
521 s = Severity::Suppress;
522 } else {
523 s = Severity::Warn;
524 } // if
525 SemanticWarning_Set( warning, s );
526 } // if
527 break;
528 case 'y': // dump AST on error
529 errorp = true;
530 break;
531 case 'z': // dump as codegen rather than AST
532 codegenp = true;
533 break;
534 case 'Z': // prettyprint during codegen (i.e. print unmangled names, etc.)
535 prettycodegenp = true;
536 break;
537 case 'D': // ignore -Dxxx
538 break;
539 case 'F': // source file-name without suffix
540 filename = optarg;
541 break;
542 case '?':
543 if ( optopt ) { // short option ?
544 assertf( false, "Unknown option: -%c\n", (char)optopt );
545 } else {
546 assertf( false, "Unknown option: %s\n", argv[optind - 1] );
547 } // if
548 #if defined(__GNUC__) && __GNUC__ >= 7
549 __attribute__((fallthrough));
550 #endif
551 default:
552 abort();
553 } // switch
554 } // while
555
556 if ( Werror ) {
557 SemanticWarning_WarningAsError();
558 } // if
559 if ( Wsuppress ) {
560 SemanticWarning_SuppressAll();
561 } // if
562 // for ( const auto w : WarningFormats ) {
563 // cout << w.name << ' ' << (int)w.severity << endl;
564 // } // for
565} // parse_cmdline
566
567static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
568 extern int yyparse( void );
569 extern FILE * yyin;
570 extern int yylineno;
571
572 ::linkage = linkage; // set globals
573 yyin = input;
574 yylineno = 1;
575 int parseStatus = yyparse();
576
577 fclose( input );
578 if ( shouldExit || parseStatus != 0 ) {
579 exit( parseStatus );
580 } // if
581} // parse
582
583static bool notPrelude( Declaration * decl ) {
584 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
585} // notPrelude
586
587static void dump( list< Declaration * > & translationUnit, ostream & out ) {
588 list< Declaration * > decls;
589
590 if ( noprotop ) {
591 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
592 } else {
593 decls = translationUnit;
594 } // if
595
596 // depending on commandline options, either generate code or dump the AST
597 if ( codegenp ) {
598 CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
599 } else {
600 printAll( decls, out );
601 }
602 deleteAll( translationUnit );
603} // dump
604
605// Local Variables: //
606// tab-width: 4 //
607// mode: c++ //
608// compile-command: "make install" //
609// End: //
Note: See TracBrowser for help on using the repository browser.