/
genopt.cc
1596 lines (1273 loc) · 39.3 KB
/
genopt.cc
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 "genopt.h"
#include <string.h>
#include "llvm_config_begin.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/CallSite.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Dominators.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Analysis/Lint.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/ADT/SmallSet.h>
#if PONY_LLVM >= 600
#include <llvm-c/DebugInfo.h>
#endif
#include "llvm_config_end.h"
#include "../../libponyrt/mem/heap.h"
#include "ponyassert.h"
using namespace llvm;
using namespace llvm::legacy;
static __pony_thread_local compile_t* the_compiler;
static void print_transform(compile_t* c, Instruction* i, const char* s)
{
errors_t* errors = c->opt->check.errors;
if((c == NULL) || !c->opt->print_stats)
return;
/* Starting with LLVM 3.7.0-final getDebugLog may return a
* DebugLoc without a valid underlying MDNode* for instructions
* that have no direct source location, instead of returning 0
* for getLine().
*/
while(!i->getDebugLoc())
{
i = i->getNextNode();
if(i == nullptr)
return;
}
DebugLoc loc = i->getDebugLoc();
DILocation* location = loc.get();
DIScope* scope = location->getScope();
DILocation* at = location->getInlinedAt();
if(at != NULL)
{
DIScope* scope_at = at->getScope();
errorf(errors, NULL, "[%s] %s:%u:%u@%s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope->getFilename().str().c_str(), loc.getLine(), loc.getCol(),
scope_at->getFilename().str().c_str(), at->getLine(),
at->getColumn(), s);
}
else {
errorf(errors, NULL, "[%s] %s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope->getFilename().str().c_str(), loc.getLine(), loc.getCol(), s);
}
}
// TODO: remove for 6.0.1: https://reviews.llvm.org/D44140
#if PONY_LLVM == 600
PONY_EXTERN_C_BEGIN
void LLVMInitializeInstCombine_Pony(LLVMPassRegistryRef R) {
initializeInstructionCombiningPassPass(*unwrap(R));
}
PONY_EXTERN_C_END
#endif
class HeapToStack : public FunctionPass
{
public:
static char ID;
compile_t* c;
HeapToStack() : FunctionPass(ID)
{
c = the_compiler;
}
bool runOnFunction(Function& f)
{
DominatorTree& dt = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
BasicBlock& entry = f.getEntryBlock();
IRBuilder<> builder(&entry, entry.begin());
bool changed = false;
for(auto block = f.begin(), end = f.end(); block != end; ++block)
{
for(auto iter = block->begin(), end = block->end(); iter != end; )
{
Instruction* inst = &(*(iter++));
if(runOnInstruction(builder, inst, dt, f))
changed = true;
}
}
return changed;
}
bool runOnInstruction(IRBuilder<>& builder, Instruction* inst,
DominatorTree& dt, Function& f)
{
CallSite call(inst);
if(!call.getInstruction())
return false;
Function* fun = call.getCalledFunction();
if(fun == NULL)
return false;
bool small = false;
if(fun->getName().compare("pony_alloc") == 0)
{
// Nothing.
} else if(fun->getName().compare("pony_alloc_small") == 0) {
small = true;
} else {
return false;
}
Value* size = call.getArgument(1);
c->opt->check.stats.heap_alloc++;
ConstantInt* int_size = dyn_cast_or_null<ConstantInt>(size);
if(int_size == NULL)
{
print_transform(c, inst, "variable size allocation");
return false;
}
uint64_t alloc_size = int_size->getZExtValue();
if(small)
{
// Convert a heap index to a size.
int_size = ConstantInt::get(builder.getInt64Ty(),
((int64_t)1) << (alloc_size + HEAP_MINBITS));
} else {
if(alloc_size > 1024)
{
print_transform(c, inst, "large allocation");
return false;
}
}
SmallVector<CallInst*, 4> tail;
SmallVector<Instruction*, 4> new_calls;
if(!canStackAlloc(inst, dt, tail, new_calls))
return false;
for(auto iter = tail.begin(), end = tail.end(); iter != end; ++iter)
(*iter)->setTailCall(false);
// TODO: for variable size alloca, don't insert at the beginning.
Instruction* begin = &(*call.getCaller()->getEntryBlock().begin());
unsigned int align = target_is_ilp32(c->opt->triple) ? 4 : 8;
#if PONY_LLVM < 500
AllocaInst* replace = new AllocaInst(builder.getInt8Ty(), int_size, align,
"", begin);
#else
AllocaInst* replace = new AllocaInst(builder.getInt8Ty(),
0, int_size, align, "", begin);
#endif
replace->setDebugLoc(call->getDebugLoc());
inst->replaceAllUsesWith(replace);
#if PONY_LLVM < 400
(void)f;
#else
if (call.isInvoke())
{
InvokeInst *invoke = cast<InvokeInst>(call.getInstruction());
BranchInst::Create(invoke->getNormalDest(), invoke);
invoke->getUnwindDest()->removePredecessor(call->getParent());
}
CallGraphWrapperPass *cg_pass =
getAnalysisIfAvailable<CallGraphWrapperPass>();
CallGraph *cg = cg_pass ? &cg_pass->getCallGraph() : nullptr;
CallGraphNode *cg_node = cg ? (*cg)[&f] : nullptr;
if (cg_node)
{
cg_node->removeCallEdgeFor(call);
}
#endif
inst->eraseFromParent();
for(auto new_call: new_calls)
{
// Force constructor inlining to see if fields can be stack-allocated.
InlineFunctionInfo ifi{};
InlineFunction(CallSite(new_call), ifi);
}
print_transform(c, replace, "stack allocation");
c->opt->check.stats.heap_alloc--;
c->opt->check.stats.stack_alloc++;
return true;
}
bool canStackAlloc(Instruction* alloc, DominatorTree& dt,
SmallVector<CallInst*, 4>& tail, SmallVector<Instruction*, 4>& new_calls)
{
// This is based on the pass in the LDC compiler.
SmallVector<Use*, 16> work;
SmallSet<Use*, 16> visited;
for(auto iter = alloc->use_begin(), end = alloc->use_end();
iter != end; ++iter)
{
Use* use = &(*iter);
visited.insert(use);
work.push_back(use);
}
while(!work.empty())
{
Use* use = work.pop_back_val();
Instruction* inst = cast<Instruction>(use->getUser());
Value* value = use->get();
switch(inst->getOpcode())
{
case Instruction::Call:
case Instruction::Invoke:
{
CallSite call(inst);
if(call.onlyReadsMemory())
{
// If the function is readnone or readonly, and the return value
// isn't and does not contain a pointer, it isn't captured.
Type* type = inst->getType();
if(type->isVoidTy() ||
type->isFPOrFPVectorTy() ||
type->isIntOrIntVectorTy()
)
{
// Doesn't return any pointers, so it isn't captured.
break;
}
}
if(inst->getMetadata("pony.newcall") != NULL)
new_calls.push_back(inst);
auto first = call.arg_begin();
for(auto iter = first, end = call.arg_end(); iter != end; ++iter)
{
if(iter->get() == value)
{
// If it's not marked as nocapture, it's captured.
if(!call.doesNotCapture((unsigned)(iter - first)))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, inst, "captured here (call arg)");
return false;
}
if(call.isCall())
{
CallInst* ci = cast<CallInst>(inst);
if(ci->isTailCall())
tail.push_back(ci);
}
}
}
break;
}
case Instruction::Load:
break;
case Instruction::Store:
{
// If we store the pointer, it is captured.
// TODO: if we store the pointer in something that is stack allocated
// is it still captured?
if(value == inst->getOperand(0))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, inst, "captured here (store)");
return false;
}
break;
}
case Instruction::BitCast:
case Instruction::GetElementPtr:
case Instruction::PHI:
case Instruction::Select:
{
// If a derived pointer can be reused, it can't be stack allocated.
if(canBeReused(inst, alloc, dt))
return false;
// Check that the new value isn't captured.
for(auto iter = inst->use_begin(), end = inst->use_end();
iter != end; ++iter)
{
Use* use = &(*iter);
if(visited.insert(use).second)
work.push_back(use);
}
break;
}
default:
{
// If it's anything else, assume it's captured just in case.
print_transform(c, alloc, "captured allocation");
print_transform(c, inst, "captured here (unknown)");
return false;
}
}
}
return true;
}
bool canBeReused(Instruction* def, Instruction* alloc, DominatorTree& dt)
{
if(def->use_empty() || !dt.dominates(def, alloc))
return false;
BasicBlock* def_block = def->getParent();
BasicBlock* alloc_block = alloc->getParent();
SmallSet<User*, 16> users;
SmallSet<BasicBlock*, 16> user_blocks;
for(auto iter = def->use_begin(), end = def->use_end();
iter != end; ++iter)
{
Use* use = &(*iter);
Instruction* user = cast<Instruction>(use->getUser());
BasicBlock* user_block = user->getParent();
if((alloc_block != user_block) && dt.dominates(alloc_block, user_block))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, def, "captured here (dominated reuse)");
return true;
}
if(!isa<PHINode>(user))
{
users.insert(user);
user_blocks.insert(user_block);
}
}
typedef std::pair<BasicBlock*, Instruction*> Work;
SmallVector<Work, 16> work;
SmallSet<BasicBlock*, 16> visited;
Instruction* start = alloc->getNextNode();
work.push_back(Work(alloc_block, start));
while(!work.empty())
{
Work w = work.pop_back_val();
BasicBlock* bb = w.first;
Instruction* inst = w.second;
if(user_blocks.count(bb))
{
if((bb != def_block) && (bb != alloc_block))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, def,
"captured here (block contains neither alloc nor def)");
return true;
}
while(inst != nullptr)
{
if((inst == def) || (inst == alloc))
break;
if(users.count(inst))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, inst, "captured here (reused)");
return true;
}
inst = inst->getNextNode();
}
}
else if((bb == def_block) || ((bb == alloc_block) && (inst != start)))
{
continue;
}
TerminatorInst* term = bb->getTerminator();
unsigned count = term->getNumSuccessors();
for(unsigned i = 0; i < count; i++)
{
BasicBlock* successor = term->getSuccessor(i);
inst = &successor->front();
bool found = false;
while(isa<PHINode>(inst))
{
if(def == cast<PHINode>(inst)->getIncomingValueForBlock(bb))
{
print_transform(c, alloc, "captured allocation");
print_transform(c, inst, "captured here (phi use)");
return true;
}
if(def == inst)
found = true;
inst = inst->getNextNode();
}
if(!found &&
visited.insert(successor).second &&
dt.dominates(def_block, successor))
{
work.push_back(Work(successor, inst));
}
}
}
return false;
}
void getAnalysisUsage(AnalysisUsage& use) const
{
use.addRequired<DominatorTreeWrapperPass>();
}
};
char HeapToStack::ID = 0;
static RegisterPass<HeapToStack>
H2S("heap2stack", "Move heap allocations to the stack");
static void addHeapToStackPass(const PassManagerBuilder& pmb,
PassManagerBase& pm)
{
if(pmb.OptLevel >= 2) {
pm.add(new DominatorTreeWrapperPass());
pm.add(new HeapToStack());
}
}
class DispatchPonyCtx : public FunctionPass
{
public:
static char ID;
DispatchPonyCtx() : FunctionPass(ID)
{}
bool runOnFunction(Function& f)
{
// Check if we're in a Dispatch function.
StringRef name = f.getName();
if(name.size() < 10 || name.rfind("_Dispatch") != name.size() - 9)
return false;
pony_assert(f.arg_size() > 0);
Value* ctx = &(*f.arg_begin());
bool changed = false;
for(auto block = f.begin(), end = f.end(); block != end; ++block)
{
for(auto iter = block->begin(), end = block->end(); iter != end; ++iter)
{
Instruction* inst = &(*iter);
if(runOnInstruction(inst, ctx))
changed = true;
}
}
return changed;
}
bool runOnInstruction(Instruction* inst, Value* ctx)
{
CallSite call(inst);
if(!call.getInstruction())
return false;
Function* fun = call.getCalledFunction();
if(fun == NULL)
return false;
if(fun->getName().compare("pony_ctx") != 0)
return false;
inst->replaceAllUsesWith(ctx);
return true;
}
};
char DispatchPonyCtx::ID = 1;
static RegisterPass<DispatchPonyCtx>
DPC("dispatchponyctx", "Replace pony_ctx calls in a dispatch function by the\
context passed to the function");
static void addDispatchPonyCtxPass(const PassManagerBuilder& pmb,
PassManagerBase& pm)
{
if(pmb.OptLevel >= 2)
pm.add(new DispatchPonyCtx());
}
class MergeRealloc : public FunctionPass
{
public:
static char ID;
compile_t* c;
Function* alloc_fn;
Function* alloc_small_fn;
Function* alloc_large_fn;
MergeRealloc() : FunctionPass(ID)
{
c = the_compiler;
alloc_fn = NULL;
alloc_small_fn = NULL;
alloc_large_fn = NULL;
}
bool doInitialization(Module& m)
{
alloc_fn = m.getFunction("pony_alloc");
alloc_small_fn = m.getFunction("pony_alloc_small");
alloc_large_fn = m.getFunction("pony_alloc_large");
if(alloc_fn == NULL)
alloc_fn = declareAllocFunction(m, "pony_alloc", unwrap(c->intptr),
HEAP_MIN, true);
if(alloc_small_fn == NULL)
alloc_small_fn = declareAllocFunction(m, "pony_alloc_small",
unwrap(c->i32), HEAP_MIN, false);
if(alloc_large_fn == NULL)
alloc_large_fn = declareAllocFunction(m, "pony_alloc_large",
unwrap(c->intptr), HEAP_MAX << 1, false);
return false;
}
bool runOnFunction(Function& f)
{
BasicBlock& entry = f.getEntryBlock();
IRBuilder<> builder(&entry, entry.begin());
bool changed = false;
SmallVector<Instruction*, 16> new_allocs;
SmallVector<Instruction*, 16> removed;
for(auto block = f.begin(), end = f.end(); block != end; ++block)
{
for(auto iter = block->begin(), end = block->end(); iter != end; ++iter)
{
Instruction* inst = &(*iter);
if(runOnInstruction(builder, inst, new_allocs, removed))
changed = true;
}
}
while(!new_allocs.empty())
{
// If we get here, changed is already true
Instruction* inst = new_allocs.pop_back_val();
runOnInstruction(builder, inst, new_allocs, removed);
}
for(auto elt : removed)
elt->eraseFromParent();
return changed;
}
bool runOnInstruction(IRBuilder<>& builder, Instruction* inst,
SmallVector<Instruction*, 16>& new_allocs,
SmallVector<Instruction*, 16>& removed)
{
if(std::find(removed.begin(), removed.end(), inst) != removed.end())
return false;
CallSite call(inst);
if(!call.getInstruction())
return false;
Function* fun = call.getCalledFunction();
if(fun == NULL)
return false;
int alloc_type;
if(fun->getName().compare("pony_alloc") == 0)
{
alloc_type = 0;
} else if(fun->getName().compare("pony_alloc_small") == 0) {
alloc_type = 1;
} else if(fun->getName().compare("pony_alloc_large") == 0) {
alloc_type = -1;
} else if(fun->getName().compare("pony_realloc") == 0) {
Value* old_ptr = call.getArgument(1);
if(dyn_cast_or_null<ConstantPointerNull>(old_ptr) == NULL)
return false;
Value* new_size = call.getArgument(2);
builder.SetInsertPoint(inst);
Value* replace = mergeNoOp(builder, call.getArgument(0), new_size);
new_allocs.push_back(reinterpret_cast<Instruction*>(replace));
inst->replaceAllUsesWith(replace);
removed.push_back(inst);
return true;
} else {
return false;
}
Value* old_size = call.getArgument(1);
ConstantInt* old_int_size = dyn_cast_or_null<ConstantInt>(old_size);
CallInst* realloc = findRealloc(inst);
Value* replace;
if(old_int_size == NULL)
{
if(realloc == NULL || !isZeroRealloc(realloc))
return false;
do
{
realloc->replaceAllUsesWith(inst);
realloc->eraseFromParent();
realloc = findRealloc(inst);
} while(realloc != NULL && isZeroRealloc(realloc));
return true;
} else {
// Alloc sizes always fit in size_t. We can safely cast.
size_t old_alloc_size = (size_t)old_int_size->getZExtValue();
if(realloc == NULL)
{
if(alloc_type != 0)
return false;
// Not realloc'd, but we can still turn a generic allocation into a
// small/large one.
builder.SetInsertPoint(inst);
replace = mergeConstant(builder, call.getArgument(0), old_alloc_size);
} else {
Value* new_size = realloc->getArgOperand(2);
if(alloc_type > 0) // Small allocation.
old_alloc_size = ((size_t)1) << (old_alloc_size + HEAP_MINBITS);
ConstantInt* new_int_size = dyn_cast_or_null<ConstantInt>(new_size);
if(new_int_size == NULL)
{
if(old_alloc_size != 0)
return false;
builder.SetInsertPoint(realloc);
replace = mergeNoOp(builder, call.getArgument(0), new_size);
new_allocs.push_back(reinterpret_cast<Instruction*>(replace));
} else {
size_t new_alloc_size = (size_t)new_int_size->getZExtValue();
new_alloc_size = std::max(old_alloc_size, new_alloc_size);
replace = mergeReallocChain(builder, call, &realloc, new_alloc_size,
new_allocs);
}
realloc->replaceAllUsesWith(replace);
realloc->eraseFromParent();
}
}
inst->replaceAllUsesWith(replace);
removed.push_back(inst);
return true;
}
CallInst* findRealloc(Instruction* alloc)
{
CallInst* realloc = NULL;
for(auto iter = alloc->use_begin(), end = alloc->use_end();
iter != end; ++iter)
{
Use* use = &(*iter);
CallInst* call = dyn_cast_or_null<CallInst>(use->getUser());
if(call == NULL)
continue;
Function* fun = call->getCalledFunction();
if(fun == NULL)
continue;
if(fun->getName().compare("pony_realloc") == 0)
{
if(realloc != NULL)
{
// TODO: Handle more than one realloc path (caused by conditionals).
return NULL;
}
realloc = call;
}
}
return realloc;
}
Value* mergeReallocChain(IRBuilder<>& builder, CallSite alloc,
CallInst** last_realloc, size_t alloc_size,
SmallVector<Instruction*, 16>& new_allocs)
{
builder.SetInsertPoint(alloc.getInstruction());
Value* replace = mergeConstant(builder, alloc.getArgument(0), alloc_size);
while(alloc_size == 0)
{
// replace is a LLVM null pointer here. We have to handle any realloc
// chain before losing call use information.
CallInst* next_realloc = findRealloc(*last_realloc);
if(next_realloc == NULL)
break;
Value* new_size = next_realloc->getArgOperand(2);
ConstantInt* new_int_size = dyn_cast_or_null<ConstantInt>(new_size);
if(new_int_size == NULL)
{
builder.SetInsertPoint(next_realloc);
replace = mergeNoOp(builder, alloc.getArgument(0), new_size);
alloc_size = 1;
} else {
alloc_size = (size_t)new_int_size->getZExtValue();
builder.SetInsertPoint(*last_realloc);
replace = mergeConstant(builder, alloc.getArgument(0), alloc_size);
}
new_allocs.push_back(reinterpret_cast<Instruction*>(replace));
(*last_realloc)->replaceAllUsesWith(replace);
(*last_realloc)->eraseFromParent();
*last_realloc = next_realloc;
}
return replace;
}
Value* mergeNoOp(IRBuilder<>& builder, Value* ctx, Value* size)
{
Value* args[2];
args[0] = ctx;
args[1] = size;
CallInst* inst = builder.CreateCall(alloc_fn, ArrayRef<Value*>(args, 2));
inst->setTailCall();
return inst;
}
Value* mergeConstant(IRBuilder<>& builder, Value* ctx, size_t size)
{
Function* used_alloc_fn;
IntegerType* int_type;
if(size == 0)
{
return ConstantPointerNull::get(builder.getInt8PtrTy());
} else if(size <= HEAP_MAX) {
used_alloc_fn = alloc_small_fn;
int_type = unwrap<IntegerType>(c->i32);
size = ponyint_heap_index(size);
} else {
used_alloc_fn = alloc_large_fn;
int_type = unwrap<IntegerType>(c->intptr);
}
Value* args[2];
args[0] = ctx;
args[1] = ConstantInt::get(int_type, size);
CallInst* inst = builder.CreateCall(used_alloc_fn,
ArrayRef<Value*>(args, 2));
inst->setTailCall();
return inst;
}
Function* declareAllocFunction(Module& m, std::string const& name,
Type* size_type, size_t min_size, bool can_be_null)
{
Type* params[2];
params[0] = unwrap(c->void_ptr);
params[1] = size_type;
FunctionType* fn_type = FunctionType::get(unwrap(c->void_ptr),
ArrayRef<Type*>(params, 2), false);
Function* fn = Function::Create(fn_type, Function::ExternalLinkage, name,
&m);
#if PONY_LLVM < 500
unsigned functionIndex = AttributeSet::FunctionIndex;
unsigned returnIndex = AttributeSet::ReturnIndex;
#else
unsigned functionIndex = AttributeList::FunctionIndex;
unsigned returnIndex = AttributeList::ReturnIndex;
#endif
fn->addAttribute(functionIndex, Attribute::NoUnwind);
fn->addAttribute(functionIndex,
Attribute::InaccessibleMemOrArgMemOnly);
#if PONY_LLVM < 500
fn->setDoesNotAlias(0);
#endif
if(can_be_null)
fn->addDereferenceableOrNullAttr(returnIndex, min_size);
else
fn->addDereferenceableAttr(returnIndex, min_size);
AttrBuilder attr;
attr.addAlignmentAttr(target_is_ilp32(c->opt->triple) ? 4 : 8);
#if PONY_LLVM < 500
fn->addAttributes(returnIndex, AttributeSet::get(m.getContext(),
returnIndex, attr));
#else
fn->addAttributes(returnIndex, AttributeSet::get(m.getContext(), attr));
#endif
return fn;
}
bool isZeroRealloc(CallInst* realloc)
{
Value* new_size = realloc->getArgOperand(2);
ConstantInt* new_int_size = dyn_cast_or_null<ConstantInt>(new_size);
if(new_int_size == NULL)
return false;
uint64_t new_alloc_size = new_int_size->getZExtValue();
if(new_alloc_size != 0)
return false;
return true;
}
};
char MergeRealloc::ID = 2;
static RegisterPass<MergeRealloc>
MR("mergerealloc", "Merge successive reallocations of the same variable");
static void addMergeReallocPass(const PassManagerBuilder& pmb,
PassManagerBase& pm)
{
if(pmb.OptLevel >= 2)
pm.add(new MergeRealloc());
}
class MergeMessageSend : public BasicBlockPass
{
public:
struct MsgFnGroup
{
BasicBlock::iterator alloc, trace, done, send;
};
enum MsgKind
{
MsgNone,
MsgNoTrace,
MsgTrace
};
static char ID;
compile_t* c;
Function* send_next_fn;
Function* msg_chain_fn;
Function* sendv_single_fn;
MergeMessageSend() : BasicBlockPass(ID)
{
c = the_compiler;
send_next_fn = nullptr;
msg_chain_fn = nullptr;
sendv_single_fn = nullptr;
}
bool doInitialization(Module& m)
{
send_next_fn = m.getFunction("pony_send_next");
msg_chain_fn = m.getFunction("pony_chain");
sendv_single_fn = m.getFunction("pony_sendv_single");
if(send_next_fn == NULL)
send_next_fn = declareTraceNextFn(m);
if(msg_chain_fn == NULL)
msg_chain_fn = declareMsgChainFn(m);
return false;
}
bool doInitialization(Function& f)
{
(void)f;
return false;
}
bool runOnBasicBlock(BasicBlock& b)
{
auto start = b.begin();
auto end = b.end();
bool changed = false;
SmallVector<CallInst*, 16> sends;
while(start != end)
{
MsgFnGroup first;
MsgKind first_kind = findMsgSend(start, end, true, first);
switch(first_kind)
{
case MsgNone:
start = end;
break;
default:
{
sends.push_back(cast<CallInst>(&(*first.send)));
bool stop = false;
while(!stop)
{
MsgFnGroup next;
MsgKind next_kind = findMsgSend(std::next(first.send), end, false,
next);
switch(next_kind)
{
case MsgNone:
stop = true;
break;