source: src/main.cc@ 83ab931

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 83ab931 was e523b07, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Implemented the nolib configuration

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