source: src/main.cc@ 903f7c3

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 903f7c3 was 4810867, checked in by ajbeach <ajbeach@…>, 8 years ago

Added basic line directives to code generation.

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