-
Notifications
You must be signed in to change notification settings - Fork 44
/
macro-assembler-aarch64.cc
3182 lines (2692 loc) · 103 KB
/
macro-assembler-aarch64.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015, VIXL authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ARM Limited nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "macro-assembler-aarch64.h"
#include <cctype>
namespace vixl {
namespace aarch64 {
void Pool::Release() {
if (--monitor_ == 0) {
// Ensure the pool has not been blocked for too long.
VIXL_ASSERT(masm_->GetCursorOffset() < checkpoint_);
}
}
void Pool::SetNextCheckpoint(ptrdiff_t checkpoint) {
masm_->checkpoint_ = std::min(masm_->checkpoint_, checkpoint);
checkpoint_ = checkpoint;
}
LiteralPool::LiteralPool(MacroAssembler* masm)
: Pool(masm),
size_(0),
first_use_(-1),
recommended_checkpoint_(kNoCheckpointRequired) {}
LiteralPool::~LiteralPool() VIXL_NEGATIVE_TESTING_ALLOW_EXCEPTION {
VIXL_ASSERT(IsEmpty());
VIXL_ASSERT(!IsBlocked());
for (std::vector<RawLiteral*>::iterator it = deleted_on_destruction_.begin();
it != deleted_on_destruction_.end();
it++) {
delete *it;
}
}
void LiteralPool::Reset() {
std::vector<RawLiteral*>::iterator it, end;
for (it = entries_.begin(), end = entries_.end(); it != end; ++it) {
RawLiteral* literal = *it;
if (literal->deletion_policy_ == RawLiteral::kDeletedOnPlacementByPool) {
delete literal;
}
}
entries_.clear();
size_ = 0;
first_use_ = -1;
Pool::Reset();
recommended_checkpoint_ = kNoCheckpointRequired;
}
void LiteralPool::CheckEmitFor(size_t amount, EmitOption option) {
if (IsEmpty() || IsBlocked()) return;
ptrdiff_t distance = masm_->GetCursorOffset() + amount - first_use_;
if (distance >= kRecommendedLiteralPoolRange) {
Emit(option);
}
}
void LiteralPool::CheckEmitForBranch(size_t range) {
if (IsEmpty() || IsBlocked()) return;
if (GetMaxSize() >= range) Emit();
}
// We use a subclass to access the protected `ExactAssemblyScope` constructor
// giving us control over the pools. This allows us to use this scope within
// code emitting pools without creating a circular dependency.
// We keep the constructor private to restrict usage of this helper class.
class ExactAssemblyScopeWithoutPoolsCheck : public ExactAssemblyScope {
private:
ExactAssemblyScopeWithoutPoolsCheck(MacroAssembler* masm, size_t size)
: ExactAssemblyScope(masm,
size,
ExactAssemblyScope::kExactSize,
ExactAssemblyScope::kIgnorePools) {}
friend void LiteralPool::Emit(LiteralPool::EmitOption);
friend void VeneerPool::Emit(VeneerPool::EmitOption, size_t);
};
void LiteralPool::Emit(EmitOption option) {
// There is an issue if we are asked to emit a blocked or empty pool.
VIXL_ASSERT(!IsBlocked());
VIXL_ASSERT(!IsEmpty());
size_t pool_size = GetSize();
size_t emit_size = pool_size;
if (option == kBranchRequired) emit_size += kInstructionSize;
Label end_of_pool;
VIXL_ASSERT(emit_size % kInstructionSize == 0);
{
CodeBufferCheckScope guard(masm_,
emit_size,
CodeBufferCheckScope::kCheck,
CodeBufferCheckScope::kExactSize);
#ifdef VIXL_DEBUG
// Also explicitly disallow usage of the `MacroAssembler` here.
masm_->SetAllowMacroInstructions(false);
#endif
if (option == kBranchRequired) {
ExactAssemblyScopeWithoutPoolsCheck eas_guard(masm_, kInstructionSize);
masm_->b(&end_of_pool);
}
{
// Marker indicating the size of the literal pool in 32-bit words.
VIXL_ASSERT((pool_size % kWRegSizeInBytes) == 0);
ExactAssemblyScopeWithoutPoolsCheck eas_guard(masm_, kInstructionSize);
masm_->ldr(xzr, static_cast<int>(pool_size / kWRegSizeInBytes));
}
// Now populate the literal pool.
std::vector<RawLiteral*>::iterator it, end;
for (it = entries_.begin(), end = entries_.end(); it != end; ++it) {
VIXL_ASSERT((*it)->IsUsed());
masm_->place(*it);
}
if (option == kBranchRequired) masm_->bind(&end_of_pool);
#ifdef VIXL_DEBUG
masm_->SetAllowMacroInstructions(true);
#endif
}
Reset();
}
void LiteralPool::AddEntry(RawLiteral* literal) {
// A literal must be registered immediately before its first use. Here we
// cannot control that it is its first use, but we check no code has been
// emitted since its last use.
VIXL_ASSERT(masm_->GetCursorOffset() == literal->GetLastUse());
UpdateFirstUse(masm_->GetCursorOffset());
VIXL_ASSERT(masm_->GetCursorOffset() >= first_use_);
entries_.push_back(literal);
size_ += literal->GetSize();
}
void LiteralPool::UpdateFirstUse(ptrdiff_t use_position) {
first_use_ = std::min(first_use_, use_position);
if (first_use_ == -1) {
first_use_ = use_position;
SetNextRecommendedCheckpoint(GetNextRecommendedCheckpoint());
SetNextCheckpoint(first_use_ + Instruction::kLoadLiteralRange);
} else {
VIXL_ASSERT(use_position > first_use_);
}
}
void VeneerPool::Reset() {
Pool::Reset();
unresolved_branches_.Reset();
}
void VeneerPool::Release() {
if (--monitor_ == 0) {
VIXL_ASSERT(IsEmpty() || masm_->GetCursorOffset() <
unresolved_branches_.GetFirstLimit());
}
}
void VeneerPool::RegisterUnresolvedBranch(ptrdiff_t branch_pos,
Label* label,
ImmBranchType branch_type) {
VIXL_ASSERT(!label->IsBound());
BranchInfo branch_info = BranchInfo(branch_pos, label, branch_type);
unresolved_branches_.insert(branch_info);
UpdateNextCheckPoint();
// TODO: In debug mode register the label with the assembler to make sure it
// is bound with masm Bind and not asm bind.
}
void VeneerPool::DeleteUnresolvedBranchInfoForLabel(Label* label) {
if (IsEmpty()) {
VIXL_ASSERT(checkpoint_ == kNoCheckpointRequired);
return;
}
if (label->IsLinked()) {
Label::LabelLinksIterator links_it(label);
for (; !links_it.Done(); links_it.Advance()) {
ptrdiff_t link_offset = *links_it.Current();
Instruction* link = masm_->GetInstructionAt(link_offset);
// ADR instructions are not handled.
if (BranchTypeUsesVeneers(link->GetBranchType())) {
BranchInfo branch_info(link_offset, label, link->GetBranchType());
unresolved_branches_.erase(branch_info);
}
}
}
UpdateNextCheckPoint();
}
bool VeneerPool::ShouldEmitVeneer(int64_t first_unreacheable_pc,
size_t amount) {
ptrdiff_t offset =
kPoolNonVeneerCodeSize + amount + GetMaxSize() + GetOtherPoolsMaxSize();
return (masm_->GetCursorOffset() + offset) > first_unreacheable_pc;
}
void VeneerPool::CheckEmitFor(size_t amount, EmitOption option) {
if (IsEmpty()) return;
VIXL_ASSERT(masm_->GetCursorOffset() + kPoolNonVeneerCodeSize <
unresolved_branches_.GetFirstLimit());
if (IsBlocked()) return;
if (ShouldEmitVeneers(amount)) {
Emit(option, amount);
} else {
UpdateNextCheckPoint();
}
}
void VeneerPool::Emit(EmitOption option, size_t amount) {
// There is an issue if we are asked to emit a blocked or empty pool.
VIXL_ASSERT(!IsBlocked());
VIXL_ASSERT(!IsEmpty());
Label end;
if (option == kBranchRequired) {
ExactAssemblyScopeWithoutPoolsCheck guard(masm_, kInstructionSize);
masm_->b(&end);
}
// We want to avoid generating veneer pools too often, so generate veneers for
// branches that don't immediately require a veneer but will soon go out of
// range.
static const size_t kVeneerEmissionMargin = 1 * KBytes;
for (BranchInfoSetIterator it(&unresolved_branches_); !it.Done();) {
BranchInfo* branch_info = it.Current();
if (ShouldEmitVeneer(branch_info->first_unreacheable_pc_,
amount + kVeneerEmissionMargin)) {
CodeBufferCheckScope scope(masm_,
kVeneerCodeSize,
CodeBufferCheckScope::kCheck,
CodeBufferCheckScope::kExactSize);
ptrdiff_t branch_pos = branch_info->pc_offset_;
Instruction* branch = masm_->GetInstructionAt(branch_pos);
Label* label = branch_info->label_;
// Patch the branch to point to the current position, and emit a branch
// to the label.
Instruction* veneer = masm_->GetCursorAddress<Instruction*>();
branch->SetImmPCOffsetTarget(veneer);
{
ExactAssemblyScopeWithoutPoolsCheck guard(masm_, kInstructionSize);
masm_->b(label);
}
// Update the label. The branch patched does not point to it any longer.
label->DeleteLink(branch_pos);
it.DeleteCurrentAndAdvance();
} else {
it.AdvanceToNextType();
}
}
UpdateNextCheckPoint();
masm_->bind(&end);
}
MacroAssembler::MacroAssembler(PositionIndependentCodeOption pic)
: Assembler(pic),
#ifdef VIXL_DEBUG
allow_macro_instructions_(true),
#endif
generate_simulator_code_(VIXL_AARCH64_GENERATE_SIMULATOR_CODE),
sp_(sp),
tmp_list_(ip0, ip1),
v_tmp_list_(d31),
p_tmp_list_(CPURegList::Empty(CPURegister::kPRegister)),
current_scratch_scope_(NULL),
literal_pool_(this),
veneer_pool_(this),
recommended_checkpoint_(Pool::kNoCheckpointRequired),
fp_nan_propagation_(NoFPMacroNaNPropagationSelected) {
checkpoint_ = GetNextCheckPoint();
#ifndef VIXL_DEBUG
USE(allow_macro_instructions_);
#endif
}
MacroAssembler::MacroAssembler(size_t capacity,
PositionIndependentCodeOption pic)
: Assembler(capacity, pic),
#ifdef VIXL_DEBUG
allow_macro_instructions_(true),
#endif
generate_simulator_code_(VIXL_AARCH64_GENERATE_SIMULATOR_CODE),
sp_(sp),
tmp_list_(ip0, ip1),
v_tmp_list_(d31),
p_tmp_list_(CPURegList::Empty(CPURegister::kPRegister)),
current_scratch_scope_(NULL),
literal_pool_(this),
veneer_pool_(this),
recommended_checkpoint_(Pool::kNoCheckpointRequired),
fp_nan_propagation_(NoFPMacroNaNPropagationSelected) {
checkpoint_ = GetNextCheckPoint();
}
MacroAssembler::MacroAssembler(byte* buffer,
size_t capacity,
PositionIndependentCodeOption pic)
: Assembler(buffer, capacity, pic),
#ifdef VIXL_DEBUG
allow_macro_instructions_(true),
#endif
generate_simulator_code_(VIXL_AARCH64_GENERATE_SIMULATOR_CODE),
sp_(sp),
tmp_list_(ip0, ip1),
v_tmp_list_(d31),
p_tmp_list_(CPURegList::Empty(CPURegister::kPRegister)),
current_scratch_scope_(NULL),
literal_pool_(this),
veneer_pool_(this),
recommended_checkpoint_(Pool::kNoCheckpointRequired),
fp_nan_propagation_(NoFPMacroNaNPropagationSelected) {
checkpoint_ = GetNextCheckPoint();
}
MacroAssembler::~MacroAssembler() {}
void MacroAssembler::Reset() {
Assembler::Reset();
VIXL_ASSERT(!literal_pool_.IsBlocked());
literal_pool_.Reset();
veneer_pool_.Reset();
checkpoint_ = GetNextCheckPoint();
}
void MacroAssembler::FinalizeCode(FinalizeOption option) {
if (!literal_pool_.IsEmpty()) {
// The user may decide to emit more code after Finalize, emit a branch if
// that's the case.
literal_pool_.Emit(option == kUnreachable ? Pool::kNoBranchRequired
: Pool::kBranchRequired);
}
VIXL_ASSERT(veneer_pool_.IsEmpty());
Assembler::FinalizeCode();
}
void MacroAssembler::CheckEmitFor(size_t amount) {
CheckEmitPoolsFor(amount);
GetBuffer()->EnsureSpaceFor(amount);
}
void MacroAssembler::CheckEmitPoolsFor(size_t amount) {
literal_pool_.CheckEmitFor(amount);
veneer_pool_.CheckEmitFor(amount);
checkpoint_ = GetNextCheckPoint();
}
int MacroAssembler::MoveImmediateHelper(MacroAssembler* masm,
const Register& rd,
uint64_t imm) {
bool emit_code = (masm != NULL);
VIXL_ASSERT(IsUint32(imm) || IsInt32(imm) || rd.Is64Bits());
// The worst case for size is mov 64-bit immediate to sp:
// * up to 4 instructions to materialise the constant
// * 1 instruction to move to sp
MacroEmissionCheckScope guard(masm);
// Immediates on Aarch64 can be produced using an initial value, and zero to
// three move keep operations.
//
// Initial values can be generated with:
// 1. 64-bit move zero (movz).
// 2. 32-bit move inverted (movn).
// 3. 64-bit move inverted.
// 4. 32-bit orr immediate.
// 5. 64-bit orr immediate.
// Move-keep may then be used to modify each of the 16-bit half words.
//
// The code below supports all five initial value generators, and
// applying move-keep operations to move-zero and move-inverted initial
// values.
// Try to move the immediate in one instruction, and if that fails, switch to
// using multiple instructions.
if (OneInstrMoveImmediateHelper(masm, rd, imm)) {
return 1;
} else {
int instruction_count = 0;
unsigned reg_size = rd.GetSizeInBits();
// Generic immediate case. Imm will be represented by
// [imm3, imm2, imm1, imm0], where each imm is 16 bits.
// A move-zero or move-inverted is generated for the first non-zero or
// non-0xffff immX, and a move-keep for subsequent non-zero immX.
uint64_t ignored_halfword = 0;
bool invert_move = false;
// If the number of 0xffff halfwords is greater than the number of 0x0000
// halfwords, it's more efficient to use move-inverted.
if (CountClearHalfWords(~imm, reg_size) >
CountClearHalfWords(imm, reg_size)) {
ignored_halfword = 0xffff;
invert_move = true;
}
// Mov instructions can't move values into the stack pointer, so set up a
// temporary register, if needed.
UseScratchRegisterScope temps;
Register temp;
if (emit_code) {
temps.Open(masm);
temp = rd.IsSP() ? temps.AcquireSameSizeAs(rd) : rd;
}
// Iterate through the halfwords. Use movn/movz for the first non-ignored
// halfword, and movk for subsequent halfwords.
VIXL_ASSERT((reg_size % 16) == 0);
bool first_mov_done = false;
for (unsigned i = 0; i < (reg_size / 16); i++) {
uint64_t imm16 = (imm >> (16 * i)) & 0xffff;
if (imm16 != ignored_halfword) {
if (!first_mov_done) {
if (invert_move) {
if (emit_code) masm->movn(temp, ~imm16 & 0xffff, 16 * i);
instruction_count++;
} else {
if (emit_code) masm->movz(temp, imm16, 16 * i);
instruction_count++;
}
first_mov_done = true;
} else {
// Construct a wider constant.
if (emit_code) masm->movk(temp, imm16, 16 * i);
instruction_count++;
}
}
}
VIXL_ASSERT(first_mov_done);
// Move the temporary if the original destination register was the stack
// pointer.
if (rd.IsSP()) {
if (emit_code) masm->mov(rd, temp);
instruction_count++;
}
return instruction_count;
}
}
void MacroAssembler::B(Label* label, BranchType type, Register reg, int bit) {
VIXL_ASSERT((reg.Is(NoReg) || (type >= kBranchTypeFirstUsingReg)) &&
((bit == -1) || (type >= kBranchTypeFirstUsingBit)));
if (kBranchTypeFirstCondition <= type && type <= kBranchTypeLastCondition) {
B(static_cast<Condition>(type), label);
} else {
switch (type) {
case always:
B(label);
break;
case never:
break;
case reg_zero:
Cbz(reg, label);
break;
case reg_not_zero:
Cbnz(reg, label);
break;
case reg_bit_clear:
Tbz(reg, bit, label);
break;
case reg_bit_set:
Tbnz(reg, bit, label);
break;
default:
VIXL_UNREACHABLE();
}
}
}
void MacroAssembler::B(Label* label) {
// We don't need to check the size of the literal pool, because the size of
// the literal pool is already bounded by the literal range, which is smaller
// than the range of this branch.
VIXL_ASSERT(Instruction::GetImmBranchForwardRange(UncondBranchType) >
Instruction::kLoadLiteralRange);
SingleEmissionCheckScope guard(this);
b(label);
}
void MacroAssembler::B(Label* label, Condition cond) {
// We don't need to check the size of the literal pool, because the size of
// the literal pool is already bounded by the literal range, which is smaller
// than the range of this branch.
VIXL_ASSERT(Instruction::GetImmBranchForwardRange(CondBranchType) >
Instruction::kLoadLiteralRange);
VIXL_ASSERT(allow_macro_instructions_);
VIXL_ASSERT((cond != al) && (cond != nv));
EmissionCheckScope guard(this, 2 * kInstructionSize);
if (label->IsBound() && LabelIsOutOfRange(label, CondBranchType)) {
Label done;
b(&done, InvertCondition(cond));
b(label);
bind(&done);
} else {
if (!label->IsBound()) {
veneer_pool_.RegisterUnresolvedBranch(GetCursorOffset(),
label,
CondBranchType);
}
b(label, cond);
}
}
void MacroAssembler::Cbnz(const Register& rt, Label* label) {
// We don't need to check the size of the literal pool, because the size of
// the literal pool is already bounded by the literal range, which is smaller
// than the range of this branch.
VIXL_ASSERT(Instruction::GetImmBranchForwardRange(CompareBranchType) >
Instruction::kLoadLiteralRange);
VIXL_ASSERT(allow_macro_instructions_);
VIXL_ASSERT(!rt.IsZero());
EmissionCheckScope guard(this, 2 * kInstructionSize);
if (label->IsBound() && LabelIsOutOfRange(label, CondBranchType)) {
Label done;
cbz(rt, &done);
b(label);
bind(&done);
} else {
if (!label->IsBound()) {
veneer_pool_.RegisterUnresolvedBranch(GetCursorOffset(),
label,
CompareBranchType);
}
cbnz(rt, label);
}
}
void MacroAssembler::Cbz(const Register& rt, Label* label) {
// We don't need to check the size of the literal pool, because the size of
// the literal pool is already bounded by the literal range, which is smaller
// than the range of this branch.
VIXL_ASSERT(Instruction::GetImmBranchForwardRange(CompareBranchType) >
Instruction::kLoadLiteralRange);
VIXL_ASSERT(allow_macro_instructions_);
VIXL_ASSERT(!rt.IsZero());
EmissionCheckScope guard(this, 2 * kInstructionSize);
if (label->IsBound() && LabelIsOutOfRange(label, CondBranchType)) {
Label done;
cbnz(rt, &done);
b(label);
bind(&done);
} else {
if (!label->IsBound()) {
veneer_pool_.RegisterUnresolvedBranch(GetCursorOffset(),
label,
CompareBranchType);
}
cbz(rt, label);
}
}
void MacroAssembler::Tbnz(const Register& rt, unsigned bit_pos, Label* label) {
// This is to avoid a situation where emitting a veneer for a TBZ/TBNZ branch
// can become impossible because we emit the literal pool first.
literal_pool_.CheckEmitForBranch(
Instruction::GetImmBranchForwardRange(TestBranchType));
VIXL_ASSERT(allow_macro_instructions_);
VIXL_ASSERT(!rt.IsZero());
EmissionCheckScope guard(this, 2 * kInstructionSize);
if (label->IsBound() && LabelIsOutOfRange(label, TestBranchType)) {
Label done;
tbz(rt, bit_pos, &done);
b(label);
bind(&done);
} else {
if (!label->IsBound()) {
veneer_pool_.RegisterUnresolvedBranch(GetCursorOffset(),
label,
TestBranchType);
}
tbnz(rt, bit_pos, label);
}
}
void MacroAssembler::Tbz(const Register& rt, unsigned bit_pos, Label* label) {
// This is to avoid a situation where emitting a veneer for a TBZ/TBNZ branch
// can become impossible because we emit the literal pool first.
literal_pool_.CheckEmitForBranch(
Instruction::GetImmBranchForwardRange(TestBranchType));
VIXL_ASSERT(allow_macro_instructions_);
VIXL_ASSERT(!rt.IsZero());
EmissionCheckScope guard(this, 2 * kInstructionSize);
if (label->IsBound() && LabelIsOutOfRange(label, TestBranchType)) {
Label done;
tbnz(rt, bit_pos, &done);
b(label);
bind(&done);
} else {
if (!label->IsBound()) {
veneer_pool_.RegisterUnresolvedBranch(GetCursorOffset(),
label,
TestBranchType);
}
tbz(rt, bit_pos, label);
}
}
void MacroAssembler::Bind(Label* label, BranchTargetIdentifier id) {
VIXL_ASSERT(allow_macro_instructions_);
veneer_pool_.DeleteUnresolvedBranchInfoForLabel(label);
if (id == EmitBTI_none) {
bind(label);
} else {
// Emit this inside an ExactAssemblyScope to ensure there are no extra
// instructions between the bind and the target identifier instruction.
ExactAssemblyScope scope(this, kInstructionSize);
bind(label);
if (id == EmitPACIASP) {
paciasp();
} else if (id == EmitPACIBSP) {
pacibsp();
} else {
bti(id);
}
}
}
// Bind a label to a specified offset from the start of the buffer.
void MacroAssembler::BindToOffset(Label* label, ptrdiff_t offset) {
VIXL_ASSERT(allow_macro_instructions_);
veneer_pool_.DeleteUnresolvedBranchInfoForLabel(label);
Assembler::BindToOffset(label, offset);
}
void MacroAssembler::And(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, AND);
}
void MacroAssembler::Ands(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, ANDS);
}
void MacroAssembler::Tst(const Register& rn, const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
Ands(AppropriateZeroRegFor(rn), rn, operand);
}
void MacroAssembler::Bic(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, BIC);
}
void MacroAssembler::Bics(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, BICS);
}
void MacroAssembler::Orr(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, ORR);
}
void MacroAssembler::Orn(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, ORN);
}
void MacroAssembler::Eor(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, EOR);
}
void MacroAssembler::Eon(const Register& rd,
const Register& rn,
const Operand& operand) {
VIXL_ASSERT(allow_macro_instructions_);
LogicalMacro(rd, rn, operand, EON);
}
void MacroAssembler::LogicalMacro(const Register& rd,
const Register& rn,
const Operand& operand,
LogicalOp op) {
// The worst case for size is logical immediate to sp:
// * up to 4 instructions to materialise the constant
// * 1 instruction to do the operation
// * 1 instruction to move to sp
MacroEmissionCheckScope guard(this);
UseScratchRegisterScope temps(this);
// Use `rd` as a temp, if we can.
temps.Include(rd);
// We read `rn` after evaluating `operand`.
temps.Exclude(rn);
// It doesn't matter if `operand` is in `temps` (e.g. because it alises `rd`)
// because we don't need it after it is evaluated.
if (operand.IsImmediate()) {
uint64_t immediate = operand.GetImmediate();
unsigned reg_size = rd.GetSizeInBits();
// If the operation is NOT, invert the operation and immediate.
if ((op & NOT) == NOT) {
op = static_cast<LogicalOp>(op & ~NOT);
immediate = ~immediate;
}
// Ignore the top 32 bits of an immediate if we're moving to a W register.
if (rd.Is32Bits()) {
// Check that the top 32 bits are consistent.
VIXL_ASSERT(((immediate >> kWRegSize) == 0) ||
((immediate >> kWRegSize) == 0xffffffff));
immediate &= kWRegMask;
}
VIXL_ASSERT(rd.Is64Bits() || IsUint32(immediate));
// Special cases for all set or all clear immediates.
if (immediate == 0) {
switch (op) {
case AND:
Mov(rd, 0);
return;
case ORR:
VIXL_FALLTHROUGH();
case EOR:
Mov(rd, rn);
return;
case ANDS:
VIXL_FALLTHROUGH();
case BICS:
break;
default:
VIXL_UNREACHABLE();
}
} else if ((rd.Is64Bits() && (immediate == UINT64_C(0xffffffffffffffff))) ||
(rd.Is32Bits() && (immediate == UINT64_C(0x00000000ffffffff)))) {
switch (op) {
case AND:
Mov(rd, rn);
return;
case ORR:
Mov(rd, immediate);
return;
case EOR:
Mvn(rd, rn);
return;
case ANDS:
VIXL_FALLTHROUGH();
case BICS:
break;
default:
VIXL_UNREACHABLE();
}
}
unsigned n, imm_s, imm_r;
if (IsImmLogical(immediate, reg_size, &n, &imm_s, &imm_r)) {
// Immediate can be encoded in the instruction.
LogicalImmediate(rd, rn, n, imm_s, imm_r, op);
} else {
// Immediate can't be encoded: synthesize using move immediate.
Register temp = temps.AcquireSameSizeAs(rn);
VIXL_ASSERT(!temp.Aliases(rn));
// If the left-hand input is the stack pointer, we can't pre-shift the
// immediate, as the encoding won't allow the subsequent post shift.
PreShiftImmMode mode = rn.IsSP() ? kNoShift : kAnyShift;
Operand imm_operand = MoveImmediateForShiftedOp(temp, immediate, mode);
if (rd.Is(sp) || rd.Is(wsp)) {
// If rd is the stack pointer we cannot use it as the destination
// register so we use the temp register as an intermediate again.
Logical(temp, rn, imm_operand, op);
Mov(rd, temp);
} else {
Logical(rd, rn, imm_operand, op);
}
}
} else if (operand.IsExtendedRegister()) {
VIXL_ASSERT(operand.GetRegister().GetSizeInBits() <= rd.GetSizeInBits());
// Add/sub extended supports shift <= 4. We want to support exactly the
// same modes here.
VIXL_ASSERT(operand.GetShiftAmount() <= 4);
VIXL_ASSERT(
operand.GetRegister().Is64Bits() ||
((operand.GetExtend() != UXTX) && (operand.GetExtend() != SXTX)));
Register temp = temps.AcquireSameSizeAs(rn);
VIXL_ASSERT(!temp.Aliases(rn));
EmitExtendShift(temp,
operand.GetRegister(),
operand.GetExtend(),
operand.GetShiftAmount());
Logical(rd, rn, Operand(temp), op);
} else {
// The operand can be encoded in the instruction.
VIXL_ASSERT(operand.IsShiftedRegister());
Logical(rd, rn, operand, op);
}
}
void MacroAssembler::Mov(const Register& rd,
const Operand& operand,
DiscardMoveMode discard_mode) {
VIXL_ASSERT(allow_macro_instructions_);
// The worst case for size is mov immediate with up to 4 instructions.
MacroEmissionCheckScope guard(this);
if (operand.IsImmediate()) {
// Call the macro assembler for generic immediates.
Mov(rd, operand.GetImmediate());
} else if (operand.IsShiftedRegister() && (operand.GetShiftAmount() != 0)) {
// Emit a shift instruction if moving a shifted register. This operation
// could also be achieved using an orr instruction (like orn used by Mvn),
// but using a shift instruction makes the disassembly clearer.
EmitShift(rd,
operand.GetRegister(),
operand.GetShift(),
operand.GetShiftAmount());
} else if (operand.IsExtendedRegister()) {
// Emit an extend instruction if moving an extended register. This handles
// extend with post-shift operations, too.
EmitExtendShift(rd,
operand.GetRegister(),
operand.GetExtend(),
operand.GetShiftAmount());
} else {
Mov(rd, operand.GetRegister(), discard_mode);
}
}
void MacroAssembler::Movi16bitHelper(const VRegister& vd, uint64_t imm) {
VIXL_ASSERT(IsUint16(imm));
int byte1 = (imm & 0xff);
int byte2 = ((imm >> 8) & 0xff);
if (byte1 == byte2) {
movi(vd.Is64Bits() ? vd.V8B() : vd.V16B(), byte1);
} else if (byte1 == 0) {
movi(vd, byte2, LSL, 8);
} else if (byte2 == 0) {
movi(vd, byte1);
} else if (byte1 == 0xff) {
mvni(vd, ~byte2 & 0xff, LSL, 8);
} else if (byte2 == 0xff) {
mvni(vd, ~byte1 & 0xff);
} else {
UseScratchRegisterScope temps(this);
Register temp = temps.AcquireW();
movz(temp, imm);
dup(vd, temp);
}
}
void MacroAssembler::Movi32bitHelper(const VRegister& vd, uint64_t imm) {
VIXL_ASSERT(IsUint32(imm));
uint8_t bytes[sizeof(imm)];
memcpy(bytes, &imm, sizeof(imm));
// All bytes are either 0x00 or 0xff.
{
bool all0orff = true;
for (int i = 0; i < 4; ++i) {
if ((bytes[i] != 0) && (bytes[i] != 0xff)) {
all0orff = false;
break;
}
}
if (all0orff == true) {
movi(vd.Is64Bits() ? vd.V1D() : vd.V2D(), ((imm << 32) | imm));
return;
}
}
// Of the 4 bytes, only one byte is non-zero.
for (int i = 0; i < 4; i++) {
if ((imm & (0xff << (i * 8))) == imm) {
movi(vd, bytes[i], LSL, i * 8);
return;
}
}
// Of the 4 bytes, only one byte is not 0xff.
for (int i = 0; i < 4; i++) {
uint32_t mask = ~(0xff << (i * 8));
if ((imm & mask) == mask) {
mvni(vd, ~bytes[i] & 0xff, LSL, i * 8);
return;
}
}
// Immediate is of the form 0x00MMFFFF.
if ((imm & 0xff00ffff) == 0x0000ffff) {
movi(vd, bytes[2], MSL, 16);
return;
}