1 //===-- X86AsmBackend.cpp - X86 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 "MCTargetDesc/X86BaseInfo.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/BinaryFormat/ELF.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixupKindInfo.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCMachObjectWriter.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
getFixupKindLog2Size(unsigned Kind)29 static unsigned getFixupKindLog2Size(unsigned Kind) {
30 switch (Kind) {
31 default:
32 llvm_unreachable("invalid fixup kind!");
33 case FK_PCRel_1:
34 case FK_SecRel_1:
35 case FK_Data_1:
36 return 0;
37 case FK_PCRel_2:
38 case FK_SecRel_2:
39 case FK_Data_2:
40 return 1;
41 case FK_PCRel_4:
42 case X86::reloc_riprel_4byte:
43 case X86::reloc_riprel_4byte_relax:
44 case X86::reloc_riprel_4byte_relax_rex:
45 case X86::reloc_riprel_4byte_movq_load:
46 case X86::reloc_signed_4byte:
47 case X86::reloc_signed_4byte_relax:
48 case X86::reloc_global_offset_table:
49 case X86::reloc_branch_4byte_pcrel:
50 case FK_SecRel_4:
51 case FK_Data_4:
52 return 2;
53 case FK_PCRel_8:
54 case FK_SecRel_8:
55 case FK_Data_8:
56 case X86::reloc_global_offset_table8:
57 return 3;
58 }
59 }
60
61 namespace {
62
63 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
64 public:
X86ELFObjectWriter(bool is64Bit,uint8_t OSABI,uint16_t EMachine,bool HasRelocationAddend,bool foobar)65 X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
66 bool HasRelocationAddend, bool foobar)
67 : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
68 };
69
70 class X86AsmBackend : public MCAsmBackend {
71 const MCSubtargetInfo &STI;
72 public:
X86AsmBackend(const Target & T,const MCSubtargetInfo & STI)73 X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
74 : MCAsmBackend(support::little), STI(STI) {}
75
getNumFixupKinds() const76 unsigned getNumFixupKinds() const override {
77 return X86::NumTargetFixupKinds;
78 }
79
getFixupKindInfo(MCFixupKind Kind) const80 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
81 const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
82 {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
83 {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
84 {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
85 {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
86 {"reloc_signed_4byte", 0, 32, 0},
87 {"reloc_signed_4byte_relax", 0, 32, 0},
88 {"reloc_global_offset_table", 0, 32, 0},
89 {"reloc_global_offset_table8", 0, 64, 0},
90 {"reloc_branch_4byte_pcrel", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
91 };
92
93 if (Kind < FirstTargetFixupKind)
94 return MCAsmBackend::getFixupKindInfo(Kind);
95
96 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
97 "Invalid kind!");
98 assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
99 return Infos[Kind - FirstTargetFixupKind];
100 }
101
applyFixup(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,MutableArrayRef<char> Data,uint64_t Value,bool IsResolved,const MCSubtargetInfo * STI) const102 void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
103 const MCValue &Target, MutableArrayRef<char> Data,
104 uint64_t Value, bool IsResolved,
105 const MCSubtargetInfo *STI) const override {
106 unsigned Size = 1 << getFixupKindLog2Size(Fixup.getKind());
107
108 assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
109
110 // Check that uppper bits are either all zeros or all ones.
111 // Specifically ignore overflow/underflow as long as the leakage is
112 // limited to the lower bits. This is to remain compatible with
113 // other assemblers.
114 assert(isIntN(Size * 8 + 1, Value) &&
115 "Value does not fit in the Fixup field");
116
117 for (unsigned i = 0; i != Size; ++i)
118 Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
119 }
120
121 bool mayNeedRelaxation(const MCInst &Inst,
122 const MCSubtargetInfo &STI) const override;
123
124 bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
125 const MCRelaxableFragment *DF,
126 const MCAsmLayout &Layout) const override;
127
128 void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
129 MCInst &Res) const override;
130
131 bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
132 };
133 } // end anonymous namespace
134
getRelaxedOpcodeBranch(const MCInst & Inst,bool is16BitMode)135 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool is16BitMode) {
136 unsigned Op = Inst.getOpcode();
137 switch (Op) {
138 default:
139 return Op;
140 case X86::JAE_1:
141 return (is16BitMode) ? X86::JAE_2 : X86::JAE_4;
142 case X86::JA_1:
143 return (is16BitMode) ? X86::JA_2 : X86::JA_4;
144 case X86::JBE_1:
145 return (is16BitMode) ? X86::JBE_2 : X86::JBE_4;
146 case X86::JB_1:
147 return (is16BitMode) ? X86::JB_2 : X86::JB_4;
148 case X86::JE_1:
149 return (is16BitMode) ? X86::JE_2 : X86::JE_4;
150 case X86::JGE_1:
151 return (is16BitMode) ? X86::JGE_2 : X86::JGE_4;
152 case X86::JG_1:
153 return (is16BitMode) ? X86::JG_2 : X86::JG_4;
154 case X86::JLE_1:
155 return (is16BitMode) ? X86::JLE_2 : X86::JLE_4;
156 case X86::JL_1:
157 return (is16BitMode) ? X86::JL_2 : X86::JL_4;
158 case X86::JMP_1:
159 return (is16BitMode) ? X86::JMP_2 : X86::JMP_4;
160 case X86::JNE_1:
161 return (is16BitMode) ? X86::JNE_2 : X86::JNE_4;
162 case X86::JNO_1:
163 return (is16BitMode) ? X86::JNO_2 : X86::JNO_4;
164 case X86::JNP_1:
165 return (is16BitMode) ? X86::JNP_2 : X86::JNP_4;
166 case X86::JNS_1:
167 return (is16BitMode) ? X86::JNS_2 : X86::JNS_4;
168 case X86::JO_1:
169 return (is16BitMode) ? X86::JO_2 : X86::JO_4;
170 case X86::JP_1:
171 return (is16BitMode) ? X86::JP_2 : X86::JP_4;
172 case X86::JS_1:
173 return (is16BitMode) ? X86::JS_2 : X86::JS_4;
174 }
175 }
176
getRelaxedOpcodeArith(const MCInst & Inst)177 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
178 unsigned Op = Inst.getOpcode();
179 switch (Op) {
180 default:
181 return Op;
182
183 // IMUL
184 case X86::IMUL16rri8: return X86::IMUL16rri;
185 case X86::IMUL16rmi8: return X86::IMUL16rmi;
186 case X86::IMUL32rri8: return X86::IMUL32rri;
187 case X86::IMUL32rmi8: return X86::IMUL32rmi;
188 case X86::IMUL64rri8: return X86::IMUL64rri32;
189 case X86::IMUL64rmi8: return X86::IMUL64rmi32;
190
191 // AND
192 case X86::AND16ri8: return X86::AND16ri;
193 case X86::AND16mi8: return X86::AND16mi;
194 case X86::AND32ri8: return X86::AND32ri;
195 case X86::AND32mi8: return X86::AND32mi;
196 case X86::AND64ri8: return X86::AND64ri32;
197 case X86::AND64mi8: return X86::AND64mi32;
198
199 // OR
200 case X86::OR16ri8: return X86::OR16ri;
201 case X86::OR16mi8: return X86::OR16mi;
202 case X86::OR32ri8: return X86::OR32ri;
203 case X86::OR32mi8: return X86::OR32mi;
204 case X86::OR64ri8: return X86::OR64ri32;
205 case X86::OR64mi8: return X86::OR64mi32;
206
207 // XOR
208 case X86::XOR16ri8: return X86::XOR16ri;
209 case X86::XOR16mi8: return X86::XOR16mi;
210 case X86::XOR32ri8: return X86::XOR32ri;
211 case X86::XOR32mi8: return X86::XOR32mi;
212 case X86::XOR64ri8: return X86::XOR64ri32;
213 case X86::XOR64mi8: return X86::XOR64mi32;
214
215 // ADD
216 case X86::ADD16ri8: return X86::ADD16ri;
217 case X86::ADD16mi8: return X86::ADD16mi;
218 case X86::ADD32ri8: return X86::ADD32ri;
219 case X86::ADD32mi8: return X86::ADD32mi;
220 case X86::ADD64ri8: return X86::ADD64ri32;
221 case X86::ADD64mi8: return X86::ADD64mi32;
222
223 // ADC
224 case X86::ADC16ri8: return X86::ADC16ri;
225 case X86::ADC16mi8: return X86::ADC16mi;
226 case X86::ADC32ri8: return X86::ADC32ri;
227 case X86::ADC32mi8: return X86::ADC32mi;
228 case X86::ADC64ri8: return X86::ADC64ri32;
229 case X86::ADC64mi8: return X86::ADC64mi32;
230
231 // SUB
232 case X86::SUB16ri8: return X86::SUB16ri;
233 case X86::SUB16mi8: return X86::SUB16mi;
234 case X86::SUB32ri8: return X86::SUB32ri;
235 case X86::SUB32mi8: return X86::SUB32mi;
236 case X86::SUB64ri8: return X86::SUB64ri32;
237 case X86::SUB64mi8: return X86::SUB64mi32;
238
239 // SBB
240 case X86::SBB16ri8: return X86::SBB16ri;
241 case X86::SBB16mi8: return X86::SBB16mi;
242 case X86::SBB32ri8: return X86::SBB32ri;
243 case X86::SBB32mi8: return X86::SBB32mi;
244 case X86::SBB64ri8: return X86::SBB64ri32;
245 case X86::SBB64mi8: return X86::SBB64mi32;
246
247 // CMP
248 case X86::CMP16ri8: return X86::CMP16ri;
249 case X86::CMP16mi8: return X86::CMP16mi;
250 case X86::CMP32ri8: return X86::CMP32ri;
251 case X86::CMP32mi8: return X86::CMP32mi;
252 case X86::CMP64ri8: return X86::CMP64ri32;
253 case X86::CMP64mi8: return X86::CMP64mi32;
254
255 // PUSH
256 case X86::PUSH32i8: return X86::PUSHi32;
257 case X86::PUSH16i8: return X86::PUSHi16;
258 case X86::PUSH64i8: return X86::PUSH64i32;
259 }
260 }
261
getRelaxedOpcode(const MCInst & Inst,bool is16BitMode)262 static unsigned getRelaxedOpcode(const MCInst &Inst, bool is16BitMode) {
263 unsigned R = getRelaxedOpcodeArith(Inst);
264 if (R != Inst.getOpcode())
265 return R;
266 return getRelaxedOpcodeBranch(Inst, is16BitMode);
267 }
268
mayNeedRelaxation(const MCInst & Inst,const MCSubtargetInfo & STI) const269 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst,
270 const MCSubtargetInfo &STI) const {
271 // Branches can always be relaxed in either mode.
272 if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
273 return true;
274
275 // Check if this instruction is ever relaxable.
276 if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
277 return false;
278
279
280 // Check if the relaxable operand has an expression. For the current set of
281 // relaxable instructions, the relaxable operand is always the last operand.
282 unsigned RelaxableOp = Inst.getNumOperands() - 1;
283 if (Inst.getOperand(RelaxableOp).isExpr())
284 return true;
285
286 return false;
287 }
288
fixupNeedsRelaxation(const MCFixup & Fixup,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const289 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
290 uint64_t Value,
291 const MCRelaxableFragment *DF,
292 const MCAsmLayout &Layout) const {
293 // Relax if the value is too big for a (signed) i8.
294 return int64_t(Value) != int64_t(int8_t(Value));
295 }
296
297 // FIXME: Can tblgen help at all here to verify there aren't other instructions
298 // we can relax?
relaxInstruction(const MCInst & Inst,const MCSubtargetInfo & STI,MCInst & Res) const299 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
300 const MCSubtargetInfo &STI,
301 MCInst &Res) const {
302 // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
303 bool is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
304 unsigned RelaxedOp = getRelaxedOpcode(Inst, is16BitMode);
305
306 if (RelaxedOp == Inst.getOpcode()) {
307 SmallString<256> Tmp;
308 raw_svector_ostream OS(Tmp);
309 Inst.dump_pretty(OS);
310 OS << "\n";
311 report_fatal_error("unexpected instruction to relax: " + OS.str());
312 }
313
314 Res = Inst;
315 Res.setOpcode(RelaxedOp);
316 }
317
318 /// Write a sequence of optimal nops to the output, covering \p Count
319 /// bytes.
320 /// \return - true on success, false on failure
writeNopData(raw_ostream & OS,uint64_t Count) const321 bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
322 static const char Nops[10][11] = {
323 // nop
324 "\x90",
325 // xchg %ax,%ax
326 "\x66\x90",
327 // nopl (%[re]ax)
328 "\x0f\x1f\x00",
329 // nopl 0(%[re]ax)
330 "\x0f\x1f\x40\x00",
331 // nopl 0(%[re]ax,%[re]ax,1)
332 "\x0f\x1f\x44\x00\x00",
333 // nopw 0(%[re]ax,%[re]ax,1)
334 "\x66\x0f\x1f\x44\x00\x00",
335 // nopl 0L(%[re]ax)
336 "\x0f\x1f\x80\x00\x00\x00\x00",
337 // nopl 0L(%[re]ax,%[re]ax,1)
338 "\x0f\x1f\x84\x00\x00\x00\x00\x00",
339 // nopw 0L(%[re]ax,%[re]ax,1)
340 "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
341 // nopw %cs:0L(%[re]ax,%[re]ax,1)
342 "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
343 };
344
345 // This CPU doesn't support long nops. If needed add more.
346 // FIXME: We could generated something better than plain 0x90.
347 if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
348 for (uint64_t i = 0; i < Count; ++i)
349 OS << '\x90';
350 return true;
351 }
352
353 // 15-bytes is the longest single NOP instruction, but 10-bytes is
354 // commonly the longest that can be efficiently decoded.
355 uint64_t MaxNopLength = 10;
356 if (STI.getFeatureBits()[X86::ProcIntelSLM])
357 MaxNopLength = 7;
358 else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
359 MaxNopLength = 15;
360 else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
361 MaxNopLength = 11;
362
363 // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
364 // length.
365 do {
366 const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
367 const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
368 for (uint8_t i = 0; i < Prefixes; i++)
369 OS << '\x66';
370 const uint8_t Rest = ThisNopLength - Prefixes;
371 if (Rest != 0)
372 OS.write(Nops[Rest - 1], Rest);
373 Count -= ThisNopLength;
374 } while (Count != 0);
375
376 return true;
377 }
378
379 /* *** */
380
381 namespace {
382
383 class ELFX86AsmBackend : public X86AsmBackend {
384 public:
385 uint8_t OSABI;
ELFX86AsmBackend(const Target & T,uint8_t OSABI,const MCSubtargetInfo & STI)386 ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
387 : X86AsmBackend(T, STI), OSABI(OSABI) {}
388 };
389
390 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
391 public:
ELFX86_32AsmBackend(const Target & T,uint8_t OSABI,const MCSubtargetInfo & STI)392 ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
393 const MCSubtargetInfo &STI)
394 : ELFX86AsmBackend(T, OSABI, STI) {}
395
396 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const397 createObjectTargetWriter() const override {
398 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
399 }
400 };
401
402 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
403 public:
ELFX86_X32AsmBackend(const Target & T,uint8_t OSABI,const MCSubtargetInfo & STI)404 ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
405 const MCSubtargetInfo &STI)
406 : ELFX86AsmBackend(T, OSABI, STI) {}
407
408 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const409 createObjectTargetWriter() const override {
410 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
411 ELF::EM_X86_64);
412 }
413 };
414
415 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
416 public:
ELFX86_IAMCUAsmBackend(const Target & T,uint8_t OSABI,const MCSubtargetInfo & STI)417 ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
418 const MCSubtargetInfo &STI)
419 : ELFX86AsmBackend(T, OSABI, STI) {}
420
421 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const422 createObjectTargetWriter() const override {
423 return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
424 ELF::EM_IAMCU);
425 }
426 };
427
428 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
429 public:
ELFX86_64AsmBackend(const Target & T,uint8_t OSABI,const MCSubtargetInfo & STI)430 ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
431 const MCSubtargetInfo &STI)
432 : ELFX86AsmBackend(T, OSABI, STI) {}
433
434 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const435 createObjectTargetWriter() const override {
436 return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
437 }
438 };
439
440 class WindowsX86AsmBackend : public X86AsmBackend {
441 bool Is64Bit;
442
443 public:
WindowsX86AsmBackend(const Target & T,bool is64Bit,const MCSubtargetInfo & STI)444 WindowsX86AsmBackend(const Target &T, bool is64Bit,
445 const MCSubtargetInfo &STI)
446 : X86AsmBackend(T, STI)
447 , Is64Bit(is64Bit) {
448 }
449
getFixupKind(StringRef Name) const450 Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
451 return StringSwitch<Optional<MCFixupKind>>(Name)
452 .Case("dir32", FK_Data_4)
453 .Case("secrel32", FK_SecRel_4)
454 .Case("secidx", FK_SecRel_2)
455 .Default(MCAsmBackend::getFixupKind(Name));
456 }
457
458 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const459 createObjectTargetWriter() const override {
460 return createX86WinCOFFObjectWriter(Is64Bit);
461 }
462 };
463
464 namespace CU {
465
466 /// Compact unwind encoding values.
467 enum CompactUnwindEncodings {
468 /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
469 /// the return address, then [RE]SP is moved to [RE]BP.
470 UNWIND_MODE_BP_FRAME = 0x01000000,
471
472 /// A frameless function with a small constant stack size.
473 UNWIND_MODE_STACK_IMMD = 0x02000000,
474
475 /// A frameless function with a large constant stack size.
476 UNWIND_MODE_STACK_IND = 0x03000000,
477
478 /// No compact unwind encoding is available.
479 UNWIND_MODE_DWARF = 0x04000000,
480
481 /// Mask for encoding the frame registers.
482 UNWIND_BP_FRAME_REGISTERS = 0x00007FFF,
483
484 /// Mask for encoding the frameless registers.
485 UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
486 };
487
488 } // end CU namespace
489
490 class DarwinX86AsmBackend : public X86AsmBackend {
491 const MCRegisterInfo &MRI;
492
493 /// Number of registers that can be saved in a compact unwind encoding.
494 enum { CU_NUM_SAVED_REGS = 6 };
495
496 mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
497 bool Is64Bit;
498
499 unsigned OffsetSize; ///< Offset of a "push" instruction.
500 unsigned MoveInstrSize; ///< Size of a "move" instruction.
501 unsigned StackDivide; ///< Amount to adjust stack size by.
502 protected:
503 /// Size of a "push" instruction for the given register.
PushInstrSize(unsigned Reg) const504 unsigned PushInstrSize(unsigned Reg) const {
505 switch (Reg) {
506 case X86::EBX:
507 case X86::ECX:
508 case X86::EDX:
509 case X86::EDI:
510 case X86::ESI:
511 case X86::EBP:
512 case X86::RBX:
513 case X86::RBP:
514 return 1;
515 case X86::R12:
516 case X86::R13:
517 case X86::R14:
518 case X86::R15:
519 return 2;
520 }
521 return 1;
522 }
523
524 /// Implementation of algorithm to generate the compact unwind encoding
525 /// for the CFI instructions.
526 uint32_t
generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const527 generateCompactUnwindEncodingImpl(ArrayRef<MCCFIInstruction> Instrs) const {
528 if (Instrs.empty()) return 0;
529
530 // Reset the saved registers.
531 unsigned SavedRegIdx = 0;
532 memset(SavedRegs, 0, sizeof(SavedRegs));
533
534 bool HasFP = false;
535
536 // Encode that we are using EBP/RBP as the frame pointer.
537 uint32_t CompactUnwindEncoding = 0;
538
539 unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
540 unsigned InstrOffset = 0;
541 unsigned StackAdjust = 0;
542 unsigned StackSize = 0;
543 unsigned PrevStackSize = 0;
544 unsigned NumDefCFAOffsets = 0;
545
546 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
547 const MCCFIInstruction &Inst = Instrs[i];
548
549 switch (Inst.getOperation()) {
550 default:
551 // Any other CFI directives indicate a frame that we aren't prepared
552 // to represent via compact unwind, so just bail out.
553 return 0;
554 case MCCFIInstruction::OpDefCfaRegister: {
555 // Defines a frame pointer. E.g.
556 //
557 // movq %rsp, %rbp
558 // L0:
559 // .cfi_def_cfa_register %rbp
560 //
561 HasFP = true;
562
563 // If the frame pointer is other than esp/rsp, we do not have a way to
564 // generate a compact unwinding representation, so bail out.
565 if (MRI.getLLVMRegNum(Inst.getRegister(), true) !=
566 (Is64Bit ? X86::RBP : X86::EBP))
567 return 0;
568
569 // Reset the counts.
570 memset(SavedRegs, 0, sizeof(SavedRegs));
571 StackAdjust = 0;
572 SavedRegIdx = 0;
573 InstrOffset += MoveInstrSize;
574 break;
575 }
576 case MCCFIInstruction::OpDefCfaOffset: {
577 // Defines a new offset for the CFA. E.g.
578 //
579 // With frame:
580 //
581 // pushq %rbp
582 // L0:
583 // .cfi_def_cfa_offset 16
584 //
585 // Without frame:
586 //
587 // subq $72, %rsp
588 // L0:
589 // .cfi_def_cfa_offset 80
590 //
591 PrevStackSize = StackSize;
592 StackSize = std::abs(Inst.getOffset()) / StackDivide;
593 ++NumDefCFAOffsets;
594 break;
595 }
596 case MCCFIInstruction::OpOffset: {
597 // Defines a "push" of a callee-saved register. E.g.
598 //
599 // pushq %r15
600 // pushq %r14
601 // pushq %rbx
602 // L0:
603 // subq $120, %rsp
604 // L1:
605 // .cfi_offset %rbx, -40
606 // .cfi_offset %r14, -32
607 // .cfi_offset %r15, -24
608 //
609 if (SavedRegIdx == CU_NUM_SAVED_REGS)
610 // If there are too many saved registers, we cannot use a compact
611 // unwind encoding.
612 return CU::UNWIND_MODE_DWARF;
613
614 unsigned Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
615 SavedRegs[SavedRegIdx++] = Reg;
616 StackAdjust += OffsetSize;
617 InstrOffset += PushInstrSize(Reg);
618 break;
619 }
620 }
621 }
622
623 StackAdjust /= StackDivide;
624
625 if (HasFP) {
626 if ((StackAdjust & 0xFF) != StackAdjust)
627 // Offset was too big for a compact unwind encoding.
628 return CU::UNWIND_MODE_DWARF;
629
630 // Get the encoding of the saved registers when we have a frame pointer.
631 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
632 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
633
634 CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
635 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
636 CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
637 } else {
638 // If the amount of the stack allocation is the size of a register, then
639 // we "push" the RAX/EAX register onto the stack instead of adjusting the
640 // stack pointer with a SUB instruction. We don't support the push of the
641 // RAX/EAX register with compact unwind. So we check for that situation
642 // here.
643 if ((NumDefCFAOffsets == SavedRegIdx + 1 &&
644 StackSize - PrevStackSize == 1) ||
645 (Instrs.size() == 1 && NumDefCFAOffsets == 1 && StackSize == 2))
646 return CU::UNWIND_MODE_DWARF;
647
648 SubtractInstrIdx += InstrOffset;
649 ++StackAdjust;
650
651 if ((StackSize & 0xFF) == StackSize) {
652 // Frameless stack with a small stack size.
653 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
654
655 // Encode the stack size.
656 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
657 } else {
658 if ((StackAdjust & 0x7) != StackAdjust)
659 // The extra stack adjustments are too big for us to handle.
660 return CU::UNWIND_MODE_DWARF;
661
662 // Frameless stack with an offset too large for us to encode compactly.
663 CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
664
665 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
666 // instruction.
667 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
668
669 // Encode any extra stack adjustments (done via push instructions).
670 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
671 }
672
673 // Encode the number of registers saved. (Reverse the list first.)
674 std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
675 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
676
677 // Get the encoding of the saved registers when we don't have a frame
678 // pointer.
679 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
680 if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
681
682 // Encode the register encoding.
683 CompactUnwindEncoding |=
684 RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
685 }
686
687 return CompactUnwindEncoding;
688 }
689
690 private:
691 /// Get the compact unwind number for a given register. The number
692 /// corresponds to the enum lists in compact_unwind_encoding.h.
getCompactUnwindRegNum(unsigned Reg) const693 int getCompactUnwindRegNum(unsigned Reg) const {
694 static const MCPhysReg CU32BitRegs[7] = {
695 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
696 };
697 static const MCPhysReg CU64BitRegs[] = {
698 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
699 };
700 const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
701 for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
702 if (*CURegs == Reg)
703 return Idx;
704
705 return -1;
706 }
707
708 /// Return the registers encoded for a compact encoding with a frame
709 /// pointer.
encodeCompactUnwindRegistersWithFrame() const710 uint32_t encodeCompactUnwindRegistersWithFrame() const {
711 // Encode the registers in the order they were saved --- 3-bits per
712 // register. The list of saved registers is assumed to be in reverse
713 // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
714 uint32_t RegEnc = 0;
715 for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
716 unsigned Reg = SavedRegs[i];
717 if (Reg == 0) break;
718
719 int CURegNum = getCompactUnwindRegNum(Reg);
720 if (CURegNum == -1) return ~0U;
721
722 // Encode the 3-bit register number in order, skipping over 3-bits for
723 // each register.
724 RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
725 }
726
727 assert((RegEnc & 0x3FFFF) == RegEnc &&
728 "Invalid compact register encoding!");
729 return RegEnc;
730 }
731
732 /// Create the permutation encoding used with frameless stacks. It is
733 /// passed the number of registers to be saved and an array of the registers
734 /// saved.
encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const735 uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
736 // The saved registers are numbered from 1 to 6. In order to encode the
737 // order in which they were saved, we re-number them according to their
738 // place in the register order. The re-numbering is relative to the last
739 // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
740 // that order:
741 //
742 // Orig Re-Num
743 // ---- ------
744 // 6 6
745 // 2 2
746 // 4 3
747 // 5 3
748 //
749 for (unsigned i = 0; i < RegCount; ++i) {
750 int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
751 if (CUReg == -1) return ~0U;
752 SavedRegs[i] = CUReg;
753 }
754
755 // Reverse the list.
756 std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
757
758 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
759 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
760 unsigned Countless = 0;
761 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
762 if (SavedRegs[j] < SavedRegs[i])
763 ++Countless;
764
765 RenumRegs[i] = SavedRegs[i] - Countless - 1;
766 }
767
768 // Take the renumbered values and encode them into a 10-bit number.
769 uint32_t permutationEncoding = 0;
770 switch (RegCount) {
771 case 6:
772 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
773 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
774 + RenumRegs[4];
775 break;
776 case 5:
777 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
778 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
779 + RenumRegs[5];
780 break;
781 case 4:
782 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
783 + 3 * RenumRegs[4] + RenumRegs[5];
784 break;
785 case 3:
786 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
787 + RenumRegs[5];
788 break;
789 case 2:
790 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
791 break;
792 case 1:
793 permutationEncoding |= RenumRegs[5];
794 break;
795 }
796
797 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
798 "Invalid compact register encoding!");
799 return permutationEncoding;
800 }
801
802 public:
DarwinX86AsmBackend(const Target & T,const MCRegisterInfo & MRI,const MCSubtargetInfo & STI,bool Is64Bit)803 DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
804 const MCSubtargetInfo &STI, bool Is64Bit)
805 : X86AsmBackend(T, STI), MRI(MRI), Is64Bit(Is64Bit) {
806 memset(SavedRegs, 0, sizeof(SavedRegs));
807 OffsetSize = Is64Bit ? 8 : 4;
808 MoveInstrSize = Is64Bit ? 3 : 2;
809 StackDivide = Is64Bit ? 8 : 4;
810 }
811 };
812
813 class DarwinX86_32AsmBackend : public DarwinX86AsmBackend {
814 public:
DarwinX86_32AsmBackend(const Target & T,const MCRegisterInfo & MRI,const MCSubtargetInfo & STI)815 DarwinX86_32AsmBackend(const Target &T, const MCRegisterInfo &MRI,
816 const MCSubtargetInfo &STI)
817 : DarwinX86AsmBackend(T, MRI, STI, false) {}
818
819 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const820 createObjectTargetWriter() const override {
821 return createX86MachObjectWriter(/*Is64Bit=*/false,
822 MachO::CPU_TYPE_I386,
823 MachO::CPU_SUBTYPE_I386_ALL);
824 }
825
826 /// Generate the compact unwind encoding for the CFI instructions.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const827 uint32_t generateCompactUnwindEncoding(
828 ArrayRef<MCCFIInstruction> Instrs) const override {
829 return generateCompactUnwindEncodingImpl(Instrs);
830 }
831 };
832
833 class DarwinX86_64AsmBackend : public DarwinX86AsmBackend {
834 const MachO::CPUSubTypeX86 Subtype;
835 public:
DarwinX86_64AsmBackend(const Target & T,const MCRegisterInfo & MRI,const MCSubtargetInfo & STI,MachO::CPUSubTypeX86 st)836 DarwinX86_64AsmBackend(const Target &T, const MCRegisterInfo &MRI,
837 const MCSubtargetInfo &STI, MachO::CPUSubTypeX86 st)
838 : DarwinX86AsmBackend(T, MRI, STI, true), Subtype(st) {}
839
840 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const841 createObjectTargetWriter() const override {
842 return createX86MachObjectWriter(/*Is64Bit=*/true, MachO::CPU_TYPE_X86_64,
843 Subtype);
844 }
845
846 /// Generate the compact unwind encoding for the CFI instructions.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const847 uint32_t generateCompactUnwindEncoding(
848 ArrayRef<MCCFIInstruction> Instrs) const override {
849 return generateCompactUnwindEncodingImpl(Instrs);
850 }
851 };
852
853 } // end anonymous namespace
854
createX86_32AsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)855 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
856 const MCSubtargetInfo &STI,
857 const MCRegisterInfo &MRI,
858 const MCTargetOptions &Options) {
859 const Triple &TheTriple = STI.getTargetTriple();
860 if (TheTriple.isOSBinFormatMachO())
861 return new DarwinX86_32AsmBackend(T, MRI, STI);
862
863 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
864 return new WindowsX86AsmBackend(T, false, STI);
865
866 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
867
868 if (TheTriple.isOSIAMCU())
869 return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
870
871 return new ELFX86_32AsmBackend(T, OSABI, STI);
872 }
873
createX86_64AsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)874 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
875 const MCSubtargetInfo &STI,
876 const MCRegisterInfo &MRI,
877 const MCTargetOptions &Options) {
878 const Triple &TheTriple = STI.getTargetTriple();
879 if (TheTriple.isOSBinFormatMachO()) {
880 MachO::CPUSubTypeX86 CS =
881 StringSwitch<MachO::CPUSubTypeX86>(TheTriple.getArchName())
882 .Case("x86_64h", MachO::CPU_SUBTYPE_X86_64_H)
883 .Default(MachO::CPU_SUBTYPE_X86_64_ALL);
884 return new DarwinX86_64AsmBackend(T, MRI, STI, CS);
885 }
886
887 if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
888 return new WindowsX86AsmBackend(T, true, STI);
889
890 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
891
892 if (TheTriple.getEnvironment() == Triple::GNUX32)
893 return new ELFX86_X32AsmBackend(T, OSABI, STI);
894 return new ELFX86_64AsmBackend(T, OSABI, STI);
895 }
896