1 //===-- HexagonAsmBackend.cpp - Hexagon Assembler Backend -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Hexagon.h"
11 #include "HexagonFixupKinds.h"
12 #include "HexagonMCTargetDesc.h"
13 #include "MCTargetDesc/HexagonBaseInfo.h"
14 #include "MCTargetDesc/HexagonMCChecker.h"
15 #include "MCTargetDesc/HexagonMCCodeEmitter.h"
16 #include "MCTargetDesc/HexagonMCInstrInfo.h"
17 #include "MCTargetDesc/HexagonMCShuffler.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFObjectWriter.h"
23 #include "llvm/MC/MCFixupKindInfo.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/TargetRegistry.h"
27 
28 #include <sstream>
29 
30 using namespace llvm;
31 using namespace Hexagon;
32 
33 #define DEBUG_TYPE "hexagon-asm-backend"
34 
35 static cl::opt<bool> DisableFixup
36   ("mno-fixup", cl::desc("Disable fixing up resolved relocations for Hexagon"));
37 
38 namespace {
39 
40 class HexagonAsmBackend : public MCAsmBackend {
41   uint8_t OSABI;
42   StringRef CPU;
43   mutable uint64_t relaxedCnt;
44   std::unique_ptr <MCInstrInfo> MCII;
45   std::unique_ptr <MCInst *> RelaxTarget;
46   MCInst * Extender;
47 
48   void ReplaceInstruction(MCCodeEmitter &E, MCRelaxableFragment &RF,
49                           MCInst &HMB) const {
50     SmallVector<MCFixup, 4> Fixups;
51     SmallString<256> Code;
52     raw_svector_ostream VecOS(Code);
53     E.encodeInstruction(HMB, VecOS, Fixups, RF.getSubtargetInfo());
54 
55     // Update the fragment.
56     RF.setInst(HMB);
57     RF.getContents() = Code;
58     RF.getFixups() = Fixups;
59   }
60 public:
61   HexagonAsmBackend(const Target &T, uint8_t OSABI, StringRef CPU) :
62     OSABI(OSABI), MCII (T.createMCInstrInfo()), RelaxTarget(new MCInst *),
63     Extender(nullptr) {}
64 
65   MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const override {
66     return createHexagonELFObjectWriter(OS, OSABI, CPU);
67   }
68 
69   void setExtender(MCContext &Context) const {
70     if (Extender == nullptr)
71       const_cast<HexagonAsmBackend *>(this)->Extender = new (Context) MCInst;
72   }
73 
74   MCInst *takeExtender() const {
75     assert(Extender != nullptr);
76     MCInst * Result = Extender;
77     const_cast<HexagonAsmBackend *>(this)->Extender = nullptr;
78     return Result;
79   }
80 
81   unsigned getNumFixupKinds() const override {
82     return Hexagon::NumTargetFixupKinds;
83   }
84 
85   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
86     const static MCFixupKindInfo Infos[Hexagon::NumTargetFixupKinds] = {
87       // This table *must* be in same the order of fixup_* kinds in
88       // HexagonFixupKinds.h.
89       //
90       // namei                          offset  bits  flags
91       { "fixup_Hexagon_B22_PCREL",        0,    32,   MCFixupKindInfo::FKF_IsPCRel },
92       { "fixup_Hexagon_B15_PCREL",        0,    32,   MCFixupKindInfo::FKF_IsPCRel },
93       { "fixup_Hexagon_B7_PCREL",         0,    32,   MCFixupKindInfo::FKF_IsPCRel },
94       { "fixup_Hexagon_LO16",             0,    32,   0 },
95       { "fixup_Hexagon_HI16",             0,    32,   0 },
96       { "fixup_Hexagon_32",               0,    32,   0 },
97       { "fixup_Hexagon_16",               0,    32,   0 },
98       { "fixup_Hexagon_8",                0,    32,   0 },
99       { "fixup_Hexagon_GPREL16_0",        0,    32,   0 },
100       { "fixup_Hexagon_GPREL16_1",        0,    32,   0 },
101       { "fixup_Hexagon_GPREL16_2",        0,    32,   0 },
102       { "fixup_Hexagon_GPREL16_3",        0,    32,   0 },
103       { "fixup_Hexagon_HL16",             0,    32,   0 },
104       { "fixup_Hexagon_B13_PCREL",        0,    32,   MCFixupKindInfo::FKF_IsPCRel },
105       { "fixup_Hexagon_B9_PCREL",         0,    32,   MCFixupKindInfo::FKF_IsPCRel },
106       { "fixup_Hexagon_B32_PCREL_X",      0,    32,   MCFixupKindInfo::FKF_IsPCRel },
107       { "fixup_Hexagon_32_6_X",           0,    32,   0 },
108       { "fixup_Hexagon_B22_PCREL_X",      0,    32,   MCFixupKindInfo::FKF_IsPCRel },
109       { "fixup_Hexagon_B15_PCREL_X",      0,    32,   MCFixupKindInfo::FKF_IsPCRel },
110       { "fixup_Hexagon_B13_PCREL_X",      0,    32,   MCFixupKindInfo::FKF_IsPCRel },
111       { "fixup_Hexagon_B9_PCREL_X",       0,    32,   MCFixupKindInfo::FKF_IsPCRel },
112       { "fixup_Hexagon_B7_PCREL_X",       0,    32,   MCFixupKindInfo::FKF_IsPCRel },
113       { "fixup_Hexagon_16_X",             0,    32,   0 },
114       { "fixup_Hexagon_12_X",             0,    32,   0 },
115       { "fixup_Hexagon_11_X",             0,    32,   0 },
116       { "fixup_Hexagon_10_X",             0,    32,   0 },
117       { "fixup_Hexagon_9_X",              0,    32,   0 },
118       { "fixup_Hexagon_8_X",              0,    32,   0 },
119       { "fixup_Hexagon_7_X",              0,    32,   0 },
120       { "fixup_Hexagon_6_X",              0,    32,   0 },
121       { "fixup_Hexagon_32_PCREL",         0,    32,   MCFixupKindInfo::FKF_IsPCRel },
122       { "fixup_Hexagon_COPY",             0,    32,   0 },
123       { "fixup_Hexagon_GLOB_DAT",         0,    32,   0 },
124       { "fixup_Hexagon_JMP_SLOT",         0,    32,   0 },
125       { "fixup_Hexagon_RELATIVE",         0,    32,   0 },
126       { "fixup_Hexagon_PLT_B22_PCREL",    0,    32,   MCFixupKindInfo::FKF_IsPCRel },
127       { "fixup_Hexagon_GOTREL_LO16",      0,    32,   0 },
128       { "fixup_Hexagon_GOTREL_HI16",      0,    32,   0 },
129       { "fixup_Hexagon_GOTREL_32",        0,    32,   0 },
130       { "fixup_Hexagon_GOT_LO16",         0,    32,   0 },
131       { "fixup_Hexagon_GOT_HI16",         0,    32,   0 },
132       { "fixup_Hexagon_GOT_32",           0,    32,   0 },
133       { "fixup_Hexagon_GOT_16",           0,    32,   0 },
134       { "fixup_Hexagon_DTPMOD_32",        0,    32,   0 },
135       { "fixup_Hexagon_DTPREL_LO16",      0,    32,   0 },
136       { "fixup_Hexagon_DTPREL_HI16",      0,    32,   0 },
137       { "fixup_Hexagon_DTPREL_32",        0,    32,   0 },
138       { "fixup_Hexagon_DTPREL_16",        0,    32,   0 },
139       { "fixup_Hexagon_GD_PLT_B22_PCREL", 0,    32,   MCFixupKindInfo::FKF_IsPCRel },
140       { "fixup_Hexagon_LD_PLT_B22_PCREL", 0,    32,   MCFixupKindInfo::FKF_IsPCRel },
141       { "fixup_Hexagon_GD_GOT_LO16",      0,    32,   0 },
142       { "fixup_Hexagon_GD_GOT_HI16",      0,    32,   0 },
143       { "fixup_Hexagon_GD_GOT_32",        0,    32,   0 },
144       { "fixup_Hexagon_GD_GOT_16",        0,    32,   0 },
145       { "fixup_Hexagon_LD_GOT_LO16",      0,    32,   0 },
146       { "fixup_Hexagon_LD_GOT_HI16",      0,    32,   0 },
147       { "fixup_Hexagon_LD_GOT_32",        0,    32,   0 },
148       { "fixup_Hexagon_LD_GOT_16",        0,    32,   0 },
149       { "fixup_Hexagon_IE_LO16",          0,    32,   0 },
150       { "fixup_Hexagon_IE_HI16",          0,    32,   0 },
151       { "fixup_Hexagon_IE_32",            0,    32,   0 },
152       { "fixup_Hexagon_IE_16",            0,    32,   0 },
153       { "fixup_Hexagon_IE_GOT_LO16",      0,    32,   0 },
154       { "fixup_Hexagon_IE_GOT_HI16",      0,    32,   0 },
155       { "fixup_Hexagon_IE_GOT_32",        0,    32,   0 },
156       { "fixup_Hexagon_IE_GOT_16",        0,    32,   0 },
157       { "fixup_Hexagon_TPREL_LO16",       0,    32,   0 },
158       { "fixup_Hexagon_TPREL_HI16",       0,    32,   0 },
159       { "fixup_Hexagon_TPREL_32",         0,    32,   0 },
160       { "fixup_Hexagon_TPREL_16",         0,    32,   0 },
161       { "fixup_Hexagon_6_PCREL_X",        0,    32,   MCFixupKindInfo::FKF_IsPCRel },
162       { "fixup_Hexagon_GOTREL_32_6_X",    0,    32,   0 },
163       { "fixup_Hexagon_GOTREL_16_X",      0,    32,   0 },
164       { "fixup_Hexagon_GOTREL_11_X",      0,    32,   0 },
165       { "fixup_Hexagon_GOT_32_6_X",       0,    32,   0 },
166       { "fixup_Hexagon_GOT_16_X",         0,    32,   0 },
167       { "fixup_Hexagon_GOT_11_X",         0,    32,   0 },
168       { "fixup_Hexagon_DTPREL_32_6_X",    0,    32,   0 },
169       { "fixup_Hexagon_DTPREL_16_X",      0,    32,   0 },
170       { "fixup_Hexagon_DTPREL_11_X",      0,    32,   0 },
171       { "fixup_Hexagon_GD_GOT_32_6_X",    0,    32,   0 },
172       { "fixup_Hexagon_GD_GOT_16_X",      0,    32,   0 },
173       { "fixup_Hexagon_GD_GOT_11_X",      0,    32,   0 },
174       { "fixup_Hexagon_LD_GOT_32_6_X",    0,    32,   0 },
175       { "fixup_Hexagon_LD_GOT_16_X",      0,    32,   0 },
176       { "fixup_Hexagon_LD_GOT_11_X",      0,    32,   0 },
177       { "fixup_Hexagon_IE_32_6_X",        0,    32,   0 },
178       { "fixup_Hexagon_IE_16_X",          0,    32,   0 },
179       { "fixup_Hexagon_IE_GOT_32_6_X",    0,    32,   0 },
180       { "fixup_Hexagon_IE_GOT_16_X",      0,    32,   0 },
181       { "fixup_Hexagon_IE_GOT_11_X",      0,    32,   0 },
182       { "fixup_Hexagon_TPREL_32_6_X",     0,    32,   0 },
183       { "fixup_Hexagon_TPREL_16_X",       0,    32,   0 },
184       { "fixup_Hexagon_TPREL_11_X",       0,    32,   0 }
185     };
186 
187     if (Kind < FirstTargetFixupKind)
188       return MCAsmBackend::getFixupKindInfo(Kind);
189 
190     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
191            "Invalid kind!");
192     return Infos[Kind - FirstTargetFixupKind];
193   }
194 
195   /// processFixupValue - Target hook to adjust the literal value of a fixup
196   /// if necessary. IsResolved signals whether the caller believes a relocation
197   /// is needed; the target can modify the value. The default does nothing.
198   void processFixupValue(const MCAssembler &Asm, const MCAsmLayout &Layout,
199                          const MCFixup &Fixup, const MCFragment *DF,
200                          const MCValue &Target, uint64_t &Value,
201                          bool &IsResolved) override {
202     MCFixupKind Kind = Fixup.getKind();
203 
204     switch((unsigned)Kind) {
205       default:
206         llvm_unreachable("Unknown Fixup Kind!");
207 
208       case fixup_Hexagon_LO16:
209       case fixup_Hexagon_HI16:
210       case fixup_Hexagon_16:
211       case fixup_Hexagon_8:
212       case fixup_Hexagon_GPREL16_0:
213       case fixup_Hexagon_GPREL16_1:
214       case fixup_Hexagon_GPREL16_2:
215       case fixup_Hexagon_GPREL16_3:
216       case fixup_Hexagon_HL16:
217       case fixup_Hexagon_32_6_X:
218       case fixup_Hexagon_16_X:
219       case fixup_Hexagon_12_X:
220       case fixup_Hexagon_11_X:
221       case fixup_Hexagon_10_X:
222       case fixup_Hexagon_9_X:
223       case fixup_Hexagon_8_X:
224       case fixup_Hexagon_7_X:
225       case fixup_Hexagon_6_X:
226       case fixup_Hexagon_COPY:
227       case fixup_Hexagon_GLOB_DAT:
228       case fixup_Hexagon_JMP_SLOT:
229       case fixup_Hexagon_RELATIVE:
230       case fixup_Hexagon_PLT_B22_PCREL:
231       case fixup_Hexagon_GOTREL_LO16:
232       case fixup_Hexagon_GOTREL_HI16:
233       case fixup_Hexagon_GOTREL_32:
234       case fixup_Hexagon_GOT_LO16:
235       case fixup_Hexagon_GOT_HI16:
236       case fixup_Hexagon_GOT_32:
237       case fixup_Hexagon_GOT_16:
238       case fixup_Hexagon_DTPMOD_32:
239       case fixup_Hexagon_DTPREL_LO16:
240       case fixup_Hexagon_DTPREL_HI16:
241       case fixup_Hexagon_DTPREL_32:
242       case fixup_Hexagon_DTPREL_16:
243       case fixup_Hexagon_GD_PLT_B22_PCREL:
244       case fixup_Hexagon_LD_PLT_B22_PCREL:
245       case fixup_Hexagon_GD_GOT_LO16:
246       case fixup_Hexagon_GD_GOT_HI16:
247       case fixup_Hexagon_GD_GOT_32:
248       case fixup_Hexagon_GD_GOT_16:
249       case fixup_Hexagon_LD_GOT_LO16:
250       case fixup_Hexagon_LD_GOT_HI16:
251       case fixup_Hexagon_LD_GOT_32:
252       case fixup_Hexagon_LD_GOT_16:
253       case fixup_Hexagon_IE_LO16:
254       case fixup_Hexagon_IE_HI16:
255       case fixup_Hexagon_IE_32:
256       case fixup_Hexagon_IE_16:
257       case fixup_Hexagon_IE_GOT_LO16:
258       case fixup_Hexagon_IE_GOT_HI16:
259       case fixup_Hexagon_IE_GOT_32:
260       case fixup_Hexagon_IE_GOT_16:
261       case fixup_Hexagon_TPREL_LO16:
262       case fixup_Hexagon_TPREL_HI16:
263       case fixup_Hexagon_TPREL_32:
264       case fixup_Hexagon_TPREL_16:
265       case fixup_Hexagon_GOTREL_32_6_X:
266       case fixup_Hexagon_GOTREL_16_X:
267       case fixup_Hexagon_GOTREL_11_X:
268       case fixup_Hexagon_GOT_32_6_X:
269       case fixup_Hexagon_GOT_16_X:
270       case fixup_Hexagon_GOT_11_X:
271       case fixup_Hexagon_DTPREL_32_6_X:
272       case fixup_Hexagon_DTPREL_16_X:
273       case fixup_Hexagon_DTPREL_11_X:
274       case fixup_Hexagon_GD_GOT_32_6_X:
275       case fixup_Hexagon_GD_GOT_16_X:
276       case fixup_Hexagon_GD_GOT_11_X:
277       case fixup_Hexagon_LD_GOT_32_6_X:
278       case fixup_Hexagon_LD_GOT_16_X:
279       case fixup_Hexagon_LD_GOT_11_X:
280       case fixup_Hexagon_IE_32_6_X:
281       case fixup_Hexagon_IE_16_X:
282       case fixup_Hexagon_IE_GOT_32_6_X:
283       case fixup_Hexagon_IE_GOT_16_X:
284       case fixup_Hexagon_IE_GOT_11_X:
285       case fixup_Hexagon_TPREL_32_6_X:
286       case fixup_Hexagon_TPREL_16_X:
287       case fixup_Hexagon_TPREL_11_X:
288       case fixup_Hexagon_32_PCREL:
289       case fixup_Hexagon_6_PCREL_X:
290       case fixup_Hexagon_23_REG:
291         // These relocations should always have a relocation recorded
292         IsResolved = false;
293         return;
294 
295       case fixup_Hexagon_B22_PCREL:
296         //IsResolved = false;
297         break;
298 
299       case fixup_Hexagon_B13_PCREL:
300       case fixup_Hexagon_B13_PCREL_X:
301       case fixup_Hexagon_B32_PCREL_X:
302       case fixup_Hexagon_B22_PCREL_X:
303       case fixup_Hexagon_B15_PCREL:
304       case fixup_Hexagon_B15_PCREL_X:
305       case fixup_Hexagon_B9_PCREL:
306       case fixup_Hexagon_B9_PCREL_X:
307       case fixup_Hexagon_B7_PCREL:
308       case fixup_Hexagon_B7_PCREL_X:
309         if (DisableFixup)
310           IsResolved = false;
311         break;
312 
313       case FK_Data_1:
314       case FK_Data_2:
315       case FK_Data_4:
316       case FK_PCRel_4:
317       case fixup_Hexagon_32:
318         // Leave these relocations alone as they are used for EH.
319         return;
320     }
321   }
322 
323   /// getFixupKindNumBytes - The number of bytes the fixup may change.
324   static unsigned getFixupKindNumBytes(unsigned Kind) {
325     switch (Kind) {
326     default:
327         return 0;
328 
329       case FK_Data_1:
330         return 1;
331       case FK_Data_2:
332         return 2;
333       case FK_Data_4:         // this later gets mapped to R_HEX_32
334       case FK_PCRel_4:        // this later gets mapped to R_HEX_32_PCREL
335       case fixup_Hexagon_32:
336       case fixup_Hexagon_B32_PCREL_X:
337       case fixup_Hexagon_B22_PCREL:
338       case fixup_Hexagon_B22_PCREL_X:
339       case fixup_Hexagon_B15_PCREL:
340       case fixup_Hexagon_B15_PCREL_X:
341       case fixup_Hexagon_B13_PCREL:
342       case fixup_Hexagon_B13_PCREL_X:
343       case fixup_Hexagon_B9_PCREL:
344       case fixup_Hexagon_B9_PCREL_X:
345       case fixup_Hexagon_B7_PCREL:
346       case fixup_Hexagon_B7_PCREL_X:
347         return 4;
348     }
349   }
350 
351   // Make up for left shift when encoding the operand.
352   static uint64_t adjustFixupValue(MCFixupKind Kind, uint64_t Value) {
353     switch((unsigned)Kind) {
354       default:
355         break;
356 
357       case fixup_Hexagon_B7_PCREL:
358       case fixup_Hexagon_B9_PCREL:
359       case fixup_Hexagon_B13_PCREL:
360       case fixup_Hexagon_B15_PCREL:
361       case fixup_Hexagon_B22_PCREL:
362         Value >>= 2;
363         break;
364 
365       case fixup_Hexagon_B7_PCREL_X:
366       case fixup_Hexagon_B9_PCREL_X:
367       case fixup_Hexagon_B13_PCREL_X:
368       case fixup_Hexagon_B15_PCREL_X:
369       case fixup_Hexagon_B22_PCREL_X:
370         Value &= 0x3f;
371         break;
372 
373       case fixup_Hexagon_B32_PCREL_X:
374         Value >>= 6;
375         break;
376     }
377     return (Value);
378   }
379 
380   void HandleFixupError(const int bits, const int align_bits,
381     const int64_t FixupValue, const char *fixupStr) const {
382     // Error: value 1124 out of range: -1024-1023 when resolving
383     // symbol in file xprtsock.S
384     const APInt IntMin = APInt::getSignedMinValue(bits+align_bits);
385     const APInt IntMax = APInt::getSignedMaxValue(bits+align_bits);
386     std::stringstream errStr;
387     errStr << "\nError: value " <<
388       FixupValue <<
389       " out of range: " <<
390       IntMin.getSExtValue() <<
391       "-" <<
392       IntMax.getSExtValue() <<
393       " when resolving " <<
394       fixupStr <<
395       " fixup\n";
396     llvm_unreachable(errStr.str().c_str());
397   }
398 
399   /// ApplyFixup - Apply the \arg Value for given \arg Fixup into the provided
400   /// data fragment, at the offset specified by the fixup and following the
401   /// fixup kind as appropriate.
402   void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
403                   uint64_t FixupValue, bool IsPCRel) const override {
404 
405     // When FixupValue is 0 the relocation is external and there
406     // is nothing for us to do.
407     if (!FixupValue) return;
408 
409     MCFixupKind Kind = Fixup.getKind();
410     uint64_t Value;
411     uint32_t InstMask;
412     uint32_t Reloc;
413 
414     // LLVM gives us an encoded value, we have to convert it back
415     // to a real offset before we can use it.
416     uint32_t Offset = Fixup.getOffset();
417     unsigned NumBytes = getFixupKindNumBytes(Kind);
418     assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
419     char* InstAddr = Data + Offset;
420 
421     Value = adjustFixupValue(Kind, FixupValue);
422     if(!Value)
423       return;
424     signed sValue = (signed)Value;
425 
426     switch((unsigned)Kind) {
427       default:
428         return;
429 
430       case fixup_Hexagon_B7_PCREL:
431         if (!(isIntN(7, sValue)))
432           HandleFixupError(7, 2, (int64_t)FixupValue, "B7_PCREL");
433       case fixup_Hexagon_B7_PCREL_X:
434         InstMask = 0x00001f18;  // Word32_B7
435         Reloc = (((Value >> 2) & 0x1f) << 8) |    // Value 6-2 = Target 12-8
436                 ((Value & 0x3) << 3);             // Value 1-0 = Target 4-3
437         break;
438 
439       case fixup_Hexagon_B9_PCREL:
440         if (!(isIntN(9, sValue)))
441           HandleFixupError(9, 2, (int64_t)FixupValue, "B9_PCREL");
442       case fixup_Hexagon_B9_PCREL_X:
443         InstMask = 0x003000fe;  // Word32_B9
444         Reloc = (((Value >> 7) & 0x3) << 20) |    // Value 8-7 = Target 21-20
445                 ((Value & 0x7f) << 1);            // Value 6-0 = Target 7-1
446         break;
447 
448         // Since the existing branches that use this relocation cannot be
449         // extended, they should only be fixed up if the target is within range.
450       case fixup_Hexagon_B13_PCREL:
451         if (!(isIntN(13, sValue)))
452           HandleFixupError(13, 2, (int64_t)FixupValue, "B13_PCREL");
453       case fixup_Hexagon_B13_PCREL_X:
454         InstMask = 0x00202ffe;  // Word32_B13
455         Reloc = (((Value >> 12) & 0x1) << 21) |    // Value 12   = Target 21
456                 (((Value >> 11) & 0x1) << 13) |    // Value 11   = Target 13
457                 ((Value & 0x7ff) << 1);            // Value 10-0 = Target 11-1
458         break;
459 
460       case fixup_Hexagon_B15_PCREL:
461         if (!(isIntN(15, sValue)))
462           HandleFixupError(15, 2, (int64_t)FixupValue, "B15_PCREL");
463       case fixup_Hexagon_B15_PCREL_X:
464         InstMask = 0x00df20fe;  // Word32_B15
465         Reloc = (((Value >> 13) & 0x3) << 22) |    // Value 14-13 = Target 23-22
466                 (((Value >> 8) & 0x1f) << 16) |    // Value 12-8  = Target 20-16
467                 (((Value >> 7) & 0x1)  << 13) |    // Value 7     = Target 13
468                 ((Value & 0x7f) << 1);             // Value 6-0   = Target 7-1
469         break;
470 
471       case fixup_Hexagon_B22_PCREL:
472         if (!(isIntN(22, sValue)))
473           HandleFixupError(22, 2, (int64_t)FixupValue, "B22_PCREL");
474       case fixup_Hexagon_B22_PCREL_X:
475         InstMask = 0x01ff3ffe;  // Word32_B22
476         Reloc = (((Value >> 13) & 0x1ff) << 16) |  // Value 21-13 = Target 24-16
477                 ((Value & 0x1fff) << 1);           // Value 12-0  = Target 13-1
478         break;
479 
480       case fixup_Hexagon_B32_PCREL_X:
481         InstMask = 0x0fff3fff;  // Word32_X26
482         Reloc = (((Value >> 14) & 0xfff) << 16) |  // Value 25-14 = Target 27-16
483                 (Value & 0x3fff);                  // Value 13-0  = Target 13-0
484         break;
485 
486       case FK_Data_1:
487       case FK_Data_2:
488       case FK_Data_4:
489       case fixup_Hexagon_32:
490         InstMask = 0xffffffff;  // Word32
491         Reloc = Value;
492         break;
493     }
494 
495     DEBUG(dbgs() << "Name=" << getFixupKindInfo(Kind).Name << "(" <<
496           (unsigned)Kind << ")\n");
497     DEBUG(uint32_t OldData = 0;
498           for (unsigned i = 0; i < NumBytes; i++)
499             OldData |= (InstAddr[i] << (i * 8)) & (0xff << (i * 8));
500           dbgs() << "\tBValue=0x"; dbgs().write_hex(Value) <<
501             ": AValue=0x"; dbgs().write_hex(FixupValue) <<
502             ": Offset=" << Offset <<
503             ": Size=" << DataSize <<
504             ": OInst=0x"; dbgs().write_hex(OldData) <<
505             ": Reloc=0x"; dbgs().write_hex(Reloc););
506 
507     // For each byte of the fragment that the fixup touches, mask in the
508     // bits from the fixup value. The Value has been "split up" into the
509     // appropriate bitfields above.
510     for (unsigned i = 0; i < NumBytes; i++){
511       InstAddr[i] &= uint8_t(~InstMask >> (i * 8)) & 0xff; // Clear reloc bits
512       InstAddr[i] |= uint8_t(Reloc >> (i * 8)) & 0xff;     // Apply new reloc
513     }
514 
515     DEBUG(uint32_t NewData = 0;
516           for (unsigned i = 0; i < NumBytes; i++)
517             NewData |= (InstAddr[i] << (i * 8)) & (0xff << (i * 8));
518           dbgs() << ": NInst=0x"; dbgs().write_hex(NewData) << "\n";);
519   }
520 
521   bool isInstRelaxable(MCInst const &HMI) const {
522     const MCInstrDesc &MCID = HexagonMCInstrInfo::getDesc(*MCII, HMI);
523     bool Relaxable = false;
524     // Branches and loop-setup insns are handled as necessary by relaxation.
525     if (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeJ ||
526         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) ==
527              HexagonII::TypeCOMPOUND &&
528          MCID.isBranch()) ||
529         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeNV &&
530          MCID.isBranch()) ||
531         (llvm::HexagonMCInstrInfo::getType(*MCII, HMI) == HexagonII::TypeCR &&
532          HMI.getOpcode() != Hexagon::C4_addipc))
533       if (HexagonMCInstrInfo::isExtendable(*MCII, HMI)) {
534         Relaxable = true;
535         MCOperand const &Operand =
536             HMI.getOperand(HexagonMCInstrInfo::getExtendableOp(*MCII, HMI));
537         if (HexagonMCInstrInfo::mustNotExtend(*Operand.getExpr()))
538           Relaxable = false;
539       }
540 
541     return Relaxable;
542   }
543 
544   /// MayNeedRelaxation - Check whether the given instruction may need
545   /// relaxation.
546   ///
547   /// \param Inst - The instruction to test.
548   bool mayNeedRelaxation(MCInst const &Inst) const override {
549     return true;
550   }
551 
552   /// fixupNeedsRelaxation - Target specific predicate for whether a given
553   /// fixup requires the associated instruction to be relaxed.
554   bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved,
555                                     uint64_t Value,
556                                     const MCRelaxableFragment *DF,
557                                     const MCAsmLayout &Layout) const override {
558     MCInst const &MCB = DF->getInst();
559     assert(HexagonMCInstrInfo::isBundle(MCB));
560 
561     *RelaxTarget = nullptr;
562     MCInst &MCI = const_cast<MCInst &>(HexagonMCInstrInfo::instruction(
563         MCB, Fixup.getOffset() / HEXAGON_INSTR_SIZE));
564     bool Relaxable = isInstRelaxable(MCI);
565     if (Relaxable == false)
566       return false;
567     // If we cannot resolve the fixup value, it requires relaxation.
568     if (!Resolved) {
569       switch ((unsigned)Fixup.getKind()) {
570       case fixup_Hexagon_B22_PCREL:
571       // GetFixupCount assumes B22 won't relax
572       // Fallthrough
573       default:
574         return false;
575         break;
576       case fixup_Hexagon_B13_PCREL:
577       case fixup_Hexagon_B15_PCREL:
578       case fixup_Hexagon_B9_PCREL:
579       case fixup_Hexagon_B7_PCREL: {
580         if (HexagonMCInstrInfo::bundleSize(MCB) < HEXAGON_PACKET_SIZE) {
581           ++relaxedCnt;
582           *RelaxTarget = &MCI;
583           setExtender(Layout.getAssembler().getContext());
584           return true;
585         } else {
586           return false;
587         }
588         break;
589       }
590       }
591     }
592 
593     MCFixupKind Kind = Fixup.getKind();
594     int64_t sValue = Value;
595     int64_t maxValue;
596 
597     switch ((unsigned)Kind) {
598     case fixup_Hexagon_B7_PCREL:
599       maxValue = 1 << 8;
600       break;
601     case fixup_Hexagon_B9_PCREL:
602       maxValue = 1 << 10;
603       break;
604     case fixup_Hexagon_B15_PCREL:
605       maxValue = 1 << 16;
606       break;
607     case fixup_Hexagon_B22_PCREL:
608       maxValue = 1 << 23;
609       break;
610     default:
611       maxValue = INT64_MAX;
612       break;
613     }
614 
615     bool isFarAway = -maxValue > sValue || sValue > maxValue - 1;
616 
617     if (isFarAway) {
618       if (HexagonMCInstrInfo::bundleSize(MCB) < HEXAGON_PACKET_SIZE) {
619         ++relaxedCnt;
620         *RelaxTarget = &MCI;
621         setExtender(Layout.getAssembler().getContext());
622         return true;
623       }
624     }
625 
626     return false;
627   }
628 
629   /// Simple predicate for targets where !Resolved implies requiring relaxation
630   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
631                             const MCRelaxableFragment *DF,
632                             const MCAsmLayout &Layout) const override {
633     llvm_unreachable("Handled by fixupNeedsRelaxationAdvanced");
634   }
635 
636   void relaxInstruction(MCInst const & Inst,
637                         MCInst & Res) const override {
638     assert(HexagonMCInstrInfo::isBundle(Inst) &&
639            "Hexagon relaxInstruction only works on bundles");
640 
641     Res = HexagonMCInstrInfo::createBundle();
642     // Copy the results into the bundle.
643     bool Update = false;
644     for (auto &I : HexagonMCInstrInfo::bundleInstructions(Inst)) {
645       MCInst &CrntHMI = const_cast<MCInst &>(*I.getInst());
646 
647       // if immediate extender needed, add it in
648       if (*RelaxTarget == &CrntHMI) {
649         Update = true;
650         assert((HexagonMCInstrInfo::bundleSize(Res) < HEXAGON_PACKET_SIZE) &&
651                "No room to insert extender for relaxation");
652 
653         MCInst *HMIx = takeExtender();
654         *HMIx = HexagonMCInstrInfo::deriveExtender(
655                 *MCII, CrntHMI,
656                 HexagonMCInstrInfo::getExtendableOperand(*MCII, CrntHMI));
657         Res.addOperand(MCOperand::createInst(HMIx));
658         *RelaxTarget = nullptr;
659       }
660       // now copy over the original instruction(the one we may have extended)
661       Res.addOperand(MCOperand::createInst(I.getInst()));
662     }
663     (void)Update;
664     assert(Update && "Didn't find relaxation target");
665   }
666 
667   bool writeNopData(uint64_t Count,
668                     MCObjectWriter * OW) const override {
669     static const uint32_t Nopcode  = 0x7f000000, // Hard-coded NOP.
670                           ParseIn  = 0x00004000, // In packet parse-bits.
671                           ParseEnd = 0x0000c000; // End of packet parse-bits.
672 
673     while(Count % HEXAGON_INSTR_SIZE) {
674       DEBUG(dbgs() << "Alignment not a multiple of the instruction size:" <<
675           Count % HEXAGON_INSTR_SIZE << "/" << HEXAGON_INSTR_SIZE << "\n");
676       --Count;
677       OW->write8(0);
678     }
679 
680     while(Count) {
681       Count -= HEXAGON_INSTR_SIZE;
682       // Close the packet whenever a multiple of the maximum packet size remains
683       uint32_t ParseBits = (Count % (HEXAGON_PACKET_SIZE * HEXAGON_INSTR_SIZE))?
684                            ParseIn: ParseEnd;
685       OW->write32(Nopcode | ParseBits);
686     }
687     return true;
688   }
689 
690   void finishLayout(MCAssembler const &Asm,
691                     MCAsmLayout &Layout) const override {
692     for (auto I : Layout.getSectionOrder()) {
693       auto &Fragments = I->getFragmentList();
694       for (auto &J : Fragments) {
695         switch (J.getKind()) {
696         default:
697           break;
698         case MCFragment::FT_Align: {
699           auto Size = Asm.computeFragmentSize(Layout, J);
700           for (auto K = J.getIterator();
701                K != Fragments.begin() && Size >= HEXAGON_PACKET_SIZE;) {
702             --K;
703             switch (K->getKind()) {
704             default:
705               break;
706             case MCFragment::FT_Align: {
707               // Don't pad before other alignments
708               Size = 0;
709               break;
710             }
711             case MCFragment::FT_Relaxable: {
712               auto &RF = cast<MCRelaxableFragment>(*K);
713               auto &Inst = const_cast<MCInst &>(RF.getInst());
714               while (Size > 0 && HexagonMCInstrInfo::bundleSize(Inst) < 4) {
715                 MCInst *Nop = new (Asm.getContext()) MCInst;
716                 Nop->setOpcode(Hexagon::A2_nop);
717                 Inst.addOperand(MCOperand::createInst(Nop));
718                 Size -= 4;
719                 if (!HexagonMCChecker(
720                            *MCII, RF.getSubtargetInfo(), Inst, Inst,
721                            *Asm.getContext().getRegisterInfo()).check()) {
722                   Inst.erase(Inst.end() - 1);
723                   Size = 0;
724                 }
725               }
726               bool Error = HexagonMCShuffle(*MCII, RF.getSubtargetInfo(), Inst);
727               //assert(!Error);
728               (void)Error;
729               ReplaceInstruction(Asm.getEmitter(), RF, Inst);
730               Layout.invalidateFragmentsFrom(&RF);
731               Size = 0; // Only look back one instruction
732               break;
733             }
734             }
735           }
736         }
737         }
738       }
739     }
740   }
741 };
742 } // end anonymous namespace
743 
744 namespace llvm {
745 MCAsmBackend *createHexagonAsmBackend(Target const &T,
746                                       MCRegisterInfo const & /*MRI*/,
747                                       const Triple &TT, StringRef CPU) {
748   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
749   return new HexagonAsmBackend(T, OSABI, CPU);
750 }
751 }
752