source: src/main.cc@ 1932e8a

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 1932e8a was b9f8274, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Removed the validate sub-pass interface. This also showed an extra include in CandidateFinder, also removed.

  • Property mode set to 100644
File size: 33.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 : Peter Buhr and Rob Schluntz
10// Created On : Fri May 15 23:12:02 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Jul 12 12:02:00 2022
13// Update Count : 675
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 <cassert> // for assertf
20#include <cstdio> // for fopen, FILE, fclose, stdin
21#include <cstdlib> // for exit, free, abort, EXIT_F...
22#include <csignal> // for signal, SIGABRT, SIGSEGV
23#include <cstring> // for index
24#include <fstream> // for ofstream
25#include <iostream> // for operator<<, basic_ostream
26#include <iomanip>
27#include <iterator> // for back_inserter
28#include <list> // for list
29#include <string> // for char_traits, operator<<
30
31using namespace std;
32
33#include "AST/Convert.hpp"
34#include "CompilationState.h"
35#include "../config.h" // for CFA_LIBDIR
36#include "CodeGen/FixMain.h" // for FixMain
37#include "CodeGen/FixNames.h" // for fixNames
38#include "CodeGen/Generate.h" // for generate
39#include "CodeGen/LinkOnce.h" // for translateLinkOnce
40#include "CodeTools/DeclStats.h" // for printDeclStats
41#include "CodeTools/ResolvProtoDump.h" // for dumpAsResolvProto
42#include "CodeTools/TrackLoc.h" // for fillLocations
43#include "Common/CodeLocationTools.hpp" // for forceFillCodeLocations
44#include "Common/CompilerError.h" // for CompilerError
45#include "Common/DeclStats.hpp" // for printDeclStats
46#include "Common/ResolvProtoDump.hpp" // for dumpAsResolverProto
47#include "Common/Stats.h"
48#include "Common/PassVisitor.h"
49#include "Common/SemanticError.h" // for SemanticError
50#include "Common/UnimplementedError.h" // for UnimplementedError
51#include "Common/utility.h" // for deleteAll, filter, printAll
52#include "Concurrency/Keywords.h" // for implementMutex, implement...
53#include "Concurrency/Waitfor.h" // for generateWaitfor
54#include "ControlStruct/ExceptDecl.h" // for translateExcept
55#include "ControlStruct/ExceptTranslate.h" // for translateEHM
56#include "ControlStruct/FixLabels.hpp" // for fixLabels
57#include "ControlStruct/HoistControlDecls.hpp" // hoistControlDecls
58#include "ControlStruct/Mutate.h" // for mutate
59#include "GenPoly/Box.h" // for box
60#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
61#include "GenPoly/Lvalue.h" // for convertLvalue
62#include "GenPoly/Specialize.h" // for convertSpecializations
63#include "InitTweak/FixInit.h" // for fix
64#include "InitTweak/GenInit.h" // for genInit
65#include "MakeLibCfa.h" // for makeLibCfa
66#include "Parser/ParseNode.h" // for DeclarationNode, buildList
67#include "Parser/TypedefTable.h" // for TypedefTable
68#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
69#include "ResolvExpr/CandidatePrinter.hpp" // for printCandidates
70#include "ResolvExpr/Resolver.h" // for resolve
71#include "SymTab/Validate.h" // for validate
72#include "SymTab/ValidateType.h" // for linkReferenceToTypes
73#include "SynTree/LinkageSpec.h" // for Spec, Cforall, Intrinsic
74#include "SynTree/Declaration.h" // for Declaration
75#include "SynTree/Visitor.h" // for acceptAll
76#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
77#include "Validate/Autogen.hpp" // for autogenerateRoutines
78#include "Validate/CompoundLiteral.hpp" // for handleCompoundLiterals
79#include "Validate/EliminateTypedef.hpp" // for eliminateTypedef
80#include "Validate/EnumAndPointerDecay.hpp" // for decayEnumsAndPointers
81#include "Validate/FindSpecialDecls.h" // for findGlobalDecls
82#include "Validate/FixQualifiedTypes.hpp" // for fixQualifiedTypes
83#include "Validate/FixReturnTypes.hpp" // for fixReturnTypes
84#include "Validate/ForallPointerDecay.hpp" // for decayForallPointers
85#include "Validate/GenericParameter.hpp" // for fillGenericParameters, tr...
86#include "Validate/HoistStruct.hpp" // for hoistStruct
87#include "Validate/HoistTypeDecls.hpp" // for hoistTypeDecls
88#include "Validate/InitializerLength.hpp" // for setLengthFromInitializer
89#include "Validate/LabelAddressFixer.hpp" // for fixLabelAddresses
90#include "Validate/LinkReferenceToTypes.hpp" // for linkReferenceToTypes
91#include "Validate/ReplaceTypedef.hpp" // for replaceTypedef
92#include "Validate/ReturnCheck.hpp" // for checkReturnStatements
93#include "Validate/VerifyCtorDtorAssign.hpp" // for verifyCtorDtorAssign
94#include "Virtual/ExpandCasts.h" // for expandCasts
95
96static void NewPass( const char * const name ) {
97 Stats::Heap::newPass( name );
98 using namespace Stats::Counters;
99 {
100 static auto group = build<CounterGroup>( "Pass Visitor" );
101 auto pass = build<CounterGroup>( name, group );
102 pass_visitor_stats.depth = 0;
103 pass_visitor_stats.avg = build<AverageCounter<double>>( "Average Depth", pass );
104 pass_visitor_stats.max = build<MaxCounter<double>>( "Max Depth", pass );
105 }
106 {
107 static auto group = build<CounterGroup>( "Syntax Node" );
108 auto pass = build<CounterGroup>( name, group );
109 BaseSyntaxNode::new_nodes = build<SimpleCounter>( "Allocs", pass );
110 }
111}
112
113#define PASS( name, pass ) \
114 if ( errorp ) { cerr << name << endl; } \
115 NewPass(name); \
116 Stats::Time::StartBlock(name); \
117 pass; \
118 Stats::Time::StopBlock();
119
120LinkageSpec::Spec linkage = LinkageSpec::Cforall;
121TypedefTable typedefTable;
122DeclarationNode * parseTree = nullptr; // program parse tree
123
124static bool waiting_for_gdb = false; // flag to set cfa-cpp to wait for gdb on start
125
126static string PreludeDirector = "";
127
128static void parse_cmdline( int argc, char * argv[] );
129static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
130static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
131static void dump( ast::TranslationUnit && transUnit, ostream & out = cout );
132
133static void backtrace( int start ) { // skip first N stack frames
134 enum { Frames = 50, }; // maximum number of stack frames
135 void * array[Frames];
136 size_t size = ::backtrace( array, Frames );
137 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
138
139 *index( messages[0], '(' ) = '\0'; // find executable name
140 cerr << "Stack back trace for: " << messages[0] << endl;
141
142 // skip last 2 stack frames after main
143 for ( unsigned int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
144 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
145
146 for ( char * p = messages[i]; *p; p += 1 ) { // find parantheses and +offset
147 if ( *p == '(' ) {
148 mangled_name = p;
149 } else if ( *p == '+' ) {
150 offset_begin = p;
151 } else if ( *p == ')' ) {
152 offset_end = p;
153 break;
154 } // if
155 } // for
156
157 // if line contains symbol, attempt to demangle
158 int frameNo = i - start;
159 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
160 *mangled_name++ = '\0'; // delimit strings
161 *offset_begin++ = '\0';
162 *offset_end++ = '\0';
163
164 int status;
165 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
166 // bug in __cxa_demangle for single-character lower-case non-mangled names
167 if ( status == 0 ) { // demangling successful ?
168 cerr << "(" << frameNo << ") " << messages[i] << " : "
169 << real_name << "+" << offset_begin << offset_end << endl;
170 } else { // otherwise, output mangled name
171 cerr << "(" << frameNo << ") " << messages[i] << " : "
172 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
173 } // if
174
175 free( real_name );
176 } else { // otherwise, print the whole line
177 cerr << "(" << frameNo << ") " << messages[i] << endl;
178 } // if
179 } // for
180
181 free( messages );
182} // backtrace
183
184#define SIGPARMS int sig __attribute__(( unused )), siginfo_t * sfp __attribute__(( unused )), ucontext_t * cxt __attribute__(( unused ))
185
186static void _Signal(struct sigaction & act, int sig, int flags ) {
187 act.sa_flags = flags;
188
189 if ( sigaction( sig, &act, nullptr ) == -1 ) {
190 cerr << "*cfa-cpp compilation error* problem installing signal handler, error(" << errno << ") " << strerror( errno ) << endl;
191 _exit( EXIT_FAILURE );
192 } // if
193}
194
195static void Signal( int sig, void (* handler)(SIGPARMS), int flags ) {
196 struct sigaction act;
197 act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
198 _Signal(act, sig, flags);
199} // Signal
200
201static void Signal( int sig, void (* handler)(int), int flags ) {
202 struct sigaction act;
203 act.sa_handler = handler;
204 _Signal(act, sig, flags);
205} // Signal
206
207static void sigSegvBusHandler( SIGPARMS ) {
208 if ( sfp->si_addr == nullptr ) {
209 cerr << "Null pointer (nullptr) dereference." << endl;
210 } else {
211 cerr << (sig == SIGSEGV ? "Segment fault" : "Bus error") << " at memory location " << sfp->si_addr << "." << endl
212 << "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript." << endl;
213 } // if
214 backtrace( 2 ); // skip first 2 stack frames
215 abort(); // cause core dump for debugging
216} // sigSegvBusHandler
217
218static void sigFpeHandler( SIGPARMS ) {
219 const char * msg;
220
221 switch ( sfp->si_code ) {
222 case FPE_INTDIV: case FPE_FLTDIV: msg = "divide by zero"; break;
223 case FPE_FLTOVF: msg = "overflow"; break;
224 case FPE_FLTUND: msg = "underflow"; break;
225 case FPE_FLTRES: msg = "inexact result"; break;
226 case FPE_FLTINV: msg = "invalid operation"; break;
227 default: msg = "unknown";
228 } // choose
229 cerr << "Computation error " << msg << " at location " << sfp->si_addr << endl
230 << "Possible cause is constant-expression evaluation invalid." << endl;
231 backtrace( 2 ); // skip first 2 stack frames
232 abort(); // cause core dump for debugging
233} // sigFpeHandler
234
235static void sigAbortHandler( SIGPARMS ) {
236 backtrace( 6 ); // skip first 6 stack frames
237 Signal( SIGABRT, SIG_DFL, SA_SIGINFO ); // reset default signal handler
238 raise( SIGABRT ); // reraise SIGABRT
239} // sigAbortHandler
240
241int main( int argc, char * argv[] ) {
242 FILE * input; // use FILE rather than istream because yyin is FILE
243 ostream * output = & cout;
244 list< Declaration * > translationUnit;
245
246 Signal( SIGSEGV, sigSegvBusHandler, SA_SIGINFO );
247 Signal( SIGBUS, sigSegvBusHandler, SA_SIGINFO );
248 Signal( SIGFPE, sigFpeHandler, SA_SIGINFO );
249 Signal( SIGABRT, sigAbortHandler, SA_SIGINFO );
250
251 // cout << "main" << endl;
252 // for ( int i = 0; i < argc; i += 1 ) {
253 // cout << '\t' << argv[i] << endl;
254 // } // for
255
256 parse_cmdline( argc, argv ); // process command-line arguments
257 CodeGen::FixMain::setReplaceMain( !nomainp );
258
259 if ( waiting_for_gdb ) {
260 cerr << "Waiting for gdb" << endl;
261 cerr << "run :" << endl;
262 cerr << " gdb attach " << getpid() << endl;
263 raise(SIGSTOP);
264 } // if
265
266 try {
267 // choose to read the program from a file or stdin
268 if ( optind < argc ) { // any commands after the flags ? => input file name
269 input = fopen( argv[ optind ], "r" );
270 assertf( input, "cannot open %s because %s\n", argv[ optind ], strerror( errno ) );
271 optind += 1;
272 } else { // no input file name
273 input = stdin;
274 } // if
275
276 Stats::Time::StartGlobal();
277 NewPass("Parse");
278 Stats::Time::StartBlock("Parse");
279
280 // read in the builtins, extras, and the prelude
281 if ( ! nopreludep ) { // include gcc builtins
282 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
283
284 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
285
286 // Read to gcc builtins, if not generating the cfa library
287 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
288 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
289 parse( gcc_builtins, LinkageSpec::Compiler );
290
291 // read the extra prelude in, if not generating the cfa library
292 FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
293 assertf( extras, "cannot open extras.cf\n" );
294 parse( extras, LinkageSpec::BuiltinC );
295
296 if ( ! libcfap ) {
297 // read the prelude in, if not generating the cfa library
298 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
299 assertf( prelude, "cannot open prelude.cfa\n" );
300 parse( prelude, LinkageSpec::Intrinsic );
301
302 // Read to cfa builtins, if not generating the cfa library
303 FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
304 assertf( builtins, "cannot open builtins.cf\n" );
305 parse( builtins, LinkageSpec::BuiltinCFA );
306 } // if
307 } // if
308
309 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
310
311 if ( parsep ) {
312 parseTree->printList( cout );
313 delete parseTree;
314 return EXIT_SUCCESS;
315 } // if
316
317 buildList( parseTree, translationUnit );
318 delete parseTree;
319 parseTree = nullptr;
320
321 if ( astp ) {
322 dump( translationUnit );
323 return EXIT_SUCCESS;
324 } // if
325
326 // Temporary: fill locations after parsing so that every node has a location, for early error messages.
327 // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
328 // works okay for now.
329 CodeTools::fillLocations( translationUnit );
330 Stats::Time::StopBlock();
331
332 PASS( "Translate Exception Declarations", ControlStruct::translateExcept( translationUnit ) );
333 if ( exdeclp ) {
334 dump( translationUnit );
335 return EXIT_SUCCESS;
336 } // if
337
338 CodeTools::fillLocations( translationUnit );
339
340 if( useNewAST ) {
341 CodeTools::fillLocations( translationUnit );
342
343 if (Stats::Counters::enabled) {
344 ast::pass_visitor_stats.avg = Stats::Counters::build<Stats::Counters::AverageCounter<double>>("Average Depth - New");
345 ast::pass_visitor_stats.max = Stats::Counters::build<Stats::Counters::MaxCounter<double>>("Max depth - New");
346 }
347 auto transUnit = convert( move( translationUnit ) );
348
349 forceFillCodeLocations( transUnit );
350
351 // Must happen before auto-gen, or anything that examines ops.
352 PASS( "Verify Ctor, Dtor & Assign", Validate::verifyCtorDtorAssign( transUnit ) );
353
354 PASS( "Hoist Type Decls", Validate::hoistTypeDecls( transUnit ) );
355 // Hoist Type Decls pulls some declarations out of contexts where
356 // locations are not tracked. Perhaps they should be, but for now
357 // the full fill solves it.
358 forceFillCodeLocations( transUnit );
359
360 PASS( "Replace Typedefs", Validate::replaceTypedef( transUnit ) );
361
362 // Must happen before auto-gen.
363 PASS( "Fix Return Types", Validate::fixReturnTypes( transUnit ) );
364
365 // Must happen before Link Reference to Types, it needs correct
366 // types for mangling.
367 PASS( "Enum and Pointer Decay", Validate::decayEnumsAndPointers( transUnit ) );
368
369 // Must happen before auto-gen, because it uses the sized flag.
370 PASS( "Link Reference To Types", Validate::linkReferenceToTypes( transUnit ) );
371
372 // Must happen after Link References To Types,
373 // because aggregate members are accessed.
374 PASS( "Fix Qualified Types", Validate::fixQualifiedTypes( transUnit ) );
375
376 PASS( "Hoist Struct", Validate::hoistStruct( transUnit ) );
377 PASS( "Eliminate Typedef", Validate::eliminateTypedef( transUnit ) );
378
379 // Check as early as possible. Can't happen before
380 // LinkReferenceToType, observed failing when attempted
381 // before eliminateTypedef
382 PASS( "Validate Generic Parameters", Validate::fillGenericParameters( transUnit ) );
383
384 PASS( "Translate Dimensions", Validate::translateDimensionParameters( transUnit ) );
385 PASS( "Check Function Returns", Validate::checkReturnStatements( transUnit ) );
386
387 // Must happen before Autogen.
388 PASS( "Fix Return Statements", InitTweak::fixReturnStatements( transUnit ) );
389
390 PASS( "Implement Concurrent Keywords", Concurrency::implementKeywords( transUnit ) );
391
392 // Must be after implement concurrent keywords; because uniqueIds
393 // must be set on declaration before resolution.
394 // Must happen before autogen routines are added.
395 PASS( "Forall Pointer Decay", Validate::decayForallPointers( transUnit ) );
396
397 // Must happen before autogen routines are added.
398 PASS( "Hoist Control Declarations", ControlStruct::hoistControlDecls( transUnit ) );
399
400 // Must be after enum and pointer decay.
401 // Must be before compound literals.
402 PASS( "Generate Autogen Routines", Validate::autogenerateRoutines( transUnit ) );
403
404 PASS( "Implement Mutex", Concurrency::implementMutex( transUnit ) );
405 PASS( "Implement Thread Start", Concurrency::implementThreadStarter( transUnit ) );
406 PASS( "Compound Literal", Validate::handleCompoundLiterals( transUnit ) );
407 PASS( "Set Length From Initializer", Validate::setLengthFromInitializer( transUnit ) );
408 PASS( "Find Global Decls", Validate::findGlobalDecls( transUnit ) );
409 PASS( "Fix Label Address", Validate::fixLabelAddresses( transUnit ) );
410
411 if ( symtabp ) {
412 return EXIT_SUCCESS;
413 } // if
414
415 if ( expraltp ) {
416 ResolvExpr::printCandidates( transUnit );
417 return EXIT_SUCCESS;
418 } // if
419
420 if ( validp ) {
421 dump( move( transUnit ) );
422 return EXIT_SUCCESS;
423 } // if
424
425 PASS( "Translate Throws", ControlStruct::translateThrows( transUnit ) );
426 PASS( "Fix Labels", ControlStruct::fixLabels( transUnit ) );
427 PASS( "Fix Names", CodeGen::fixNames( transUnit ) );
428 PASS( "Gen Init", InitTweak::genInit( transUnit ) );
429 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( transUnit ) );
430
431 if ( libcfap ) {
432 // Generate the bodies of cfa library functions.
433 LibCfa::makeLibCfa( transUnit );
434 } // if
435
436 if ( declstatsp ) {
437 printDeclStats( transUnit );
438 return EXIT_SUCCESS;
439 } // if
440
441 if ( bresolvep ) {
442 dump( move( transUnit ) );
443 return EXIT_SUCCESS;
444 } // if
445
446 if ( resolvprotop ) {
447 dumpAsResolverProto( transUnit );
448 return EXIT_SUCCESS;
449 } // if
450
451 PASS( "Resolve", ResolvExpr::resolve( transUnit ) );
452 if ( exprp ) {
453 dump( move( transUnit ) );
454 return EXIT_SUCCESS;
455 } // if
456
457 forceFillCodeLocations( transUnit );
458
459 PASS( "Fix Init", InitTweak::fix(transUnit, buildingLibrary()));
460
461 // fix ObjectDecl - replaces ConstructorInit nodes
462 if ( ctorinitp ) {
463 dump( move( transUnit ) );
464 return EXIT_SUCCESS;
465 } // if
466
467 // Currently not working due to unresolved issues with UniqueExpr
468 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( transUnit ) ); // 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
469
470 PASS( "Translate Tries", ControlStruct::translateTries( transUnit ) );
471 PASS( "Gen Waitfor", Concurrency::generateWaitFor( transUnit ) );
472
473 translationUnit = convert( move( transUnit ) );
474 } else {
475 // add the assignment statement after the initialization of a type parameter
476 PASS( "Validate", SymTab::validate( translationUnit ) );
477
478 if ( symtabp ) {
479 deleteAll( translationUnit );
480 return EXIT_SUCCESS;
481 } // if
482
483 if ( expraltp ) {
484 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
485 acceptAll( translationUnit, printer );
486 return EXIT_SUCCESS;
487 } // if
488
489 if ( validp ) {
490 dump( translationUnit );
491 return EXIT_SUCCESS;
492 } // if
493
494 PASS( "Translate Throws", ControlStruct::translateThrows( translationUnit ) );
495 PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
496 PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
497 PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
498 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
499
500 if ( libcfap ) {
501 // Generate the bodies of cfa library functions.
502 LibCfa::makeLibCfa( translationUnit );
503 } // if
504
505 if ( declstatsp ) {
506 CodeTools::printDeclStats( translationUnit );
507 deleteAll( translationUnit );
508 return EXIT_SUCCESS;
509 } // if
510
511 if ( bresolvep ) {
512 dump( translationUnit );
513 return EXIT_SUCCESS;
514 } // if
515
516 CodeTools::fillLocations( translationUnit );
517
518 if ( resolvprotop ) {
519 CodeTools::dumpAsResolvProto( translationUnit );
520 return EXIT_SUCCESS;
521 } // if
522
523 PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
524 if ( exprp ) {
525 dump( translationUnit );
526 return EXIT_SUCCESS;
527 }
528
529 PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
530
531 // fix ObjectDecl - replaces ConstructorInit nodes
532 if ( ctorinitp ) {
533 dump ( translationUnit );
534 return EXIT_SUCCESS;
535 } // if
536
537 PASS( "Expand Unique Expr", 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
538 PASS( "Translate Tries", ControlStruct::translateTries( translationUnit ) );
539 PASS( "Gen Waitfor", Concurrency::generateWaitFor( translationUnit ) );
540 }
541
542 PASS( "Convert Specializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
543
544 PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
545
546 if ( tuplep ) {
547 dump( translationUnit );
548 return EXIT_SUCCESS;
549 } // if
550
551 PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
552
553 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
554 if ( genericsp ) {
555 dump( translationUnit );
556 return EXIT_SUCCESS;
557 } // if
558
559 PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
560
561 if ( bboxp ) {
562 dump( translationUnit );
563 return EXIT_SUCCESS;
564 } // if
565 PASS( "Box", GenPoly::box( translationUnit ) );
566
567 PASS( "Link-Once", CodeGen::translateLinkOnce( translationUnit ) );
568
569 // Code has been lowered to C, now we can start generation.
570
571 if ( bcodegenp ) {
572 dump( translationUnit );
573 return EXIT_SUCCESS;
574 } // if
575
576 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
577 output = new ofstream( argv[ optind ] );
578 } // if
579
580 CodeTools::fillLocations( translationUnit );
581 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
582
583 CodeGen::FixMain::fix( translationUnit, *output,
584 (PreludeDirector + "/bootloader.c").c_str() );
585 if ( output != &cout ) {
586 delete output;
587 } // if
588 } catch ( SemanticErrorException & e ) {
589 if ( errorp ) {
590 cerr << "---AST at error:---" << endl;
591 dump( translationUnit, cerr );
592 cerr << endl << "---End of AST, begin error message:---\n" << endl;
593 } // if
594 e.print();
595 if ( output != &cout ) {
596 delete output;
597 } // if
598 return EXIT_FAILURE;
599 } catch ( UnimplementedError & e ) {
600 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
601 if ( output != &cout ) {
602 delete output;
603 } // if
604 return EXIT_FAILURE;
605 } catch ( CompilerError & e ) {
606 cerr << "Compiler Error: " << e.get_what() << endl;
607 cerr << "(please report bugs to [REDACTED])" << endl;
608 if ( output != &cout ) {
609 delete output;
610 } // if
611 return EXIT_FAILURE;
612 } catch ( std::bad_alloc & ) {
613 cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
614 backtrace( 1 );
615 abort();
616 } catch ( ... ) {
617 exception_ptr eptr = current_exception();
618 try {
619 if (eptr) {
620 rethrow_exception(eptr);
621 } else {
622 cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
623 } // if
624 } catch( const exception & e ) {
625 cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
626 } // try
627 return EXIT_FAILURE;
628 } // try
629
630 deleteAll( translationUnit );
631 Stats::print();
632 return EXIT_SUCCESS;
633} // main
634
635
636static const char optstring[] = ":c:ghlLmNnpdOAP:S:twW:D:";
637
638enum { PreludeDir = 128 };
639static struct option long_opts[] = {
640 { "colors", required_argument, nullptr, 'c' },
641 { "gdb", no_argument, nullptr, 'g' },
642 { "help", no_argument, nullptr, 'h' },
643 { "libcfa", no_argument, nullptr, 'l' },
644 { "linemarks", no_argument, nullptr, 'L' },
645 { "no-main", no_argument, 0, 'm' },
646 { "no-linemarks", no_argument, nullptr, 'N' },
647 { "no-prelude", no_argument, nullptr, 'n' },
648 { "prototypes", no_argument, nullptr, 'p' },
649 { "deterministic-out", no_argument, nullptr, 'd' },
650 { "old-ast", no_argument, nullptr, 'O'},
651 { "new-ast", no_argument, nullptr, 'A'},
652 { "print", required_argument, nullptr, 'P' },
653 { "prelude-dir", required_argument, nullptr, PreludeDir },
654 { "statistics", required_argument, nullptr, 'S' },
655 { "tree", no_argument, nullptr, 't' },
656 { "", no_argument, nullptr, 0 }, // -w
657 { "", no_argument, nullptr, 0 }, // -W
658 { "", no_argument, nullptr, 0 }, // -D
659 { nullptr, 0, nullptr, 0 }
660}; // long_opts
661
662static const char * description[] = {
663 "diagnostic color: never, always, auto", // -c
664 "wait for gdb to attach", // -g
665 "print translator help message", // -h
666 "generate libcfa.c", // -l
667 "generate line marks", // -L
668 "do not replace main", // -m
669 "do not generate line marks", // -N
670 "do not read prelude", // -n
671 "do not generate prelude prototypes => prelude not printed", // -p
672 "only print deterministic output", // -d
673 "Use the old-ast", // -O
674 "Use the new-ast", // -A
675 "print", // -P
676 "<directory> prelude directory for debug/nodebug", // no flag
677 "<option-list> enable profiling information: counters, heap, time, all, none", // -S
678 "building cfa standard lib", // -t
679 "", // -w
680 "", // -W
681 "", // -D
682}; // description
683
684static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
685
686static struct Printopts {
687 const char * name;
688 int & flag;
689 int val;
690 const char * descript;
691} printopts[] = {
692 { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
693 { "asterr", errorp, true, "print AST on error" },
694 { "declstats", declstatsp, true, "code property statistics" },
695 { "parse", yydebug, true, "yacc (parsing) debug information" },
696 { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
697 { "rproto", resolvprotop, true, "resolver-proto instance" },
698 { "rsteps", resolvep, true, "print resolver steps" },
699 { "tree", parsep, true, "print parse tree" },
700 // code dumps
701 { "ast", astp, true, "print AST after parsing" },
702 { "exdecl", exdeclp, true, "print AST after translating exception decls" },
703 { "symevt", symtabp, true, "print AST after symbol table events" },
704 { "altexpr", expraltp, true, "print alternatives for expressions" },
705 { "astdecl", validp, true, "print AST after declaration validation pass" },
706 { "resolver", bresolvep, true, "print AST before resolver step" },
707 { "astexpr", exprp, true, "print AST after expression analysis" },
708 { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
709 { "tuple", tuplep, true, "print AST after tuple expansion" },
710 { "astgen", genericsp, true, "print AST after instantiate generics" },
711 { "box", bboxp, true, "print AST before box step" },
712 { "codegen", bcodegenp, true, "print AST before code generation" },
713};
714enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
715
716static void usage( char * argv[] ) {
717 cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
718 int i = 0, j = 1; // j skips starting colon
719 for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
720 if ( long_opts[i].name[0] != '\0' ) { // hidden option, internal usage only
721 if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
722 cout << " -" << optstring[j] << ",";
723 } else { // no flag
724 j -= 1; // compensate
725 cout << " ";
726 } // if
727 cout << " --" << left << setw(12) << long_opts[i].name << " ";
728 if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
729 cout << "one of: " << endl;
730 for ( int i = 0; i < printoptsSize; i += 1 ) {
731 cout << setw(10) << " " << left << setw(10) << printopts[i].name << " " << printopts[i].descript << endl;
732 } // for
733 } else {
734 cout << description[i] << endl;
735 } // if
736 } // if
737 if ( optstring[j + 1] == ':' ) j += 1;
738 } // for
739 if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
740 exit( EXIT_FAILURE );
741} // usage
742
743static void parse_cmdline( int argc, char * argv[] ) {
744 opterr = 0; // (global) prevent getopt from printing error messages
745
746 bool Wsuppress = false, Werror = false;
747 int c;
748 while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
749 switch ( c ) {
750 case 'c': // diagnostic colors
751 if ( strcmp( optarg, "always" ) == 0 ) {
752 ErrorHelpers::colors = ErrorHelpers::Colors::Always;
753 } else if ( strcmp( optarg, "never" ) == 0 ) {
754 ErrorHelpers::colors = ErrorHelpers::Colors::Never;
755 } else if ( strcmp( optarg, "auto" ) == 0 ) {
756 ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
757 } // if
758 break;
759 case 'h': // help message
760 usage( argv ); // no return
761 break;
762 case 'l': // generate libcfa.c
763 libcfap = true;
764 break;
765 case 'L': // generate line marks
766 linemarks = true;
767 break;
768 case 'm': // do not replace main
769 nomainp = true;
770 break;
771 case 'N': // do not generate line marks
772 linemarks = false;
773 break;
774 case 'n': // do not read prelude
775 nopreludep = true;
776 break;
777 case 'p': // generate prototypes for prelude functions
778 genproto = true;
779 break;
780 case 'd': // don't print non-deterministic output
781 deterministic_output = true;
782 break;
783 case 'O': // don't print non-deterministic output
784 useNewAST = false;
785 break;
786 case 'A': // don't print non-deterministic output
787 useNewAST = true;
788 break;
789 case 'P': // print options
790 for ( int i = 0;; i += 1 ) {
791 if ( i == printoptsSize ) {
792 cout << "Unknown --print option " << optarg << endl;
793 goto Default;
794 } // if
795 if ( strcmp( optarg, printopts[i].name ) == 0 ) {
796 printopts[i].flag = printopts[i].val;
797 break;
798 } // if
799 } // for
800 break;
801 case PreludeDir: // prelude directory for debug/nodebug, hidden
802 PreludeDirector = optarg;
803 break;
804 case 'S': // enable profiling information, argument comma separated list of names
805 Stats::parse_params( optarg );
806 break;
807 case 't': // building cfa stdlib
808 treep = true;
809 break;
810 case 'g': // wait for gdb
811 waiting_for_gdb = true;
812 break;
813 case 'w': // suppress all warnings, hidden
814 Wsuppress = true;
815 break;
816 case 'W': // coordinate gcc -W with CFA, hidden
817 if ( strcmp( optarg, "all" ) == 0 ) {
818 SemanticWarning_EnableAll();
819 } else if ( strcmp( optarg, "error" ) == 0 ) {
820 Werror = true;
821 } else {
822 char * warning = optarg;
823 Severity s;
824 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
825 warning += 3;
826 s = Severity::Suppress;
827 } else {
828 s = Severity::Warn;
829 } // if
830 SemanticWarning_Set( warning, s );
831 } // if
832 break;
833 case 'D': // ignore -Dxxx, forwarded by cpp, hidden
834 break;
835 case '?': // unknown option
836 if ( optopt ) { // short option ?
837 cout << "Unknown option -" << (char)optopt << endl;
838 } else {
839 cout << "Unknown option " << argv[optind - 1] << endl;
840 } // if
841 goto Default;
842 case ':': // missing option
843 if ( optopt ) { // short option ?
844 cout << "Missing option for -" << (char)optopt << endl;
845 } else {
846 cout << "Missing option for " << argv[optind - 1] << endl;
847 } // if
848 goto Default;
849 Default:
850 default:
851 usage( argv ); // no return
852 } // switch
853 } // while
854
855 if ( Werror ) {
856 SemanticWarning_WarningAsError();
857 } // if
858 if ( Wsuppress ) {
859 SemanticWarning_SuppressAll();
860 } // if
861 // for ( const auto w : WarningFormats ) {
862 // cout << w.name << ' ' << (int)w.severity << endl;
863 // } // for
864} // parse_cmdline
865
866static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
867 extern int yyparse( void );
868 extern FILE * yyin;
869 extern int yylineno;
870
871 ::linkage = linkage; // set globals
872 yyin = input;
873 yylineno = 1;
874 int parseStatus = yyparse();
875
876 fclose( input );
877 if ( shouldExit || parseStatus != 0 ) {
878 exit( parseStatus );
879 } // if
880} // parse
881
882static bool notPrelude( Declaration * decl ) {
883 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
884} // notPrelude
885
886static void dump( list< Declaration * > & translationUnit, ostream & out ) {
887 list< Declaration * > decls;
888
889 if ( genproto ) {
890 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
891 } else {
892 decls = translationUnit;
893 } // if
894
895 // depending on commandline options, either generate code or dump the AST
896 if ( codegenp ) {
897 CodeGen::generate( decls, out, ! genproto, prettycodegenp );
898 } else {
899 printAll( decls, out );
900 } // if
901 deleteAll( translationUnit );
902} // dump
903
904static void dump( ast::TranslationUnit && transUnit, ostream & out ) {
905 std::list< Declaration * > translationUnit = convert( move( transUnit ) );
906 dump( translationUnit, out );
907}
908
909// Local Variables: //
910// tab-width: 4 //
911// mode: c++ //
912// compile-command: "make install" //
913// End: //
Note: See TracBrowser for help on using the repository browser.