-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompilation.cpp
1590 lines (1360 loc) · 39.4 KB
/
Compilation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Compiler.h"
#include "Project.h"
#include "Source.h"
#include "Expressions.h"
#include "DeclarationExpressions.h"
#include "ControlExpressions.h"
#include "Lexer.h"
#include "Types/Function.h"
#ifdef _WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <llvm-c/Core.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/Host.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/IR/AssemblyAnnotationWriter.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/raw_os_ostream.h>
//#include <llvm/CodeGen/CommandFlags.h>
//#include <llvm/Target/TargetRegisterInfo.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Target/TargetMachine.h>
//#include <llvm/Target/TargetSubtargetInfo.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/GlobalVariable.h>
#ifdef _WIN32
#include <Windows.h>
#endif
/*#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif // _DEBUG*/
using namespace Jet;
//options for the linker
#ifdef _WIN32
#define USE_MSVC
#else
#define USE_GCC
#endif
std::string Jet::exec(const char* cmd) {
#ifdef _WIN32
FILE* pipe = _popen(cmd, "r");
#else
FILE* pipe = popen(cmd, "r");
#endif
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
#ifdef _WIN32
_pclose(pipe);
#else
pclose(pipe);
#endif
return result;
}
llvm::LLVMContext llvm_context_jet;
Compilation::Compilation(JetProject* proj) : builder(llvm_context_jet), context(llvm_context_jet), project(proj)
{
this->typecheck = false;
this->target = 0;
this->ns = new Namespace;
this->ns->parent = 0;
this->global = this->ns;
//insert basic types
this->FloatType = new Type("float", Types::Float);
ns->members.insert({ "float", this->FloatType });
this->DoubleType = new Type("double", Types::Double);
ns->members.insert({ "double", this->DoubleType });
ns->members.insert({ "long", new Type("long", Types::Long) });
ns->members.insert({ "ulong", new Type("ulong", Types::ULong) });
this->IntType = new Type("int", Types::Int);
ns->members.insert({ "int", this->IntType });
ns->members.insert({ "uint", new Type("uint", Types::UInt) });
ns->members.insert({ "short", new Type("short", Types::Short) });
ns->members.insert({ "ushort", new Type("ushort", Types::UShort) });
ns->members.insert({ "char", new Type("char", Types::Char) });
ns->members.insert({ "uchar", new Type("uchar", Types::UChar) });
this->BoolType = new Type("bool", Types::Bool);
ns->members.insert({ "bool", this->BoolType });
// NEED TO BE SURE NOT TO FREE THIS
ns->members.insert({ "void", &VoidType });// new Type("void", Types::Void) });
for (auto ii : ns->members)
{
if (ii.second.type == SymbolType::Type)
ii.second.ty->ns = ns;
}
this->CharPointerType = ns->members.find("char")->second.ty->GetPointerType();
}
Compilation::~Compilation()
{
//free global namespace
delete this->global;
//free ASTs
for (auto ii : asts)
{
//std::string out;
//if (errors == 0)
//{
//MemberRenamer renamer("string", "length", "apples", this);
//ii.second->Visit(&renamer);
//ii.second->Print(out, sources[ii.first]);
//}
//printf("%s",out.c_str());
delete ii.second;
}
//free sources
for (auto ii : sources)
delete ii.second;
//free function types
for (auto ii : function_types)
delete ii.second;
//free functions
for (auto ii : this->functions)
delete ii;
//free traits
for (auto ii : this->traits)
delete ii.second;
delete this->target;
//dont delete this->project we dont have ownership
delete this->debug;
delete this->module;
}
#ifndef _WIN32
int64_t gettime2()//returns time in microseconds
{
static __time_t start;
timespec time;
//gettimeofday(&time, 0);
clock_gettime(CLOCK_MONOTONIC, &time);
return (int64_t)time.tv_sec*1000000 + time.tv_nsec/1000;
}
#endif
class StackTime
{
bool enable;
public:
long long start;
long long rate;
char* name;
StackTime(char* name, bool enable = true);
~StackTime();
};
StackTime::StackTime(char* name, bool time)
{
this->name = name;
this->enable = time;
#ifndef _WIN32
start = gettime2();
rate = 1000000;
#else
QueryPerformanceCounter((LARGE_INTEGER *)&start);
QueryPerformanceFrequency((LARGE_INTEGER *)&rate);
#endif
}
StackTime::~StackTime()
{
long long end;
#ifdef _WIN32
QueryPerformanceCounter((LARGE_INTEGER *)&end);
#else
end = gettime2();
#endif
if (this->enable == false)
return;
long long diff = end - start;
float dt = ((double)diff) / ((double)rate);
printf("%s Time: %f seconds\n", this->name, dt);
}
class TraitChecker : public ExpressionVisitor
{
Compilation* compiler;
public:
TraitChecker(Compilation* compiler) : compiler(compiler)
{
}
virtual void Visit(CallExpression* expr)
{
auto fun = dynamic_cast<FunctionExpression*>(expr->parent->parent);
if (fun == 0)
return;
if (auto index = dynamic_cast<IndexExpression*>(expr->left))
{
if (auto str = dynamic_cast<StructExpression*>(fun->parent))
{
if (str->templates)
{
auto trait = compiler->LookupType(str->templates->front().type.text);
//check if the call fits the trait
//auto out = index->GetBaseType(this->compiler);
//printf("hi");
}
}
}
}
};
extern std::string generate_jet_from_header(const char* header);
Compilation* Compilation::Make(JetProject* project, DiagnosticBuilder* diagnostics, bool time, int debug)
{
Compilation* compilation = new Compilation(project);
compilation->diagnostics = diagnostics;
diagnostics->compilation = compilation;
char olddir[500];
getcwd(olddir, 500);
std::string path = project->path;
path += '/';
if (path.length() > 1)
chdir(path.c_str());
std::vector<std::pair<std::string, char*>> lib_symbols;
const std::vector<std::string>& resolved_deps = project->ResolveDependencies();
int deps = project->dependencies.size();
for (int i = 0; i < deps; i++)
{
auto ii = resolved_deps[i];
if (resolved_deps[i].length() == 0)
{
throw 7;// we are missing a dependency
}
//read in declarations for each dependency
std::string symbol_filepath = ii + "/build/symbols.jlib";
std::ifstream symbols(symbol_filepath, std::ios_base::binary);
if (symbols.is_open() == false)
{
for (auto ii : lib_symbols)
delete[] ii.second;
diagnostics->Error("Dependency include of '" + ii + "' failed: could not find symbol file!", "project.jp");
//restore working directory
chdir(olddir);
return 0;
}
//parse symbols
symbols.seekg(0, std::ios::end); // go to the end
std::streamoff length = symbols.tellg(); // report location (this is the length)
symbols.seekg(0, std::ios::beg); // go back to the beginning
int start;
symbols.read((char*)&start, 4);
symbols.seekg(start + 4, std::ios::beg);
char* buffer = new char[length + 1 - start - 4]; // allocate memory for a buffer of appropriate dimension
symbols.read(buffer, length); // read the whole file into the buffer
buffer[length - start - 4] = 0;
symbols.close();
//ok, need to parse this out into different lines/files
lib_symbols.push_back({ symbol_filepath, buffer });
}
//spin off children and lets compile this!
compilation->module = new llvm::Module(project->project_name, compilation->context);
compilation->debug = new llvm::DIBuilder(*compilation->module, true);
bool emit_debug = debug > 0;
auto emission_kind = debug <= 1 ? llvm::DICompileUnit::DebugEmissionKind::LineTablesOnly : llvm::DICompileUnit::DebugEmissionKind::FullDebug;
char tmp_cwd[500];
getcwd(tmp_cwd, 500);
auto file = compilation->debug->createFile("../aaaa.jet", "");
compilation->debug_info.cu = compilation->debug->createCompileUnit(llvm::dwarf::DW_LANG_C, file, "Jet Compiler", false, "", 0, "", emission_kind, 0, emit_debug);
//compile it
//first lets create the global context!!
//ok this will be the main entry point it initializes everything, then calls the program's entry point
int errors = 0;
auto global = new CompilerContext(compilation, 0);
compilation->current_function = global;
compilation->sources = project->GetSources();
//add default defines
auto defines = project->defines;
#ifdef _WIN32
defines["WINDOWS"] = true;
#else
defines["LINUX"] = true;
#endif
if (debug > 1)// project debug info is enabled
defines["DEBUG"] = true;
else
defines["RELEASE"] = true;
//build converted headers and add their source
for (auto hdr : project->headers)
{
std::string two = hdr;
std::string outfile = two + ".jet";
//if the header already exists, dont regenerate
FILE* hdr = fopen(outfile.c_str(), "r");
if (hdr == 0)//for now just run it every time
{
//fix conversion of attributes for calling convention and fix function pointers
std::string str = generate_jet_from_header(two.c_str());
if (str.length() == 0)
{
diagnostics->Error("Could not find header file '" + two + "' to convert.\n", "project.jp");
errors++;
}
else
{
std::ofstream o(two + ".jet");
o << str;
o.close();
}
}
else
{
fclose(hdr);
}
//add the source
std::ifstream t(outfile, std::ios::in | std::ios::binary);
if (t)
{
t.seekg(0, std::ios::end); // go to the end
std::streamoff length = t.tellg(); // report location (this is the length)
t.seekg(0, std::ios::beg); // go back to the beginning
char* buffer = new char[length + 1]; // allocate memory for a buffer of appropriate dimension
t.read(buffer, length); // read the whole file into the buffer
buffer[length] = 0;
t.close();
compilation->sources[outfile] = new Source(buffer, outfile);
}
}
//read in symbols from lib
std::vector<BlockExpression*> symbol_asts;
std::vector<Source*> symbol_sources;
{
StackTime timer("Reading Symbols", time);
compilation->compiling_includes = true;
std::map<std::string, std::string*> source_strings;//used so we can reuse them
for (auto buffer : lib_symbols)
{
//parse into sources so we can use them below
const char* data = buffer.second;
unsigned int len = strlen(buffer.second);
std::string current_filename = buffer.first;
//lets read each line at a time
int i = 0;
while (i < len)
{
//find end of the line
int start = i;
while ( i < len && data[i++] != '\n') { }
int end = i-1;
const char* line = &data[start];
if (end - start > 6 && data[start] == '/'
&& data[start + 1] == '/'
&& data[start + 2] == '!'
&& data[start + 3] == '@'
&& data[start + 4] == '!')
{
const char* file_name = &data[start + 5];
//look for end of file_name
int p = start+5;
while (p < len && data[p++] != '@') {}
current_filename = std::string(file_name, p-(start+6));
}
//insert the line into the correct source...
// use current_filename to look up the source
auto source = source_strings.find(current_filename);
if (source == source_strings.end())
{
//create new one and add it to the list
source_strings[current_filename] = new std::string();
source = source_strings.find(current_filename);
}
//ok now insert
source->second->append(line, end - start + 1);
}
}
for (auto ii : source_strings)
{
//copy into sources now that we are done
char* data = new char[ii.second->size()+1];
strcpy(data, ii.second->c_str());
delete ii.second;//free the strings now that we are done with them
Source* src = new Source(data, ii.first);
compilation->sources["#symbols_" + std::to_string(symbol_asts.size() + 1)] = src;
BlockExpression* result = src->GetAST(diagnostics, {});
if (diagnostics->GetErrors().size())
{
delete result;
printf("Compilation Stopped, Error Parsing Symbols\n");
delete compilation;
compilation = 0;
errors = 1;
goto error;
}
try
{
result->CompileDeclarations(global);
symbol_asts.push_back(result);
symbol_sources.push_back(src);
}
catch (...)
{
delete result;
printf("Compilation Stopped, Error Parsing Symbols\n");
delete compilation;
compilation = 0;
errors = 1;
goto error;
}
compilation->asts["#symbols_" + std::to_string(symbol_asts.size())] = result;
//this fixes some errors, need to resolve them later
compilation->debug_info.file = compilation->debug->createFile("temp",
compilation->debug_info.cu->getDirectory());
//compilation->ResolveTypes();
}
compilation->ResolveTypes();
compilation->compiling_includes = false;
}
//read in each file
//these two blocks could be multithreaded! theoretically
{
StackTime timer("Parsing Files and Compiling Declarations", time);
for (auto file : compilation->sources)
{
if (file.second == 0)
{
diagnostics->Error("Could not find file '" + file.first + "'.", "project.jp");
//printf("Could not find file '%s'!\n", file.first.c_str());
errors = 1;
goto error;
}
if (file.first[0] == '#')//ignore symbol files, we already parsed them
continue;
BlockExpression* result = file.second->GetAST(diagnostics, defines);
if (diagnostics->GetErrors().size())
{//stop if we encountered a parsing error
printf("Compilation Stopped, Parser Error\n");
errors = 1;
delete compilation;
compilation = 0;
goto error;
}
//TraitChecker checker(compilation);
//result->Visit(&checker);
compilation->asts[file.first] = result;
compilation->current_function = global;
//do this for each file
for (auto ii : result->statements)
{
try
{
ii->CompileDeclarations(global);//guaranteed not to throw?
}
catch (int x)
{
errors++;
goto error;
}
}
}
}
//this fixes some errors, need to resolve them later
compilation->debug_info.file = compilation->debug->createFile("temp",
compilation->debug_info.cu->getDirectory());
try
{
StackTime tt("Resolving Types", time);
compilation->ResolveTypes();
}
catch (int x)
{
errors++;
goto error;
}
{
StackTime timer("Final Compiler Pass", time);
for (auto result : compilation->asts)
{
if (result.first[0] == '#')
continue;
compilation->current_function = global;
compilation->debug_info.file = compilation->debug->createFile(result.first,
compilation->debug_info.cu->getDirectory());
compilation->builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, compilation->debug_info.file));
//make sure to set the file name differently for different files
//then do this for each file
for (auto ii : result.second->statements)
{
//catch any exceptions
compilation->typecheck = true;
try
{
ii->TypeCheck(global);
}
catch (int x)
{
compilation->ns = compilation->global;
errors++;
compilation->typecheck = false;
continue;
}
compilation->typecheck = false;
try
{
ii->Compile(global);
}
catch (int x)
{
compilation->ns = compilation->global;
errors++;
}
compilation->ns = compilation->global;
}
//compile any templates that were missed
for (auto temp : compilation->unfinished_templates)
{
temp->FinishCompilingTemplate(compilation);
}
}
}
//figure out how to get me working with multiple definitions
/*auto init = global->AddFunction("_jet_initializer", compilation->ns->members.find("int")->second.ty, {}, false, false);
if (project->IsExecutable())
{
//this->builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, init->function->scope.get()));
//init->Call("puts", { init->String("hello from initializer") });
//todo: put intializers here
if (project->IsExecutable())
init->Call("main", {});
}
init->Return(global->Integer(0));*/
error:
//restore working directory
chdir(olddir);
return compilation;
}
char* ReadDependenciesFromSymbols(const char* path, int& size)
{
auto file = fopen(path, "rb");
if (file)
{
fread(&size, 4, 1, file);
if (size < 0)
{
printf("Invalid dependency symbol file!\n");
return 0;
}
char* data = new char[size];
fread(data, size, 1, file);
fclose(file);
return data;
}
return 0;
}
std::string LinkLibLD(const std::string& path)
{
int div = path.find_last_of('\\');
int d2 = path.find_last_of('/');
if (d2 > div)
div = d2;
std::string file = path.substr(div+1);
std::string lib_name = file;
//strip off any extension
if (lib_name.find_last_of('.'))
{
lib_name = lib_name.substr(0, lib_name.find_last_of('.'));
}
if (lib_name.length() > 3 && lib_name[0] == 'l'
&& lib_name[1] == 'i'
&& lib_name[2] == 'b')
{
lib_name = lib_name.substr(3);
}
std::string folder = path.substr(0, div);
std::string out;
if (div > -1)
out += " -L\"" + folder + "\" ";
else
out += " -L. ";
out += " -l\"" + lib_name + "\" ";
return out;
}
void Compilation::Assemble(const std::string& target, const std::string& linker, int olevel, bool time, bool output_ir)
{
if (this->diagnostics->GetErrors().size() > 0)
return;
StackTime timer("Assembling Output", time);
char olddir[500];
getcwd(olddir, 500);
std::string path = project->path;
path += '/';
if (path.length() > 1)
chdir(path.c_str());
//make the output folder
#ifndef _WIN32
mkdir("build/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#else
mkdir("build/");
#endif
//set target
//add string
//linux i686-pc-linux-gnu
//raspbian arm-pc-linux-gnueabif"armv6-linux-gnueabihf"
this->SetTarget(target);
debug->finalize();
if (olevel > 0)
this->Optimize(olevel);
//output the IR for debugging
if (output_ir)
this->OutputIR("build/output.ir");
//output the .o file and .jlib for this package
this->OutputPackage(project->project_name, olevel, time);
//and handling the arguments as well as function overloads, which is still a BIG problem
//need name mangling
//then, if and only if I am an executable, make the .exe
if (project->IsExecutable())
{
printf("Compiling Executable...\n");
std::string used_linker = linker;
#ifdef USE_GCC
if (linker == "")
used_linker = "ld";
#else
if (linker == "")
used_linker = "link.exe";
#endif
//working gcc command, use this
////C:\Users\Matthew\Desktop\VM\AsmVM2\AsmVM\async>ld build/async.o ../jetcore/build
// /jetcore.o -l:"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib\msvcrt
// .lib" -l:"C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86\kernel32.li
/// b" -o build/async_test.exe --entry _main
if (used_linker.find("link.exe") == -1)
{
std::string cmd = linker + " ";// "ld ";//"gcc -L. -g ";//-e_jet_initializer
//set entry
cmd += "--entry _main ";
cmd += "\"build/" + project->project_name + ".o\" ";
cmd += "-o \"build/" + project->project_name + ".exe\" ";
//todo need to make sure to link in deps of deps also fix linking
//need to link each dependency
for (auto ii : project->ResolveDependencies())
{
cmd += "\"" + ii + "/build/";//cmd += "-L" + ii + "/build/ ";
cmd += GetNameFromPath(ii) + ".o\" ";
}
//then for each dependency add libs that it needs to link
for (auto ii : project->ResolveDependencies())
{
//open up and read first part of the jlib file
int size;
char* data = ReadDependenciesFromSymbols((ii + "/build/symbols.jlib").c_str(), size);
if (data == 0)
{
//probably an error
}
int pos = 0;
while (pos < size)
{
const char* file = &data[pos];
if (file[0])
cmd += LinkLibLD(file);
pos += strlen(&data[pos]) + 1;
}
delete[] data;
}
for (auto ii : project->libs)
cmd += LinkLibLD(ii);
//rename _context into this in generators, figure out why passing by value into async doesnt work
// implement basic containers
printf("\n%s\n", cmd.c_str());
auto res = exec(cmd.c_str());
printf(res.c_str());
}
else
{
std::string cmd = "link.exe /DEBUG /INCREMENTAL:NO /NOLOGO ";
//cmd += "/ENTRY:main ";// "/ENTRY:_jet_initializer ";
cmd += "build/" + project->project_name + ".o ";
cmd += "/OUT:build/" + project->project_name + ".exe ";
//need to link each dependency
for (auto ii : project->dependencies)
cmd += ii + "/build/lib" + GetNameFromPath(ii) + ".a ";
//then for each dependency add libs that it needs to link
for (auto ii : project->ResolveDependencies())
{
//open up and read first part of the jlib file
int size;
char* data = ReadDependenciesFromSymbols((ii + "/build/symbols.jlib").c_str(), size);
if (data == 0)
{
//probably an error
}
int pos = 0;
while (pos < size)
{
const char* file = &data[pos];
if (file[0])
cmd += " \"" + std::string(file) + "\"";
pos += strlen(&data[pos]) + 1;
}
delete[] data;
}
for (auto ii : project->libs)
cmd += " \"" + ii + "\"";
auto res = exec(cmd.c_str());
printf(res.c_str());
}
}
else
{
std::vector<std::string> temps;
//need to put this stuff in the .jlib file later
printf("Compiling Lib...\n");
#ifndef USE_GCC
std::string ar = "llvm-ar";
#else
std::string ar = "ar";
#endif
std::string cmd = ar + " rcs build/lib" + project->project_name + ".a ";
cmd += "build/" + project->project_name + ".o ";
for (auto ii : project->ResolveDependencies())
{
//need to extract then merge
//can use llvm-ar or just ar
std::string cm = ar + " x " + ii + "/build/lib" + GetNameFromPath(ii) + ".a";
auto res = exec(cm.c_str());
printf(res.c_str());
//get a list of the extracted files
cm = ar + " t " + ii + "/build/lib" + GetNameFromPath(ii) + ".a";
res = exec(cm.c_str());
int i = 0;
while (true)
{
std::string file;
if (i >= res.length())
break;
while (res[i] != '\n')
file += res[i++];
i++;
temps.push_back(file);
cmd += file + " ";
}
}
auto res = exec(cmd.c_str());
printf(res.c_str());
//delete temporary files
for (auto ii : temps)
#ifndef _WIN32
remove(ii.c_str());
#else
DeleteFileA(ii.c_str());
#endif
}
//restore working directory
chdir(olddir);
}
void Compilation::Optimize(int level)
{
//do inlining
llvm::legacy::PassManager MPM;
if (level > 0)
{
MPM.add(llvm::createFunctionInliningPass(level, 3, false));
MPM.run(*module);
}
llvm::legacy::FunctionPassManager OurFPM(module);
// Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures.
//TheModule->setDataLayout(*TheExecutionEngine->getDataLayout());
// Do the main datalayout
//OurFPM.add(new llvm::DataLayoutPass());
// Provide basic AliasAnalysis support for GVN.
//OurFPM.add(llvm::createBasicAliasAnalysisPass());
// Do simple "peephole" optimizations and bit-twiddling optzns.
OurFPM.add(llvm::createInstructionCombiningPass());
// Reassociate expressions.
OurFPM.add(llvm::createReassociatePass());
OurFPM.add(llvm::createInstructionSimplifierPass());
// Promote allocas to registers
OurFPM.add(llvm::createPromoteMemoryToRegisterPass());
// Eliminate Common SubExpressions.
//OurFPM.add(llvm::createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
OurFPM.add(llvm::createCFGSimplificationPass());
if (level > 1)
OurFPM.add(llvm::createDeadCodeEliminationPass());
OurFPM.doInitialization();
//run it on all functions
for (auto fun : this->functions)
{
if (fun && fun->f && fun->expression)
{
OurFPM.run(*fun->f);
}
}
}
#include <llvm\Support\ARMEHABI.h>
void Compilation::SetTarget(const std::string& triple)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmParser();
llvm::InitializeNativeTargetAsmPrinter();
//LLVMInitializeARMTarget();
//LLVMInitializeARMAsmPrinter();
//LLVMInitializeARMTargetMC();
//LLVMInitializeARMTargetInfo();
//LLVMInitializeMSP430Target();
//llvm::initializeTarget()
auto MCPU = llvm::sys::getHostCPUName();
llvm::Triple TheTriple;
if (triple.length())
{
TheTriple.setTriple(triple);
MCPU = "";
}
else
{
if (TheTriple.getTriple().empty())
TheTriple.setTriple(llvm::sys::getDefaultTargetTriple());
}
//ok, now for linux builds...
//TheTriple = llvm::Triple("i686", "pc", "linux", "gnu");
// Get the target specific parser.
std::string Error;
const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TheTriple.str(), Error);
if (TheTarget == 0)
{
printf("ERROR: Invalid target string! Using system default.\n");
TheTriple.setTriple(llvm::sys::getDefaultTargetTriple());
//ok, now for linux builds...
//TheTriple = llvm::Triple("i686", "pc", "linux", "gnu");
// Get the target specific parser.
std::string Error;
TheTarget = llvm::TargetRegistry::lookupTarget(TheTriple.str(), Error);
}
//for linux builds use i686-pc-linux-gnu
//ok add linux builds
llvm::TargetOptions Options;// = llvm::InitTargetOptionsFromCodeGenFlags();
//Options.MCOption
//Options.DisableIntegratedAS = NoIntegratedAssembler;
//Options.MCOptions.ShowMCEncoding = llvm::ShowMCEncoding;
//Options.MCOptions.MCUseDwarfDirectory = llvm::EnableDwarfDirectory;
std::string FeaturesStr;
llvm::CodeGenOpt::Level OLvl = llvm::CodeGenOpt::Default;
Options.MCOptions.AsmVerbose = false;// llvm::AsmVerbose;
Options.DebuggerTuning = llvm::DebuggerKind::GDB;
//llvm::TargetMachine Target(*(llvm::Target*)TheTarget, TheTriple.getTriple(), MCPU, FeaturesStr, Options);
auto RelocModel = llvm::Reloc::Static;//this could be problematic
auto CodeModel = llvm::CodeModel::Medium;
this->target = TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, Options, RelocModel, CodeModel, OLvl);
module->setDataLayout(this->target->createDataLayout());
}
void Compilation::OutputPackage(const std::string& project_name, int o_level, bool time)
{
llvm::legacy::PassManager MPM;
std::error_code ec;
llvm::raw_fd_ostream strr("build/" + project_name + ".o", ec, llvm::sys::fs::OpenFlags::F_None);
//ok, watch out for unsupported calling conventions, need way to specifiy code for windows/linux/cpu
//add pass to emit the object file
target->addPassesToEmitFile(MPM, strr, llvm::TargetMachine::CodeGenFileType::CGFT_ObjectFile, false);