-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathTypeOptimizer.cpp
More file actions
2342 lines (2243 loc) · 85.7 KB
/
TypeOptimizer.cpp
File metadata and controls
2342 lines (2243 loc) · 85.7 KB
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
//===-- TypeOptimizer.cpp - Cheerp helper -------------------------------===//
//
// Cheerp: The C++ compiler for the Web
//
// This file is distributed under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE.TXT for details.
//
// Copyright 2015-2023 Leaning Technologies
//
//===----------------------------------------------------------------------===//
#include "llvm/InitializePasses.h"
#include "llvm/Cheerp/Utility.h"
#include "llvm/Cheerp/TypeOptimizer.h"
#include "llvm/Cheerp/CommandLine.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/ModRef.h"
#include "llvm/Support/raw_ostream.h"
#include <set>
using namespace llvm;
namespace cheerp
{
bool TypeOptimizer::isI64ToRewrite(const Type* t)
{
return t->isIntegerTy(64) && (!UseBigInts || LinearOutput == AsmJs);
}
void TypeOptimizer::addAllBaseTypesForByteLayout(StructType* st, Type* baseType)
{
if(ArrayType* AT=dyn_cast<ArrayType>(baseType))
addAllBaseTypesForByteLayout(st, AT->getElementType());
else if(StructType* ST=dyn_cast<StructType>(baseType))
{
// TODO: This is broken for unions inside union. We would need to indirectly reference them.
for(uint32_t i=0;i<ST->getNumElements();i++)
addAllBaseTypesForByteLayout(st, ST->getElementType(i));
}
else
{
// If there is no base type so far, initialize it
auto it = baseTypesForByteLayout.find(st);
if(it == baseTypesForByteLayout.end())
baseTypesForByteLayout.insert(std::make_pair(st, baseType));
else if (it->second != baseType)
{
// The known base type is not the same as the passed one
it->second = NULL;
}
}
}
void TypeOptimizer::pushAllBaseConstantElements(SmallVector<llvm::Constant*, 4>& newElements, Constant* C, Type* baseType)
{
if(C->getType()==baseType)
newElements.push_back(C);
else if(ArrayType* AT=dyn_cast<ArrayType>(C->getType()))
{
if(ConstantArray* CA=dyn_cast<ConstantArray>(C))
{
for(unsigned i=0;i<AT->getNumElements();i++)
pushAllBaseConstantElements(newElements, CA->getOperand(i), baseType);
}
else if(ConstantDataSequential* CDS=dyn_cast<ConstantDataSequential>(C))
{
for(unsigned i=0;i<AT->getNumElements();i++)
pushAllBaseConstantElements(newElements, CDS->getElementAsConstant(i), baseType);
}
else
{
assert(isa<ConstantAggregateZero>(C));
// TODO: Could be optimized as we know that the elements should all be of baseType
for(unsigned i=0;i<AT->getNumElements();i++)
pushAllBaseConstantElements(newElements, Constant::getNullValue(AT->getElementType()), baseType);
}
}
else if(StructType* ST=dyn_cast<StructType>(C->getType()))
{
if(ConstantStruct* CS=dyn_cast<ConstantStruct>(C))
{
for(unsigned i=0;i<ST->getNumElements();i++)
pushAllBaseConstantElements(newElements, CS->getOperand(i), baseType);
}
else
{
assert(isa<ConstantAggregateZero>(C));
// TODO: Could be optimized as we know that the elements should all be of baseType
for(unsigned i=0;i<ST->getNumElements();i++)
pushAllBaseConstantElements(newElements, Constant::getNullValue(ST->getElementType(i)), baseType);
}
}
else
{
// It's not an aggregate and not the baseType, something is wrong here
assert(false);
}
}
llvm::StructType* TypeOptimizer::isEscapingStructGEP(const User* GEP)
{
if(GEP->getNumOperands()<3)
return nullptr;
// Keep track of all structure fields that "escapes" (used by more than load/stores)
if(!hasNonLoadStoreUses(GEP))
return nullptr;
StructType* containerStructType = dyn_cast<StructType>(cheerp::getGEPContainerType(GEP));
return containerStructType;
}
void TypeOptimizer::gatherAllTypesInfo(const Module& M)
{
for(const Function& F: M)
{
for(const BasicBlock& BB: F)
{
for(const Instruction& I: BB)
{
if(const IntrinsicInst* II=dyn_cast<IntrinsicInst>(&I))
{
if(II->getIntrinsicID()==Intrinsic::cheerp_downcast)
{
Type* opType = II->getParamElementType(0);
Type* retType = II->getRetElementType();
// In the special case of downcast from i8* to i8* we are dealing with exceptions.
// We collect the types info from another syntetic downcast, so just skip here.
if(opType->isIntegerTy())
{
assert(retType->isIntegerTy(8));
continue;
}
StructType* sourceType = cast<StructType>(opType);
if(sourceType->hasAsmJS())
continue;
// In the special case of downcast to i8* we are dealing with member function pointers
// Just give up and assume that all the bases may be needed.
// Also give up in the special case of downcast to the same type.
// It is used for thrown types.
if(retType->isIntegerTy(8) || retType == opType)
{
do
{
downcastSourceToDestinationsMapping[sourceType].clear();
uint32_t firstBase;
uint32_t baseCount;
bool hasBases = TypeSupport::getBasesInfo(M, sourceType, firstBase, baseCount);
if (!hasBases)
continue;
StructType::element_iterator el, end;
for (el = sourceType->element_begin()+firstBase, end = sourceType->element_begin()+firstBase+baseCount; el != end; ++el)
{
downcastSourceToDestinationsMapping[cast<StructType>(*el)].clear();
}
}
while((sourceType = sourceType->getDirectBase()));
continue;
}
// If a source type is downcasted with an offset != 0 we can't collapse the type
// we keep track of this by setting the mapping to an empty vector
if(!isa<ConstantInt>(II->getOperand(1)) || cast<ConstantInt>(II->getOperand(1))->getZExtValue() != 0)
{
downcastSourceToDestinationsMapping[sourceType].clear();
continue;
}
// If the offset is 0 we need to append the destination type to the mapping
// If the source type is in the map, but the vector is empty it means that we were
// in the case above, so we don't add the new destType
StructType* destType = cast<StructType>(retType);
auto it=downcastSourceToDestinationsMapping.find(sourceType);
if(it != downcastSourceToDestinationsMapping.end() && it->second.empty())
continue;
downcastSourceToDestinationsMapping[sourceType].insert(destType);
}
else if(II->getIntrinsicID() == Intrinsic::cheerp_virtualcast)
{
// We can't collapse the source of a virtualcast, keep track of this by setting the mapping to an empty vector
assert(II->getParamElementType(0));
StructType* sourceType = cast<StructType>(II->getParamElementType(0));
downcastSourceToDestinationsMapping[sourceType].clear();
}
}
else if(const BitCastInst* BC=dyn_cast<BitCastInst>(&I))
{
if (!BC->getDestTy()->isPointerTy())
continue;
// Find out all the types that bytelayout structs are casted to
StructType* st = dyn_cast<StructType>(BC->getSrcTy()->getNonOpaquePointerElementType());
if(!st || !st->hasByteLayout())
continue;
addAllBaseTypesForByteLayout(st, BC->getDestTy()->getNonOpaquePointerElementType());
}
else if(const GetElementPtrInst* GEP=dyn_cast<GetElementPtrInst>(&I))
{
StructType* containerStructType = isEscapingStructGEP(GEP);
if(!containerStructType)
continue;
uint32_t fieldIndex = cast<ConstantInt>(*std::prev(GEP->op_end()))->getZExtValue();
escapingFields.emplace(containerStructType, fieldIndex, TypeAndIndex::STRUCT_MEMBER);
}
}
}
// Mark the function as only used by wasm if it is used only by direct calls
// from other wasm functions. If so, we don't need to lower i64 in the
// signature
if (!F.hasAddressTaken() && F.getSection() == StringRef("asmjs") && LinearOutput == Wasm)
{
bool onlyCalledByWasm = true;
for (auto& U: F.uses())
{
if (Instruction* I = dyn_cast<Instruction>(U.getUser()))
{
// NOTE: Invokes from wasm mean that we need js wrappers
// (see InvokeWrapping), so they count as calls from js
if (I->getParent()->getParent()->getSection() != StringRef("asmjs") || isa<InvokeInst>(I))
{
onlyCalledByWasm = false;
break;
}
}
else
{
onlyCalledByWasm = false;
break;
}
}
if (onlyCalledByWasm)
{
onlyCalledByWasmFuncs.insert(&F);
}
}
}
if (!UseBigInts)
{
//Special functions that may need to be reachable from genericjs
auto markAsReachable = [this](Function* F)
{
if (F) {
onlyCalledByWasmFuncs.erase(F);
}
};
markAsReachable(M.getFunction("__modti3"));
markAsReachable(M.getFunction("__umodti3"));
markAsReachable(M.getFunction("__divti3"));
markAsReachable(M.getFunction("__udivti3"));
}
// Ugly, we need to iterate over constant GEPs, but they are per-context and not per-module
SmallVector<ConstantExpr*, 4> ConstantGEPs;
ConstantExpr::getAllFromOpcode(ConstantGEPs, M.getContext(), Instruction::GetElementPtr);
for(ConstantExpr* GEP: ConstantGEPs)
{
StructType* containerStructType = isEscapingStructGEP(GEP);
if(!containerStructType)
continue;
uint32_t fieldIndex = cast<ConstantInt>(*std::prev(GEP->op_end()))->getZExtValue();
escapingFields.emplace(containerStructType, fieldIndex, TypeAndIndex::STRUCT_MEMBER);
}
}
/**
We can only collapse a downcast source if all the possible destinations collapse as well
*/
bool TypeOptimizer::isUnsafeDowncastSource(StructType* st)
{
auto it=downcastSourceToDestinationsMapping.find(st);
if(it == downcastSourceToDestinationsMapping.end())
return false;
// If the destinations set is empty it means that we have a downcast with an offset != 0
// and we should not collapse this source
if(it->second.empty())
return true;
// Finally, try to rewrite every destination type, if they all collapse the source will collapse as well
for(StructType* destSt: it->second)
{
const TypeMappingInfo& destStInfo=rewriteType(destSt);
if(destStInfo.elementMappingKind != TypeMappingInfo::COLLAPSED)
return true;
}
return false;
}
bool TypeOptimizer::canCollapseStruct(llvm::StructType* st, llvm::StructType* newStruct, llvm::Type* newType)
{
if (newStruct == nullptr)
{
assert(st->isLiteral());
return true;
}
// Stop if the element is just a int8, we may be dealing with an empty struct
// Empty structs are unsafe as the int8 inside is just a placeholder and will be replaced
// by a different type in a derived class
// TODO: If pointers could be collapsed we may have implicit casts between base classes and derived classes
// NOTE: We allow the collapsing of client pointers
if(!TypeSupport::isJSExportedType(newStruct, *module) &&
!TypeSupport::hasByteLayout(st) &&
!newType->isIntegerTy(8) && (!newType->isPointerTy() || TypeSupport::isClientPtrType(cast<PointerType>(newType))))
{
// If this type is an unsafe downcast source and can't be collapse
// we need to fall through to correctly set the mapped element
if(!isUnsafeDowncastSource(st))
{
return true;
}
}
return false;
}
//The results of this function are meaningless for packed Struct, since there is no clear meaning of what alignment means
//This function is ok with returning a lower bound, but should never overestimate the alignment
llvm::Align TypeOptimizer::getAlignmentAfterRewrite(llvm::Type* t)
{
auto it = cacheAlignmentAfterRewrite.find(t);
if (it != cacheAlignmentAfterRewrite.end())
return it->second;
llvm::Align align(1);
std::set<llvm::Type*> computed;
std::vector<llvm::Type*> queue;
queue.push_back(t);
while (queue.size())
{
llvm::Type* curr = queue.back();
queue.pop_back();
if (computed.count(curr))
continue;
if (StructType* str = dyn_cast<StructType>(curr))
{
if(str->isPacked())
continue;
//Visit all members
for(uint32_t i=0;i<str->getNumElements();i++)
queue.push_back(str->getElementType(i));
}
else if (ArrayType* at = dyn_cast<ArrayType>(curr))
{
queue.push_back(at->getElementType());
}
else if (isI64ToRewrite(curr))
{
align = std::max(align, Align(4));
}
else
{
align = std::max(align, DL->getPrefTypeAlign(curr));
}
}
cacheAlignmentAfterRewrite[t] = align;
return align;
}
TypeOptimizer::TypeMappingInfo TypeOptimizer::rewriteTypeWithAlignmentInfo(llvm::Type* t, TypeOptimizer::AlignmentInfo& info)
{
info.first = DL->getPrefTypeAlign(t);
TypeMappingInfo mappingInfo = rewriteType(t);
info.second = getAlignmentAfterRewrite(mappingInfo.mappedType);
return mappingInfo;
}
TypeOptimizer::TypeMappingInfo TypeOptimizer::rewriteType(Type* t, Type* et)
{
assert(!newStructTypes.count(t));
auto typeMappingIt=typesMapping.find(t);
if(typeMappingIt!=typesMapping.end())
{
auto mappingInfo = typeMappingIt->second;
if(mappingInfo.elementMappingKind == TypeMappingInfo::COLLAPSING)
{
// When we find a COLLAPSING type, we forward the request if the contained type is a struct
// otherwise it will set the COLLAPSING_BUT_USED flag, in which case we need to abort the rewrite
// See also below how the COLLAPSING flag is used
if(mappingInfo.mappedType->isStructTy())
{
assert(mappingInfo.mappedType != t);
return rewriteType(mappingInfo.mappedType);
}
else
mappingInfo.elementMappingKind = TypeMappingInfo::COLLAPSING_BUT_USED;
}
return mappingInfo;
}
auto CacheAndReturn = [&](Type* ret, TypeMappingInfo::MAPPING_KIND kind)
{
return typesMapping[t] = TypeMappingInfo(ret, kind);
};
if(StructType* st=dyn_cast<StructType>(t))
{
if(TypeSupport::isClientType(st))
return CacheAndReturn(st, TypeMappingInfo::IDENTICAL);
if(st->isOpaque())
return CacheAndReturn(st, TypeMappingInfo::IDENTICAL);
while(TypeSupport::hasByteLayout(st))
{
addAllBaseTypesForByteLayout(st, st);
// If the data of this byte layout struct is always accessed as the same type, we can replace it with an array of that type
// This is useful for an idiom used by C++ graphics code to have a vector both accessible as named elements and as an array
// union { struct { double x,y,z; }; double elemets[3]; };
auto it=baseTypesForByteLayout.find(st);
assert(it!=baseTypesForByteLayout.end());
if(it->second == NULL)
break;
// Check that the struct fits exactly N values of the base type
uint32_t structSize = DL->getTypeAllocSize(st);
uint32_t elementSize = DL->getTypeAllocSize(it->second);
if(structSize % elementSize)
break;
bool areSubStructsConvertible = true;
// Every struct type inside the struct must be also convertible to array
for(uint32_t i=0;i<st->getNumElements();i++)
{
StructType* subSt = dyn_cast<StructType>(st->getElementType(i));
if(!subSt)
continue;
if(!subSt->hasByteLayout())
{
// If subSt is a struct but not bytelayout code generation is broken
areSubStructsConvertible = false;
break;
}
const TypeMappingInfo& subInfo = rewriteType(subSt);
if(subInfo.elementMappingKind != TypeMappingInfo::BYTE_LAYOUT_TO_ARRAY)
{
areSubStructsConvertible = false;
break;
}
}
if(!areSubStructsConvertible)
break;
uint32_t numElements = structSize / elementSize;
// See if we can replace it with a single element
if(numElements==1)
return CacheAndReturn(it->second, TypeMappingInfo::BYTE_LAYOUT_TO_ARRAY);
// Replace this byte layout struct with an array
Type* newType = ArrayType::get(it->second, numElements);
return CacheAndReturn(newType, TypeMappingInfo::BYTE_LAYOUT_TO_ARRAY);
}
// Generate a new type if it's not a literal struct. It may end up being the same as the old one
// In case of literal, it will be created as a literal at the end.
StructType* newStruct=nullptr;
if (!st->isLiteral())
newStruct=StructType::create(st->getContext());
#ifndef NDEBUG
newStructTypes.insert(newStruct);
#endif
if(st->hasName())
{
SmallString<20> name=st->getName();
st->setName("obsoletestruct");
newStruct->setName(name);
}
// Tentatively map the type to the newStruct, it may be overridden if the type is collapsed
if (!st->isLiteral())
typesMapping[t] = TypeMappingInfo(newStruct, TypeMappingInfo::IDENTICAL);
// Since we can merge arrays of the same type in an struct it is possible that at the end of the process a single type will remain
TypeMappingInfo::MAPPING_KIND newStructKind = TypeMappingInfo::IDENTICAL;
// Forge the new element types
SmallVector<Type*, 4> newTypes;
bool hasMergedArrays=false;
std::vector<std::pair<uint32_t, uint32_t>> membersMapping;
if (st->hasAsmJS() || (st->hasByteLayout() && st->getNumElements() > 1))
{
//Given that a collection of member would have currentSize, and the next member requires a given alignRequired
//Basically, solve X = currentSize + something, with X%alignment == 0 and something as small as possible, and then return X
auto padStruct = [](uint32_t currentSize, llvm::Align alignRequired) -> uint32_t
{
const uint32_t log2Align = Log2(alignRequired); //either 0,1,2,3, depending on the required alignment
const uint32_t toBeAlignedTo = 1u << log2Align; //either 1,2,4,8
uint32_t padSize = currentSize + toBeAlignedTo - 1; //add either 0, 1, 3, 7
padSize >>= log2Align;
padSize <<= log2Align; //zeros the least significant 0,1,2,3 bits
return padSize;
};
const auto& SL = DL->getStructLayout(st);
uint32_t currentSize = 0;
llvm::Align maxAlignment(1);
for(uint32_t i=0;i<st->getNumElements();i++)
{
AlignmentInfo alignmentInfo;
alignmentInfo.first = alignmentInfo.second = llvm::Align(1);
Type* elTy = st->getElementType(i);
Type* nextTy = st->isPacked() ?
rewriteType(elTy) : //packed -> rewrite type blindly
rewriteTypeWithAlignmentInfo(elTy, alignmentInfo); //!packed -> perform alignment checks
assert(alignmentInfo.first >= alignmentInfo.second);
maxAlignment = std::max(maxAlignment, alignmentInfo.second);
assert(alignmentInfo.first >= alignmentInfo.second);
const uint32_t originalPaddedSize = SL->getElementOffset(i);
const uint32_t nextPaddedSize = padStruct(currentSize, alignmentInfo.second);
const uint32_t toAdd = originalPaddedSize - currentSize;
assert(toAdd < 32);
//Padding bytes are inserted only if adding them actually change the size
//eg. {i8, i32, i64} -> {i8, i32, padding?? ,[2 x i32]}
//Here padding is not needed (originalPaddedSize 8 vs nextPaddedSize 8), so the resulting struct will be {i8, i32, [2 x i32]}
//eg. {i8, i64} -> {i8, padding??, [2 x i32]}
//Here padding is needed (originalPaddedSize 8 vs nextPaddedSize 4), so ther resulting struct will be {i8, [7 x i8], [2 x i32]}
if (originalPaddedSize != nextPaddedSize && toAdd)
{
currentSize += toAdd;
//An array [toAdd x i8] is added
newTypes.push_back(ArrayType::get(IntegerType::get(module->getContext(), 8), toAdd));
newStructKind = TypeMappingInfo::PADDING;
}
currentSize = padStruct(currentSize, alignmentInfo.second); //First grow pad currentSize to the appropriate alignment
currentSize += DL->getTypeAllocSize(elTy); //Then add the next type dimension
membersMapping.push_back({newTypes.size(), 0}); //Note that the second field is unused
newTypes.push_back(nextTy);
}
const uint32_t originalSize = DL->getTypeAllocSize(st);
const uint32_t totalPaddedSize = padStruct(currentSize, maxAlignment);
const uint32_t toAdd = originalSize - currentSize;
assert( toAdd < 8 );
//Pad the struct at the end
//The problematic test case is something like {i8, i64, i8} -> {i8, [7 x i8], [2 x i32], i8, ???}
//In the original struct, the allocation size is 24 (17 rounded to the next multiple of 8)
//while in the rewritten struct it will be 20 (17 rounded to the next multiple of 4), so we need to pad the end correctly
if (originalSize != totalPaddedSize && toAdd)
{
currentSize += toAdd;
//An array [toAdd x i8] is added
newTypes.push_back(ArrayType::get(IntegerType::get(module->getContext(), 8), toAdd));
newStructKind = TypeMappingInfo::PADDING;
}
currentSize = padStruct(currentSize, maxAlignment);
//If we ever padded, memorize the member mappings
if (newStructKind == TypeMappingInfo::PADDING)
{
membersMappingData.insert(std::make_pair(st, std::move(membersMapping)));
}
//TypeOptimizer should not change the dimension of a given structure
assert(DL->getTypeAllocSize(st) == currentSize);
}
else if(st->getNumElements() > 1)
{
// We want to merge arrays of the same type in the same object
// So, for each element type, keep track if there is already an array
std::unordered_map<Type*, uint32_t> arraysFound;
// Keep track of currently fillable integers
std::vector<std::pair<uint32_t, uint8_t>> mergedInts;
uint32_t directBaseLimit=0;
// We may need to update the bases metadata for this type
NamedMDNode* namedBasesMetadata = nullptr;
if (!st->isLiteral())
namedBasesMetadata = TypeSupport::getBasesMetadata(newStruct, *module);
uint32_t firstBaseBegin, firstBaseEnd;
if(namedBasesMetadata)
{
MDNode* md = namedBasesMetadata->getOperand(0);
firstBaseBegin=getIntFromValue(cast<ConstantAsMetadata>(md->getOperand(0))->getValue());
firstBaseEnd=firstBaseBegin;
}
for(uint32_t i=0;i<st->getNumElements();i++)
{
// We can't merge arrats across bases, so when we reach the limit of the previous direct base we
// reset the merging state and compute a new limit
if(i==directBaseLimit)
{
arraysFound.clear();
mergedInts.clear();
StructType* curBase=st;
while(curBase->getDirectBase() && curBase->getDirectBase()->getNumElements()>i && isa<StructType>(rewriteType(curBase->getDirectBase()).mappedType))
curBase=curBase->getDirectBase();
directBaseLimit=curBase->getNumElements();
}
Type* elementType=st->getElementType(i);
Type* rewrittenType=rewriteType(elementType);
if(ArrayType* at=dyn_cast<ArrayType>(rewrittenType))
{
Type* arrayElementType=rewrittenType->getArrayElementType();
auto arraysFoundIt=arraysFound.find(arrayElementType);
// An array is already available for this type, just extend it
if(arraysFoundIt!=arraysFound.end())
{
uint32_t typeIndex = arraysFoundIt->second;
ArrayType* previousArrayType = cast<ArrayType>(newTypes[typeIndex]);
newTypes[typeIndex] = ArrayType::get(arrayElementType, previousArrayType->getNumElements() + at->getNumElements());
membersMapping.push_back(std::make_pair(typeIndex, previousArrayType->getNumElements()));
if(i < firstBaseBegin)
firstBaseEnd--;
hasMergedArrays=true;
continue;
}
// Insert this array in the map, we will insert it in the vector just below
arraysFound[arrayElementType] = newTypes.size();
}
else if(IntegerType* it=dyn_cast<IntegerType>(rewrittenType))
{
TypeAndIndex typeAndIndex(st, i, TypeAndIndex::STRUCT_MEMBER);
bool fieldEscapes = escapingFields.count(typeAndIndex);
// Merge small integers together to reduce memory usage
if(!fieldEscapes && it->getBitWidth() < 32)
{
// Look for an integer than can be filled
bool mergedThisInt = false;
for(size_t m=0;m<mergedInts.size();m++)
{
auto& mergedInt = mergedInts[m];
if(mergedInt.second < it->getBitWidth() || (it->getBitWidth()%8 != 0))
continue;
// There is enough space in an integer. Promote the type and merge with this one
IntegerType* oldType = cast<IntegerType>(newTypes[mergedInt.first]);
newTypes[mergedInt.first] = IntegerType::get(module->getContext(), oldType->getBitWidth()+it->getBitWidth());
membersMapping.push_back(std::make_pair(mergedInt.first, 32-mergedInt.second));
mergedInt.second -= it->getBitWidth();
// Remove fully used integers
if(mergedInt.second == 0)
mergedInts.erase(mergedInts.begin()+m);
if(i < firstBaseBegin)
firstBaseEnd--;
hasMergedArrays=true;
mergedThisInt=true;
break;
}
if(mergedThisInt)
continue;
// Not enough space on any integer
mergedInts.push_back(std::make_pair(newTypes.size(), 32 - it->getBitWidth()));
}
}
membersMapping.push_back(std::make_pair(newTypes.size(), 0));
// Add the new type
newTypes.push_back(rewrittenType);
}
assert(!st->hasByteLayout());
assert(membersMapping.size() == st->getNumElements());
if(hasMergedArrays)
{
assert(!newTypes.empty());
membersMappingData.insert(std::make_pair(st, std::move(membersMapping)));
newStructKind = TypeMappingInfo::MERGED_MEMBER_ARRAYS;
// Update bases metadata
if(namedBasesMetadata)
{
Type* Int32 = IntegerType::get(module->getContext(), 32);
Metadata* newBasesMeta[] = { ConstantAsMetadata::get(ConstantInt::get(Int32, firstBaseEnd))};
MDNode* newMD = MDNode::get(module->getContext(), newBasesMeta);
// The bases metadata has numerous duplicated entries, so fix all of them
// TODO: Remove duplicated entries
for(uint32_t i=0;i<namedBasesMetadata->getNumOperands();i++)
namedBasesMetadata->setOperand(i, newMD);
}
}
assert(!st->hasAsmJS());
if(newTypes.size() == 1 && canCollapseStruct(st, newStruct, newTypes[0]))
{
Type* collapsed = newTypes[0];
if(newStructKind != TypeMappingInfo::MERGED_MEMBER_ARRAYS)
return CacheAndReturn(collapsed, TypeMappingInfo::COLLAPSED);
else
return CacheAndReturn(collapsed, TypeMappingInfo::MERGED_MEMBER_ARRAYS_AND_COLLAPSED);
}
}
else if(st->getNumElements() == 1)
{
// Try to collapse the struct to this element
llvm::Type* elementType = st->getElementType(0);
assert(!st->hasAsmJS());
if(canCollapseStruct(st, newStruct, elementType))
{
// To fix the following case A { B { C { A* } } } -> C { C* }
// we prime the mapping to the contained element and use the COLLAPSING flag
typesMapping[st] = TypeMappingInfo(elementType, TypeMappingInfo::COLLAPSING);
Type* collapsed = rewriteType(elementType);
if(typesMapping[st].elementMappingKind != TypeMappingInfo::COLLAPSING_BUT_USED)
{
assert(typesMapping[st].elementMappingKind == TypeMappingInfo::COLLAPSING);
if(newStructKind != TypeMappingInfo::MERGED_MEMBER_ARRAYS)
return CacheAndReturn(collapsed, TypeMappingInfo::COLLAPSED);
else
return CacheAndReturn(collapsed, TypeMappingInfo::MERGED_MEMBER_ARRAYS_AND_COLLAPSED);
}
typesMapping[st] = TypeMappingInfo(newStruct, TypeMappingInfo::IDENTICAL);
elementType = collapsed;
}
else
{
// Can't collapse, rewrite the member now
elementType = rewriteType(elementType);
}
newTypes.push_back(elementType);
}
StructType* newDirectBase = st->getDirectBase() ? dyn_cast<StructType>(rewriteType(st->getDirectBase()).mappedType) : NULL;
if (st->isLiteral())
{
newStruct = StructType::get(st->getContext(), newTypes, st->isPacked(), newDirectBase, st->hasByteLayout(), st->hasAsmJS());
typesMapping[t] = TypeMappingInfo(newStruct, TypeMappingInfo::IDENTICAL);
}
else
newStruct->setBody(newTypes, st->isPacked(), newDirectBase, st->hasByteLayout(), st->hasAsmJS());
return CacheAndReturn(newStruct, newStructKind);
}
if(FunctionType* ft=dyn_cast<FunctionType>(t))
{
return CacheAndReturn(rewriteFunctionType(ft, false), TypeMappingInfo::IDENTICAL);
}
if(PointerType* pt=dyn_cast<PointerType>(t))
{
// NOTE: The only observable effects of this GPET are:
// 1. The element type of another pointer, that will not be needed with opaque pointers.
// 2. The element mapping kind of POINTER_FROM_ARRAY, but the cases where this is needed *should* all be passing the correct 'et' parameter.
// This GPET will disappear naturally once the switch to opaque pointers is made.
Type* elementType = et ? et : pt->getPointerElementType();
Type* newType = rewriteType(elementType);
if(newType->isArrayTy())
{
// It's never a good idea to use pointers to array, we may end up creating wrapper arrays for arrays
return CacheAndReturn(PointerType::get(newType->getArrayElementType(), pt->getAddressSpace()), TypeMappingInfo::POINTER_FROM_ARRAY);
}
else if(newType == elementType)
return CacheAndReturn(pt, TypeMappingInfo::IDENTICAL);
else
return CacheAndReturn(PointerType::get(newType, pt->getPointerAddressSpace()), TypeMappingInfo::IDENTICAL);
}
if(ArrayType* at=dyn_cast<ArrayType>(t))
{
Type* elementType = at->getElementType();
const TypeMappingInfo& newInfo = rewriteType(elementType);
Type* newType = newInfo.mappedType;
if(ArrayType* subArray=dyn_cast<ArrayType>(newType))
{
// Flatten arrays of array
return CacheAndReturn(ArrayType::get(newType->getArrayElementType(), at->getNumElements()*subArray->getNumElements()),
TypeMappingInfo::FLATTENED_ARRAY);
}
else if(newType == elementType)
return CacheAndReturn(at, TypeMappingInfo::IDENTICAL);
else
return CacheAndReturn(ArrayType::get(newType, at->getNumElements()), TypeMappingInfo::IDENTICAL);
}
if (isI64ToRewrite(t))
{
t = ArrayType::get(IntegerType::get(t->getContext(), 32), 2);
return CacheAndReturn(t, TypeMappingInfo::IDENTICAL);
}
if (FixedVectorType* vt=dyn_cast<FixedVectorType>(t))
{
Type* elementType = vt->getElementType();
if (elementType->isIntegerTy())
return CacheAndReturn(vt, TypeMappingInfo::IDENTICAL);
const TypeMappingInfo& newInfo = rewriteType(elementType);
Type* newType = newInfo.mappedType;
if (newType == elementType)
return CacheAndReturn(vt, TypeMappingInfo::IDENTICAL);
else
return CacheAndReturn(FixedVectorType::get(newType, vt->getNumElements()), TypeMappingInfo::IDENTICAL);
}
return CacheAndReturn(t, TypeMappingInfo::IDENTICAL);
}
FunctionType* TypeOptimizer::rewriteFunctionType(FunctionType* ft, bool keepI64)
{
Type* newReturnType = nullptr;
if (isI64ToRewrite(ft->getReturnType()) && keepI64)
{
newReturnType = ft->getReturnType();
}
else if (isI64ToRewrite(ft->getReturnType()))
{
newReturnType = IntegerType::get(ft->getContext(), 32);
}
else
{
newReturnType = rewriteType(ft->getReturnType());
}
SmallVector<Type*, 4> newParameters;
for(uint32_t i=0;i<ft->getNumParams();i++)
{
Type* oldP = ft->getParamType(i);
if (isI64ToRewrite(oldP))
{
if (keepI64)
newParameters.push_back(oldP);
else
{
Type* Int32Ty = IntegerType::get(oldP->getContext(), 32);
newParameters.push_back(Int32Ty);
newParameters.push_back(Int32Ty);
}
}
else
newParameters.push_back(rewriteType(oldP));
}
return FunctionType::get(newReturnType, newParameters, ft->isVarArg());
}
void TypeOptimizer::pushAllArrayConstantElements(SmallVector<Constant*, 4>& newElements, Constant* array)
{
ArrayType* AT=cast<ArrayType>(array->getType());
if(ConstantArray* CA=dyn_cast<ConstantArray>(array))
{
for(unsigned i=0;i<AT->getNumElements();i++)
newElements.push_back(CA->getOperand(i));
}
else if(ConstantDataSequential* CDS=dyn_cast<ConstantDataSequential>(array))
{
for(unsigned i=0;i<AT->getNumElements();i++)
newElements.push_back(CDS->getElementAsConstant(i));
}
else
{
assert(isa<ConstantAggregateZero>(array));
for(unsigned i=0;i<AT->getNumElements();i++)
newElements.push_back(Constant::getNullValue(AT->getElementType()));
}
}
std::pair<Constant*, uint8_t> TypeOptimizer::rewriteConstant(Constant* C, bool rewriteI64)
{
// Immediately return for globals, we should never try to map their type as they are already rewritten
if(isa<GlobalAlias>(C))
return std::make_pair(C, 0);
if(GlobalValue* GV=dyn_cast<GlobalValue>(C))
{
assert(globalsMapping.count(GV));
return std::make_pair(globalsMapping[GV], 0);
}
TypeMappingInfo newTypeInfo = rewriteType(C->getType());
auto const_it = constantCache.find({C, rewriteI64});
if (const_it != constantCache.end())
return const_it->second;
auto CacheAndReturn = [&](Constant* result, uint8_t offset) -> std::pair<Constant*, uint8_t>
{
auto ret = std::make_pair(result, offset);
constantCache[{C, rewriteI64}] = ret;
return ret;
};
if (ConstantExpr* CE=dyn_cast<ConstantExpr>(C))
{
auto getOriginalGlobalType = [&](Constant* C) -> Type*
{
GlobalValue* GV = dyn_cast<GlobalValue>(C);
if(!GV)
return C->getType();
auto it = globalTypeMapping.find(GV);
if(it == globalTypeMapping.end())
return C->getType();
else
return it->second;
};
switch(CE->getOpcode())
{
case Instruction::GetElementPtr:
{
Constant* ptrOperand = CE->getOperand(0);
Type* ptrType = getOriginalGlobalType(ptrOperand);
auto rewrittenOperand = rewriteConstant(ptrOperand, false);
assert(rewrittenOperand.second==0);
ptrOperand = rewrittenOperand.first;
SmallVector<Value*, 4> newIndexes;
Type* srcType = rewriteType(cast<GEPOperator>(CE)->getSourceElementType());
Type* targetType = rewriteType(cast<GEPOperator>(CE)->getResultElementType());
SmallVector<Value*, 2> idxs;
for (auto Op = CE->op_begin()+1; Op != CE->op_end(); ++Op)
{
idxs.push_back(*Op);
}
if (isa<ArrayType>(srcType))
srcType = cast<ArrayType>(srcType)->getElementType();
uint8_t mergedIntegerOffset=rewriteGEPIndexes(newIndexes, ptrType, cast<GEPOperator>(CE)->getSourceElementType(), idxs, targetType, NULL, CE->getType());
return CacheAndReturn(ConstantExpr::getGetElementPtr(srcType, ptrOperand, newIndexes), mergedIntegerOffset);
}
case Instruction::BitCast:
{
auto rewrittenOperand = rewriteConstant(CE->getOperand(0), false);
assert(rewrittenOperand.second == 0);
Constant* srcOperand = rewrittenOperand.first;
return CacheAndReturn(ConstantExpr::getBitCast(srcOperand, newTypeInfo.mappedType), 0);
}
case Instruction::AddrSpaceCast:
{
auto rewrittenOperand = rewriteConstant(CE->getOperand(0), false);
assert(rewrittenOperand.second == 0);
Constant* srcOperand = rewrittenOperand.first;
return CacheAndReturn(ConstantExpr::getPointerBitCastOrAddrSpaceCast(srcOperand, newTypeInfo.mappedType), 0);
}
case Instruction::IntToPtr:
{
return CacheAndReturn(ConstantExpr::getIntToPtr(CE->getOperand(0), newTypeInfo.mappedType), 0);
}
default:
{
// Get a cloned CE with rewritten operands
std::vector<Constant*> newOperands;
for(Use& op: CE->operands())
{
auto rewrittenOperand = rewriteConstant(cast<Constant>(op), false);
assert(rewrittenOperand.second == 0);
newOperands.push_back(rewrittenOperand.first);
}
return CacheAndReturn(CE->getWithOperands(newOperands), 0);
}
}
}
else if(ConstantStruct* CS=dyn_cast<ConstantStruct>(C))
{
if(newTypeInfo.elementMappingKind == TypeMappingInfo::BYTE_LAYOUT_TO_ARRAY)
{
auto baseTypeIt = baseTypesForByteLayout.find(cast<StructType>(CS->getType()));
assert(baseTypeIt != baseTypesForByteLayout.end() && baseTypeIt->second);
// Forge a ConstantArray
SmallVector<Constant*, 4> newElements;
pushAllBaseConstantElements(newElements, CS, baseTypeIt->second);
if(newElements.size() == 1)
return std::make_pair(newElements[0], 0);
ArrayType* newArrayType = ArrayType::get(baseTypeIt->second, newElements.size());
return CacheAndReturn(ConstantArray::get(newArrayType, newElements), 0);
}
else if(newTypeInfo.elementMappingKind == TypeMappingInfo::COLLAPSED)
{
assert(cast<StructType>(CS->getType())->getNumElements()==1);
Constant* element = CS->getOperand(0);
auto result = rewriteConstant(element, rewriteI64);
constantCache[{C, rewriteI64}] = result;
return result;
}
auto membersMappingIt = membersMappingData.find(CS->getType());
bool hasMergedArrays = newTypeInfo.elementMappingKind == TypeMappingInfo::MERGED_MEMBER_ARRAYS ||
newTypeInfo.elementMappingKind == TypeMappingInfo::MERGED_MEMBER_ARRAYS_AND_COLLAPSED;
assert(!hasMergedArrays || membersMappingIt != membersMappingData.end());
SmallVector<Constant*, 4> newElements;
if(newTypeInfo.elementMappingKind == TypeMappingInfo::PADDING)
{
for(uint32_t i=0;i<CS->getNumOperands();i++)
{
//Check whether an intermediate paddign has to be added
if (membersMappingData[CS->getType()][i].first > newElements.size())
{
assert(isa<StructType>(newTypeInfo.mappedType));
newElements.push_back(UndefValue::get(dyn_cast<StructType>(newTypeInfo.mappedType)->getElementType((int)newElements.size())));
}
Constant* element = CS->getOperand(i);
auto rewrittenOperand = rewriteConstant(element, rewriteI64);
assert(rewrittenOperand.second == 0);
Constant* newElement = rewrittenOperand.first;
newElements.push_back(newElement);
}
//Check whether there is a last padding to be added
if (dyn_cast<StructType>(newTypeInfo.mappedType)->getNumElements() > newElements.size())
{
assert(isa<StructType>(newTypeInfo.mappedType));
newElements.push_back(UndefValue::get(dyn_cast<StructType>(newTypeInfo.mappedType)->getElementType((int)newElements.size())));
}
return CacheAndReturn(ConstantStruct::get(cast<StructType>(newTypeInfo.mappedType), newElements), 0);
}
// Check if some of the contained constant arrays needs to be merged
for(uint32_t i=0;i<CS->getNumOperands();i++)
{
Constant* element = CS->getOperand(i);
auto rewrittenOperand = rewriteConstant(element, rewriteI64);
assert(rewrittenOperand.second == 0);
Constant* newElement = rewrittenOperand.first;
if(hasMergedArrays && membersMappingIt->second[i].first != (newElements.size()))
{
// This element has been remapped to another one. It must be an array
SmallVector<Constant*, 4> mergedArrayElements;
Constant* oldMember = newElements[membersMappingIt->second[i].first];
if(isa<ArrayType>(oldMember->getType()))
{
assert(oldMember->getType()->getArrayElementType() == newElement->getType()->getArrayElementType());
// Insert all the elements of the existing member
pushAllArrayConstantElements(mergedArrayElements, oldMember);
pushAllArrayConstantElements(mergedArrayElements, newElement);
// Forge a new array and replace oldMember
ArrayType* mergedType = ArrayType::get(oldMember->getType()->getArrayElementType(), mergedArrayElements.size());
newElements[membersMappingIt->second[i].first] = ConstantArray::get(mergedType, mergedArrayElements);
}
else if(isa<IntegerType>(oldMember->getType()))