forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 48
/
MCPlusBuilder.h
2121 lines (1795 loc) · 78.6 KB
/
MCPlusBuilder.h
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
//===- bolt/Core/MCPlusBuilder.h - Interface for MCPlus ---------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of MCPlusBuilder class, which provides
// means to create/analyze/modify instructions at MCPlus level.
//
//===----------------------------------------------------------------------===//
#ifndef BOLT_CORE_MCPLUSBUILDER_H
#define BOLT_CORE_MCPLUSBUILDER_H
#include "bolt/Core/MCPlus.h"
#include "bolt/Core/Relocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCDisassembler/MCSymbolizer.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrAnalysis.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/RWMutex.h"
#include <cassert>
#include <cstdint>
#include <map>
#include <optional>
#include <system_error>
#include <unordered_map>
#include <unordered_set>
namespace llvm {
class MCContext;
class MCFixup;
class MCRegisterInfo;
class MCSymbol;
class raw_ostream;
namespace bolt {
class BinaryFunction;
/// Different types of indirect branches encountered during disassembly.
enum class IndirectBranchType : char {
UNKNOWN = 0, /// Unable to determine type.
POSSIBLE_TAIL_CALL, /// Possibly a tail call.
POSSIBLE_JUMP_TABLE, /// Possibly a switch/jump table.
POSSIBLE_PIC_JUMP_TABLE, /// Possibly a jump table for PIC.
POSSIBLE_GOTO, /// Possibly a gcc's computed goto.
POSSIBLE_FIXED_BRANCH, /// Possibly an indirect branch to a fixed location.
};
class MCPlusBuilder {
public:
using AllocatorIdTy = uint16_t;
private:
/// A struct that represents a single annotation allocator
struct AnnotationAllocator {
BumpPtrAllocator ValueAllocator;
std::unordered_set<MCPlus::MCAnnotation *> AnnotationPool;
};
/// A set of annotation allocators
std::unordered_map<AllocatorIdTy, AnnotationAllocator> AnnotationAllocators;
/// A variable that is used to generate unique ids for annotation allocators
AllocatorIdTy MaxAllocatorId = 0;
/// We encode Index and Value into a 64-bit immediate operand value.
static int64_t encodeAnnotationImm(uint8_t Index, int64_t Value) {
if (LLVM_UNLIKELY(Value != extractAnnotationValue(Value)))
report_fatal_error("annotation value out of range");
Value &= 0xff'ffff'ffff'ffff;
Value |= (int64_t)Index << 56;
return Value;
}
/// Extract annotation index from immediate operand value.
static uint8_t extractAnnotationIndex(int64_t ImmValue) {
return ImmValue >> 56;
}
/// Extract annotation value from immediate operand value.
static int64_t extractAnnotationValue(int64_t ImmValue) {
return SignExtend64<56>(ImmValue & 0xff'ffff'ffff'ffffULL);
}
std::optional<unsigned> getFirstAnnotationOpIndex(const MCInst &Inst) const {
const unsigned NumPrimeOperands = MCPlus::getNumPrimeOperands(Inst);
if (Inst.getNumOperands() == NumPrimeOperands)
return std::nullopt;
assert(Inst.getOperand(NumPrimeOperands).getInst() == nullptr &&
"Empty instruction expected.");
return NumPrimeOperands + 1;
}
MCInst::iterator getAnnotationInstOp(MCInst &Inst) const {
for (MCInst::iterator Iter = Inst.begin(); Iter != Inst.end(); ++Iter) {
if (Iter->isInst()) {
assert(Iter->getInst() == nullptr && "Empty instruction expected.");
return Iter;
}
}
return Inst.end();
}
void removeAnnotations(MCInst &Inst) const {
Inst.erase(getAnnotationInstOp(Inst), Inst.end());
}
void setAnnotationOpValue(MCInst &Inst, unsigned Index, int64_t Value) const {
const int64_t AnnotationValue = encodeAnnotationImm(Index, Value);
const std::optional<unsigned> FirstAnnotationOp =
getFirstAnnotationOpIndex(Inst);
if (!FirstAnnotationOp) {
Inst.addOperand(MCOperand::createInst(nullptr));
Inst.addOperand(MCOperand::createImm(AnnotationValue));
return;
}
for (unsigned I = *FirstAnnotationOp; I < Inst.getNumOperands(); ++I) {
const int64_t ImmValue = Inst.getOperand(I).getImm();
if (extractAnnotationIndex(ImmValue) == Index) {
Inst.getOperand(I).setImm(AnnotationValue);
return;
}
}
Inst.addOperand(MCOperand::createImm(AnnotationValue));
}
std::optional<int64_t> getAnnotationOpValue(const MCInst &Inst,
unsigned Index) const {
std::optional<unsigned> FirstAnnotationOp = getFirstAnnotationOpIndex(Inst);
if (!FirstAnnotationOp)
return std::nullopt;
for (unsigned I = *FirstAnnotationOp; I < Inst.getNumOperands(); ++I) {
const int64_t ImmValue = Inst.getOperand(I).getImm();
if (extractAnnotationIndex(ImmValue) == Index)
return extractAnnotationValue(ImmValue);
}
return std::nullopt;
}
protected:
const MCInstrAnalysis *Analysis;
const MCInstrInfo *Info;
const MCRegisterInfo *RegInfo;
const MCSubtargetInfo *STI;
/// Map annotation name into an annotation index.
StringMap<uint64_t> AnnotationNameIndexMap;
/// Names of non-standard annotations.
SmallVector<std::string, 8> AnnotationNames;
/// A mutex that is used to control parallel accesses to
/// AnnotationNameIndexMap and AnnotationsNames.
mutable llvm::sys::RWMutex AnnotationNameMutex;
/// Set TailCall annotation value to true. Clients of the target-specific
/// MCPlusBuilder classes must use convert/lower/create* interfaces instead.
void setTailCall(MCInst &Inst) const;
public:
/// Transfer annotations from \p SrcInst to \p DstInst.
void moveAnnotations(MCInst &&SrcInst, MCInst &DstInst) const {
MCInst::iterator AnnotationOp = getAnnotationInstOp(SrcInst);
for (MCInst::iterator Iter = AnnotationOp; Iter != SrcInst.end(); ++Iter)
DstInst.addOperand(*Iter);
SrcInst.erase(AnnotationOp, SrcInst.end());
}
/// Return iterator range covering def operands.
iterator_range<MCInst::iterator> defOperands(MCInst &Inst) const {
return make_range(Inst.begin(),
Inst.begin() + Info->get(Inst.getOpcode()).getNumDefs());
}
iterator_range<MCInst::const_iterator> defOperands(const MCInst &Inst) const {
return make_range(Inst.begin(),
Inst.begin() + Info->get(Inst.getOpcode()).getNumDefs());
}
/// Return iterator range covering prime use operands.
iterator_range<MCInst::iterator> useOperands(MCInst &Inst) const {
return make_range(Inst.begin() + Info->get(Inst.getOpcode()).getNumDefs(),
Inst.begin() + MCPlus::getNumPrimeOperands(Inst));
}
iterator_range<MCInst::const_iterator> useOperands(const MCInst &Inst) const {
return make_range(Inst.begin() + Info->get(Inst.getOpcode()).getNumDefs(),
Inst.begin() + MCPlus::getNumPrimeOperands(Inst));
}
public:
class InstructionIterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = MCInst;
using difference_type = std::ptrdiff_t;
using pointer = value_type *;
using reference = value_type &;
class Impl {
public:
virtual Impl *Copy() const = 0;
virtual void Next() = 0;
virtual void Prev() = 0;
virtual MCInst &Deref() = 0;
virtual bool Compare(const Impl &Other) const = 0;
virtual ~Impl() {}
};
template <typename T> class SeqImpl : public Impl {
public:
virtual Impl *Copy() const override { return new SeqImpl(Itr); }
virtual void Next() override { ++Itr; }
virtual void Prev() override { --Itr; }
virtual MCInst &Deref() override { return const_cast<MCInst &>(*Itr); }
virtual bool Compare(const Impl &Other) const override {
// assumes that Other is same underlying type
return Itr == static_cast<const SeqImpl<T> &>(Other).Itr;
}
explicit SeqImpl(T &&Itr) : Itr(std::move(Itr)) {}
explicit SeqImpl(const T &Itr) : Itr(Itr) {}
private:
T Itr;
};
template <typename T> class MapImpl : public Impl {
public:
virtual Impl *Copy() const override { return new MapImpl(Itr); }
virtual void Next() override { ++Itr; }
virtual void Prev() override { --Itr; }
virtual MCInst &Deref() override {
return const_cast<MCInst &>(Itr->second);
}
virtual bool Compare(const Impl &Other) const override {
// assumes that Other is same underlying type
return Itr == static_cast<const MapImpl<T> &>(Other).Itr;
}
explicit MapImpl(T &&Itr) : Itr(std::move(Itr)) {}
explicit MapImpl(const T &Itr) : Itr(Itr) {}
private:
T Itr;
};
InstructionIterator &operator++() {
Itr->Next();
return *this;
}
InstructionIterator &operator--() {
Itr->Prev();
return *this;
}
InstructionIterator operator++(int) {
std::unique_ptr<Impl> Tmp(Itr->Copy());
Itr->Next();
return InstructionIterator(std::move(Tmp));
}
InstructionIterator operator--(int) {
std::unique_ptr<Impl> Tmp(Itr->Copy());
Itr->Prev();
return InstructionIterator(std::move(Tmp));
}
bool operator==(const InstructionIterator &Other) const {
return Itr->Compare(*Other.Itr);
}
bool operator!=(const InstructionIterator &Other) const {
return !Itr->Compare(*Other.Itr);
}
MCInst &operator*() { return Itr->Deref(); }
MCInst *operator->() { return &Itr->Deref(); }
InstructionIterator &operator=(InstructionIterator &&Other) {
Itr = std::move(Other.Itr);
return *this;
}
InstructionIterator &operator=(const InstructionIterator &Other) {
if (this != &Other)
Itr.reset(Other.Itr->Copy());
return *this;
}
InstructionIterator() {}
InstructionIterator(const InstructionIterator &Other)
: Itr(Other.Itr->Copy()) {}
InstructionIterator(InstructionIterator &&Other)
: Itr(std::move(Other.Itr)) {}
explicit InstructionIterator(std::unique_ptr<Impl> Itr)
: Itr(std::move(Itr)) {}
InstructionIterator(InstructionListType::iterator Itr)
: Itr(new SeqImpl<InstructionListType::iterator>(Itr)) {}
template <typename T>
InstructionIterator(T *Itr) : Itr(new SeqImpl<T *>(Itr)) {}
InstructionIterator(ArrayRef<MCInst>::iterator Itr)
: Itr(new SeqImpl<ArrayRef<MCInst>::iterator>(Itr)) {}
InstructionIterator(MutableArrayRef<MCInst>::iterator Itr)
: Itr(new SeqImpl<MutableArrayRef<MCInst>::iterator>(Itr)) {}
// TODO: it would be nice to templatize this on the key type.
InstructionIterator(std::map<uint32_t, MCInst>::iterator Itr)
: Itr(new MapImpl<std::map<uint32_t, MCInst>::iterator>(Itr)) {}
private:
std::unique_ptr<Impl> Itr;
};
public:
MCPlusBuilder(const MCInstrAnalysis *Analysis, const MCInstrInfo *Info,
const MCRegisterInfo *RegInfo, const MCSubtargetInfo *STI)
: Analysis(Analysis), Info(Info), RegInfo(RegInfo), STI(STI) {
// Initialize the default annotation allocator with id 0
AnnotationAllocators.emplace(0, AnnotationAllocator());
MaxAllocatorId++;
// Build alias map
initAliases();
initSizeMap();
}
/// Create and return a target-specific MC symbolizer for the \p Function.
/// When \p CreateNewSymbols is set, the symbolizer can create new symbols
/// e.g. for jump table references.
virtual std::unique_ptr<MCSymbolizer>
createTargetSymbolizer(BinaryFunction &Function,
bool CreateNewSymbols = true) const {
return nullptr;
}
/// Initialize a new annotation allocator and return its id
AllocatorIdTy initializeNewAnnotationAllocator() {
AnnotationAllocators.emplace(MaxAllocatorId, AnnotationAllocator());
return MaxAllocatorId++;
}
/// Return the annotation allocator of a given id
AnnotationAllocator &getAnnotationAllocator(AllocatorIdTy AllocatorId) {
assert(AnnotationAllocators.count(AllocatorId) &&
"allocator not initialized");
return AnnotationAllocators.find(AllocatorId)->second;
}
// Check if an annotation allocator with the given id exists
bool checkAllocatorExists(AllocatorIdTy AllocatorId) {
return AnnotationAllocators.count(AllocatorId);
}
/// Free the values allocator within the annotation allocator
void freeValuesAllocator(AllocatorIdTy AllocatorId) {
AnnotationAllocator &Allocator = getAnnotationAllocator(AllocatorId);
for (MCPlus::MCAnnotation *Annotation : Allocator.AnnotationPool)
Annotation->~MCAnnotation();
Allocator.AnnotationPool.clear();
Allocator.ValueAllocator.Reset();
}
virtual ~MCPlusBuilder() { freeAnnotations(); }
/// Free all memory allocated for annotations
void freeAnnotations() {
for (auto &Element : AnnotationAllocators) {
AnnotationAllocator &Allocator = Element.second;
for (MCPlus::MCAnnotation *Annotation : Allocator.AnnotationPool)
Annotation->~MCAnnotation();
Allocator.AnnotationPool.clear();
Allocator.ValueAllocator.Reset();
}
}
using CompFuncTy = std::function<bool(const MCSymbol *, const MCSymbol *)>;
bool equals(const MCInst &A, const MCInst &B, CompFuncTy Comp) const;
bool equals(const MCOperand &A, const MCOperand &B, CompFuncTy Comp) const;
bool equals(const MCExpr &A, const MCExpr &B, CompFuncTy Comp) const;
virtual bool equals(const MCTargetExpr &A, const MCTargetExpr &B,
CompFuncTy Comp) const;
virtual bool isBranch(const MCInst &Inst) const {
return Analysis->isBranch(Inst);
}
virtual bool isConditionalBranch(const MCInst &Inst) const {
return Analysis->isConditionalBranch(Inst);
}
/// Returns true if Inst is a condtional move instruction
virtual bool isConditionalMove(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isUnconditionalBranch(const MCInst &Inst) const {
return Analysis->isUnconditionalBranch(Inst) && !isTailCall(Inst);
}
virtual bool isIndirectBranch(const MCInst &Inst) const {
return Analysis->isIndirectBranch(Inst);
}
/// Returns true if the instruction is memory indirect call or jump
virtual bool isBranchOnMem(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Returns true if the instruction is register indirect call or jump
virtual bool isBranchOnReg(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Check whether we support inverting this branch
virtual bool isUnsupportedBranch(const MCInst &Inst) const { return false; }
/// Return true of the instruction is of pseudo kind.
virtual bool isPseudo(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isPseudo();
}
/// Return true if the relocation type needs to be registered in the function.
/// These code relocations are used in disassembly to better understand code.
///
/// For ARM, they help us decode instruction operands unambiguously, but
/// sometimes we might discard them because we already have the necessary
/// information in the instruction itself (e.g. we don't need to record CALL
/// relocs in ARM because we can fully decode the target from the call
/// operand).
///
/// For X86, they might be used in scanExternalRefs when we want to skip
/// a function but still patch references inside it.
virtual bool shouldRecordCodeRelocation(uint64_t RelType) const {
llvm_unreachable("not implemented");
return false;
}
/// Creates x86 pause instruction.
virtual void createPause(MCInst &Inst) const {
llvm_unreachable("not implemented");
}
virtual void createLfence(MCInst &Inst) const {
llvm_unreachable("not implemented");
}
virtual void createPushRegister(MCInst &Inst, MCPhysReg Reg,
unsigned Size) const {
llvm_unreachable("not implemented");
}
virtual void createPopRegister(MCInst &Inst, MCPhysReg Reg,
unsigned Size) const {
llvm_unreachable("not implemented");
}
virtual void createPushFlags(MCInst &Inst, unsigned Size) const {
llvm_unreachable("not implemented");
}
virtual void createPopFlags(MCInst &Inst, unsigned Size) const {
llvm_unreachable("not implemented");
}
virtual void createDirectCall(MCInst &Inst, const MCSymbol *Target,
MCContext *Ctx, bool IsTailCall) {
llvm_unreachable("not implemented");
}
virtual MCPhysReg getX86R11() const { llvm_unreachable("not implemented"); }
virtual unsigned getShortBranchOpcode(unsigned Opcode) const {
llvm_unreachable("not implemented");
return 0;
}
/// Create increment contents of target by 1 for Instrumentation
virtual InstructionListType
createInstrIncMemory(const MCSymbol *Target, MCContext *Ctx, bool IsLeaf,
unsigned CodePointerSize) const {
llvm_unreachable("not implemented");
return InstructionListType();
}
/// Return a register number that is guaranteed to not match with
/// any real register on the underlying architecture.
MCPhysReg getNoRegister() const { return MCRegister::NoRegister; }
/// Return a register corresponding to a function integer argument \p ArgNo
/// if the argument is passed in a register. Or return the result of
/// getNoRegister() otherwise. The enumeration starts at 0.
///
/// Note: this should depend on a used calling convention.
virtual MCPhysReg getIntArgRegister(unsigned ArgNo) const {
llvm_unreachable("not implemented");
}
virtual bool isIndirectCall(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isCall(const MCInst &Inst) const {
return Analysis->isCall(Inst) || isTailCall(Inst);
}
virtual bool isReturn(const MCInst &Inst) const {
return Analysis->isReturn(Inst);
}
virtual bool isTerminator(const MCInst &Inst) const;
virtual bool isNoop(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isBreakpoint(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isPrefix(const MCInst &Inst) const { return false; }
virtual bool isRep(const MCInst &Inst) const { return false; }
virtual bool deleteREPPrefix(MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isPop(const MCInst &Inst) const { return false; }
/// Return true if the instruction is used to terminate an indirect branch.
virtual bool isTerminateBranch(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Return the width, in bytes, of the memory access performed by \p Inst, if
/// this is a pop instruction. Return zero otherwise.
virtual int getPopSize(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return 0;
}
virtual bool isPush(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Return the width, in bytes, of the memory access performed by \p Inst, if
/// this is a push instruction. Return zero otherwise.
virtual int getPushSize(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return 0;
}
virtual bool isSUB(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isLEA64r(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isLeave(const MCInst &Inst) const { return false; }
virtual bool isADRP(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isADR(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual void getADRReg(const MCInst &Inst, MCPhysReg &RegName) const {
llvm_unreachable("not implemented");
}
virtual bool isMoveMem2Reg(const MCInst &Inst) const { return false; }
virtual bool mayLoad(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).mayLoad();
}
virtual bool mayStore(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).mayStore();
}
virtual bool isAArch64ExclusiveLoad(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isAArch64ExclusiveStore(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isAArch64ExclusiveClear(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isCleanRegXOR(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
virtual bool isPacked(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Returns true if First/Second is a AUIPC/JALR call pair.
virtual bool isRISCVCall(const MCInst &First, const MCInst &Second) const {
llvm_unreachable("not implemented");
return false;
}
/// Used to fill the executable space with instructions
/// that will trap.
virtual StringRef getTrapFillValue() const {
llvm_unreachable("not implemented");
return StringRef();
}
/// Interface and basic functionality of a MCInstMatcher. The idea is to make
/// it easy to match one or more MCInsts against a tree-like pattern and
/// extract the fragment operands. Example:
///
/// auto IndJmpMatcher =
/// matchIndJmp(matchAdd(matchAnyOperand(), matchAnyOperand()));
/// if (!IndJmpMatcher->match(...))
/// return false;
///
/// This matches an indirect jump whose target register is defined by an
/// add to form the target address. Matchers should also allow extraction
/// of operands, for example:
///
/// uint64_t Scale;
/// auto IndJmpMatcher = BC.MIA->matchIndJmp(
/// BC.MIA->matchAnyOperand(), BC.MIA->matchImm(Scale),
/// BC.MIA->matchReg(), BC.MIA->matchAnyOperand());
/// if (!IndJmpMatcher->match(...))
/// return false;
///
/// Here we are interesting in extracting the scale immediate in an indirect
/// jump fragment.
///
struct MCInstMatcher {
MutableArrayRef<MCInst> InstrWindow;
MutableArrayRef<MCInst>::iterator CurInst;
virtual ~MCInstMatcher() {}
/// Returns true if the pattern is matched. Needs MCRegisterInfo and
/// MCInstrAnalysis for analysis. InstrWindow contains an array
/// where the last instruction is always the instruction to start matching
/// against a fragment, potentially matching more instructions before it.
/// If OpNum is greater than 0, we will not match against the last
/// instruction itself but against an operand of the last instruction given
/// by the index OpNum. If this operand is a register, we will immediately
/// look for a previous instruction defining this register and match against
/// it instead. This parent member function contains common bookkeeping
/// required to implement this behavior.
virtual bool match(const MCRegisterInfo &MRI, MCPlusBuilder &MIA,
MutableArrayRef<MCInst> InInstrWindow, int OpNum) {
InstrWindow = InInstrWindow;
CurInst = InstrWindow.end();
if (!next())
return false;
if (OpNum < 0)
return true;
if (static_cast<unsigned int>(OpNum) >=
MCPlus::getNumPrimeOperands(*CurInst))
return false;
const MCOperand &Op = CurInst->getOperand(OpNum);
if (!Op.isReg())
return true;
MCPhysReg Reg = Op.getReg();
while (next()) {
const MCInstrDesc &InstrDesc = MIA.Info->get(CurInst->getOpcode());
if (InstrDesc.hasDefOfPhysReg(*CurInst, Reg, MRI)) {
InstrWindow = InstrWindow.slice(0, CurInst - InstrWindow.begin() + 1);
return true;
}
}
return false;
}
/// If successfully matched, calling this function will add an annotation
/// to all instructions that were matched. This is used to easily tag
/// instructions for deletion and implement match-and-replace operations.
virtual void annotate(MCPlusBuilder &MIA, StringRef Annotation) {}
/// Moves internal instruction iterator to the next instruction, walking
/// backwards for pattern matching (effectively the previous instruction in
/// regular order).
bool next() {
if (CurInst == InstrWindow.begin())
return false;
--CurInst;
return true;
}
};
/// Matches any operand
struct AnyOperandMatcher : MCInstMatcher {
MCOperand &Op;
AnyOperandMatcher(MCOperand &Op) : Op(Op) {}
bool match(const MCRegisterInfo &MRI, MCPlusBuilder &MIA,
MutableArrayRef<MCInst> InInstrWindow, int OpNum) override {
auto I = InInstrWindow.end();
if (I == InInstrWindow.begin())
return false;
--I;
if (OpNum < 0 ||
static_cast<unsigned int>(OpNum) >= MCPlus::getNumPrimeOperands(*I))
return false;
Op = I->getOperand(OpNum);
return true;
}
};
/// Matches operands that are immediates
struct ImmMatcher : MCInstMatcher {
uint64_t &Imm;
ImmMatcher(uint64_t &Imm) : Imm(Imm) {}
bool match(const MCRegisterInfo &MRI, MCPlusBuilder &MIA,
MutableArrayRef<MCInst> InInstrWindow, int OpNum) override {
if (!MCInstMatcher::match(MRI, MIA, InInstrWindow, OpNum))
return false;
if (OpNum < 0)
return false;
const MCOperand &Op = CurInst->getOperand(OpNum);
if (!Op.isImm())
return false;
Imm = Op.getImm();
return true;
}
};
/// Matches operands that are MCSymbols
struct SymbolMatcher : MCInstMatcher {
const MCSymbol *&Sym;
SymbolMatcher(const MCSymbol *&Sym) : Sym(Sym) {}
bool match(const MCRegisterInfo &MRI, MCPlusBuilder &MIA,
MutableArrayRef<MCInst> InInstrWindow, int OpNum) override {
if (!MCInstMatcher::match(MRI, MIA, InInstrWindow, OpNum))
return false;
if (OpNum < 0)
return false;
Sym = MIA.getTargetSymbol(*CurInst, OpNum);
return Sym != nullptr;
}
};
/// Matches operands that are registers
struct RegMatcher : MCInstMatcher {
MCPhysReg &Reg;
RegMatcher(MCPhysReg &Reg) : Reg(Reg) {}
bool match(const MCRegisterInfo &MRI, MCPlusBuilder &MIA,
MutableArrayRef<MCInst> InInstrWindow, int OpNum) override {
auto I = InInstrWindow.end();
if (I == InInstrWindow.begin())
return false;
--I;
if (OpNum < 0 ||
static_cast<unsigned int>(OpNum) >= MCPlus::getNumPrimeOperands(*I))
return false;
const MCOperand &Op = I->getOperand(OpNum);
if (!Op.isReg())
return false;
Reg = Op.getReg();
return true;
}
};
std::unique_ptr<MCInstMatcher> matchAnyOperand(MCOperand &Op) const {
return std::unique_ptr<MCInstMatcher>(new AnyOperandMatcher(Op));
}
std::unique_ptr<MCInstMatcher> matchAnyOperand() const {
static MCOperand Unused;
return std::unique_ptr<MCInstMatcher>(new AnyOperandMatcher(Unused));
}
std::unique_ptr<MCInstMatcher> matchReg(MCPhysReg &Reg) const {
return std::unique_ptr<MCInstMatcher>(new RegMatcher(Reg));
}
std::unique_ptr<MCInstMatcher> matchReg() const {
static MCPhysReg Unused;
return std::unique_ptr<MCInstMatcher>(new RegMatcher(Unused));
}
std::unique_ptr<MCInstMatcher> matchImm(uint64_t &Imm) const {
return std::unique_ptr<MCInstMatcher>(new ImmMatcher(Imm));
}
std::unique_ptr<MCInstMatcher> matchImm() const {
static uint64_t Unused;
return std::unique_ptr<MCInstMatcher>(new ImmMatcher(Unused));
}
std::unique_ptr<MCInstMatcher> matchSymbol(const MCSymbol *&Sym) const {
return std::unique_ptr<MCInstMatcher>(new SymbolMatcher(Sym));
}
std::unique_ptr<MCInstMatcher> matchSymbol() const {
static const MCSymbol *Unused;
return std::unique_ptr<MCInstMatcher>(new SymbolMatcher(Unused));
}
virtual std::unique_ptr<MCInstMatcher>
matchIndJmp(std::unique_ptr<MCInstMatcher> Target) const {
llvm_unreachable("not implemented");
return nullptr;
}
virtual std::unique_ptr<MCInstMatcher>
matchIndJmp(std::unique_ptr<MCInstMatcher> Base,
std::unique_ptr<MCInstMatcher> Scale,
std::unique_ptr<MCInstMatcher> Index,
std::unique_ptr<MCInstMatcher> Offset) const {
llvm_unreachable("not implemented");
return nullptr;
}
virtual std::unique_ptr<MCInstMatcher>
matchAdd(std::unique_ptr<MCInstMatcher> A,
std::unique_ptr<MCInstMatcher> B) const {
llvm_unreachable("not implemented");
return nullptr;
}
virtual std::unique_ptr<MCInstMatcher>
matchLoadAddr(std::unique_ptr<MCInstMatcher> Target) const {
llvm_unreachable("not implemented");
return nullptr;
}
virtual std::unique_ptr<MCInstMatcher>
matchLoad(std::unique_ptr<MCInstMatcher> Base,
std::unique_ptr<MCInstMatcher> Scale,
std::unique_ptr<MCInstMatcher> Index,
std::unique_ptr<MCInstMatcher> Offset) const {
llvm_unreachable("not implemented");
return nullptr;
}
/// \brief Given a branch instruction try to get the address the branch
/// targets. Return true on success, and the address in Target.
virtual bool evaluateBranch(const MCInst &Inst, uint64_t Addr, uint64_t Size,
uint64_t &Target) const {
return Analysis->evaluateBranch(Inst, Addr, Size, Target);
}
/// Return true if one of the operands of the \p Inst instruction uses
/// PC-relative addressing.
/// Note that PC-relative branches do not fall into this category.
virtual bool hasPCRelOperand(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}
/// Return a number of the operand representing a memory.
/// Return -1 if the instruction doesn't have an explicit memory field.
virtual int getMemoryOperandNo(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return -1;
}
/// Return true if the instruction is encoded using EVEX (AVX-512).
virtual bool hasEVEXEncoding(const MCInst &Inst) const { return false; }
/// Return true if a pair of instructions represented by \p Insts
/// could be fused into a single uop.
virtual bool isMacroOpFusionPair(ArrayRef<MCInst> Insts) const {
llvm_unreachable("not implemented");
return false;
}
struct X86MemOperand {
unsigned BaseRegNum;
int64_t ScaleImm;
unsigned IndexRegNum;
int64_t DispImm;
unsigned SegRegNum;
const MCExpr *DispExpr = nullptr;
};
/// Given an instruction with (compound) memory operand, evaluate and return
/// the corresponding values. Note that the operand could be in any position,
/// but there is an assumption there's only one compound memory operand.
/// Return true upon success, return false if the instruction does not have
/// a memory operand.
///
/// Since a Displacement field could be either an immediate or an expression,
/// the function sets either \p DispImm or \p DispExpr value.
virtual std::optional<X86MemOperand>
evaluateX86MemoryOperand(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return std::nullopt;
}
/// Given an instruction with memory addressing attempt to statically compute
/// the address being accessed. Return true on success, and the address in
/// \p Target.
///
/// For RIP-relative addressing the caller is required to pass instruction
/// \p Address and \p Size.
virtual bool evaluateMemOperandTarget(const MCInst &Inst, uint64_t &Target,
uint64_t Address = 0,
uint64_t Size = 0) const {
llvm_unreachable("not implemented");
return false;
}
/// Return operand iterator pointing to displacement in the compound memory
/// operand if such exists. Return Inst.end() otherwise.
virtual MCInst::iterator getMemOperandDisp(MCInst &Inst) const {
llvm_unreachable("not implemented");
return Inst.end();
}
/// Analyze \p Inst and return true if this instruction accesses \p Size
/// bytes of the stack frame at position \p StackOffset. \p IsLoad and
/// \p IsStore are set accordingly. If both are set, it means it is a
/// instruction that reads and updates the same memory location. \p Reg is set
/// to the source register in case of a store or destination register in case
/// of a load. If the store does not use a source register, \p SrcImm will
/// contain the source immediate and \p IsStoreFromReg will be set to false.
/// \p Simple is false if the instruction is not fully understood by
/// companion functions "replaceMemOperandWithImm" or
/// "replaceMemOperandWithReg".
virtual bool isStackAccess(const MCInst &Inst, bool &IsLoad, bool &IsStore,
bool &IsStoreFromReg, MCPhysReg &Reg,
int32_t &SrcImm, uint16_t &StackPtrReg,
int64_t &StackOffset, uint8_t &Size,
bool &IsSimple, bool &IsIndexed) const {
llvm_unreachable("not implemented");
return false;
}
/// Convert a stack accessing load/store instruction in \p Inst to a PUSH
/// or POP saving/restoring the source/dest reg in \p Inst. The original
/// stack offset in \p Inst is ignored.
virtual void changeToPushOrPop(MCInst &Inst) const {
llvm_unreachable("not implemented");
}
/// Identify stack adjustment instructions -- those that change the stack
/// pointer by adding or subtracting an immediate.
virtual bool isStackAdjustment(const MCInst &Inst) const {
llvm_unreachable("not implemented");
return false;
}