This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
/
GlobalDepsAnalyzer.cpp
1516 lines (1338 loc) · 45.5 KB
/
GlobalDepsAnalyzer.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
//===-- GlobalDepsAnalyzer.cpp - Remove unused functions/globals -----------===//
//
// Cheerp: The C++ compiler for the Web
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// Copyright 2011-2020 Leaning Technologies
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "GlobalDepsAnalyzer"
#include <algorithm>
#include <llvm/Analysis/OptimizationRemarkEmitter.h>
#include "llvm/ADT/Statistic.h"
#include "llvm/Cheerp/CommandLine.h"
#include "llvm/Cheerp/GlobalDepsAnalyzer.h"
#include "llvm/Cheerp/Registerize.h"
#include "llvm/Cheerp/Utility.h"
#include "llvm/Cheerp/LinearMemoryHelper.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
using namespace llvm;
STATISTIC(NumRemovedGlobals, "Number of unused globals which have been removed");
namespace cheerp {
using namespace std;
char GlobalDepsAnalyzer::ID = 0;
const char* wasmNullptrName = "__wasm_nullptr";
StringRef GlobalDepsAnalyzer::getPassName() const
{
return "GlobalDepsAnalyzer";
}
GlobalDepsAnalyzer::GlobalDepsAnalyzer(MATH_MODE mathMode_, bool llcPass, bool wasmStart)
: ModulePass(ID), hasBuiltin{{false}}, mathMode(mathMode_), DL(NULL),
TLI(NULL), entryPoint(NULL), hasCreateClosureUsers(false), hasVAArgs(false),
hasPointerArrays(false), hasAsmJS(false), hasAsmJSMalloc(false),
mayNeedAsmJSFree(false), llcPass(llcPass), wasmStart(wasmStart), delayPrintf(true),
hasUndefinedSymbolErrors(false), forceTypedArrays(false)
{
}
void GlobalDepsAnalyzer::getAnalysisUsage(AnalysisUsage& AU) const
{
AU.addPreserved<cheerp::PointerAnalyzer>();
AU.addPreserved<cheerp::Registerize>();
llvm::ModulePass::getAnalysisUsage(AU);
}
static void createNullptrFunction(llvm::Module& module)
{
llvm::Function* wasmNullptr = module.getFunction(StringRef(wasmNullptrName));
if (wasmNullptr)
return;
// Create a dummy function that prevents nullptr conflicts, since the first
// function address is zero.
IRBuilder<> builder(module.getContext());
auto fTy = FunctionType::get(builder.getVoidTy(), false);
auto stub = Function::Create(fTy, Function::InternalLinkage, wasmNullptrName, &module);
stub->setSection("asmjs");
auto block = BasicBlock::Create(module.getContext(), "entry", stub);
builder.SetInsertPoint(block);
builder.CreateUnreachable();
}
static void callGlobalConstructorsOnStart(llvm::Module& M, GlobalDepsAnalyzer& GDA)
{
// Determine if a function should be constructed that calls the global
// constructors on start. The function will not be constructed when there
// are no global constructors.
auto constructors = cheerp::ModuleGlobalConstructors(M);
if (!constructors || constructors->op_begin() == constructors->op_end())
return;
// Create the function with the call instructions.
IRBuilder<> builder(M.getContext());
auto fTy = FunctionType::get(builder.getVoidTy(), false);
auto stub = Function::Create(fTy, Function::InternalLinkage, "_start", &M);
stub->setSection("asmjs");
auto block = BasicBlock::Create(M.getContext(), "entry", stub);
builder.SetInsertPoint(block);
for (auto it = constructors->op_begin(); it != constructors->op_end(); ++it)
{
assert(isa<ConstantStruct>(it));
ConstantStruct* cs = cast<ConstantStruct>(it);
assert(isa<Function>(cs->getAggregateElement(1)));
Function* F = cast<Function>(cs->getAggregateElement(1));
if (F->getSection() != StringRef("asmjs"))
continue;
builder.CreateCall(F, {});
}
builder.CreateRet(nullptr);
return;
}
void GlobalDepsAnalyzer::simplifyCalls(llvm::Module & module) const
{
std::vector<llvm::CallInst*> deleteList;
auto LibCallReplacer = [](Instruction *I, Value *With)
{
I->replaceAllUsesWith(With);
I->eraseFromParent();
};
OptimizationRemarkEmitter ORE;
LibCallSimplifier callSimplifier(*DL, TLI, ORE, nullptr, nullptr, LibCallReplacer);
for (Function& F : module.getFunctionList()) {
F.setPersonalityFn(nullptr);
const bool isAsmJS = (F.getSection() == StringRef("asmjs"));
for (BasicBlock& bb : F)
{
for (Instruction& I : bb)
{
if (isa<CallInst>(I)) {
CallInst& ci = cast<CallInst>(I);
//Replace call(bitcast) with bitcast(call)
//Might fail and leave the CI calling to a bitcast if the prerequisite are not met (eg. the number of paramethers differ)
if (isAsmJS && !FixWrongFuncCasts)
replaceCallOfBitCastWithBitCastOfCall(ci, /*mayFail*/ true);
Function* calledFunc = ci.getCalledFunction();
// Skip indirect calls
if (calledFunc == nullptr)
continue;
if (Value* with = callSimplifier.optimizeCall(&ci)) {
ci.replaceAllUsesWith(with);
deleteList.push_back(&ci);
continue;
}
}
}
}
}
for (CallInst* ci : deleteList) {
ci->eraseFromParent();
}
}
void GlobalDepsAnalyzer::extendLifetime(Function* F)
{
assert(F);
externals.push_back(F);
VisitedSet visited;
SubExprVec vec;
visitGlobal( F, visited, vec );
assert( visited.empty() );
}
bool GlobalDepsAnalyzer::runOnModule( llvm::Module & module )
{
DL = &module.getDataLayout();
assert(DL);
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
TLI = TLIP ? &TLIP->getTLI() : nullptr;
assert(TLI);
VisitedSet visited;
simplifyCalls(module);
if (!llcPass)
{
for (Function& F : module.getFunctionList())
{
//Those intrinsics may come back as result of other optimizations
//And we may need the actual functions to lower the intrinsics
const auto builtinID = BuiltinInstr::getMathBuiltin(F);
const auto typedBuiltinID = TypedBuiltinInstr::getMathTypedBuiltin(F);
if (cheerp::BuiltinInstr::isValidJSMathBuiltin(builtinID)
|| isValidWasmMathBuiltin(typedBuiltinID)
|| cheerp::TypedBuiltinInstr::mayBeLoweredInto(F)
|| F.getName() == "memcpy"
|| F.getName() == "memset"
|| F.getName() == "memmove")
{
if (TypedBuiltinInstr::isAlwaysExactNatively(typedBuiltinID))
continue;
extendLifetime(&F);
}
}
}
// Replace calls like 'printf("Hello!")' with 'puts("Hello!")'.
for (Function& F : module.getFunctionList()) {
F.setPersonalityFn(nullptr);
bool asmjs = F.getSection() == StringRef("asmjs");
for (BasicBlock& bb : F)
{
bool advance = false; //Do not advance at the start
for (BasicBlock::iterator instructionIterator = bb.begin(); ;)
{
//Might be useful NOT to advance mid-iteration in case of deletions
//The base case is doing the advancement at the start of the cycle
if (advance)
{
++instructionIterator;
}
advance = true;
if (instructionIterator == bb.end())
break;
Instruction& I = *instructionIterator;
if (isa<CallInst>(I)) {
CallInst* ci = cast<CallInst>(&I);
Function* calledFunc = ci->getCalledFunction();
// Skip indirect calls
if (calledFunc == nullptr)
continue;
if (Function* F = TypedBuiltinInstr::functionToLowerInto(*calledFunc, module))
{
ci->setCalledFunction(F);
continue;
}
unsigned II = calledFunc->getIntrinsicID();
if(asmjs)
{
if(II == Intrinsic::cheerp_allocate)
{
Function* F = module.getFunction("malloc");
assert(F);
Type* oldType = ci->getType();
if(oldType != F->getReturnType())
{
Instruction* newCast = new BitCastInst(UndefValue::get(F->getReturnType()), oldType, "", ci->getNextNode());
ci->replaceAllUsesWith(newCast);
ci->mutateType(F->getReturnType());
newCast->setOperand(0, ci);
}
ci->setCalledFunction(F);
}
else if(II == Intrinsic::cheerp_reallocate)
{
Function* F = module.getFunction("realloc");
assert(F);
Type* oldType = ci->getType();
if(oldType != F->getReturnType())
{
Instruction* newParamCast = new BitCastInst(ci->getOperand(0), F->getReturnType(), "", ci);
ci->setOperand(0, newParamCast);
Instruction* newCast = new BitCastInst(UndefValue::get(F->getReturnType()), oldType, "", ci->getNextNode());
ci->replaceAllUsesWith(newCast);
ci->mutateType(F->getReturnType());
newCast->setOperand(0, ci);
}
ci->setCalledFunction(F);
}
else if(II == Intrinsic::cheerp_deallocate)
{
Function* F = module.getFunction("free");
assert(F);
ci->setCalledFunction(F);
Type* oldType = ci->getOperand(0)->getType();
Type* newType = F->arg_begin()->getType();
if(oldType != newType)
{
Instruction* newCast = new BitCastInst(ci->getOperand(0), newType, "", ci);
ci->setOperand(0, newCast);
}
}
}
if(II == Intrinsic::exp2)
{
// Expand this to pow, we can't simply forward to the libc since exp2 is optimized away to the intrinsic itself
if (!llcPass)
continue;
Type* t = ci->getType();
Function* F = module.getFunction(t->isFloatTy() ? "powf" : "pow");
CallInst* newCall = CallInst::Create(F, { ConstantFP::get(t, 2.0), ci->getOperand(0) }, "", ci);
ci->replaceAllUsesWith(newCall);
//Set up loop variable, so the next loop will check and possibly expand newCall
--instructionIterator;
advance = false;
assert(&*instructionIterator == newCall);
ci->eraseFromParent();
continue;
}
// Replace math intrinsics with C library calls if necessary
if(llcPass)
{
const auto& builtin = TypedBuiltinInstr::getMathTypedBuiltin(*calledFunc);
if (builtin == TypedBuiltinInstr::UNSUPPORTED)
{
llvm::errs() << calledFunc->getName() << " is not supported\n";
llvm_unreachable("Unsupported builtin can not be lowered\n");
}
if (mathMode != NO_BUILTINS)
continue;
if (builtin == TypedBuiltinInstr::NONE)
continue;
if (TypedBuiltinInstr::isAlwaysExactNatively(builtin))
continue;
Function* F = module.getFunction(functionName(builtin));
assert(F);
ci->setCalledFunction(F);
}
}
}
}
}
DenseSet<const Function*> droppedMathBuiltins;
// Drop the code for math functions that will be replaced by builtins
if (mathMode != NO_BUILTINS && llcPass)
{
for (Function& F : module.getFunctionList())
{
//Builtins could be inserted in the function table, for now just avoid to drop them
if (F.hasAddressTaken())
continue;
const auto builtinID = BuiltinInstr::getMathBuiltin(F);
if (cheerp::BuiltinInstr::isValidJSMathBuiltin(builtinID))
{
//Preserve sinf and cosf if in WASM modality
if (mathMode == WASM_BUILTINS &&
(BuiltinInstr::COS_F == builtinID ||
BuiltinInstr::SIN_F == builtinID))
continue;
F.deleteBody();
droppedMathBuiltins.insert(&F);
}
}
}
//Compile the list of JS methods
//Look for metadata which ends in _methods. They are the have the list
//of exported methods for JS layout classes
for (NamedMDNode & namedNode : module.named_metadata() )
{
StringRef name = namedNode.getName();
if(name.endswith("_methods") && (name.startswith("class._Z") || name.startswith("struct._Z")))
{
StructType * t = TypeSupport::getJSExportedTypeFromMetadata(name, module).first;
visitStruct(t);
}
else if(name!="jsexported_free_functions")
continue;
for (const MDNode * node : namedNode.operands() )
{
assert( isa<Function>(cast<ConstantAsMetadata>(node->getOperand(0))->getValue()) );
Function* f = cast<Function>(cast<ConstantAsMetadata>(node->getOperand(0))->getValue());
extendLifetime(f);
if (f->getSection() == StringRef("asmjs"))
{
asmJSExportedFuncions.insert(f);
}
}
}
for (NamedMDNode & namedNode : module.named_metadata() )
{
StringRef name = namedNode.getName();
if(name.endswith("_bases"))
{
MDNode* basesMeta = namedNode.getOperand(0);
assert(basesMeta->getNumOperands()>=1);
uint32_t firstBase = cast<ConstantInt>(cast<ConstantAsMetadata>(basesMeta->getOperand(0))->getValue())->getZExtValue();
StructType * t = module.getTypeByName(name.drop_back(6));
if (t)
basesInfo.emplace(t, firstBase);
}
}
llvm::Function* webMainOrMain = module.getFunction("_Z7webMainv");
if (webMainOrMain || (webMainOrMain = module.getFunction("webMain")) ||
(webMainOrMain = module.getFunction("main")))
{
// Webmain entry point
extendLifetime(webMainOrMain);
}
else
{
llvm::errs() << "warning: webMain or main entry point not found\n";
}
entryPoint = webMainOrMain;
//Process constructors
const ConstantArray* constructors = ModuleGlobalConstructors(module);
// Random things which may go boom
if (constructors) {
auto getConstructorPriority = []( const Constant * p ) -> uint32_t
{
assert( isa< ConstantStruct >(p) );
assert( isa< ConstantInt >(p->getAggregateElement(0u) ) );
return cast<ConstantInt>(p->getAggregateElement(0u) )->getSExtValue();
};
auto getConstructorFunction = []( const Constant * p ) -> llvm::Function *
{
assert( isa< ConstantStruct >(p) );
assert( isa< Function >(p->getAggregateElement(1) ) );
return cast<Function>( p->getAggregateElement(1) );
};
auto getConstructorData = [](const Constant* p) -> const llvm::Constant*
{
assert(isa<ConstantStruct>(p) );
if (!p->getAggregateElement(2))
return nullptr;
return p->getAggregateElement(2);
};
auto constComparator = [&]( const Constant * lhs, const Constant * rhs ) -> bool
{
return std::make_pair( getConstructorPriority(lhs), lhs) <
std::make_pair( getConstructorPriority(rhs), rhs);
};
std::set< const Constant *, decltype(constComparator) > requiredConstructors( constComparator );
for (ConstantArray::const_op_iterator it = constructors->op_begin();
it != constructors->op_end(); ++it)
{
assert( isa<Constant>(it) );
const Constant * p = cast<Constant>(it);
requiredConstructors.insert(p);
SubExprVec vec;
visitGlobal( getConstructorFunction(p), visited, vec );
const llvm::Constant* data = getConstructorData(p);
if (data)
visitConstant(data, visited, vec);
assert( visited.empty() );
}
constructorsNeeded.reserve( requiredConstructors.size() );
std::transform( requiredConstructors.begin(),
requiredConstructors.end(),
std::back_inserter(constructorsNeeded),
getConstructorFunction );
// Make sure the constructors are considered externals
for(Function* F: constructorsNeeded)
externals.push_back(F);
auto constructorVar = module.getGlobalVariable("llvm.global_ctors");
reachableGlobals.insert(constructorVar);
varsOrder.push_back(constructorVar);
}
processEnqueuedFunctions();
// Detect if the code actually uses printf_float
delayPrintf = false;
bool usesFloatPrintf = false;
for (const GlobalValue* v: printfLikeQueue)
{
StringRef n = v->getName();
if(!usesFloatPrintf && isPrintfFamily(n))
usesFloatPrintf = true;
SubExprVec vec;
visitGlobal(v, visited, vec);
assert(visited.empty());
}
// Erase printf_float body if it is not used
if(!usesFloatPrintf)
{
llvm::Function* printfFloat = module.getFunction("_printf_float");
if(printfFloat)
{
printfFloat->deleteBody();
printfFloat->replaceAllUsesWith(UndefValue::get(printfFloat->getType()));
}
}
// Flush out all functions
processEnqueuedFunctions();
if(mayNeedAsmJSFree)
{
Function* ffree = module.getFunction("free");
if (ffree)
{
if(!hasAsmJSMalloc)
{
// The symbol is still used around, so keep it but make it empty
ffree->deleteBody();
Function* jsfree = module.getFunction("__genericjs__free");
// For jsfree, keep an empty body (could still be called if we don't run lto)
if (jsfree)
{
jsfree->deleteBody();
BasicBlock* Entry = BasicBlock::Create(module.getContext(),"entry", jsfree);
IRBuilder<> Builder(Entry);
Builder.CreateRetVoid();
}
}
else
{
hasAsmJS = true;
asmJSExportedFuncions.insert(ffree);
externals.push_back(ffree);
// Visit free and friends
enqueueFunction(ffree);
processEnqueuedFunctions();
reachableGlobals.insert(ffree);
}
}
}
// Create a dummy function that prevents nullptr conflicts.
if(hasAsmJS)
createNullptrFunction(module);
// Set the sret slot in the asmjs section if there is asmjs code
GlobalVariable* Sret = module.getGlobalVariable("cheerpSretSlot");
if (hasAsmJS && Sret)
Sret->setSection(StringRef("asmjs"));
auto markAsReachableIfPresent = [this, &visited](Function* F)
{
if (F) {
visitFunction(F, visited);
assert(visited.empty());
reachableGlobals.insert(F);
}
};
// Mark the __wasm_nullptr as reachable.
llvm::Function* wasmNullptr = module.getFunction(StringRef(wasmNullptrName));
markAsReachableIfPresent(wasmNullptr);
// Mark the 64-bit division functions as reachable if we are in opt.
if (!llcPass)
{
markAsReachableIfPresent(module.getFunction("__modti3"));
markAsReachableIfPresent(module.getFunction("__umodti3"));
markAsReachableIfPresent(module.getFunction("__divti3"));
markAsReachableIfPresent(module.getFunction("__udivti3"));
}
NumRemovedGlobals = filterModule(droppedMathBuiltins, module);
if(hasUndefinedSymbolErrors)
llvm::report_fatal_error("String linking enabled and undefined symbols found");
// Detect all used math builtins
if (mathMode != NO_BUILTINS && llcPass)
{
// We have already dropped all unused functions, so we can simply check if these exists
for(const Function& F: module)
{
const auto builtinID = BuiltinInstr::getMathBuiltin(F);
if (cheerp::BuiltinInstr::isValidJSMathBuiltin(builtinID))
if (mathMode != WASM_BUILTINS || !TypedBuiltinInstr::isWasmIntrinsic(&F))
hasBuiltin[builtinID] = true;
}
if (mathMode == WASM_BUILTINS)
{
//In Wasm, these are better implemented as function calls than JS builtins
hasBuiltin[BuiltinInstr::COS_F] = false;
hasBuiltin[BuiltinInstr::SIN_F] = false;
}
}
// Detect all used non-math builtins
for(const Function& F: module)
{
if(F.getIntrinsicID() == Intrinsic::cheerp_grow_memory)
{
hasBuiltin[BuiltinInstr::GROW_MEM] = true;
}
}
//Build the map of existing functions types that are called indirectly to their representative (or nullptr if multiple representative exist)
struct FunctionData
{
Function* F;
bool directlyUsed;
FunctionData(Function* F, bool directlyUsed):F(F),directlyUsed(directlyUsed)
{
}
};
struct IndirectFunctionsData
{
std::vector<FunctionData> funcs;
std::vector<CallInst*> indirectCallSites;
bool signatureUsed;
IndirectFunctionsData():signatureUsed(false)
{
}
};
auto isSingleUnreachable = [](const llvm::Function& F) -> bool
{
if (F.getInstructionCount() != 1)
return false;
for (const llvm::BasicBlock& BB : F)
for (const llvm::Instruction& I : BB)
if (!isa<UnreachableInst>(I))
return false;
return true;
};
std::vector<Function*> toUnreachable;
std::unordered_map<FunctionType*, IndirectFunctionsData, LinearMemoryHelper::FunctionSignatureHash<true>, LinearMemoryHelper::FunctionSignatureCmp<true>> validIndirectCallTypesMap;
std::unordered_set<FunctionType*, LinearMemoryHelper::FunctionSignatureHash<true>, LinearMemoryHelper::FunctionSignatureCmp<true>> validTargetOfIndirectCall;
for (Function& F : module.getFunctionList())
{
if (F.getSection() != StringRef("asmjs"))
continue;
//If a given function is composed only of unreachable instructions, it can be excluded from consideration as possible call_indirect target
if (isSingleUnreachable(F))
continue;
// Similar logic to hasAddressTaken, but we also need to find out if there is any direct use
bool hasIndirectUse = false;
bool hasDirectUse = F.hasExternalLinkage();
for (const Use &U : F.uses())
{
if(hasDirectUse && hasIndirectUse)
break;
const User *FU = U.getUser();
if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
{
hasIndirectUse = true;
continue;
}
ImmutableCallSite CS(cast<Instruction>(FU));
if (CS.isCallee(&U))
{
hasDirectUse = true;
}
else
{
hasIndirectUse = true;
}
}
if(!hasIndirectUse)
continue;
validIndirectCallTypesMap[F.getFunctionType()].funcs.emplace_back(&F, hasDirectUse);
}
//Check agains the previous set what CallInstruction are actually impossible (and remove them)
std::vector<llvm::CallInst*> unreachList;
std::vector<std::pair<llvm::CallInst*, llvm::Function*> > devirtualizedCalls;
//Fixing function casts implies that new functions types will be created
//Exporting the table implies that functions can be added outside of our control
if (!FixWrongFuncCasts && !WasmExportedTable)
{
for (Function& F : module.getFunctionList())
{
if (F.getSection() != StringRef("asmjs"))
continue;
for (BasicBlock& bb : F)
{
for (Instruction& I : bb)
{
CallInst* ci = dyn_cast<CallInst>(&I);
if (!ci)
continue;
Value* calledValue = ci->getCalledValue();
if (isa<Function>(calledValue))
continue;
//This is an indirect call, and we can check whether the called function type exist at all
auto it = validIndirectCallTypesMap.find(ci->getFunctionType());
if (it == validIndirectCallTypesMap.end())
{
// There is no indirectly used function with the signature, the code must be unreachable
unreachList.push_back(ci);
break;
}
else if(it->second.funcs.size() == 1)
{
// For this signature there is only one indirectly use function, we can devirtualize it
assert(ci->getCalledFunction() == nullptr);
assert(!isa<Function>(ci->getCalledValue()));
llvm::Function* toBeCalledFunc = it->second.funcs[0].F;
llvm::Constant* devirtualizedCall = toBeCalledFunc;
if(devirtualizedCall->getType() != calledValue->getType())
devirtualizedCall = ConstantExpr::getBitCast(devirtualizedCall, calledValue->getType());
ci->setCalledOperand(devirtualizedCall);
replaceCallOfBitCastWithBitCastOfCall(*ci);
devirtualizedCalls.push_back({ci, toBeCalledFunc});
}
else
{
it->second.indirectCallSites.push_back(ci);
validTargetOfIndirectCall.insert(it->second.funcs[0].F->getFunctionType());
}
it->second.signatureUsed = true;
}
}
}
// Apply the argument in reverse, if there is no call with a given signature we can drop the functions
for(auto& it: validIndirectCallTypesMap)
{
if(it.second.signatureUsed)
continue;
// This signature was never used, we can drop corresponding methods if they have no direct call either
for(auto& fIt: it.second.funcs)
{
if(fIt.directlyUsed)
continue;
toUnreachable.push_back(fIt.F);
}
}
}
//Avoid too much inlining of devirtualized calls
for (auto pair : devirtualizedCalls)
{
llvm::CallInst& CI = *pair.first;
llvm::Function& F = *pair.second;
if (F.getInstructionCount() > 10u)
CI.setIsNoInline();
}
//Loop over every possible call site (either direct or indirect that matches the signature)
//and check whether it happens to be that a given argument is always the same global (while skipping over UndefValues)
for (auto pair : validIndirectCallTypesMap)
{
if (pair.second.indirectCallSites.empty())
continue;
//The function can be variadic and so take a variable number of arguments in the call sites
//but up to numArgs we can find commonality and substitute them directly in the function
const uint32_t numArgs = pair.first->getNumParams();
//Check (only once for the whole group of indirect functions) all possible indirect call sites
std::vector<Value*> constantArgs(numArgs, nullptr);
std::vector<bool> toReplaceInIndirectCalls(numArgs, true);
for (uint32_t numArg=0; numArg<numArgs; numArg++)
{
Value* curr = pair.second.indirectCallSites[0]->getArgOperand(numArg);
for (auto& ci : pair.second.indirectCallSites)
{
Value* V = ci->getArgOperand(numArg);
if (curr && isa<UndefValue>(curr))
curr = V;
if (V != curr)
curr = nullptr;
}
if (curr && isa<Constant>(curr))
constantArgs[numArg] = curr;
}
//Now constantArg[0...numARgs] is either nullptr or the Constant to be substituted
for (auto& x : pair.second.funcs)
{
std::vector<CallBase*> directCalls;
//Collect all relevant direct call sites
for (Use &U : x.F->uses())
{
User *FU = U.getUser();
if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
continue;
ImmutableCallSite CS(cast<Instruction>(FU));
if (CS.isCallee(&U))
{
directCalls.push_back(cast<CallBase>(FU));
}
}
for (uint32_t numArg=0; numArg<numArgs; numArg++)
{
Value* toSubstitute = constantArgs[numArg];
//Check if all direct call sites have always the same constant
for (auto& ci : directCalls)
{
Value * V = ci->getArgOperand(numArg);
if (toSubstitute && isa<UndefValue>(toSubstitute))
toSubstitute = V;
if (V != toSubstitute)
toSubstitute = nullptr;
}
auto Arg = x.F->arg_begin();
Arg += numArg;
if (toSubstitute && isa<UndefValue>(toSubstitute))
toSubstitute = UndefValue::get(Arg->getType());
if (toSubstitute && isa<Constant>(toSubstitute) && Arg->getType() == toSubstitute->getType())
{
//Change every use of the Argument to the relevant Constant
Arg->replaceAllUsesWith(toSubstitute);
//Change in every direct call site the Constant with UndefValue
for (auto& ci : directCalls)
{
Value * V = ci->getArgOperand(numArg);
ci->setArgOperand(numArg, UndefValue::get(V->getType()));
}
}
if (!Arg->user_empty())
toReplaceInIndirectCalls[numArg] = false;
}
}
for (uint32_t numArg=0; numArg<numArgs; numArg++)
{
if (!toReplaceInIndirectCalls[numArg])
continue;
//If the common constant has been substituted in all functions of the group, we can as well change the operand to UndefValue
for (auto& ci : pair.second.indirectCallSites)
{
Value* V = ci->getArgOperand(numArg);
ci->setArgOperand(numArg, UndefValue::get(V->getType()));
}
}
}
std::unordered_set<llvm::Function*> modifiedFunctions;
//Processing has to be done in reverse, so that multiple unreachable callInst in the same BasicBlock are processed from the last to the first
//This avoid erasing the latter ones while processing the first
for (CallInst* ci : reverse(unreachList))
{
modifiedFunctions.insert(ci->getParent()->getParent());
llvm::changeToUnreachable(ci, /*UseTrap*/false);
}
for (auto f : toUnreachable)
{
// Replace the body with a single unreachable instruction
// We need this placeholder to properly satisfy code that wants a non-zero address for this function
f->deleteBody();
llvm::BasicBlock* unreachableBlock = llvm::BasicBlock::Create(f->getContext(), "", f);
new llvm::UnreachableInst(unreachableBlock->getContext(), unreachableBlock);
}
//Clean up unreachable blocks
for (Function* F : modifiedFunctions)
{
removeUnreachableBlocks(*F);
}
std::vector<Function*> toBeSubstitutedIndirectUses;
if (!llcPass)
{
for (Function& F : module.getFunctionList())
{
if (F.getSection() != StringRef("asmjs"))
continue;
if (reachableGlobals.count(&F))
continue;
if (F.getLinkage() != GlobalValue::InternalLinkage)
continue;
if (validTargetOfIndirectCall.count(F.getFunctionType()))
continue;
//If we are here it's an amsjs function, not reachable from genericjs, with internal linking and no valid indirect calls
toBeSubstitutedIndirectUses.push_back(&F);
}
}
for (Function* F : toBeSubstitutedIndirectUses)
{
std::vector<Use*> indirectUses;
for (Use &U : F->uses())
{
const User *FU = U.getUser();
if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
{
indirectUses.push_back(&U);
continue;
}
ImmutableCallSite CS(cast<Instruction>(FU));
if (CS.isCallee(&U))
{
//Nothing to do
}
else
{
indirectUses.push_back(&U);
}
}
if (indirectUses.empty())
{
//Nothing to substitute, avoid creating an empty function
continue;
}
//Create an function (with the right type) composed by a single unreachable statement
Function* placeholderFunc = Function::Create(F->getFunctionType(), F->getLinkage(), F->getName() + "_unreachable", module);
llvm::BasicBlock* unreachableBlock = llvm::BasicBlock::Create(placeholderFunc->getContext(), "", placeholderFunc);
new llvm::UnreachableInst(unreachableBlock->getContext(), unreachableBlock);
placeholderFunc->setSection("asmjs");
//Visit the function, so it's in the relevant GlobalDepsAnalyzer data structures
VisitedSet visited;
visitFunction(placeholderFunc, visited);
//Visit the indirect uses of the old functions, and change them to use the new (almost empty) function
replaceSomeUsesWith(indirectUses, placeholderFunc);
}
// Create the start function only if we have a wasm module without js loader
if (wasmStart)
callGlobalConstructorsOnStart(module, *this);
// Create the FFI wrappers if needed
if (llcPass)
{
FFIWrapping FFIW(module, asmJSImportedFuncions, functionsInsideModule, functionsOutsideModule);
FFIW.run();
}
return true;
}
void GlobalDepsAnalyzer::visitGlobal( const GlobalValue * C, VisitedSet & visited, const SubExprVec & subexpr )
{
// Delay visiting all printf-like globals, we need to dectect if printf_float is actually used
if ( delayPrintf && C->hasName() && C->getName().endswith("printf") )
{
printfLikeQueue.insert(C);
return;
}
// Cycle detector
if ( !visited.insert(C).second )
{
assert( reachableGlobals.count(C) );
if ( const GlobalVariable * GV = dyn_cast< GlobalVariable >(C) )
{
assert( !subexpr.empty() );
varsFixups.emplace( GV, subexpr );
}
return;
}
if ( reachableGlobals.insert(C).second )
{
if(const GlobalAlias * GA = dyn_cast<GlobalAlias>(C) )
{
SubExprVec vec;
visitGlobal(cast<GlobalValue>(GA->getAliasee()), visited, vec );
}
else if (const Function * F = dyn_cast<Function>(C) )
{
if ( C->getName() == StringRef("free") )