source: src/main.cc@ 86b8d16

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

Removed extra include, it should compile again.

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