source: src/main.cc@ fe293bf

Last change on this file since fe293bf was be3f163, checked in by Peter A. Buhr <pabuhr@…>, 23 months ago

rename files gcc-builtins.cf builtins.cf extras.cf bootloader.cf and sync-builtins.cf with suffix .cfa

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