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 
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDirectives.h"
21 #include "llvm/MC/MCELFObjectWriter.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 // FIXME: we should be doing checks to make sure asm operands
31 // are not out of bounds.
32 
33 namespace adjust {
34 
35 using namespace llvm;
36 
37 static void signed_width(unsigned Width, uint64_t Value,
38                          std::string Description, const MCFixup &Fixup,
39                          MCContext *Ctx = nullptr) {
40   if (!isIntN(Width, Value)) {
41     std::string Diagnostic = "out of range " + Description;
42 
43     int64_t Min = minIntN(Width);
44     int64_t Max = maxIntN(Width);
45 
46     Diagnostic += " (expected an integer in the range " + std::to_string(Min) +
47       " to " + std::to_string(Max) + ")";
48 
49     if (Ctx) {
50       Ctx->reportFatalError(Fixup.getLoc(), Diagnostic);
51     } else {
52       llvm_unreachable(Diagnostic.c_str());
53     }
54   }
55 }
56 
57 static void unsigned_width(unsigned Width, uint64_t Value,
58                            std::string Description, const MCFixup &Fixup,
59                            MCContext *Ctx = nullptr) {
60   if (!isUIntN(Width, Value)) {
61     std::string Diagnostic = "out of range " + Description;
62 
63     int64_t Max = maxUIntN(Width);
64 
65     Diagnostic += " (expected an integer in the range 0 to " +
66       std::to_string(Max) + ")";
67 
68     if (Ctx) {
69       Ctx->reportFatalError(Fixup.getLoc(), Diagnostic);
70     } else {
71       llvm_unreachable(Diagnostic.c_str());
72     }
73   }
74 }
75 
76 /// Adjusts the value of a branch target before fixup application.
77 static void adjustBranch(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
78                          MCContext *Ctx = nullptr) {
79   // We have one extra bit of precision because the value is rightshifted by
80   // one.
81   unsigned_width(Size + 1, Value, std::string("branch target"), Fixup, Ctx);
82 
83   // Rightshifts the value by one.
84   AVR::fixups::adjustBranchTarget(Value);
85 }
86 
87 /// Adjusts the value of a relative branch target before fixup application.
88 static void adjustRelativeBranch(unsigned Size, const MCFixup &Fixup,
89                                  uint64_t &Value, MCContext *Ctx = nullptr) {
90   // We have one extra bit of precision because the value is rightshifted by
91   // one.
92   signed_width(Size + 1, Value, std::string("branch target"), Fixup, Ctx);
93 
94   Value -= 2;
95 
96   // Rightshifts the value by one.
97   AVR::fixups::adjustBranchTarget(Value);
98 }
99 
100 /// 22-bit absolute fixup.
101 ///
102 /// Resolves to:
103 /// 1001 kkkk 010k kkkk kkkk kkkk 111k kkkk
104 ///
105 /// Offset of 0 (so the result is left shifted by 3 bits before application).
106 static void fixup_call(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
107                        MCContext *Ctx = nullptr) {
108   adjustBranch(Size, Fixup, Value, Ctx);
109 
110   auto top = Value & (0xf00000 << 6);   // the top four bits
111   auto middle = Value & (0x1ffff << 5); // the middle 13 bits
112   auto bottom = Value & 0x1f;           // end bottom 5 bits
113 
114   Value = (top << 6) | (middle << 3) | (bottom << 0);
115 }
116 
117 /// 7-bit PC-relative fixup.
118 ///
119 /// Resolves to:
120 /// 0000 00kk kkkk k000
121 /// Offset of 0 (so the result is left shifted by 3 bits before application).
122 static void fixup_7_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
123                           MCContext *Ctx = nullptr) {
124   adjustRelativeBranch(Size, Fixup, Value, Ctx);
125 
126   // Because the value may be negative, we must mask out the sign bits
127   Value &= 0x7f;
128 }
129 
130 /// 12-bit PC-relative fixup.
131 /// Yes, the fixup is 12 bits even though the name says otherwise.
132 ///
133 /// Resolves to:
134 /// 0000 kkkk kkkk kkkk
135 /// Offset of 0 (so the result isn't left-shifted before application).
136 static void fixup_13_pcrel(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
137                            MCContext *Ctx = nullptr) {
138   adjustRelativeBranch(Size, Fixup, Value, Ctx);
139 
140   // Because the value may be negative, we must mask out the sign bits
141   Value &= 0xfff;
142 }
143 
144 /// 6-bit fixup for the immediate operand of the ADIW family of
145 /// instructions.
146 ///
147 /// Resolves to:
148 /// 0000 0000 kk00 kkkk
149 static void fixup_6_adiw(const MCFixup &Fixup, uint64_t &Value,
150                          MCContext *Ctx = nullptr) {
151   unsigned_width(6, Value, std::string("immediate"), Fixup, Ctx);
152 
153   Value = ((Value & 0x30) << 2) | (Value & 0x0f);
154 }
155 
156 /// 5-bit port number fixup on the SBIC family of instructions.
157 ///
158 /// Resolves to:
159 /// 0000 0000 AAAA A000
160 static void fixup_port5(const MCFixup &Fixup, uint64_t &Value,
161                         MCContext *Ctx = nullptr) {
162   unsigned_width(5, Value, std::string("port number"), Fixup, Ctx);
163 
164   Value &= 0x1f;
165 
166   Value <<= 3;
167 }
168 
169 /// 6-bit port number fixup on the `IN` family of instructions.
170 ///
171 /// Resolves to:
172 /// 1011 0AAd dddd AAAA
173 static void fixup_port6(const MCFixup &Fixup, uint64_t &Value,
174                         MCContext *Ctx = nullptr) {
175   unsigned_width(6, Value, std::string("port number"), Fixup, Ctx);
176 
177   Value = ((Value & 0x30) << 5) | (Value & 0x0f);
178 }
179 
180 /// Adjusts a program memory address.
181 /// This is a simple right-shift.
182 static void pm(uint64_t &Value) { Value >>= 1; }
183 
184 /// Fixups relating to the LDI instruction.
185 namespace ldi {
186 
187 /// Adjusts a value to fix up the immediate of an `LDI Rd, K` instruction.
188 ///
189 /// Resolves to:
190 /// 0000 KKKK 0000 KKKK
191 /// Offset of 0 (so the result isn't left-shifted before application).
192 static void fixup(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
193                   MCContext *Ctx = nullptr) {
194   uint64_t upper = Value & 0xf0;
195   uint64_t lower = Value & 0x0f;
196 
197   Value = (upper << 4) | lower;
198 }
199 
200 static void neg(uint64_t &Value) { Value *= -1; }
201 
202 static void lo8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
203                 MCContext *Ctx = nullptr) {
204   Value &= 0xff;
205   ldi::fixup(Size, Fixup, Value, Ctx);
206 }
207 
208 static void hi8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
209                 MCContext *Ctx = nullptr) {
210   Value = (Value & 0xff00) >> 8;
211   ldi::fixup(Size, Fixup, Value, Ctx);
212 }
213 
214 static void hh8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
215                 MCContext *Ctx = nullptr) {
216   Value = (Value & 0xff0000) >> 16;
217   ldi::fixup(Size, Fixup, Value, Ctx);
218 }
219 
220 static void ms8(unsigned Size, const MCFixup &Fixup, uint64_t &Value,
221                 MCContext *Ctx = nullptr) {
222   Value = (Value & 0xff000000) >> 24;
223   ldi::fixup(Size, Fixup, Value, Ctx);
224 }
225 
226 } // end of ldi namespace
227 } // end of adjust namespace
228 
229 namespace llvm {
230 
231 // Prepare value for the target space for it
232 void AVRAsmBackend::adjustFixupValue(const MCFixup &Fixup,
233                                      const MCValue &Target,
234                                      uint64_t &Value,
235                                      MCContext *Ctx) const {
236   // The size of the fixup in bits.
237   uint64_t Size = AVRAsmBackend::getFixupKindInfo(Fixup.getKind()).TargetSize;
238 
239   unsigned Kind = Fixup.getKind();
240 
241   // Parsed LLVM-generated temporary labels are already
242   // adjusted for instruction size, but normal labels aren't.
243   //
244   // To handle both cases, we simply un-adjust the temporary label
245   // case so it acts like all other labels.
246   if (const MCSymbolRefExpr *A = Target.getSymA()) {
247     if (A->getSymbol().isTemporary()) {
248       switch (Kind) {
249       case FK_Data_1:
250       case FK_Data_2:
251       case FK_Data_4:
252       case FK_Data_8:
253         // Don't shift value for absolute addresses.
254         break;
255       default:
256         Value += 2;
257       }
258     }
259   }
260 
261   switch (Kind) {
262   default:
263     llvm_unreachable("unhandled fixup");
264   case AVR::fixup_7_pcrel:
265     adjust::fixup_7_pcrel(Size, Fixup, Value, Ctx);
266     break;
267   case AVR::fixup_13_pcrel:
268     adjust::fixup_13_pcrel(Size, Fixup, Value, Ctx);
269     break;
270   case AVR::fixup_call:
271     adjust::fixup_call(Size, Fixup, Value, Ctx);
272     break;
273   case AVR::fixup_ldi:
274     adjust::ldi::fixup(Size, Fixup, Value, Ctx);
275     break;
276   case AVR::fixup_lo8_ldi:
277     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
278     break;
279   case AVR::fixup_lo8_ldi_pm:
280   case AVR::fixup_lo8_ldi_gs:
281     adjust::pm(Value);
282     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
283     break;
284   case AVR::fixup_hi8_ldi:
285     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
286     break;
287   case AVR::fixup_hi8_ldi_pm:
288   case AVR::fixup_hi8_ldi_gs:
289     adjust::pm(Value);
290     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
291     break;
292   case AVR::fixup_hh8_ldi:
293   case AVR::fixup_hh8_ldi_pm:
294     if (Kind == AVR::fixup_hh8_ldi_pm) adjust::pm(Value);
295 
296     adjust::ldi::hh8(Size, Fixup, Value, Ctx);
297     break;
298   case AVR::fixup_ms8_ldi:
299     adjust::ldi::ms8(Size, Fixup, Value, Ctx);
300     break;
301 
302   case AVR::fixup_lo8_ldi_neg:
303   case AVR::fixup_lo8_ldi_pm_neg:
304     if (Kind == AVR::fixup_lo8_ldi_pm_neg) adjust::pm(Value);
305 
306     adjust::ldi::neg(Value);
307     adjust::ldi::lo8(Size, Fixup, Value, Ctx);
308     break;
309   case AVR::fixup_hi8_ldi_neg:
310   case AVR::fixup_hi8_ldi_pm_neg:
311     if (Kind == AVR::fixup_hi8_ldi_pm_neg) adjust::pm(Value);
312 
313     adjust::ldi::neg(Value);
314     adjust::ldi::hi8(Size, Fixup, Value, Ctx);
315     break;
316   case AVR::fixup_hh8_ldi_neg:
317   case AVR::fixup_hh8_ldi_pm_neg:
318     if (Kind == AVR::fixup_hh8_ldi_pm_neg) adjust::pm(Value);
319 
320     adjust::ldi::neg(Value);
321     adjust::ldi::hh8(Size, Fixup, Value, Ctx);
322     break;
323   case AVR::fixup_ms8_ldi_neg:
324     adjust::ldi::neg(Value);
325     adjust::ldi::ms8(Size, Fixup, Value, Ctx);
326     break;
327   case AVR::fixup_16:
328     adjust::unsigned_width(16, Value, std::string("port number"), Fixup, Ctx);
329 
330     Value &= 0xffff;
331     break;
332   case AVR::fixup_16_pm:
333     Value >>= 1; // Flash addresses are always shifted.
334     adjust::unsigned_width(16, Value, std::string("port number"), Fixup, Ctx);
335 
336     Value &= 0xffff;
337     break;
338 
339   case AVR::fixup_6_adiw:
340     adjust::fixup_6_adiw(Fixup, Value, Ctx);
341     break;
342 
343   case AVR::fixup_port5:
344     adjust::fixup_port5(Fixup, Value, Ctx);
345     break;
346 
347   case AVR::fixup_port6:
348     adjust::fixup_port6(Fixup, Value, Ctx);
349     break;
350 
351   // Fixups which do not require adjustments.
352   case FK_Data_1:
353   case FK_Data_2:
354   case FK_Data_4:
355   case FK_Data_8:
356     break;
357 
358   case FK_GPRel_4:
359     llvm_unreachable("don't know how to adjust this fixup");
360     break;
361   }
362 }
363 
364 std::unique_ptr<MCObjectTargetWriter>
365 AVRAsmBackend::createObjectTargetWriter() const {
366   return createAVRELFObjectWriter(MCELFObjectTargetWriter::getOSABI(OSType));
367 }
368 
369 void AVRAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
370                                const MCValue &Target,
371                                MutableArrayRef<char> Data, uint64_t Value,
372                                bool IsResolved,
373                                const MCSubtargetInfo *STI) const {
374   adjustFixupValue(Fixup, Target, Value, &Asm.getContext());
375   if (Value == 0)
376     return; // Doesn't change encoding.
377 
378   MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
379 
380   // The number of bits in the fixup mask
381   auto NumBits = Info.TargetSize + Info.TargetOffset;
382   auto NumBytes = (NumBits / 8) + ((NumBits % 8) == 0 ? 0 : 1);
383 
384   // Shift the value into position.
385   Value <<= Info.TargetOffset;
386 
387   unsigned Offset = Fixup.getOffset();
388   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
389 
390   // For each byte of the fragment that the fixup touches, mask in the
391   // bits from the fixup value.
392   for (unsigned i = 0; i < NumBytes; ++i) {
393     uint8_t mask = (((Value >> (i * 8)) & 0xff));
394     Data[Offset + i] |= mask;
395   }
396 }
397 
398 MCFixupKindInfo const &AVRAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
399   // NOTE: Many AVR fixups work on sets of non-contignous bits. We work around
400   // this by saying that the fixup is the size of the entire instruction.
401   const static MCFixupKindInfo Infos[AVR::NumTargetFixupKinds] = {
402       // This table *must* be in same the order of fixup_* kinds in
403       // AVRFixupKinds.h.
404       //
405       // name                    offset  bits  flags
406       {"fixup_32", 0, 32, 0},
407 
408       {"fixup_7_pcrel", 3, 7, MCFixupKindInfo::FKF_IsPCRel},
409       {"fixup_13_pcrel", 0, 12, MCFixupKindInfo::FKF_IsPCRel},
410 
411       {"fixup_16", 0, 16, 0},
412       {"fixup_16_pm", 0, 16, 0},
413 
414       {"fixup_ldi", 0, 8, 0},
415 
416       {"fixup_lo8_ldi", 0, 8, 0},
417       {"fixup_hi8_ldi", 0, 8, 0},
418       {"fixup_hh8_ldi", 0, 8, 0},
419       {"fixup_ms8_ldi", 0, 8, 0},
420 
421       {"fixup_lo8_ldi_neg", 0, 8, 0},
422       {"fixup_hi8_ldi_neg", 0, 8, 0},
423       {"fixup_hh8_ldi_neg", 0, 8, 0},
424       {"fixup_ms8_ldi_neg", 0, 8, 0},
425 
426       {"fixup_lo8_ldi_pm", 0, 8, 0},
427       {"fixup_hi8_ldi_pm", 0, 8, 0},
428       {"fixup_hh8_ldi_pm", 0, 8, 0},
429 
430       {"fixup_lo8_ldi_pm_neg", 0, 8, 0},
431       {"fixup_hi8_ldi_pm_neg", 0, 8, 0},
432       {"fixup_hh8_ldi_pm_neg", 0, 8, 0},
433 
434       {"fixup_call", 0, 22, 0},
435 
436       {"fixup_6", 0, 16, 0}, // non-contiguous
437       {"fixup_6_adiw", 0, 6, 0},
438 
439       {"fixup_lo8_ldi_gs", 0, 8, 0},
440       {"fixup_hi8_ldi_gs", 0, 8, 0},
441 
442       {"fixup_8", 0, 8, 0},
443       {"fixup_8_lo8", 0, 8, 0},
444       {"fixup_8_hi8", 0, 8, 0},
445       {"fixup_8_hlo8", 0, 8, 0},
446 
447       {"fixup_diff8", 0, 8, 0},
448       {"fixup_diff16", 0, 16, 0},
449       {"fixup_diff32", 0, 32, 0},
450 
451       {"fixup_lds_sts_16", 0, 16, 0},
452 
453       {"fixup_port6", 0, 16, 0}, // non-contiguous
454       {"fixup_port5", 3, 5, 0},
455   };
456 
457   if (Kind < FirstTargetFixupKind)
458     return MCAsmBackend::getFixupKindInfo(Kind);
459 
460   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
461          "Invalid kind!");
462 
463   return Infos[Kind - FirstTargetFixupKind];
464 }
465 
466 bool AVRAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
467   // If the count is not 2-byte aligned, we must be writing data into the text
468   // section (otherwise we have unaligned instructions, and thus have far
469   // bigger problems), so just write zeros instead.
470   assert((Count % 2) == 0 && "NOP instructions must be 2 bytes");
471 
472   OS.write_zeros(Count);
473   return true;
474 }
475 
476 bool AVRAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
477                                           const MCFixup &Fixup,
478                                           const MCValue &Target) {
479   switch ((unsigned) Fixup.getKind()) {
480   default: return false;
481   // Fixups which should always be recorded as relocations.
482   case AVR::fixup_7_pcrel:
483   case AVR::fixup_13_pcrel:
484   case AVR::fixup_call:
485     return true;
486   }
487 }
488 
489 MCAsmBackend *createAVRAsmBackend(const Target &T, const MCSubtargetInfo &STI,
490                                   const MCRegisterInfo &MRI,
491                                   const llvm::MCTargetOptions &TO) {
492   return new AVRAsmBackend(STI.getTargetTriple().getOS());
493 }
494 
495 } // end of namespace llvm
496 
497