xref: /llvm-project/llvm/lib/Target/AVR/MCTargetDesc/AVRAsmBackend.cpp (revision 814b34f31e163e76b816194004689985f5b9fd7b)
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 
30 namespace adjust {
31 
32 using namespace llvm;
33 
34 static void unsigned_width(unsigned Width, uint64_t Value,
35                            std::string Description, const MCFixup &Fixup,
36                            MCContext *Ctx) {
37   if (!isUIntN(Width, Value)) {
38     std::string Diagnostic = "out of range " + Description;
39 
40     int64_t Max = maxUIntN(Width);
41 
42     Diagnostic +=
43         " (expected an integer in the range 0 to " + std::to_string(Max) + ")";
44 
45     Ctx->reportError(Fixup.getLoc(), Diagnostic);
46   }
47 }
48 
49 /// Adjusts the value of a branch target before fixup application.
50 static 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(Size + 1, Value, std::string("branch target"), Fixup, Ctx);
55 
56   // Rightshifts the value by one.
57   AVR::fixups::adjustBranchTarget(Value);
58 }
59 
60 /// Adjusts the value of a relative branch target before fixup application.
61 static 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(Size, Value) && STI->hasFeature(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(Size, WrappedValue)) {
80       Value = WrappedValue;
81     }
82   }
83 
84   if (!isIntN(Size, Value)) {
85     return false;
86   }
87 
88   // Rightshifts the value by one.
89   AVR::fixups::adjustBranchTarget(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).
100 static 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).
116 static void fixup_7_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
117                           MCContext *Ctx) {
118   if (!adjustRelativeBranch(Size, Fixup, Value, 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).
132 static void fixup_13_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
133                            MCContext *Ctx) {
134   if (!adjustRelativeBranch(Size, Fixup, Value, 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
147 static void fixup_6(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
148   unsigned_width(6, Value, 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
158 static void fixup_6_adiw(const MCFixup &Fixup, uint64_t &Value,
159                          MCContext *Ctx) {
160   unsigned_width(6, Value, 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
169 static void fixup_port5(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
170   unsigned_width(5, Value, 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
181 static void fixup_port6(const MCFixup &Fixup, uint64_t &Value, MCContext *Ctx) {
182   unsigned_width(6, Value, 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
191 static void fixup_lds_sts_16(const MCFixup &Fixup, uint64_t &Value,
192                              MCContext *Ctx) {
193   unsigned_width(7, Value, 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.
199 static void pm(uint64_t &Value) { Value >>= 1; }
200 
201 /// Fixups relating to the LDI instruction.
202 namespace 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).
209 static 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 
217 static void neg(uint64_t &Value) { Value *= -1; }
218 
219 static 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 
225 static 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 
231 static 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 
237 static 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 
246 namespace llvm {
247 
248 // Prepare value for the target space for it
249 void 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(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(16, Value, 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(16, Value, 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   case FK_GPRel_4:
365     llvm_unreachable("don't know how to adjust this fixup");
366     break;
367   }
368 }
369 
370 std::unique_ptr<MCObjectTargetWriter>
371 AVRAsmBackend::createObjectTargetWriter() const {
372   return createAVRELFObjectWriter(MCELFObjectTargetWriter::getOSABI(OSType));
373 }
374 
375 void AVRAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
376                                const MCValue &Target,
377                                MutableArrayRef<char> Data, uint64_t Value,
378                                bool IsResolved,
379                                const MCSubtargetInfo *STI) const {
380   if (Fixup.getKind() >= FirstLiteralRelocationKind)
381     return;
382   adjustFixupValue(Fixup, Target, Value, &Asm.getContext());
383   if (Value == 0)
384     return; // Doesn't change encoding.
385 
386   MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
387 
388   // The number of bits in the fixup mask
389   auto NumBits = Info.TargetSize + Info.TargetOffset;
390   auto NumBytes = (NumBits / 8) + ((NumBits % 8) == 0 ? 0 : 1);
391 
392   // Shift the value into position.
393   Value <<= Info.TargetOffset;
394 
395   unsigned Offset = Fixup.getOffset();
396   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
397 
398   // For each byte of the fragment that the fixup touches, mask in the
399   // bits from the fixup value.
400   for (unsigned i = 0; i < NumBytes; ++i) {
401     uint8_t mask = (((Value >> (i * 8)) & 0xff));
402     Data[Offset + i] |= mask;
403   }
404 }
405 
406 std::optional<MCFixupKind> AVRAsmBackend::getFixupKind(StringRef Name) const {
407   unsigned Type;
408   Type = llvm::StringSwitch<unsigned>(Name)
409 #define ELF_RELOC(X, Y) .Case(#X, Y)
410 #include "llvm/BinaryFormat/ELFRelocs/AVR.def"
411 #undef ELF_RELOC
412              .Case("BFD_RELOC_NONE", ELF::R_AVR_NONE)
413              .Case("BFD_RELOC_16", ELF::R_AVR_16)
414              .Case("BFD_RELOC_32", ELF::R_AVR_32)
415              .Default(-1u);
416   if (Type != -1u)
417     return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
418   return std::nullopt;
419 }
420 
421 MCFixupKindInfo const &AVRAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
422   // NOTE: Many AVR fixups work on sets of non-contignous bits. We work around
423   // this by saying that the fixup is the size of the entire instruction.
424   const static MCFixupKindInfo Infos[AVR::NumTargetFixupKinds] = {
425       // This table *must* be in same the order of fixup_* kinds in
426       // AVRFixupKinds.h.
427       //
428       // name                    offset  bits  flags
429       {"fixup_32", 0, 32, 0},
430 
431       {"fixup_7_pcrel", 3, 7, MCFixupKindInfo::FKF_IsPCRel},
432       {"fixup_13_pcrel", 0, 12, MCFixupKindInfo::FKF_IsPCRel},
433 
434       {"fixup_16", 0, 16, 0},
435       {"fixup_16_pm", 0, 16, 0},
436 
437       {"fixup_ldi", 0, 8, 0},
438 
439       {"fixup_lo8_ldi", 0, 8, 0},
440       {"fixup_hi8_ldi", 0, 8, 0},
441       {"fixup_hh8_ldi", 0, 8, 0},
442       {"fixup_ms8_ldi", 0, 8, 0},
443 
444       {"fixup_lo8_ldi_neg", 0, 8, 0},
445       {"fixup_hi8_ldi_neg", 0, 8, 0},
446       {"fixup_hh8_ldi_neg", 0, 8, 0},
447       {"fixup_ms8_ldi_neg", 0, 8, 0},
448 
449       {"fixup_lo8_ldi_pm", 0, 8, 0},
450       {"fixup_hi8_ldi_pm", 0, 8, 0},
451       {"fixup_hh8_ldi_pm", 0, 8, 0},
452 
453       {"fixup_lo8_ldi_pm_neg", 0, 8, 0},
454       {"fixup_hi8_ldi_pm_neg", 0, 8, 0},
455       {"fixup_hh8_ldi_pm_neg", 0, 8, 0},
456 
457       {"fixup_call", 0, 22, 0},
458 
459       {"fixup_6", 0, 16, 0}, // non-contiguous
460       {"fixup_6_adiw", 0, 6, 0},
461 
462       {"fixup_lo8_ldi_gs", 0, 8, 0},
463       {"fixup_hi8_ldi_gs", 0, 8, 0},
464 
465       {"fixup_8", 0, 8, 0},
466       {"fixup_8_lo8", 0, 8, 0},
467       {"fixup_8_hi8", 0, 8, 0},
468       {"fixup_8_hlo8", 0, 8, 0},
469 
470       {"fixup_diff8", 0, 8, 0},
471       {"fixup_diff16", 0, 16, 0},
472       {"fixup_diff32", 0, 32, 0},
473 
474       {"fixup_lds_sts_16", 0, 16, 0},
475 
476       {"fixup_port6", 0, 16, 0}, // non-contiguous
477       {"fixup_port5", 3, 5, 0},
478   };
479 
480   // Fixup kinds from .reloc directive are like R_AVR_NONE. They do not require
481   // any extra processing.
482   if (Kind >= FirstLiteralRelocationKind)
483     return MCAsmBackend::getFixupKindInfo(FK_NONE);
484 
485   if (Kind < FirstTargetFixupKind)
486     return MCAsmBackend::getFixupKindInfo(Kind);
487 
488   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
489          "Invalid kind!");
490 
491   return Infos[Kind - FirstTargetFixupKind];
492 }
493 
494 bool AVRAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
495                                  const MCSubtargetInfo *STI) const {
496   // If the count is not 2-byte aligned, we must be writing data into the text
497   // section (otherwise we have unaligned instructions, and thus have far
498   // bigger problems), so just write zeros instead.
499   assert((Count % 2) == 0 && "NOP instructions must be 2 bytes");
500 
501   OS.write_zeros(Count);
502   return true;
503 }
504 
505 bool AVRAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
506                                           const MCFixup &Fixup,
507                                           const MCValue &Target,
508                                           const uint64_t Value,
509                                           const MCSubtargetInfo *STI) {
510   switch ((unsigned)Fixup.getKind()) {
511   default:
512     return Fixup.getKind() >= FirstLiteralRelocationKind;
513 
514   case AVR::fixup_7_pcrel:
515   case AVR::fixup_13_pcrel: {
516     uint64_t ValueEx = Value;
517     uint64_t Size = AVRAsmBackend::getFixupKindInfo(Fixup.getKind()).TargetSize;
518 
519     // If the jump is too large to encode it, fall back to a relocation.
520     //
521     // Note that trying to actually link that relocation *would* fail, but the
522     // hopes are that the module we're currently compiling won't be actually
523     // linked to the final binary.
524     return !adjust::adjustRelativeBranch(Size, Fixup, ValueEx, STI);
525   }
526 
527   case AVR::fixup_call:
528     return true;
529   }
530 }
531 
532 MCAsmBackend *createAVRAsmBackend(const Target &T, const MCSubtargetInfo &STI,
533                                   const MCRegisterInfo &MRI,
534                                   const llvm::MCTargetOptions &TO) {
535   return new AVRAsmBackend(STI.getTargetTriple().getOS());
536 }
537 
538 } // end of namespace llvm
539