source: src/main.cc@ 418882af

ADT ast-experimental
Last change on this file since 418882af was 3dd8f42, checked in by caparsons <caparson@…>, 3 years ago

added actor support to the compiler

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