1//===-- AVRAsmBackend.cpp - AVR Asm Backend ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AVRAsmBackend class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MCTargetDesc/AVRAsmBackend.h"
14#include "MCTargetDesc/AVRFixupKinds.h"
15#include "MCTargetDesc/AVRMCTargetDesc.h"
16#include "llvm/ADT/StringSwitch.h"
17#include "llvm/MC/MCAsmBackend.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCELFObjectWriter.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
23#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSubtargetInfo.h"
25#include "llvm/MC/MCValue.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/raw_ostream.h"
29
30namespace adjust {
31
32using namespace llvm;
33
34static void unsigned_width(unsigned Width, uint64_t Value,
35 std::string Description, const MCFixup &Fixup,
36 MCContext *Ctx) {
37 if (!isUIntN(N: Width, x: Value)) {
38 std::string Diagnostic = "out of range " + Description;
39
40 int64_t Max = maxUIntN(N: Width);
41
42 Diagnostic +=
43 " (expected an integer in the range 0 to " + std::to_string(val: Max) + ")";
44
45 Ctx->reportError(L: Fixup.getLoc(), Msg: Diagnostic);
46 }
47}
48
49/// Adjusts the value of a branch target before fixup application.
50static void adjustBranch(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
51 MCContext *Ctx) {
52 // We have one extra bit of precision because the value is rightshifted by
53 // one.
54 unsigned_width(Width: Size + 1, Value, Description: std::string("branch target"), Fixup, Ctx);
55
56 // Rightshifts the value by one.
57 AVR::fixups::adjustBranchTarget(val&: Value);
58}
59
60/// Adjusts the value of a relative branch target before fixup application.
61static bool adjustRelativeBranch(unsigned Size, const MCFixup &Fixup,
62 uint64_t &Value, const MCSubtargetInfo *STI) {
63 // Jumps are relative to the current instruction.
64 Value -= 2;
65
66 // We have one extra bit of precision because the value is rightshifted by
67 // one.
68 Size += 1;
69
70 assert(STI && "STI can not be NULL");
71
72 if (!isIntN(N: Size, x: Value) && STI->hasFeature(Feature: AVR::FeatureWrappingRjmp)) {
73 const int32_t FlashSize = 0x2000;
74 int32_t SignedValue = Value;
75
76 uint64_t WrappedValue = SignedValue > 0 ? (uint64_t)(Value - FlashSize)
77 : (uint64_t)(FlashSize + Value);
78
79 if (isIntN(N: Size, x: WrappedValue)) {
80 Value = WrappedValue;
81 }
82 }
83
84 if (!isIntN(N: Size, x: Value)) {
85 return false;
86 }
87
88 // Rightshifts the value by one.
89 AVR::fixups::adjustBranchTarget(val&: Value);
90
91 return true;
92}
93
94/// 22-bit absolute fixup.
95///
96/// Resolves to:
97/// 1001 kkkk 010k kkkk kkkk kkkk 111k kkkk
98///
99/// Offset of 0 (so the result is left shifted by 3 bits before application).
100static void fixup_call(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
101 MCContext *Ctx) {
102 adjustBranch(Size, Fixup, Value, Ctx);
103
104 auto top = Value & (0xf00000 << 6); // the top four bits
105 auto middle = Value & (0x1ffff << 5); // the middle 13 bits
106 auto bottom = Value & 0x1f; // end bottom 5 bits
107
108 Value = (top << 6) | (middle << 3) | (bottom << 0);
109}
110
111/// 7-bit PC-relative fixup.
112///
113/// Resolves to:
114/// 0000 00kk kkkk k000
115/// Offset of 0 (so the result is left shifted by 3 bits before application).
116static void fixup_7_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
117 MCContext *Ctx) {
118 if (!adjustRelativeBranch(Size, Fixup, Value, STI: Ctx->getSubtargetInfo())) {
119 llvm_unreachable("should've been emitted as a relocation");
120 }
121
122 // Because the value may be negative, we must mask out the sign bits
123 Value &= 0x7f;
124}
125
126/// 12-bit PC-relative fixup.
127/// Yes, the fixup is 12 bits even though the name says otherwise.
128///
129/// Resolves to:
130/// 0000 kkkk kkkk kkkk
131/// Offset of 0 (so the result isn't left-shifted before application).
132static void fixup_13_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
133 MCContext *Ctx) {
134 if (!adjustRelativeBranch(Size, Fixup, Value, STI: Ctx->getSubtargetInfo())) {
135 llvm_unreachable("should've been emitted as a relocation");
136 }
137
138 // Because the value may be negative, we must mask out the sign bits
139 Value &= 0xfff;
140}
141
142/// 6-bit fixup for the immediate operand of the STD/LDD family of
143/// instructions.
144///
145/// Resolves to:
146/// 10q0 qq10 0000 1qqq
147static void fixup_6(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
148 unsigned_width(Width: 6, Value, Description: std::string("immediate"), Fixup, Ctx);
149
150 Value = ((Value & 0x20) << 8) | ((Value & 0x18) << 7) | (Value & 0x07);
151}
152
153/// 6-bit fixup for the immediate operand of the ADIW family of
154/// instructions.
155///
156/// Resolves to:
157/// 0000 0000 kk00 kkkk
158static void fixup_6_adiw(const MCFixup &Fixup, uint64_t &Value,
159 MCContext *Ctx) {
160 unsigned_width(Width: 6, Value, Description: std::string("immediate"), Fixup, Ctx);
161
162 Value = ((Value & 0x30) << 2) | (Value & 0x0f);
163}
164
165/// 5-bit port number fixup on the SBIC family of instructions.
166///
167/// Resolves to:
168/// 0000 0000 AAAA A000
169static void fixup_port5(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
170 unsigned_width(Width: 5, Value, Description: std::string("port number"), Fixup, Ctx);
171
172 Value &= 0x1f;
173
174 Value <<= 3;
175}
176
177/// 6-bit port number fixup on the IN family of instructions.
178///
179/// Resolves to:
180/// 1011 0AAd dddd AAAA
181static void fixup_port6(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
182 unsigned_width(Width: 6, Value, Description: std::string("port number"), Fixup, Ctx);
183
184 Value = ((Value & 0x30) << 5) | (Value & 0x0f);
185}
186
187/// 7-bit data space address fixup for the LDS/STS instructions on AVRTiny.
188///
189/// Resolves to:
190/// 1010 ikkk dddd kkkk
191static void fixup_lds_sts_16(const MCFixup &Fixup, uint64_t &Value,
192 MCContext *Ctx) {
193 unsigned_width(Width: 7, Value, Description: std::string("immediate"), Fixup, Ctx);
194 Value = ((Value & 0x70) << 8) | (Value & 0x0f);
195}
196
197/// Adjusts a program memory address.
198/// This is a simple right-shift.
199static void pm(uint64_t &Value) { Value >>= 1; }
200
201/// Fixups relating to the LDI instruction.
202namespace ldi {
203
204/// Adjusts a value to fix up the immediate of an `LDI Rd, K` instruction.
205///
206/// Resolves to:
207/// 0000 KKKK 0000 KKKK
208/// Offset of 0 (so the result isn't left-shifted before application).
209static void fixup(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
210 MCContext *Ctx) {
211 uint64_t upper = Value & 0xf0;
212 uint64_t lower = Value & 0x0f;
213
214 Value = (upper << 4) | lower;
215}
216
217static void neg(uint64_t &Value) { Value *= -1; }
218
219static void lo8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
220 MCContext *Ctx) {
221 Value &= 0xff;
222 ldi::fixup(Size, Fixup, Value, Ctx);
223}
224
225static void hi8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
226 MCContext *Ctx) {
227 Value = (Value & 0xff00) >> 8;
228 ldi::fixup(Size, Fixup, Value, Ctx);
229}
230
231static void hh8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
232 MCContext *Ctx) {
233 Value = (Value & 0xff0000) >> 16;
234 ldi::fixup(Size, Fixup, Value, Ctx);
235}
236
237static void ms8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
238 MCContext *Ctx) {
239 Value = (Value & 0xff000000) >> 24;
240 ldi::fixup(Size, Fixup, Value, Ctx);
241}
242
243} // namespace ldi
244} // namespace adjust
245
246namespace llvm {
247
248// Prepare value for the target space for it
249void AVRAsmBackend::adjustFixupValue(const MCFixup &Fixup,
250 const MCValue &Target, uint64_t &Value,
251 MCContext *Ctx) const {
252 // The size of the fixup in bits.
253 uint64_t Size = AVRAsmBackend::getFixupKindInfo(Kind: Fixup.getKind()).TargetSize;
254
255 unsigned Kind = Fixup.getKind();
256 switch (Kind) {
257 default:
258 llvm_unreachable("unhandled fixup");
259 case AVR::fixup_7_pcrel:
260 adjust::fixup_7_pcrel(Size, Fixup, Value, Ctx);
261 break;
262 case AVR::fixup_13_pcrel:
263 adjust::fixup_13_pcrel(Size, Fixup, Value, Ctx);
264 break;
265 case AVR::fixup_call:
266 adjust::fixup_call(Size, Fixup, Value, Ctx);
267 break;
268 case AVR::fixup_ldi:
269 adjust::ldi::fixup(Size, Fixup, Value, Ctx);
270 break;
271 case AVR::fixup_lo8_ldi:
272 adjust::ldi::lo8(Size, Fixup, Value, Ctx);
273 break;
274 case AVR::fixup_lo8_ldi_pm:
275 case AVR::fixup_lo8_ldi_gs:
276 adjust::pm(Value);
277 adjust::ldi::lo8(Size, Fixup, Value, Ctx);
278 break;
279 case AVR::fixup_hi8_ldi:
280 adjust::ldi::hi8(Size, Fixup, Value, Ctx);
281 break;
282 case AVR::fixup_hi8_ldi_pm:
283 case AVR::fixup_hi8_ldi_gs:
284 adjust::pm(Value);
285 adjust::ldi::hi8(Size, Fixup, Value, Ctx);
286 break;
287 case AVR::fixup_hh8_ldi:
288 case AVR::fixup_hh8_ldi_pm:
289 if (Kind == AVR::fixup_hh8_ldi_pm)
290 adjust::pm(Value);
291
292 adjust::ldi::hh8(Size, Fixup, Value, Ctx);
293 break;
294 case AVR::fixup_ms8_ldi:
295 adjust::ldi::ms8(Size, Fixup, Value, Ctx);
296 break;
297
298 case AVR::fixup_lo8_ldi_neg:
299 case AVR::fixup_lo8_ldi_pm_neg:
300 if (Kind == AVR::fixup_lo8_ldi_pm_neg)
301 adjust::pm(Value);
302
303 adjust::ldi::neg(Value);
304 adjust::ldi::lo8(Size, Fixup, Value, Ctx);
305 break;
306 case AVR::fixup_hi8_ldi_neg:
307 case AVR::fixup_hi8_ldi_pm_neg:
308 if (Kind == AVR::fixup_hi8_ldi_pm_neg)
309 adjust::pm(Value);
310
311 adjust::ldi::neg(Value);
312 adjust::ldi::hi8(Size, Fixup, Value, Ctx);
313 break;
314 case AVR::fixup_hh8_ldi_neg:
315 case AVR::fixup_hh8_ldi_pm_neg:
316 if (Kind == AVR::fixup_hh8_ldi_pm_neg)
317 adjust::pm(Value);
318
319 adjust::ldi::neg(Value);
320 adjust::ldi::hh8(Size, Fixup, Value, Ctx);
321 break;
322 case AVR::fixup_ms8_ldi_neg:
323 adjust::ldi::neg(Value);
324 adjust::ldi::ms8(Size, Fixup, Value, Ctx);
325 break;
326 case AVR::fixup_16:
327 adjust::unsigned_width(Width: 16, Value, Description: std::string("port number"), Fixup, Ctx);
328
329 Value &= 0xffff;
330 break;
331 case AVR::fixup_16_pm:
332 Value >>= 1; // Flash addresses are always shifted.
333 adjust::unsigned_width(Width: 16, Value, Description: std::string("port number"), Fixup, Ctx);
334
335 Value &= 0xffff;
336 break;
337
338 case AVR::fixup_6:
339 adjust::fixup_6(Fixup, Value, Ctx);
340 break;
341 case AVR::fixup_6_adiw:
342 adjust::fixup_6_adiw(Fixup, Value, Ctx);
343 break;
344
345 case AVR::fixup_port5:
346 adjust::fixup_port5(Fixup, Value, Ctx);
347 break;
348
349 case AVR::fixup_port6:
350 adjust::fixup_port6(Fixup, Value, Ctx);
351 break;
352
353 case AVR::fixup_lds_sts_16:
354 adjust::fixup_lds_sts_16(Fixup, Value, Ctx);
355 break;
356
357 // Fixups which do not require adjustments.
358 case FK_Data_1:
359 case FK_Data_2:
360 case FK_Data_4:
361 case FK_Data_8:
362 break;
363 }
364}
365
366std::unique_ptr<MCObjectTargetWriter>
367AVRAsmBackend::createObjectTargetWriter() const {
368 return createAVRELFObjectWriter(OSABI: MCELFObjectTargetWriter::getOSABI(OSType));
369}
370
371void AVRAsmBackend::applyFixup(const MCFragment &F, const MCFixup &Fixup,
372 const MCValue &Target,
373 MutableArrayRef<char> Data, uint64_t Value,
374 bool IsResolved) {
375 // AVR sets the fixup value to bypass the assembly time overflow with a
376 // relocation.
377 if (IsResolved) {
378 auto TargetVal = MCValue::get(SymA: Target.getAddSym(), SymB: Target.getSubSym(), Val: Value,
379 Specifier: Target.getSpecifier());
380 if (forceRelocation(F, Fixup, Target: TargetVal))
381 IsResolved = false;
382 }
383 if (!IsResolved)
384 Asm->getWriter().recordRelocation(F, Fixup, Target, FixedValue&: Value);
385
386 if (mc::isRelocation(FixupKind: Fixup.getKind()))
387 return;
388 adjustFixupValue(Fixup, Target, Value, Ctx: &getContext());
389 if (Value == 0)
390 return; // Doesn't change encoding.
391
392 MCFixupKindInfo Info = getFixupKindInfo(Kind: Fixup.getKind());
393
394 // The number of bits in the fixup mask
395 unsigned NumBits = Info.TargetSize + Info.TargetOffset;
396 auto NumBytes = (NumBits / 8) + ((NumBits % 8) == 0 ? 0 : 1);
397
398 // Shift the value into position.
399 Value <<= Info.TargetOffset;
400
401 unsigned Offset = Fixup.getOffset();
402 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
403
404 // For each byte of the fragment that the fixup touches, mask in the
405 // bits from the fixup value.
406 for (unsigned i = 0; i < NumBytes; ++i) {
407 uint8_t mask = (((Value >> (i * 8)) & 0xff));
408 Data[Offset + i] |= mask;
409 }
410}
411
412std::optional<MCFixupKind> AVRAsmBackend::getFixupKind(StringRef Name) const {
413 unsigned Type;
414 Type = llvm::StringSwitch<unsigned>(Name)
415#define ELF_RELOC(X, Y) .Case(#X, Y)
416#include "llvm/BinaryFormat/ELFRelocs/AVR.def"
417#undef ELF_RELOC
418 .Case(S: "BFD_RELOC_NONE", Value: ELF::R_AVR_NONE)
419 .Case(S: "BFD_RELOC_16", Value: ELF::R_AVR_16)
420 .Case(S: "BFD_RELOC_32", Value: ELF::R_AVR_32)
421 .Default(Value: -1u);
422 if (Type != -1u)
423 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
424 return std::nullopt;
425}
426
427MCFixupKindInfo AVRAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
428 // NOTE: Many AVR fixups work on sets of non-contignous bits. We work around
429 // this by saying that the fixup is the size of the entire instruction.
430 const static MCFixupKindInfo Infos[AVR::NumTargetFixupKinds] = {
431 // This table *must* be in same the order of fixup_* kinds in
432 // AVRFixupKinds.h.
433 //
434 // name offset bits flags
435 {.Name: "fixup_32", .TargetOffset: 0, .TargetSize: 32, .Flags: 0},
436
437 {.Name: "fixup_7_pcrel", .TargetOffset: 3, .TargetSize: 7, .Flags: MCFixupKindInfo::FKF_IsPCRel},
438 {.Name: "fixup_13_pcrel", .TargetOffset: 0, .TargetSize: 12, .Flags: MCFixupKindInfo::FKF_IsPCRel},
439
440 {.Name: "fixup_16", .TargetOffset: 0, .TargetSize: 16, .Flags: 0},
441 {.Name: "fixup_16_pm", .TargetOffset: 0, .TargetSize: 16, .Flags: 0},
442
443 {.Name: "fixup_ldi", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
444
445 {.Name: "fixup_lo8_ldi", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
446 {.Name: "fixup_hi8_ldi", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
447 {.Name: "fixup_hh8_ldi", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
448 {.Name: "fixup_ms8_ldi", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
449
450 {.Name: "fixup_lo8_ldi_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
451 {.Name: "fixup_hi8_ldi_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
452 {.Name: "fixup_hh8_ldi_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
453 {.Name: "fixup_ms8_ldi_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
454
455 {.Name: "fixup_lo8_ldi_pm", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
456 {.Name: "fixup_hi8_ldi_pm", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
457 {.Name: "fixup_hh8_ldi_pm", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
458
459 {.Name: "fixup_lo8_ldi_pm_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
460 {.Name: "fixup_hi8_ldi_pm_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
461 {.Name: "fixup_hh8_ldi_pm_neg", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
462
463 {.Name: "fixup_call", .TargetOffset: 0, .TargetSize: 22, .Flags: 0},
464
465 {.Name: "fixup_6", .TargetOffset: 0, .TargetSize: 16, .Flags: 0}, // non-contiguous
466 {.Name: "fixup_6_adiw", .TargetOffset: 0, .TargetSize: 6, .Flags: 0},
467
468 {.Name: "fixup_lo8_ldi_gs", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
469 {.Name: "fixup_hi8_ldi_gs", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
470
471 {.Name: "fixup_8", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
472 {.Name: "fixup_8_lo8", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
473 {.Name: "fixup_8_hi8", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
474 {.Name: "fixup_8_hlo8", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
475
476 {.Name: "fixup_diff8", .TargetOffset: 0, .TargetSize: 8, .Flags: 0},
477 {.Name: "fixup_diff16", .TargetOffset: 0, .TargetSize: 16, .Flags: 0},
478 {.Name: "fixup_diff32", .TargetOffset: 0, .TargetSize: 32, .Flags: 0},
479
480 {.Name: "fixup_lds_sts_16", .TargetOffset: 0, .TargetSize: 16, .Flags: 0},
481
482 {.Name: "fixup_port6", .TargetOffset: 0, .TargetSize: 16, .Flags: 0}, // non-contiguous
483 {.Name: "fixup_port5", .TargetOffset: 3, .TargetSize: 5, .Flags: 0},
484 };
485
486 // Fixup kinds from .reloc directive are like R_AVR_NONE. They do not require
487 // any extra processing.
488 if (mc::isRelocation(FixupKind: Kind))
489 return MCAsmBackend::getFixupKindInfo(Kind: FK_NONE);
490
491 if (Kind < FirstTargetFixupKind)
492 return MCAsmBackend::getFixupKindInfo(Kind);
493
494 assert(unsigned(Kind - FirstTargetFixupKind) < AVR::NumTargetFixupKinds &&
495 "Invalid kind!");
496
497 return Infos[Kind - FirstTargetFixupKind];
498}
499
500bool AVRAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
501 const MCSubtargetInfo *STI) const {
502 // If the count is not 2-byte aligned, we must be writing data into the text
503 // section (otherwise we have unaligned instructions, and thus have far
504 // bigger problems), so just write zeros instead.
505 assert((Count % 2) == 0 && "NOP instructions must be 2 bytes");
506
507 OS.write_zeros(NumZeros: Count);
508 return true;
509}
510
511bool AVRAsmBackend::forceRelocation(const MCFragment &F, const MCFixup &Fixup,
512 const MCValue &Target) {
513 switch ((unsigned)Fixup.getKind()) {
514 default:
515 return false;
516
517 case AVR::fixup_7_pcrel:
518 case AVR::fixup_13_pcrel: {
519 uint64_t Offset = Target.getConstant();
520 uint64_t Size = AVRAsmBackend::getFixupKindInfo(Kind: Fixup.getKind()).TargetSize;
521
522 // If the jump is too large to encode it, fall back to a relocation.
523 //
524 // Note that trying to actually link that relocation *would* fail, but the
525 // hopes are that the module we're currently compiling won't be actually
526 // linked to the final binary.
527 return !adjust::adjustRelativeBranch(Size, Fixup, Value&: Offset,
528 STI: getContext().getSubtargetInfo());
529 }
530
531 case AVR::fixup_call:
532 return true;
533 }
534}
535
536MCAsmBackend *createAVRAsmBackend(const Target &T, const MCSubtargetInfo &STI,
537 const MCRegisterInfo &MRI,
538 const llvm::MCTargetOptions &TO) {
539 return new AVRAsmBackend(STI.getTargetTriple().getOS());
540}
541
542} // end of namespace llvm
543