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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
|
#ifndef _PASS_COMMON_H
#define _PASS_COMMON_H
#if LLVM_VERSION >= 33
#define ATTRIBUTE_SET_TY AttributeSet
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/IRBuilder.h>
#else /* LLVM_VERSION < 33 */
#define ATTRIBUTE_SET_TY AttrListPtr
#include <llvm/Function.h>
#include <llvm/Module.h>
#include <llvm/Instructions.h>
#include <llvm/Type.h>
#include <llvm/Constants.h>
#include <llvm/Intrinsics.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/IntrinsicInst.h>
#endif /* LLVM_VERSION >= 33 */
#if LLVM_VERSION >= 32
#define DATA_LAYOUT_TY DataLayout
#define ATTRIBUTE_SET_RET_IDX ATTRIBUTE_SET_TY::ReturnIndex
#define ATTRIBUTE_SET_FN_IDX ATTRIBUTE_SET_TY::FunctionIndex
#include <llvm/IR/DebugInfo.h>
#if LLVM_VERSION == 32
#include <llvm/DataLayout.h>
#include <llvm/IRBuilder.h>
#endif
#else /* LLVM_VERSION < 32 */
#define DATA_LAYOUT_TY TargetData
#define ATTRIBUTE_SET_RET_IDX 0
#define ATTRIBUTE_SET_FN_IDX (~0U)
#include <llvm/Target/TargetData.h>
#include <llvm/Analysis/DebugInfo.h>
#include <llvm/Support/IRBuilder.h>
#endif /* LLVM_VERSION >= 32 */
#if LLVM_VERSION >= 31
/* XXX Check. */
#define CONSTANT_ARRAY_INITIALIZER_TY ConstantDataArray
#else /* LLVM_VERSION < 31 */
#define CONSTANT_ARRAY_INITIALIZER_TY ConstantArray
#endif /* LLVM_VERSION >= 31 */
#if LLVM_VERSION >= 30
#define BASE_PARSER parser
#define TYPECONST
#else /* LLVM_VERSION < 30 */
#define BASE_PARSER basic_parser
#define TYPECONST const
#endif /* LLVM_VERSION >= 30 */
#if LLVM_VERSION >= 29
#define VALUE_TO_VALUE_MAP_TY ValueToValueMapTy
#else /* LLVM_VERSION < 29 */
#define VALUE_TO_VALUE_MAP_TY ValueMap<const Value*, Value*>
#endif /* LLVM_VERSION >= 29 */
#define ZERO_CONSTANT_INT(M) ConstantInt::get((M).getContext(), APInt(32, 0, 10))
#define VOID_PTR_TY(M) PointerType::get(IntegerType::get((M).getContext(), 8), 0)
#define VOID_PTR_PTR_TY(M) PointerType::get(PointerType::get(IntegerType::get((M).getContext(), 8), 0), 0)
#define FOREACH_FUNC(M, F, B) do { \
Module::FunctionListType &__FL = (M).getFunctionList(); \
for (Module::iterator __MI = __FL.begin(); __MI != __FL.end(); ++__MI) { \
const Function *F = __MI; \
if (F->isIntrinsic()) \
continue; \
B \
} \
} while(0)
#define FOREACH_FUNC_INS(F, I, B) do { \
for (Function::const_iterator __FI = F->begin(), __FE = F->end(); __FI != __FE; ++__FI) { \
for (BasicBlock::const_iterator __BI = __FI->begin(), BE = __FI->end(); __BI != BE; ++__BI) { \
Instruction *I = (Instruction*) ((unsigned long) &(*__BI)); \
B \
} \
} \
} while(0)
#define FOREACH_FUNC_CS(F, CS, B) do { \
FOREACH_FUNC_INS(F, I, \
CallSite CS = PassUtil::getCallSiteFromInstruction(I); \
if (!CS.getInstruction()) \
continue; \
B \
); \
} while(0)
#define DEBUG_LLVM_DEBUG_API 0
typedef enum PassUtilLinkageTypeE {
PASS_UTIL_LINKAGE_NONE = 0,
PASS_UTIL_LINKAGE_WEAK,
PASS_UTIL_LINKAGE_COMMON,
PASS_UTIL_LINKAGE_EXTERNAL,
PASS_UTIL_LINKAGE_EXTERNAL_WEAK,
PASS_UTIL_LINKAGE_WEAK_POINTER,
PASS_UTIL_LINKAGE_PRIVATE,
__NUM_PASS_UTIL_LINKAGE_TYPES
/* Values here should only be appended at the end, external components (e.g., scripts) may be relying on them.*/
} PassUtilLinkageType;
#define PASS_UTIL_LINKAGE_TYPE_STRINGS \
"NONE", \
"WEAK", \
"COMMON", \
"EXTERNAL", \
"EXTERNAL_WEAK", \
"WEAK_POINTER", \
"PRIVATE"
typedef enum PassUtilPropE {
PASS_UTIL_PROP_NONE,
PASS_UTIL_PROP_NOINLINE,
PASS_UTIL_PROP_USED,
PASS_UTIL_PROP_PRESERVE,
__NUM_PASS_UTIL_PROPS
} PassUtilProp;
#define PASS_UTIL_FLAG(F) (1 << F)
#define PASS_COMMON_INIT_ONCE() \
Module *PassUtil::M = NULL; \
using namespace llvm;
namespace llvm {
class PassUtil {
public:
static void writeTypeSymbolic(raw_string_ostream &OS, TYPECONST Type *type, const Module *M);
static const std::string getTypeDescription(TYPECONST Type* type);
static MDNode *findDbgGlobalDeclare(GlobalVariable *V);
static MDNode *findDbgSubprogramDeclare(const Function *F);
static void getDbgLocationInfoRelPath(const std::string &baseDir, const std::string &filename, const std::string &directory, std::string &relPath);
static void getDbgLocationInfo(DIDescriptor &DID, const std::string &baseDir, std::string *filename, std::string *directory, std::string *relPath);
static bool getInstrDbgLocationInfo(Instruction *I, const std::string &baseDir, std::string *filename, std::string *directory, std::string *relPath, unsigned int *lineNum, bool expand=true);
static unsigned getDbgSubrangeNumElements(const DISubrange &subrange);
static bool isDbgVectorTy(const DIType &type);
static DIType getDITypeDerivedFrom(const DIDerivedType &type);
static DIType getDITypeFromRef(const DITypeRef &ref);
static bool isOpaqueTy(TYPECONST Type *type);
static bool isPrimitiveTy(TYPECONST Type *type);
static Constant* getGetElementPtrConstant(Constant *constant, std::vector<Value*> &indexes);
static GetElementPtrInst* createGetElementPtrInstruction(Value *ptr, std::vector<Value*> &indexes, const Twine &NameStr="", Instruction *InsertBefore=0);
static GetElementPtrInst* createGetElementPtrInstruction(Value *ptr, std::vector<Value*> &indexes, const Twine &NameStr="", BasicBlock *InsertAtEnd=0);
static CallInst* createCallInstruction(Value *F, std::vector<Value*> &args, const Twine &NameStr="", Instruction *InsertBefore=0);
static CallInst* createCallInstruction(Value *F, std::vector<Value*> &args, const Twine &NameStr="", BasicBlock *InsertAtEnd=0);
static Function* getIntrinsicFunction(Module &M, Intrinsic::ID id, TYPECONST Type** types=NULL, unsigned size=0);
static FunctionType* getFunctionType(TYPECONST Type* Result, std::vector<TYPECONST Type*> &argsTy, bool isVarArg=false);
static Function* setFunctionProperties(Function *F, unsigned long properties);
static Function* createFunctionWeakPtrWrapper(Module &M, StringRef Name, FunctionType *Ty);
static Function* getOrInsertFunction(Module &M, StringRef Name, FunctionType *Ty, PassUtilLinkageType insertLinkage, unsigned long properties);
static PassUtilLinkageType getFunctionPassUtilLinkageType(Function *F);
static std::string getPassUtilLinkageTypeString(PassUtilLinkageType linkageType);
static void getFunctionEntryExits(Function *F, BasicBlock **entryBlock, std::vector<BasicBlock*> *exitBlocks);
static bool isReturnedValue(Function *F, Value *V);
static CallSite getCallSiteFromInstruction(Instruction *I);
static CallSite getCallSiteFromUser(User *U);
static void getFunctionsInDirectBUCallgraph(Function* F, std::set<Function*> &funcs);
static void getAllocaInfo(Function *F, Instruction **allocaInsertionPoint, Instruction **firstNonAllocaInst);
static Constant* getStringConstantArray(Module &M, const std::string &string);
static GlobalVariable* getStringGlobalVariable(Module &M, const std::string &string, const std::string &varName = ".str.pu", const std::string &varSection = "", Constant **getElementPtrExpr=NULL, bool cacheable=false);
static ATTRIBUTE_SET_TY remapCallSiteAttributes(CallSite &CS, int argOffset);
static void parseStringListOpt(std::vector<std::string> &vector, const std::string &string, const std::string &separator = ":");
static void parseStringPairListOpt(std::set<std::pair<std::string, std::string> > &set, const std::string &string, const std::string &listSeparator = ":", const std::string &pairSeparator = ";");
static void parseRegexListOpt(std::vector<Regex*> &list, const std::string &string);
static bool matchRegexes(std::string string, std::vector<Regex*> ®exes);
static void setModule(Module *M);
static void getModuleName(Module &M, std::string *fullName, std::string *dirName, std::string *baseName);
static unsigned long getTypeHash(TYPECONST Type* type, unsigned maxLevel=11);
private:
static Module *M;
};
inline void PassUtil::writeTypeSymbolic(raw_string_ostream &OS, TYPECONST Type *type, const Module *M) {
#if LLVM_VERSION >= 30
/* XXX Check. */
type->print(OS);
return;
#else
return WriteTypeSymbolic(OS, type, M);
#endif
}
inline const std::string PassUtil::getTypeDescription(TYPECONST Type* type) {
std::string string;
#if LLVM_VERSION >= 30
/* XXX Check. */
raw_string_ostream ostream(string);
type->print(ostream);
ostream.flush();
#else
string = type->getDescription();
#endif
return string;
}
inline MDNode *PassUtil::findDbgGlobalDeclare(GlobalVariable *V) {
#if LLVM_VERSION >= 30
const Module *M = V->getParent();
NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.cu");
if (!NMD)
return 0;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
DICompileUnit CU(NMD->getOperand(i));
DIArray GVs = CU.getGlobalVariables();
for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
DIDescriptor DIG(GVs.getElement(i));
if (DIGlobalVariable(DIG).getGlobal() == V)
return DIG;
}
}
return 0;
#else
const Module *M = V->getParent();
NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
if (!NMD)
return 0;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
if (!DIG.isGlobalVariable())
continue;
if (DIGlobalVariable(DIG).getGlobal() == V)
return DIG;
}
return 0;
#endif
}
inline MDNode *PassUtil::findDbgSubprogramDeclare(const Function *V) {
#if LLVM_VERSION >= 30
const Module *M = V->getParent();
NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.cu");
if (!NMD)
return 0;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
DICompileUnit CU(NMD->getOperand(i));
DIArray SPs = CU.getSubprograms();
for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
DISubprogram DIS(SPs.getElement(i));
if (DIS.getFunction() == V) {
return DIS;
}
}
}
return 0;
#else
const Module *M = V->getParent();
NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp");
if (!NMD)
return 0;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
if (!DIG.isSubprogram())
continue;
if (DISubprogram(DIG).getFunction() == V)
return DIG;
}
return 0;
#endif
}
inline void PassUtil::getDbgLocationInfoRelPath(const std::string &baseDir, const std::string &filename, const std::string &directory, std::string &relPath) {
StringRef directoryRef(directory);
std::pair<StringRef, StringRef> stringPair = directoryRef.split(baseDir);
relPath = (stringPair.second.compare("") ? stringPair.second.str() : stringPair.first.str()) + "/" + filename;
#if DEBUG_LLVM_DEBUG_API
errs() << " - getDbgLocationInfoRelPath: Location Info is: " << directory << " | " << filename << " | " << relPath << "\n";
#endif
}
inline void PassUtil::getDbgLocationInfo(DIDescriptor &DID, const std::string &baseDir, std::string *filename, std::string *directory, std::string *relPath) {
StringRef _directory;
StringRef _filename;
if (DID.isGlobalVariable()) {
#if LLVM_VERSION >= 30
_directory = ((DIGlobalVariable*)&DID)->getDirectory();
_filename = ((DIGlobalVariable*)&DID)->getFilename();
#else
_directory = ((DIGlobalVariable*)&DID)->getCompileUnit().getDirectory();
_filename = ((DIGlobalVariable*)&DID)->getCompileUnit().getFilename();
#endif
#if DEBUG_LLVM_DEBUG_API
errs() << "DIGlobalVariable name is: " << ((DIGlobalVariable*)&DID)->getName() << "\n";
#endif
}
else if (DID.isSubprogram()) {
_directory = ((DISubprogram*)&DID)->getDirectory();
_filename = ((DISubprogram*)&DID)->getFilename();
#if DEBUG_LLVM_DEBUG_API
errs() << "DISubprogram name is: " << ((DISubprogram*)&DID)->getName() << "\n";
#endif
}
else {
DIScope DIS;
assert (DID.isVariable());
DIS = ((DIVariable*)&DID)->getContext();
if (DIS.isSubprogram()) {
_directory = ((DISubprogram*)&DIS)->getDirectory();
_filename = ((DISubprogram*)&DIS)->getFilename();
#if DEBUG_LLVM_DEBUG_API
errs() << "DIVariable (SP) name is: " << ((DIVariable*)&DID)->getName() << "\n";
#endif
}
else if (DIS.isLexicalBlock()) {
_directory = ((DILexicalBlock*)&DIS)->getDirectory();
_filename = ((DILexicalBlock*)&DIS)->getFilename();
#if DEBUG_LLVM_DEBUG_API
errs() << "DIVariable (LB) name is: " << ((DIVariable*)&DID)->getName() << "\n";
#endif
}
else {
#if LLVM_VERSION >= 30
assert(DIS.isLexicalBlockFile());
_directory = ((DILexicalBlockFile*)&DIS)->getDirectory();
_filename = ((DILexicalBlockFile*)&DIS)->getFilename();
#if DEBUG_LLVM_DEBUG_API
errs() << "DIVariable (LBF) name is: " << ((DIVariable*)&DID)->getName() << "\n";
#endif
#else
assert(0 && "Unexpected DIScope instance!");
#endif
}
}
if (filename) {
*filename = _filename;
}
if (directory) {
*directory = _directory;
}
if (relPath) {
getDbgLocationInfoRelPath(baseDir, _filename, _directory, *relPath);
}
}
inline bool PassUtil::getInstrDbgLocationInfo(Instruction *I, const std::string &baseDir, std::string *filename, std::string *directory, std::string *relPath, unsigned int *lineNum, bool expand) {
BasicBlock::iterator BI = I;
MDNode *N = BI->getMetadata("dbg");
if (!N && !expand) {
return false;
}
while(!N) {
if (BI->isTerminator()) {
BranchInst *BInst = dyn_cast<BranchInst>(BI);
if (BInst && BInst->isUnconditional()) {
BI = BInst->getSuccessor(0)->front();
N = BI->getMetadata("dbg");
continue;
}
return false;
}
BI++;
N = BI->getMetadata("dbg");
}
DILocation DIL(N);
StringRef _directory = DIL.getDirectory();
StringRef _filename = DIL.getFilename();
if (filename) {
*filename = _filename;
}
if (directory) {
*directory = _directory;
}
if (relPath) {
getDbgLocationInfoRelPath(baseDir, _filename, _directory, *relPath);
}
if (lineNum) {
*lineNum = DIL.getLineNumber();
}
return true;
}
inline unsigned PassUtil::getDbgSubrangeNumElements(const DISubrange &subrange) {
#if LLVM_VERSION >= 33
const unsigned numElements = (unsigned) subrange.getCount();
#else
const unsigned low = (unsigned) subrange.getLo();
const unsigned high = (unsigned) subrange.getHi();
const unsigned numElements = high - low + 1;
#endif
return numElements;
}
inline bool PassUtil::isDbgVectorTy(const DIType &type) {
#if LLVM_VERSION >= 33
return type.isVector();
#else
return type.getTag() == dwarf::DW_TAG_vector_type;
#endif
}
inline DIType PassUtil::getDITypeDerivedFrom(const DIDerivedType &type) {
#if LLVM_VERSION >= 34
static DITypeIdentifierMap TypeIdentifierMap;
static bool TypeMapInitialized = false;
if (!TypeMapInitialized) {
assert(PassUtil::M && "Set module first!");
if (NamedMDNode *CU_Nodes = PassUtil::M->getNamedMetadata("llvm.dbg.cu")) {
TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
TypeMapInitialized = true;
}
}
return type.getTypeDerivedFrom().resolve(TypeIdentifierMap);
#else
return type.getTypeDerivedFrom();
#endif
}
inline DIType PassUtil::getDITypeFromRef(const DITypeRef &ref) {
static DITypeIdentifierMap TypeIdentifierMap;
static bool TypeMapInitialized = false;
if (!TypeMapInitialized) {
/* TODO: generate the type identifier map only once! */
assert(PassUtil::M && "Set module first!");
if (NamedMDNode *CU_Nodes = PassUtil::M->getNamedMetadata("llvm.dbg.cu")) {
TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
TypeMapInitialized = true;
}
}
return ref.resolve(TypeIdentifierMap);
}
inline bool PassUtil::isOpaqueTy(TYPECONST Type *type) {
#if LLVM_VERSION >= 30
return type->isStructTy() && (((TYPECONST StructType*)type)->isOpaque() || type->getNumContainedTypes() == 0);
#else
return type->isOpaqueTy();
#endif
}
inline bool PassUtil::isPrimitiveTy(TYPECONST Type *type) {
return type->isVoidTy() || type->isFloatingPointTy() || type->isLabelTy() || type->isMetadataTy() || type->isX86_MMXTy();
}
inline Constant* PassUtil::getGetElementPtrConstant(Constant *constant, std::vector<Value*> &indexes) {
#if LLVM_VERSION >= 30
ArrayRef<Value*> ref(indexes);
return ConstantExpr::getGetElementPtr(constant, ref);
#else
return ConstantExpr::getGetElementPtr(constant, &indexes[0], indexes.size());
#endif
}
inline GetElementPtrInst* PassUtil::createGetElementPtrInstruction(Value *ptr, std::vector<Value*> &indexes, const Twine &NameStr, Instruction *InsertBefore) {
#if LLVM_VERSION >= 30
ArrayRef<Value*> ref(indexes);
return GetElementPtrInst::Create(ptr, ref, NameStr, InsertBefore);
#else
return GetElementPtrInst::Create(ptr, indexes.begin(), indexes.end(), NameStr, InsertBefore);
#endif
}
inline GetElementPtrInst* PassUtil::createGetElementPtrInstruction(Value *ptr, std::vector<Value*> &indexes, const Twine &NameStr, BasicBlock *InsertAtEnd) {
#if LLVM_VERSION >= 30
ArrayRef<Value*> ref(indexes);
return GetElementPtrInst::Create(ptr, ref, NameStr, InsertAtEnd);
#else
return GetElementPtrInst::Create(ptr, indexes.begin(), indexes.end(), NameStr, InsertAtEnd);
#endif
}
inline CallInst* PassUtil::createCallInstruction(Value *F, std::vector<Value*> &args, const Twine &NameStr, Instruction *InsertBefore) {
#if LLVM_VERSION >= 30
ArrayRef<Value*> ref(args);
return CallInst::Create(F, ref, NameStr, InsertBefore);
#else
return CallInst::Create(F, args.begin(), args.end(), NameStr, InsertBefore);
#endif
}
inline CallInst* PassUtil::createCallInstruction(Value *F, std::vector<Value*> &args, const Twine &NameStr, BasicBlock *InsertAtEnd) {
#if LLVM_VERSION >= 30
ArrayRef<Value*> ref(args);
return CallInst::Create(F, ref, NameStr, InsertAtEnd);
#else
return CallInst::Create(F, args.begin(), args.end(), NameStr, InsertAtEnd);
#endif
}
inline Function* PassUtil::getIntrinsicFunction(Module &M, Intrinsic::ID id, TYPECONST Type** types, unsigned size) {
#if LLVM_VERSION >= 30
std::vector<TYPECONST Type*> typeVector;
for(unsigned i=0;i<size;i++) {
typeVector.push_back(types[i]);
}
ArrayRef<TYPECONST Type*> ref(typeVector);
return Intrinsic::getDeclaration(&M, id, ref);
#else
return Intrinsic::getDeclaration(&M, id, types, size);
#endif
}
inline FunctionType* PassUtil::getFunctionType(TYPECONST Type* Result, std::vector<TYPECONST Type*> &argsTy, bool isVarArg)
{
#if LLVM_VERSION >= 30
ArrayRef<TYPECONST Type*> ref(argsTy);
return FunctionType::get(Result, ref, isVarArg);
#else
return FunctionType::get(Result, argsTy, isVarArg);
#endif
}
inline Function* PassUtil::setFunctionProperties(Function *F, unsigned long props)
{
assert(F);
bool preserve = props & (PASS_UTIL_FLAG(PASS_UTIL_PROP_NOINLINE)|PASS_UTIL_FLAG(PASS_UTIL_PROP_USED)|PASS_UTIL_FLAG(PASS_UTIL_PROP_PRESERVE));
if (F->isDeclaration()) {
return F;
}
if (preserve) {
Instruction *I;
getAllocaInfo(F, NULL, &I);
assert(I);
/* Add a volatile store to a new global variable to preserve it. */
PointerType* voidPointerTy = PointerType::get(IntegerType::get(F->getContext(), 8), 0);
GlobalVariable* volatileVar = new GlobalVariable(*F->getParent(),
voidPointerTy, false, GlobalValue::CommonLinkage,
0, F->getName() + "_llvm_propvar");
volatileVar->setInitializer(ConstantPointerNull::get(voidPointerTy));
new StoreInst(ConstantExpr::getCast(Instruction::BitCast, F, voidPointerTy), volatileVar, true, I);
}
return F;
}
inline Function* PassUtil::createFunctionWeakPtrWrapper(Module &M, StringRef Name, FunctionType *Ty)
{
unsigned i;
Function *F = getOrInsertFunction(M, Name.str() + "_llvm_weakptrwrapper" , Ty, PASS_UTIL_LINKAGE_COMMON, 0);
TYPECONST Type *RetTy = Ty->getReturnType();
PointerType *FPtrTy = PointerType::get(Ty, 0);
Constant *FPtrNull = Constant::getNullValue(FPtrTy);
/* Create the global function pointer variable. */
GlobalVariable* weakPtrVar = new GlobalVariable(M, FPtrTy, false,
GlobalValue::CommonLinkage, 0, Name);
weakPtrVar->setInitializer(FPtrNull);
/* Create the wrapper function body. */
F->dropAllReferences();
BasicBlock* entryBB = BasicBlock::Create(M.getContext(), "entry",F,0);
BasicBlock* weakPtrOverridenBB = BasicBlock::Create(M.getContext(), "have." + Name.str(),F,0);
BasicBlock* endBB = BasicBlock::Create(M.getContext(), "end",F,0);
AllocaInst* retval = NULL;
/* Parse arguments. */
std::vector<AllocaInst*> argsAllocaInsts;
for (Function::arg_iterator args = F->arg_begin(); args != F->arg_end(); args++) {
Value *argValue = args;
AllocaInst *allocaInst = new AllocaInst(argValue->getType(), ".llvm.pu.args", entryBB);
argsAllocaInsts.push_back(allocaInst);
}
if (!RetTy->isVoidTy()) {
retval = new AllocaInst(RetTy, "retval", entryBB);
}
i=0;
for (Function::arg_iterator args = F->arg_begin(); args != F->arg_end(); args++, i++) {
Value *argValue = args;
AllocaInst *allocaInst = argsAllocaInsts[i];
new StoreInst(argValue, allocaInst, true, entryBB);
}
if (retval) {
new StoreInst(Constant::getNullValue(RetTy), retval, true, entryBB);
}
/* Build entry block. */
LoadInst* weakPtr = new LoadInst(weakPtrVar, "", true, entryBB);
ICmpInst* cmpInst = new ICmpInst(*entryBB, ICmpInst::ICMP_NE, weakPtr, FPtrNull, "");
BranchInst::Create(weakPtrOverridenBB, endBB, cmpInst, entryBB);
/* Build weakPtrOverriden block, only executed with a non-NULL weakPtr */
std::vector<Value*> weakPtrCallParams;
i=0;
for (Function::arg_iterator args = F->arg_begin(); args != F->arg_end(); args++, i++) {
AllocaInst *allocaInst = argsAllocaInsts[i];
weakPtrCallParams.push_back(new LoadInst(allocaInst, "", true, weakPtrOverridenBB));
}
weakPtr = new LoadInst(weakPtrVar, "", true, weakPtrOverridenBB);
CallInst* weakPtrCall = createCallInstruction(weakPtr, weakPtrCallParams, "", weakPtrOverridenBB);
weakPtrCall->setCallingConv(CallingConv::C);
if (retval) {
new StoreInst(weakPtrCall, retval, false, weakPtrOverridenBB);
}
BranchInst::Create(endBB, weakPtrOverridenBB);
/* Build end block. */
if (!retval) {
ReturnInst::Create(M.getContext(), endBB);
}
else {
LoadInst* retvalValue = new LoadInst(retval, "", false, endBB);
ReturnInst::Create(M.getContext(), retvalValue, endBB);
}
return F;
}
inline Function* PassUtil::getOrInsertFunction(Module &M, StringRef Name, FunctionType *Ty, PassUtilLinkageType insertLinkage, unsigned long properties)
{
static std::map<std::string, Function *> functionMap;
std::map<std::string, Function *>::iterator functionMapIt;
Function *F = NULL;
bool needsEmptyBody = true;
bool needsProperties = true;
bool needsIncludsion = true;
functionMapIt = functionMap.find(Name);
if (functionMapIt != functionMap.end()) {
return functionMapIt->second;
}
F = M.getFunction(Name);
if (F) {
/* If the function exists, check the type and return it. */
if (F->getFunctionType() != Ty) {
return NULL;
}
functionMap.insert(std::pair<std::string, Function *>(Name, F));
setFunctionProperties(F, properties);
return F;
}
/* Has the user requested creation of the function otherwise? */
if (insertLinkage == PASS_UTIL_LINKAGE_NONE) {
return NULL;
}
switch(insertLinkage) {
case PASS_UTIL_LINKAGE_WEAK:
/* Create empty function that can optionally be overriden at link time*/
F = Function::Create(Ty, GlobalVariable::WeakAnyLinkage, Name);
break;
case PASS_UTIL_LINKAGE_COMMON:
/* Creates empty function, non overridable. */
F = Function::Create(Ty, GlobalVariable::InternalLinkage, Name);
break;
case PASS_UTIL_LINKAGE_EXTERNAL:
/* Creates function declaration that must be defined at link time. */
F = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
needsEmptyBody = false;
break;
case PASS_UTIL_LINKAGE_EXTERNAL_WEAK:
/* Creates weak function declaration that can optionally be defined
* at link time (if undefined the linker will emit a NULL symbol).
*/
F = Function::Create(Ty, GlobalVariable::ExternalWeakLinkage, Name);
needsEmptyBody = false;
break;
case PASS_UTIL_LINKAGE_WEAK_POINTER:
/* Creates function pointer initialized to NULL that can optionally
* be initialized at runtime. Invocations are wrapped to ensure that
* indirect call is performed on a NULL pointer. This is to emulate
* Mac OS' weak_pointer attribute, which allows weak symbols to be
* overriden in LD_PRELOADED libraries at runtime.
*/
F = PassUtil::createFunctionWeakPtrWrapper(M, Name, Ty);
needsProperties = false;
needsIncludsion = false;
break;
default:
return NULL;
break;
}
if (needsIncludsion) {
M.getFunctionList().push_back(F);
}
if (needsEmptyBody) {
BasicBlock* block = BasicBlock::Create(M.getContext(), "entry", F);
IRBuilder<> builder(block);
TYPECONST Type *RetTy = Ty->getReturnType();
if (RetTy->isVoidTy()) {
builder.CreateRetVoid();
}
else {
builder.CreateRet(Constant::getNullValue(RetTy));
}
}
functionMap.insert(std::pair<std::string, Function *>(Name, F));
if (needsProperties) {
setFunctionProperties(F, properties);
}
return F;
}
inline PassUtilLinkageType PassUtil::getFunctionPassUtilLinkageType(Function *F)
{
if (F->isDeclaration()) {
return PASS_UTIL_LINKAGE_EXTERNAL;
}
if (F->hasInternalLinkage()) {
return PASS_UTIL_LINKAGE_PRIVATE;
}
return PASS_UTIL_LINKAGE_COMMON;
}
inline std::string PassUtil::getPassUtilLinkageTypeString(PassUtilLinkageType linkageType)
{
const char *strArray[] = { PASS_UTIL_LINKAGE_TYPE_STRINGS };
std::string str(strArray[linkageType]);
return str;
}
inline void PassUtil::getFunctionEntryExits(Function *F, BasicBlock **entryBlock, std::vector<BasicBlock*> *exitBlocks)
{
if (entryBlock) {
*entryBlock = &F->front();
}
if (exitBlocks) {
for(Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
if (isa<ReturnInst>(I->getTerminator()) || isa<UnreachableInst>(I->getTerminator()))
exitBlocks->push_back(I);
}
}
}
inline bool PassUtil::isReturnedValue(Function *F, Value *V)
{
std::vector<BasicBlock*> exitBlocks;
PassUtil::getFunctionEntryExits(F, NULL, &exitBlocks);
for (unsigned i=0;i<exitBlocks.size();i++) {
Instruction *I = exitBlocks[i]->getTerminator();
ReturnInst *RI = dyn_cast<ReturnInst>(I);
if (RI && RI->getReturnValue()) {
Value *RV = RI->getReturnValue();
if (RV == V) {
return true;
}
if (LoadInst *LI = dyn_cast<LoadInst>(RV)) {
if (LI->getPointerOperand() == V) {
return true;
}
}
}
}
return false;
}
inline CallSite PassUtil::getCallSiteFromInstruction(Instruction *I)
{
return getCallSiteFromUser(I);
}
inline CallSite PassUtil::getCallSiteFromUser(User *U)
{
CallSite CS(U->stripPointerCasts());
CallSite emptyCS;
Instruction *I = CS.getInstruction();
if (!I)
return emptyCS;
if (isa<CallInst>(I) && dyn_cast<CallInst>(I)->isInlineAsm())
return emptyCS;
Function *F = CS.getCalledFunction();
if (F && F->isIntrinsic())
return emptyCS;
return CS;
}
inline void PassUtil::getFunctionsInDirectBUCallgraph(Function* F, std::set<Function*> &funcs) {
if (funcs.find(F) != funcs.end())
return;
funcs.insert(F);
FOREACH_FUNC_CS(F, CS,
if (!CS.getCalledFunction())
continue;
getFunctionsInDirectBUCallgraph(CS.getCalledFunction(), funcs);
);
}
inline void PassUtil::getAllocaInfo(Function *F, Instruction **allocaInsertionPoint, Instruction **firstNonAllocaInst)
{
assert(!F->isDeclaration());
BasicBlock::iterator allocaIP = F->front().begin();
while (isa<AllocaInst>(allocaIP)) ++allocaIP;
BasicBlock::iterator firstNonAI = allocaIP;
if (firstNonAI->getName().equals("alloca point")) {
firstNonAI++;
}
if(allocaInsertionPoint) {
*allocaInsertionPoint = allocaIP;
}
if(firstNonAllocaInst) {
*firstNonAllocaInst = firstNonAI;
}
}
inline Constant* PassUtil::getStringConstantArray(Module &M, const std::string &string)
{
std::vector<Constant*> elements;
elements.reserve(string.size() + 1);
for (unsigned i = 0; i < string.size(); ++i)
elements.push_back(ConstantInt::get(Type::getInt8Ty(M.getContext()), string[i]));
// Add a null terminator to the string...
elements.push_back(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0));
ArrayType *ATy = ArrayType::get(Type::getInt8Ty(M.getContext()), elements.size());
return ConstantArray::get(ATy, elements);
}
inline GlobalVariable* PassUtil::getStringGlobalVariable(Module &M, const std::string &string, const std::string &varName, const std::string &varSection, Constant **getElementPtrExpr, bool cacheable)
{
static std::map<std::string, GlobalVariable*> stringCache;
std::map<std::string, GlobalVariable*>::iterator stringCacheIt;
std::string stringCacheKey;
GlobalVariable *strGV = NULL;
if (cacheable) {
stringCacheKey = string + "~!~!" + varName + "~!~!" + varSection;
stringCacheIt = stringCache.find(stringCacheKey);
if (stringCacheIt != stringCache.end()) {
strGV = stringCacheIt->second;
cacheable = false;
}
}
if (!strGV) {
//create a constant internal string reference
Constant *stringValue = PassUtil::getStringConstantArray(M, string);
//create the global variable, cache it, and record it in the module
strGV = new GlobalVariable(M, stringValue->getType(), true,
GlobalValue::InternalLinkage, stringValue, varName);
if (varSection.compare("")) {
strGV->setSection(varSection);
}
}
if (getElementPtrExpr) {
std::vector<Value*> strConstantIndices;
strConstantIndices.push_back(ZERO_CONSTANT_INT(M));
strConstantIndices.push_back(ZERO_CONSTANT_INT(M));
*getElementPtrExpr = PassUtil::getGetElementPtrConstant(strGV, strConstantIndices);
}
if (cacheable) {
stringCache.insert(std::pair<std::string, GlobalVariable*>(stringCacheKey, strGV));
}
return strGV;
}
inline ATTRIBUTE_SET_TY PassUtil::remapCallSiteAttributes(CallSite &CS, int argOffset)
{
ATTRIBUTE_SET_TY Attrs = CS.getAttributes();
ATTRIBUTE_SET_TY NewAttrs;
#if LLVM_VERSION >= 33
Instruction *I = CS.getInstruction();
NewAttrs.addAttributes(I->getContext(), ATTRIBUTE_SET_RET_IDX, Attrs.getRetAttributes());
NewAttrs.addAttributes(I->getContext(), ATTRIBUTE_SET_FN_IDX, Attrs.getFnAttributes());
for (unsigned i=1;i<=CS.arg_size();i++) {
NewAttrs.addAttributes(I->getContext(), i+argOffset, Attrs.getParamAttributes(i));
}
#elif LLVM_VERSION == 32
Instruction *I = CS.getInstruction();
NewAttrs.addAttr(I->getContext(), ATTRIBUTE_SET_RET_IDX, Attrs.getRetAttributes());
NewAttrs.addAttr(I->getContext(), ATTRIBUTE_SET_FN_IDX, Attrs.getFnAttributes());
for (unsigned i=1;i<=CS.arg_size();i++) {
NewAttrs.addAttr(I->getContext(), i+argOffset, Attrs.getParamAttributes(i));
}
#else
NewAttrs.addAttr(ATTRIBUTE_SET_RET_IDX, Attrs.getRetAttributes());
NewAttrs.addAttr(ATTRIBUTE_SET_FN_IDX, Attrs.getFnAttributes());
for (unsigned i=1;i<=CS.arg_size();i++) {
NewAttrs.addAttr(i+argOffset, Attrs.getParamAttributes(i));
}
#endif
return NewAttrs;
}
inline void PassUtil::parseStringListOpt(std::vector<std::string> &list, const std::string &string, const std::string &separator)
{
if(string.compare("")) {
SmallVector< StringRef, 8 > vector;
StringRef sref(string);
sref.split(vector, separator, -1, false);
list.insert(list.end(), vector.begin(), vector.end());
}
}
inline void PassUtil::parseStringPairListOpt(std::set<std::pair<std::string, std::string> > &set, const std::string &string, const std::string &listSeparator, const std::string &pairSeparator)
{
if(string.compare("")) {
SmallVector< StringRef, 8 > vector;
StringRef sref(string);
sref.split(vector, listSeparator, -1, false);
SmallVector< StringRef, 8 > parts;
while(!vector.empty()) {
StringRef token = vector.pop_back_val();
parts.clear();
token.split(parts, pairSeparator, -1, false);
assert(parts.size() == 2 && "Two tokens were expected.");
set.insert(std::pair<std::string, std::string>(parts.front(), parts.back()));
}
}
}
inline void PassUtil::parseRegexListOpt(std::vector<Regex*> &list, const std::string &string)
{
std::vector<std::string> stringList;
std::vector<std::string>::iterator it;
PassUtil::parseStringListOpt(stringList, string);
for (it = stringList.begin(); it != stringList.end(); ++it) {
Regex* regex = new Regex(*it, 0);
std::string error;
assert(regex->isValid(error));
list.push_back(regex);
}
}
inline bool PassUtil::matchRegexes(std::string string, std::vector<Regex*> ®exes)
{
for (std::vector<Regex*>::iterator it = regexes.begin(); it != regexes.end(); ++it) {
Regex *regex = *it;
if(regex->match(string, NULL)) {
return true;
}
}
return false;
}
inline void PassUtil::setModule(Module *M)
{
PassUtil::M = M;
}
inline void PassUtil::getModuleName(Module &M, std::string *fullName, std::string *dirName, std::string *baseName)
{
std::string _fullName, _dirName, _baseName;
_fullName = M.getModuleIdentifier();
SmallVector< StringRef, 8 > vector;
StringRef fullNameRef(_fullName);
fullNameRef.split(vector, "/", -1, false);
if (vector.size() > 1) {
_baseName = vector.pop_back_val();
for (unsigned i=0;i<vector.size();i++) {
_dirName.append("/");
_dirName.append(vector[i]);
}
}
else {
_baseName = _fullName;
_dirName = "/";
}
vector.clear();
StringRef baseNameRef(_baseName);
baseNameRef.split(vector, ".", -1, false);
if (vector.size() > 1) {
_baseName = vector[0];
}
if (fullName)
*fullName = _fullName;
if (dirName)
*dirName = _dirName;
if (baseName)
*baseName = _baseName;
}
inline unsigned long PassUtil::getTypeHash(TYPECONST Type* type, unsigned maxLevel)
{
static std::vector<TYPECONST Type*> nestedTypes;
static unsigned level = 0;
static unsigned counter;
unsigned long hash = 7;
if(level == 0) {
counter = 0;
}
unsigned numContainedTypes = type->getNumContainedTypes();
unsigned nestedIndex = 0;
for(unsigned i=0;i<nestedTypes.size();i++) {
if(type == nestedTypes[i]) {
nestedIndex = i+1;
break;
}
}
hash = (13*hash) ^ level;
hash = (13*hash) ^ counter++;
hash = (13*hash) ^ type->getTypeID();
hash = (13*hash) ^ nestedIndex;
if(TYPECONST IntegerType *intType = dyn_cast<IntegerType>(type)) {
hash = (13*hash) ^ intType->getBitWidth();
}
else if(TYPECONST PointerType *ptrType = dyn_cast<PointerType>(type)) {
hash = (13*hash) ^ ptrType->getElementType()->getTypeID();
}
if(nestedIndex > 0 || level >= maxLevel) {
return hash;
}
if(numContainedTypes == 0) {
return hash;
}
level++;
nestedTypes.push_back(type);
hash = (13*hash) ^ numContainedTypes;
for(unsigned i=0;i<numContainedTypes;i++) {
hash = (13*hash) ^ getTypeHash(type->getContainedType(i), maxLevel);
}
nestedTypes.pop_back();
level--;
return hash;
}
}
#endif /* _PASS_COMMON_H */
|