source: src/main.cc@ fc01219

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since fc01219 was 9490621, checked in by Andrew Beach <ajbeach@…>, 4 years ago

My work in progress implementation of ForallPointerDecay for Fangren.

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