source: src/main.cc@ 11b7028

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 resolv-new with_gc
Last change on this file since 11b7028 was f0994a1, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Read extras.cf as BuiltinC and update 64-bit test output to remove extra functions

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