1 //===-- X86AsmBackend.cpp - X86 Assembler 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 #include "MCTargetDesc/X86BaseInfo.h"
10 #include "MCTargetDesc/X86FixupKinds.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/BinaryFormat/ELF.h"
13 #include "llvm/BinaryFormat/MachO.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCELFObjectWriter.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCMachObjectWriter.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 
37 using namespace llvm;
38 
39 namespace {
40 /// A wrapper for holding a mask of the values from X86::AlignBranchBoundaryKind
41 class X86AlignBranchKind {
42 private:
43   uint8_t AlignBranchKind = 0;
44 
45 public:
46   void operator=(const std::string &Val) {
47     if (Val.empty())
48       return;
49     SmallVector<StringRef, 6> BranchTypes;
50     StringRef(Val).split(BranchTypes, '+', -1, false);
51     for (auto BranchType : BranchTypes) {
52       if (BranchType == "fused")
53         addKind(X86::AlignBranchFused);
54       else if (BranchType == "jcc")
55         addKind(X86::AlignBranchJcc);
56       else if (BranchType == "jmp")
57         addKind(X86::AlignBranchJmp);
58       else if (BranchType == "call")
59         addKind(X86::AlignBranchCall);
60       else if (BranchType == "ret")
61         addKind(X86::AlignBranchRet);
62       else if (BranchType == "indirect")
63         addKind(X86::AlignBranchIndirect);
64       else {
65         errs() << "invalid argument " << BranchType.str()
66                << " to -x86-align-branch=; each element must be one of: fused, "
67                   "jcc, jmp, call, ret, indirect.(plus separated)";
68       }
69     }
70   }
71 
72   operator uint8_t() const { return AlignBranchKind; }
73   void addKind(X86::AlignBranchBoundaryKind Value) { AlignBranchKind |= Value; }
74 };
75 
76 X86AlignBranchKind X86AlignBranchKindLoc;
77 
78 cl::opt<unsigned> X86AlignBranchBoundary(
79     "x86-align-branch-boundary", cl::init(0),
80     cl::desc(
81         "Control how the assembler should align branches with NOP. If the "
82         "boundary's size is not 0, it should be a power of 2 and no less "
83         "than 32. Branches will be aligned to prevent from being across or "
84         "against the boundary of specified size. The default value 0 does not "
85         "align branches."));
86 
87 cl::opt<X86AlignBranchKind, true, cl::parser<std::string>> X86AlignBranch(
88     "x86-align-branch",
89     cl::desc(
90         "Specify types of branches to align (plus separated list of types):"
91              "\njcc      indicates conditional jumps"
92              "\nfused    indicates fused conditional jumps"
93              "\njmp      indicates direct unconditional jumps"
94              "\ncall     indicates direct and indirect calls"
95              "\nret      indicates rets"
96              "\nindirect indicates indirect unconditional jumps"),
97     cl::location(X86AlignBranchKindLoc));
98 
99 cl::opt<bool> X86AlignBranchWithin32BBoundaries(
100     "x86-branches-within-32B-boundaries", cl::init(false),
101     cl::desc(
102         "Align selected instructions to mitigate negative performance impact "
103         "of Intel's micro code update for errata skx102.  May break "
104         "assumptions about labels corresponding to particular instructions, "
105         "and should be used with caution."));
106 
107 cl::opt<unsigned> X86PadMaxPrefixSize(
108     "x86-pad-max-prefix-size", cl::init(0),
109     cl::desc("Maximum number of prefixes to use for padding"));
110 
111 cl::opt<bool> X86PadForAlign(
112     "x86-pad-for-align", cl::init(true), cl::Hidden,
113     cl::desc("Pad previous instructions to implement align directives"));
114 
115 cl::opt<bool> X86PadForBranchAlign(
116     "x86-pad-for-branch-align", cl::init(true), cl::Hidden,
117     cl::desc("Pad previous instructions to implement branch alignment"));
118 
119 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
120 public:
121   X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
122                      bool HasRelocationAddend, bool foobar)
123     : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAddend) {}
124 };
125 
126 class X86AsmBackend : public MCAsmBackend {
127   const MCSubtargetInfo &STI;
128   std::unique_ptr<const MCInstrInfo> MCII;
129   X86AlignBranchKind AlignBranchType;
130   Align AlignBoundary;
131   unsigned TargetPrefixMax = 0;
132 
133   MCInst PrevInst;
134   MCBoundaryAlignFragment *PendingBA = nullptr;
135   std::pair<MCFragment *, size_t> PrevInstPosition;
136   bool CanPadInst;
137 
138   uint8_t determinePaddingPrefix(const MCInst &Inst) const;
139   bool isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const;
140   bool needAlign(const MCInst &Inst) const;
141   bool canPadBranches(MCObjectStreamer &OS) const;
142   bool canPadInst(const MCInst &Inst, MCObjectStreamer &OS) const;
143 
144 public:
145   X86AsmBackend(const Target &T, const MCSubtargetInfo &STI)
146       : MCAsmBackend(support::little), STI(STI),
147         MCII(T.createMCInstrInfo()) {
148     if (X86AlignBranchWithin32BBoundaries) {
149       // At the moment, this defaults to aligning fused branches, unconditional
150       // jumps, and (unfused) conditional jumps with nops.  Both the
151       // instructions aligned and the alignment method (nop vs prefix) may
152       // change in the future.
153       AlignBoundary = assumeAligned(32);;
154       AlignBranchType.addKind(X86::AlignBranchFused);
155       AlignBranchType.addKind(X86::AlignBranchJcc);
156       AlignBranchType.addKind(X86::AlignBranchJmp);
157     }
158     // Allow overriding defaults set by master flag
159     if (X86AlignBranchBoundary.getNumOccurrences())
160       AlignBoundary = assumeAligned(X86AlignBranchBoundary);
161     if (X86AlignBranch.getNumOccurrences())
162       AlignBranchType = X86AlignBranchKindLoc;
163     if (X86PadMaxPrefixSize.getNumOccurrences())
164       TargetPrefixMax = X86PadMaxPrefixSize;
165   }
166 
167   bool allowAutoPadding() const override;
168   bool allowEnhancedRelaxation() const override;
169   void emitInstructionBegin(MCObjectStreamer &OS, const MCInst &Inst) override;
170   void emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst) override;
171 
172   unsigned getNumFixupKinds() const override {
173     return X86::NumTargetFixupKinds;
174   }
175 
176   Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
177 
178   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override;
179 
180   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
181                              const MCValue &Target) override;
182 
183   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
184                   const MCValue &Target, MutableArrayRef<char> Data,
185                   uint64_t Value, bool IsResolved,
186                   const MCSubtargetInfo *STI) const override;
187 
188   bool mayNeedRelaxation(const MCInst &Inst,
189                          const MCSubtargetInfo &STI) const override;
190 
191   bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
192                             const MCRelaxableFragment *DF,
193                             const MCAsmLayout &Layout) const override;
194 
195   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
196                         MCInst &Res) const override;
197 
198   bool padInstructionViaRelaxation(MCRelaxableFragment &RF,
199                                    MCCodeEmitter &Emitter,
200                                    unsigned &RemainingSize) const;
201 
202   bool padInstructionViaPrefix(MCRelaxableFragment &RF, MCCodeEmitter &Emitter,
203                                unsigned &RemainingSize) const;
204 
205   bool padInstructionEncoding(MCRelaxableFragment &RF, MCCodeEmitter &Emitter,
206                               unsigned &RemainingSize) const;
207 
208   void finishLayout(MCAssembler const &Asm, MCAsmLayout &Layout) const override;
209 
210   bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
211 };
212 } // end anonymous namespace
213 
214 static unsigned getRelaxedOpcodeBranch(const MCInst &Inst, bool Is16BitMode) {
215   unsigned Op = Inst.getOpcode();
216   switch (Op) {
217   default:
218     return Op;
219   case X86::JCC_1:
220     return (Is16BitMode) ? X86::JCC_2 : X86::JCC_4;
221   case X86::JMP_1:
222     return (Is16BitMode) ? X86::JMP_2 : X86::JMP_4;
223   }
224 }
225 
226 static unsigned getRelaxedOpcodeArith(const MCInst &Inst) {
227   unsigned Op = Inst.getOpcode();
228   switch (Op) {
229   default:
230     return Op;
231 
232     // IMUL
233   case X86::IMUL16rri8: return X86::IMUL16rri;
234   case X86::IMUL16rmi8: return X86::IMUL16rmi;
235   case X86::IMUL32rri8: return X86::IMUL32rri;
236   case X86::IMUL32rmi8: return X86::IMUL32rmi;
237   case X86::IMUL64rri8: return X86::IMUL64rri32;
238   case X86::IMUL64rmi8: return X86::IMUL64rmi32;
239 
240     // AND
241   case X86::AND16ri8: return X86::AND16ri;
242   case X86::AND16mi8: return X86::AND16mi;
243   case X86::AND32ri8: return X86::AND32ri;
244   case X86::AND32mi8: return X86::AND32mi;
245   case X86::AND64ri8: return X86::AND64ri32;
246   case X86::AND64mi8: return X86::AND64mi32;
247 
248     // OR
249   case X86::OR16ri8: return X86::OR16ri;
250   case X86::OR16mi8: return X86::OR16mi;
251   case X86::OR32ri8: return X86::OR32ri;
252   case X86::OR32mi8: return X86::OR32mi;
253   case X86::OR64ri8: return X86::OR64ri32;
254   case X86::OR64mi8: return X86::OR64mi32;
255 
256     // XOR
257   case X86::XOR16ri8: return X86::XOR16ri;
258   case X86::XOR16mi8: return X86::XOR16mi;
259   case X86::XOR32ri8: return X86::XOR32ri;
260   case X86::XOR32mi8: return X86::XOR32mi;
261   case X86::XOR64ri8: return X86::XOR64ri32;
262   case X86::XOR64mi8: return X86::XOR64mi32;
263 
264     // ADD
265   case X86::ADD16ri8: return X86::ADD16ri;
266   case X86::ADD16mi8: return X86::ADD16mi;
267   case X86::ADD32ri8: return X86::ADD32ri;
268   case X86::ADD32mi8: return X86::ADD32mi;
269   case X86::ADD64ri8: return X86::ADD64ri32;
270   case X86::ADD64mi8: return X86::ADD64mi32;
271 
272    // ADC
273   case X86::ADC16ri8: return X86::ADC16ri;
274   case X86::ADC16mi8: return X86::ADC16mi;
275   case X86::ADC32ri8: return X86::ADC32ri;
276   case X86::ADC32mi8: return X86::ADC32mi;
277   case X86::ADC64ri8: return X86::ADC64ri32;
278   case X86::ADC64mi8: return X86::ADC64mi32;
279 
280     // SUB
281   case X86::SUB16ri8: return X86::SUB16ri;
282   case X86::SUB16mi8: return X86::SUB16mi;
283   case X86::SUB32ri8: return X86::SUB32ri;
284   case X86::SUB32mi8: return X86::SUB32mi;
285   case X86::SUB64ri8: return X86::SUB64ri32;
286   case X86::SUB64mi8: return X86::SUB64mi32;
287 
288    // SBB
289   case X86::SBB16ri8: return X86::SBB16ri;
290   case X86::SBB16mi8: return X86::SBB16mi;
291   case X86::SBB32ri8: return X86::SBB32ri;
292   case X86::SBB32mi8: return X86::SBB32mi;
293   case X86::SBB64ri8: return X86::SBB64ri32;
294   case X86::SBB64mi8: return X86::SBB64mi32;
295 
296     // CMP
297   case X86::CMP16ri8: return X86::CMP16ri;
298   case X86::CMP16mi8: return X86::CMP16mi;
299   case X86::CMP32ri8: return X86::CMP32ri;
300   case X86::CMP32mi8: return X86::CMP32mi;
301   case X86::CMP64ri8: return X86::CMP64ri32;
302   case X86::CMP64mi8: return X86::CMP64mi32;
303 
304     // PUSH
305   case X86::PUSH32i8:  return X86::PUSHi32;
306   case X86::PUSH16i8:  return X86::PUSHi16;
307   case X86::PUSH64i8:  return X86::PUSH64i32;
308   }
309 }
310 
311 static unsigned getRelaxedOpcode(const MCInst &Inst, bool Is16BitMode) {
312   unsigned R = getRelaxedOpcodeArith(Inst);
313   if (R != Inst.getOpcode())
314     return R;
315   return getRelaxedOpcodeBranch(Inst, Is16BitMode);
316 }
317 
318 static X86::CondCode getCondFromBranch(const MCInst &MI,
319                                        const MCInstrInfo &MCII) {
320   unsigned Opcode = MI.getOpcode();
321   switch (Opcode) {
322   default:
323     return X86::COND_INVALID;
324   case X86::JCC_1: {
325     const MCInstrDesc &Desc = MCII.get(Opcode);
326     return static_cast<X86::CondCode>(
327         MI.getOperand(Desc.getNumOperands() - 1).getImm());
328   }
329   }
330 }
331 
332 static X86::SecondMacroFusionInstKind
333 classifySecondInstInMacroFusion(const MCInst &MI, const MCInstrInfo &MCII) {
334   X86::CondCode CC = getCondFromBranch(MI, MCII);
335   return classifySecondCondCodeInMacroFusion(CC);
336 }
337 
338 /// Check if the instruction uses RIP relative addressing.
339 static bool isRIPRelative(const MCInst &MI, const MCInstrInfo &MCII) {
340   unsigned Opcode = MI.getOpcode();
341   const MCInstrDesc &Desc = MCII.get(Opcode);
342   uint64_t TSFlags = Desc.TSFlags;
343   unsigned CurOp = X86II::getOperandBias(Desc);
344   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
345   if (MemoryOperand < 0)
346     return false;
347   unsigned BaseRegNum = MemoryOperand + CurOp + X86::AddrBaseReg;
348   unsigned BaseReg = MI.getOperand(BaseRegNum).getReg();
349   return (BaseReg == X86::RIP);
350 }
351 
352 /// Check if the instruction is a prefix.
353 static bool isPrefix(const MCInst &MI, const MCInstrInfo &MCII) {
354   return X86II::isPrefix(MCII.get(MI.getOpcode()).TSFlags);
355 }
356 
357 /// Check if the instruction is valid as the first instruction in macro fusion.
358 static bool isFirstMacroFusibleInst(const MCInst &Inst,
359                                     const MCInstrInfo &MCII) {
360   // An Intel instruction with RIP relative addressing is not macro fusible.
361   if (isRIPRelative(Inst, MCII))
362     return false;
363   X86::FirstMacroFusionInstKind FIK =
364       X86::classifyFirstOpcodeInMacroFusion(Inst.getOpcode());
365   return FIK != X86::FirstMacroFusionInstKind::Invalid;
366 }
367 
368 /// X86 can reduce the bytes of NOP by padding instructions with prefixes to
369 /// get a better peformance in some cases. Here, we determine which prefix is
370 /// the most suitable.
371 ///
372 /// If the instruction has a segment override prefix, use the existing one.
373 /// If the target is 64-bit, use the CS.
374 /// If the target is 32-bit,
375 ///   - If the instruction has a ESP/EBP base register, use SS.
376 ///   - Otherwise use DS.
377 uint8_t X86AsmBackend::determinePaddingPrefix(const MCInst &Inst) const {
378   assert((STI.hasFeature(X86::Mode32Bit) || STI.hasFeature(X86::Mode64Bit)) &&
379          "Prefixes can be added only in 32-bit or 64-bit mode.");
380   const MCInstrDesc &Desc = MCII->get(Inst.getOpcode());
381   uint64_t TSFlags = Desc.TSFlags;
382 
383   // Determine where the memory operand starts, if present.
384   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
385   if (MemoryOperand != -1)
386     MemoryOperand += X86II::getOperandBias(Desc);
387 
388   unsigned SegmentReg = 0;
389   if (MemoryOperand >= 0) {
390     // Check for explicit segment override on memory operand.
391     SegmentReg = Inst.getOperand(MemoryOperand + X86::AddrSegmentReg).getReg();
392   }
393 
394   switch (TSFlags & X86II::FormMask) {
395   default:
396     break;
397   case X86II::RawFrmDstSrc: {
398     // Check segment override opcode prefix as needed (not for %ds).
399     if (Inst.getOperand(2).getReg() != X86::DS)
400       SegmentReg = Inst.getOperand(2).getReg();
401     break;
402   }
403   case X86II::RawFrmSrc: {
404     // Check segment override opcode prefix as needed (not for %ds).
405     if (Inst.getOperand(1).getReg() != X86::DS)
406       SegmentReg = Inst.getOperand(1).getReg();
407     break;
408   }
409   case X86II::RawFrmMemOffs: {
410     // Check segment override opcode prefix as needed.
411     SegmentReg = Inst.getOperand(1).getReg();
412     break;
413   }
414   }
415 
416   if (SegmentReg != 0)
417     return X86::getSegmentOverridePrefixForReg(SegmentReg);
418 
419   if (STI.hasFeature(X86::Mode64Bit))
420     return X86::CS_Encoding;
421 
422   if (MemoryOperand >= 0) {
423     unsigned BaseRegNum = MemoryOperand + X86::AddrBaseReg;
424     unsigned BaseReg = Inst.getOperand(BaseRegNum).getReg();
425     if (BaseReg == X86::ESP || BaseReg == X86::EBP)
426       return X86::SS_Encoding;
427   }
428   return X86::DS_Encoding;
429 }
430 
431 /// Check if the two instructions will be macro-fused on the target cpu.
432 bool X86AsmBackend::isMacroFused(const MCInst &Cmp, const MCInst &Jcc) const {
433   const MCInstrDesc &InstDesc = MCII->get(Jcc.getOpcode());
434   if (!InstDesc.isConditionalBranch())
435     return false;
436   if (!isFirstMacroFusibleInst(Cmp, *MCII))
437     return false;
438   const X86::FirstMacroFusionInstKind CmpKind =
439       X86::classifyFirstOpcodeInMacroFusion(Cmp.getOpcode());
440   const X86::SecondMacroFusionInstKind BranchKind =
441       classifySecondInstInMacroFusion(Jcc, *MCII);
442   return X86::isMacroFused(CmpKind, BranchKind);
443 }
444 
445 /// Check if the instruction has a variant symbol operand.
446 static bool hasVariantSymbol(const MCInst &MI) {
447   for (auto &Operand : MI) {
448     if (!Operand.isExpr())
449       continue;
450     const MCExpr &Expr = *Operand.getExpr();
451     if (Expr.getKind() == MCExpr::SymbolRef &&
452         cast<MCSymbolRefExpr>(Expr).getKind() != MCSymbolRefExpr::VK_None)
453       return true;
454   }
455   return false;
456 }
457 
458 bool X86AsmBackend::allowAutoPadding() const {
459   return (AlignBoundary != Align(1) && AlignBranchType != X86::AlignBranchNone);
460 }
461 
462 bool X86AsmBackend::allowEnhancedRelaxation() const {
463   return allowAutoPadding() && TargetPrefixMax != 0 && X86PadForBranchAlign;
464 }
465 
466 /// X86 has certain instructions which enable interrupts exactly one
467 /// instruction *after* the instruction which stores to SS.  Return true if the
468 /// given instruction has such an interrupt delay slot.
469 static bool hasInterruptDelaySlot(const MCInst &Inst) {
470   switch (Inst.getOpcode()) {
471   case X86::POPSS16:
472   case X86::POPSS32:
473   case X86::STI:
474     return true;
475 
476   case X86::MOV16sr:
477   case X86::MOV32sr:
478   case X86::MOV64sr:
479   case X86::MOV16sm:
480     if (Inst.getOperand(0).getReg() == X86::SS)
481       return true;
482     break;
483   }
484   return false;
485 }
486 
487 /// Check if the instruction to be emitted is right after any data.
488 static bool
489 isRightAfterData(MCFragment *CurrentFragment,
490                  const std::pair<MCFragment *, size_t> &PrevInstPosition) {
491   MCFragment *F = CurrentFragment;
492   // Empty data fragments may be created to prevent further data being
493   // added into the previous fragment, we need to skip them since they
494   // have no contents.
495   for (; isa_and_nonnull<MCDataFragment>(F); F = F->getPrevNode())
496     if (cast<MCDataFragment>(F)->getContents().size() != 0)
497       break;
498 
499   // Since data is always emitted into a DataFragment, our check strategy is
500   // simple here.
501   //   - If the fragment is a DataFragment
502   //     - If it's not the fragment where the previous instruction is,
503   //       returns true.
504   //     - If it's the fragment holding the previous instruction but its
505   //       size changed since the the previous instruction was emitted into
506   //       it, returns true.
507   //     - Otherwise returns false.
508   //   - If the fragment is not a DataFragment, returns false.
509   if (auto *DF = dyn_cast_or_null<MCDataFragment>(F))
510     return DF != PrevInstPosition.first ||
511            DF->getContents().size() != PrevInstPosition.second;
512 
513   return false;
514 }
515 
516 /// \returns the fragment size if it has instructions, otherwise returns 0.
517 static size_t getSizeForInstFragment(const MCFragment *F) {
518   if (!F || !F->hasInstructions())
519     return 0;
520   // MCEncodedFragmentWithContents being templated makes this tricky.
521   switch (F->getKind()) {
522   default:
523     llvm_unreachable("Unknown fragment with instructions!");
524   case MCFragment::FT_Data:
525     return cast<MCDataFragment>(*F).getContents().size();
526   case MCFragment::FT_Relaxable:
527     return cast<MCRelaxableFragment>(*F).getContents().size();
528   case MCFragment::FT_CompactEncodedInst:
529     return cast<MCCompactEncodedInstFragment>(*F).getContents().size();
530   }
531 }
532 
533 /// Return true if we can insert NOP or prefixes automatically before the
534 /// the instruction to be emitted.
535 bool X86AsmBackend::canPadInst(const MCInst &Inst, MCObjectStreamer &OS) const {
536   if (hasVariantSymbol(Inst))
537     // Linker may rewrite the instruction with variant symbol operand(e.g.
538     // TLSCALL).
539     return false;
540 
541   if (hasInterruptDelaySlot(PrevInst))
542     // If this instruction follows an interrupt enabling instruction with a one
543     // instruction delay, inserting a nop would change behavior.
544     return false;
545 
546   if (isPrefix(PrevInst, *MCII))
547     // If this instruction follows a prefix, inserting a nop/prefix would change
548     // semantic.
549     return false;
550 
551   if (isPrefix(Inst, *MCII))
552     // If this instruction is a prefix, inserting a prefix would change
553     // semantic.
554     return false;
555 
556   if (isRightAfterData(OS.getCurrentFragment(), PrevInstPosition))
557     // If this instruction follows any data, there is no clear
558     // instruction boundary, inserting a nop/prefix would change semantic.
559     return false;
560 
561   return true;
562 }
563 
564 bool X86AsmBackend::canPadBranches(MCObjectStreamer &OS) const {
565   if (!OS.getAllowAutoPadding())
566     return false;
567   assert(allowAutoPadding() && "incorrect initialization!");
568 
569   // To be Done: Currently don't deal with Bundle cases.
570   if (OS.getAssembler().isBundlingEnabled())
571     return false;
572 
573   // Branches only need to be aligned in 32-bit or 64-bit mode.
574   if (!(STI.hasFeature(X86::Mode64Bit) || STI.hasFeature(X86::Mode32Bit)))
575     return false;
576 
577   return true;
578 }
579 
580 /// Check if the instruction operand needs to be aligned.
581 bool X86AsmBackend::needAlign(const MCInst &Inst) const {
582   const MCInstrDesc &Desc = MCII->get(Inst.getOpcode());
583   return (Desc.isConditionalBranch() &&
584           (AlignBranchType & X86::AlignBranchJcc)) ||
585          (Desc.isUnconditionalBranch() &&
586           (AlignBranchType & X86::AlignBranchJmp)) ||
587          (Desc.isCall() && (AlignBranchType & X86::AlignBranchCall)) ||
588          (Desc.isReturn() && (AlignBranchType & X86::AlignBranchRet)) ||
589          (Desc.isIndirectBranch() &&
590           (AlignBranchType & X86::AlignBranchIndirect));
591 }
592 
593 /// Insert BoundaryAlignFragment before instructions to align branches.
594 void X86AsmBackend::emitInstructionBegin(MCObjectStreamer &OS,
595                                          const MCInst &Inst) {
596   CanPadInst = canPadInst(Inst, OS);
597 
598   if (!canPadBranches(OS))
599     return;
600 
601   if (!isMacroFused(PrevInst, Inst))
602     // Macro fusion doesn't happen indeed, clear the pending.
603     PendingBA = nullptr;
604 
605   if (!CanPadInst)
606     return;
607 
608   if (PendingBA && OS.getCurrentFragment()->getPrevNode() == PendingBA) {
609     // Macro fusion actually happens and there is no other fragment inserted
610     // after the previous instruction.
611     //
612     // Do nothing here since we already inserted a BoudaryAlign fragment when
613     // we met the first instruction in the fused pair and we'll tie them
614     // together in emitInstructionEnd.
615     //
616     // Note: When there is at least one fragment, such as MCAlignFragment,
617     // inserted after the previous instruction, e.g.
618     //
619     // \code
620     //   cmp %rax %rcx
621     //   .align 16
622     //   je .Label0
623     // \ endcode
624     //
625     // We will treat the JCC as a unfused branch although it may be fused
626     // with the CMP.
627     return;
628   }
629 
630   if (needAlign(Inst) || ((AlignBranchType & X86::AlignBranchFused) &&
631                           isFirstMacroFusibleInst(Inst, *MCII))) {
632     // If we meet a unfused branch or the first instuction in a fusiable pair,
633     // insert a BoundaryAlign fragment.
634     OS.insert(PendingBA = new MCBoundaryAlignFragment(AlignBoundary));
635   }
636 }
637 
638 /// Set the last fragment to be aligned for the BoundaryAlignFragment.
639 void X86AsmBackend::emitInstructionEnd(MCObjectStreamer &OS, const MCInst &Inst) {
640   PrevInst = Inst;
641   MCFragment *CF = OS.getCurrentFragment();
642   PrevInstPosition = std::make_pair(CF, getSizeForInstFragment(CF));
643   if (auto *F = dyn_cast_or_null<MCRelaxableFragment>(CF))
644     F->setAllowAutoPadding(CanPadInst);
645 
646   if (!canPadBranches(OS))
647     return;
648 
649   if (!needAlign(Inst) || !PendingBA)
650     return;
651 
652   // Tie the aligned instructions into a a pending BoundaryAlign.
653   PendingBA->setLastFragment(CF);
654   PendingBA = nullptr;
655 
656   // We need to ensure that further data isn't added to the current
657   // DataFragment, so that we can get the size of instructions later in
658   // MCAssembler::relaxBoundaryAlign. The easiest way is to insert a new empty
659   // DataFragment.
660   if (isa_and_nonnull<MCDataFragment>(CF))
661     OS.insert(new MCDataFragment());
662 
663   // Update the maximum alignment on the current section if necessary.
664   MCSection *Sec = OS.getCurrentSectionOnly();
665   if (AlignBoundary.value() > Sec->getAlignment())
666     Sec->setAlignment(AlignBoundary);
667 }
668 
669 Optional<MCFixupKind> X86AsmBackend::getFixupKind(StringRef Name) const {
670   if (STI.getTargetTriple().isOSBinFormatELF()) {
671     unsigned Type;
672     if (STI.getTargetTriple().getArch() == Triple::x86_64) {
673       Type = llvm::StringSwitch<unsigned>(Name)
674 #define ELF_RELOC(X, Y) .Case(#X, Y)
675 #include "llvm/BinaryFormat/ELFRelocs/x86_64.def"
676 #undef ELF_RELOC
677                  .Default(-1u);
678     } else {
679       Type = llvm::StringSwitch<unsigned>(Name)
680 #define ELF_RELOC(X, Y) .Case(#X, Y)
681 #include "llvm/BinaryFormat/ELFRelocs/i386.def"
682 #undef ELF_RELOC
683                  .Default(-1u);
684     }
685     if (Type == -1u)
686       return None;
687     return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
688   }
689   return MCAsmBackend::getFixupKind(Name);
690 }
691 
692 const MCFixupKindInfo &X86AsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
693   const static MCFixupKindInfo Infos[X86::NumTargetFixupKinds] = {
694       {"reloc_riprel_4byte", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
695       {"reloc_riprel_4byte_movq_load", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
696       {"reloc_riprel_4byte_relax", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
697       {"reloc_riprel_4byte_relax_rex", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
698       {"reloc_signed_4byte", 0, 32, 0},
699       {"reloc_signed_4byte_relax", 0, 32, 0},
700       {"reloc_global_offset_table", 0, 32, 0},
701       {"reloc_global_offset_table8", 0, 64, 0},
702       {"reloc_branch_4byte_pcrel", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
703   };
704 
705   // Fixup kinds from .reloc directive are like R_386_NONE/R_X86_64_NONE. They
706   // do not require any extra processing.
707   if (Kind >= FirstLiteralRelocationKind)
708     return MCAsmBackend::getFixupKindInfo(FK_NONE);
709 
710   if (Kind < FirstTargetFixupKind)
711     return MCAsmBackend::getFixupKindInfo(Kind);
712 
713   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
714          "Invalid kind!");
715   assert(Infos[Kind - FirstTargetFixupKind].Name && "Empty fixup name!");
716   return Infos[Kind - FirstTargetFixupKind];
717 }
718 
719 bool X86AsmBackend::shouldForceRelocation(const MCAssembler &,
720                                           const MCFixup &Fixup,
721                                           const MCValue &) {
722   return Fixup.getKind() >= FirstLiteralRelocationKind;
723 }
724 
725 static unsigned getFixupKindSize(unsigned Kind) {
726   switch (Kind) {
727   default:
728     llvm_unreachable("invalid fixup kind!");
729   case FK_NONE:
730     return 0;
731   case FK_PCRel_1:
732   case FK_SecRel_1:
733   case FK_Data_1:
734     return 1;
735   case FK_PCRel_2:
736   case FK_SecRel_2:
737   case FK_Data_2:
738     return 2;
739   case FK_PCRel_4:
740   case X86::reloc_riprel_4byte:
741   case X86::reloc_riprel_4byte_relax:
742   case X86::reloc_riprel_4byte_relax_rex:
743   case X86::reloc_riprel_4byte_movq_load:
744   case X86::reloc_signed_4byte:
745   case X86::reloc_signed_4byte_relax:
746   case X86::reloc_global_offset_table:
747   case X86::reloc_branch_4byte_pcrel:
748   case FK_SecRel_4:
749   case FK_Data_4:
750     return 4;
751   case FK_PCRel_8:
752   case FK_SecRel_8:
753   case FK_Data_8:
754   case X86::reloc_global_offset_table8:
755     return 8;
756   }
757 }
758 
759 void X86AsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
760                                const MCValue &Target,
761                                MutableArrayRef<char> Data,
762                                uint64_t Value, bool IsResolved,
763                                const MCSubtargetInfo *STI) const {
764   unsigned Kind = Fixup.getKind();
765   if (Kind >= FirstLiteralRelocationKind)
766     return;
767   unsigned Size = getFixupKindSize(Kind);
768 
769   assert(Fixup.getOffset() + Size <= Data.size() && "Invalid fixup offset!");
770 
771   int64_t SignedValue = static_cast<int64_t>(Value);
772   if ((Target.isAbsolute() || IsResolved) &&
773       getFixupKindInfo(Fixup.getKind()).Flags &
774       MCFixupKindInfo::FKF_IsPCRel) {
775     // check that PC relative fixup fits into the fixup size.
776     if (Size > 0 && !isIntN(Size * 8, SignedValue))
777       Asm.getContext().reportError(
778                                    Fixup.getLoc(), "value of " + Twine(SignedValue) +
779                                    " is too large for field of " + Twine(Size) +
780                                    ((Size == 1) ? " byte." : " bytes."));
781   } else {
782     // Check that uppper bits are either all zeros or all ones.
783     // Specifically ignore overflow/underflow as long as the leakage is
784     // limited to the lower bits. This is to remain compatible with
785     // other assemblers.
786     assert((Size == 0 || isIntN(Size * 8 + 1, SignedValue)) &&
787            "Value does not fit in the Fixup field");
788   }
789 
790   for (unsigned i = 0; i != Size; ++i)
791     Data[Fixup.getOffset() + i] = uint8_t(Value >> (i * 8));
792 }
793 
794 bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst,
795                                       const MCSubtargetInfo &STI) const {
796   // Branches can always be relaxed in either mode.
797   if (getRelaxedOpcodeBranch(Inst, false) != Inst.getOpcode())
798     return true;
799 
800   // Check if this instruction is ever relaxable.
801   if (getRelaxedOpcodeArith(Inst) == Inst.getOpcode())
802     return false;
803 
804 
805   // Check if the relaxable operand has an expression. For the current set of
806   // relaxable instructions, the relaxable operand is always the last operand.
807   unsigned RelaxableOp = Inst.getNumOperands() - 1;
808   if (Inst.getOperand(RelaxableOp).isExpr())
809     return true;
810 
811   return false;
812 }
813 
814 bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
815                                          uint64_t Value,
816                                          const MCRelaxableFragment *DF,
817                                          const MCAsmLayout &Layout) const {
818   // Relax if the value is too big for a (signed) i8.
819   return !isInt<8>(Value);
820 }
821 
822 // FIXME: Can tblgen help at all here to verify there aren't other instructions
823 // we can relax?
824 void X86AsmBackend::relaxInstruction(const MCInst &Inst,
825                                      const MCSubtargetInfo &STI,
826                                      MCInst &Res) const {
827   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
828   bool Is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
829   unsigned RelaxedOp = getRelaxedOpcode(Inst, Is16BitMode);
830 
831   if (RelaxedOp == Inst.getOpcode()) {
832     SmallString<256> Tmp;
833     raw_svector_ostream OS(Tmp);
834     Inst.dump_pretty(OS);
835     OS << "\n";
836     report_fatal_error("unexpected instruction to relax: " + OS.str());
837   }
838 
839   Res = Inst;
840   Res.setOpcode(RelaxedOp);
841 }
842 
843 /// Return true if this instruction has been fully relaxed into it's most
844 /// general available form.
845 static bool isFullyRelaxed(const MCRelaxableFragment &RF) {
846   auto &Inst = RF.getInst();
847   auto &STI = *RF.getSubtargetInfo();
848   bool Is16BitMode = STI.getFeatureBits()[X86::Mode16Bit];
849   return getRelaxedOpcode(Inst, Is16BitMode) == Inst.getOpcode();
850 }
851 
852 bool X86AsmBackend::padInstructionViaPrefix(MCRelaxableFragment &RF,
853                                             MCCodeEmitter &Emitter,
854                                             unsigned &RemainingSize) const {
855   if (!RF.getAllowAutoPadding())
856     return false;
857   // If the instruction isn't fully relaxed, shifting it around might require a
858   // larger value for one of the fixups then can be encoded.  The outer loop
859   // will also catch this before moving to the next instruction, but we need to
860   // prevent padding this single instruction as well.
861   if (!isFullyRelaxed(RF))
862     return false;
863 
864   const unsigned OldSize = RF.getContents().size();
865   if (OldSize == 15)
866     return false;
867 
868   const unsigned MaxPossiblePad = std::min(15 - OldSize, RemainingSize);
869   const unsigned RemainingPrefixSize = [&]() -> unsigned {
870     SmallString<15> Code;
871     raw_svector_ostream VecOS(Code);
872     Emitter.emitPrefix(RF.getInst(), VecOS, STI);
873     assert(Code.size() < 15 && "The number of prefixes must be less than 15.");
874 
875     // TODO: It turns out we need a decent amount of plumbing for the target
876     // specific bits to determine number of prefixes its safe to add.  Various
877     // targets (older chips mostly, but also Atom family) encounter decoder
878     // stalls with too many prefixes.  For testing purposes, we set the value
879     // externally for the moment.
880     unsigned ExistingPrefixSize = Code.size();
881     if (TargetPrefixMax <= ExistingPrefixSize)
882       return 0;
883     return TargetPrefixMax - ExistingPrefixSize;
884   }();
885   const unsigned PrefixBytesToAdd =
886       std::min(MaxPossiblePad, RemainingPrefixSize);
887   if (PrefixBytesToAdd == 0)
888     return false;
889 
890   const uint8_t Prefix = determinePaddingPrefix(RF.getInst());
891 
892   SmallString<256> Code;
893   Code.append(PrefixBytesToAdd, Prefix);
894   Code.append(RF.getContents().begin(), RF.getContents().end());
895   RF.getContents() = Code;
896 
897   // Adjust the fixups for the change in offsets
898   for (auto &F : RF.getFixups()) {
899     F.setOffset(F.getOffset() + PrefixBytesToAdd);
900   }
901 
902   RemainingSize -= PrefixBytesToAdd;
903   return true;
904 }
905 
906 bool X86AsmBackend::padInstructionViaRelaxation(MCRelaxableFragment &RF,
907                                                 MCCodeEmitter &Emitter,
908                                                 unsigned &RemainingSize) const {
909   if (isFullyRelaxed(RF))
910     // TODO: There are lots of other tricks we could apply for increasing
911     // encoding size without impacting performance.
912     return false;
913 
914   MCInst Relaxed;
915   relaxInstruction(RF.getInst(), *RF.getSubtargetInfo(), Relaxed);
916 
917   SmallVector<MCFixup, 4> Fixups;
918   SmallString<15> Code;
919   raw_svector_ostream VecOS(Code);
920   Emitter.encodeInstruction(Relaxed, VecOS, Fixups, *RF.getSubtargetInfo());
921   const unsigned OldSize = RF.getContents().size();
922   const unsigned NewSize = Code.size();
923   assert(NewSize >= OldSize && "size decrease during relaxation?");
924   unsigned Delta = NewSize - OldSize;
925   if (Delta > RemainingSize)
926     return false;
927   RF.setInst(Relaxed);
928   RF.getContents() = Code;
929   RF.getFixups() = Fixups;
930   RemainingSize -= Delta;
931   return true;
932 }
933 
934 bool X86AsmBackend::padInstructionEncoding(MCRelaxableFragment &RF,
935                                            MCCodeEmitter &Emitter,
936                                            unsigned &RemainingSize) const {
937   bool Changed = false;
938   if (RemainingSize != 0)
939     Changed |= padInstructionViaRelaxation(RF, Emitter, RemainingSize);
940   if (RemainingSize != 0)
941     Changed |= padInstructionViaPrefix(RF, Emitter, RemainingSize);
942   return Changed;
943 }
944 
945 void X86AsmBackend::finishLayout(MCAssembler const &Asm,
946                                  MCAsmLayout &Layout) const {
947   // See if we can further relax some instructions to cut down on the number of
948   // nop bytes required for code alignment.  The actual win is in reducing
949   // instruction count, not number of bytes.  Modern X86-64 can easily end up
950   // decode limited.  It is often better to reduce the number of instructions
951   // (i.e. eliminate nops) even at the cost of increasing the size and
952   // complexity of others.
953   if (!X86PadForAlign && !X86PadForBranchAlign)
954     return;
955 
956   DenseSet<MCFragment *> LabeledFragments;
957   for (const MCSymbol &S : Asm.symbols())
958     LabeledFragments.insert(S.getFragment(false));
959 
960   for (MCSection &Sec : Asm) {
961     if (!Sec.getKind().isText())
962       continue;
963 
964     SmallVector<MCRelaxableFragment *, 4> Relaxable;
965     for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
966       MCFragment &F = *I;
967 
968       if (LabeledFragments.count(&F))
969         Relaxable.clear();
970 
971       if (F.getKind() == MCFragment::FT_Data ||
972           F.getKind() == MCFragment::FT_CompactEncodedInst)
973         // Skip and ignore
974         continue;
975 
976       if (F.getKind() == MCFragment::FT_Relaxable) {
977         auto &RF = cast<MCRelaxableFragment>(*I);
978         Relaxable.push_back(&RF);
979         continue;
980       }
981 
982       auto canHandle = [](MCFragment &F) -> bool {
983         switch (F.getKind()) {
984         default:
985           return false;
986         case MCFragment::FT_Align:
987           return X86PadForAlign;
988         case MCFragment::FT_BoundaryAlign:
989           return X86PadForBranchAlign;
990         }
991       };
992       // For any unhandled kind, assume we can't change layout.
993       if (!canHandle(F)) {
994         Relaxable.clear();
995         continue;
996       }
997 
998 #ifndef NDEBUG
999       const uint64_t OrigOffset = Layout.getFragmentOffset(&F);
1000 #endif
1001       const uint64_t OrigSize = Asm.computeFragmentSize(Layout, F);
1002 
1003       // To keep the effects local, prefer to relax instructions closest to
1004       // the align directive.  This is purely about human understandability
1005       // of the resulting code.  If we later find a reason to expand
1006       // particular instructions over others, we can adjust.
1007       MCFragment *FirstChangedFragment = nullptr;
1008       unsigned RemainingSize = OrigSize;
1009       while (!Relaxable.empty() && RemainingSize != 0) {
1010         auto &RF = *Relaxable.pop_back_val();
1011         // Give the backend a chance to play any tricks it wishes to increase
1012         // the encoding size of the given instruction.  Target independent code
1013         // will try further relaxation, but target's may play further tricks.
1014         if (padInstructionEncoding(RF, Asm.getEmitter(), RemainingSize))
1015           FirstChangedFragment = &RF;
1016 
1017         // If we have an instruction which hasn't been fully relaxed, we can't
1018         // skip past it and insert bytes before it.  Changing its starting
1019         // offset might require a larger negative offset than it can encode.
1020         // We don't need to worry about larger positive offsets as none of the
1021         // possible offsets between this and our align are visible, and the
1022         // ones afterwards aren't changing.
1023         if (!isFullyRelaxed(RF))
1024           break;
1025       }
1026       Relaxable.clear();
1027 
1028       if (FirstChangedFragment) {
1029         // Make sure the offsets for any fragments in the effected range get
1030         // updated.  Note that this (conservatively) invalidates the offsets of
1031         // those following, but this is not required.
1032         Layout.invalidateFragmentsFrom(FirstChangedFragment);
1033       }
1034 
1035       // BoundaryAlign explicitly tracks it's size (unlike align)
1036       if (F.getKind() == MCFragment::FT_BoundaryAlign)
1037         cast<MCBoundaryAlignFragment>(F).setSize(RemainingSize);
1038 
1039 #ifndef NDEBUG
1040       const uint64_t FinalOffset = Layout.getFragmentOffset(&F);
1041       const uint64_t FinalSize = Asm.computeFragmentSize(Layout, F);
1042       assert(OrigOffset + OrigSize == FinalOffset + FinalSize &&
1043              "can't move start of next fragment!");
1044       assert(FinalSize == RemainingSize && "inconsistent size computation?");
1045 #endif
1046 
1047       // If we're looking at a boundary align, make sure we don't try to pad
1048       // its target instructions for some following directive.  Doing so would
1049       // break the alignment of the current boundary align.
1050       if (auto *BF = dyn_cast<MCBoundaryAlignFragment>(&F)) {
1051         const MCFragment *LastFragment = BF->getLastFragment();
1052         if (!LastFragment)
1053           continue;
1054         while (&*I != LastFragment)
1055           ++I;
1056       }
1057     }
1058   }
1059 
1060   // The layout is done. Mark every fragment as valid.
1061   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1062     MCSection &Section = *Layout.getSectionOrder()[i];
1063     Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1064     Asm.computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1065   }
1066 }
1067 
1068 /// Write a sequence of optimal nops to the output, covering \p Count
1069 /// bytes.
1070 /// \return - true on success, false on failure
1071 bool X86AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
1072   static const char Nops[10][11] = {
1073     // nop
1074     "\x90",
1075     // xchg %ax,%ax
1076     "\x66\x90",
1077     // nopl (%[re]ax)
1078     "\x0f\x1f\x00",
1079     // nopl 0(%[re]ax)
1080     "\x0f\x1f\x40\x00",
1081     // nopl 0(%[re]ax,%[re]ax,1)
1082     "\x0f\x1f\x44\x00\x00",
1083     // nopw 0(%[re]ax,%[re]ax,1)
1084     "\x66\x0f\x1f\x44\x00\x00",
1085     // nopl 0L(%[re]ax)
1086     "\x0f\x1f\x80\x00\x00\x00\x00",
1087     // nopl 0L(%[re]ax,%[re]ax,1)
1088     "\x0f\x1f\x84\x00\x00\x00\x00\x00",
1089     // nopw 0L(%[re]ax,%[re]ax,1)
1090     "\x66\x0f\x1f\x84\x00\x00\x00\x00\x00",
1091     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1092     "\x66\x2e\x0f\x1f\x84\x00\x00\x00\x00\x00",
1093   };
1094 
1095   // This CPU doesn't support long nops. If needed add more.
1096   // FIXME: We could generated something better than plain 0x90.
1097   if (!STI.getFeatureBits()[X86::FeatureNOPL]) {
1098     for (uint64_t i = 0; i < Count; ++i)
1099       OS << '\x90';
1100     return true;
1101   }
1102 
1103   // 15-bytes is the longest single NOP instruction, but 10-bytes is
1104   // commonly the longest that can be efficiently decoded.
1105   uint64_t MaxNopLength = 10;
1106   if (STI.getFeatureBits()[X86::FeatureFast7ByteNOP])
1107     MaxNopLength = 7;
1108   else if (STI.getFeatureBits()[X86::FeatureFast15ByteNOP])
1109     MaxNopLength = 15;
1110   else if (STI.getFeatureBits()[X86::FeatureFast11ByteNOP])
1111     MaxNopLength = 11;
1112 
1113   // Emit as many MaxNopLength NOPs as needed, then emit a NOP of the remaining
1114   // length.
1115   do {
1116     const uint8_t ThisNopLength = (uint8_t) std::min(Count, MaxNopLength);
1117     const uint8_t Prefixes = ThisNopLength <= 10 ? 0 : ThisNopLength - 10;
1118     for (uint8_t i = 0; i < Prefixes; i++)
1119       OS << '\x66';
1120     const uint8_t Rest = ThisNopLength - Prefixes;
1121     if (Rest != 0)
1122       OS.write(Nops[Rest - 1], Rest);
1123     Count -= ThisNopLength;
1124   } while (Count != 0);
1125 
1126   return true;
1127 }
1128 
1129 /* *** */
1130 
1131 namespace {
1132 
1133 class ELFX86AsmBackend : public X86AsmBackend {
1134 public:
1135   uint8_t OSABI;
1136   ELFX86AsmBackend(const Target &T, uint8_t OSABI, const MCSubtargetInfo &STI)
1137       : X86AsmBackend(T, STI), OSABI(OSABI) {}
1138 };
1139 
1140 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
1141 public:
1142   ELFX86_32AsmBackend(const Target &T, uint8_t OSABI,
1143                       const MCSubtargetInfo &STI)
1144     : ELFX86AsmBackend(T, OSABI, STI) {}
1145 
1146   std::unique_ptr<MCObjectTargetWriter>
1147   createObjectTargetWriter() const override {
1148     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI, ELF::EM_386);
1149   }
1150 };
1151 
1152 class ELFX86_X32AsmBackend : public ELFX86AsmBackend {
1153 public:
1154   ELFX86_X32AsmBackend(const Target &T, uint8_t OSABI,
1155                        const MCSubtargetInfo &STI)
1156       : ELFX86AsmBackend(T, OSABI, STI) {}
1157 
1158   std::unique_ptr<MCObjectTargetWriter>
1159   createObjectTargetWriter() const override {
1160     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1161                                     ELF::EM_X86_64);
1162   }
1163 };
1164 
1165 class ELFX86_IAMCUAsmBackend : public ELFX86AsmBackend {
1166 public:
1167   ELFX86_IAMCUAsmBackend(const Target &T, uint8_t OSABI,
1168                          const MCSubtargetInfo &STI)
1169       : ELFX86AsmBackend(T, OSABI, STI) {}
1170 
1171   std::unique_ptr<MCObjectTargetWriter>
1172   createObjectTargetWriter() const override {
1173     return createX86ELFObjectWriter(/*IsELF64*/ false, OSABI,
1174                                     ELF::EM_IAMCU);
1175   }
1176 };
1177 
1178 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
1179 public:
1180   ELFX86_64AsmBackend(const Target &T, uint8_t OSABI,
1181                       const MCSubtargetInfo &STI)
1182     : ELFX86AsmBackend(T, OSABI, STI) {}
1183 
1184   std::unique_ptr<MCObjectTargetWriter>
1185   createObjectTargetWriter() const override {
1186     return createX86ELFObjectWriter(/*IsELF64*/ true, OSABI, ELF::EM_X86_64);
1187   }
1188 };
1189 
1190 class WindowsX86AsmBackend : public X86AsmBackend {
1191   bool Is64Bit;
1192 
1193 public:
1194   WindowsX86AsmBackend(const Target &T, bool is64Bit,
1195                        const MCSubtargetInfo &STI)
1196     : X86AsmBackend(T, STI)
1197     , Is64Bit(is64Bit) {
1198   }
1199 
1200   Optional<MCFixupKind> getFixupKind(StringRef Name) const override {
1201     return StringSwitch<Optional<MCFixupKind>>(Name)
1202         .Case("dir32", FK_Data_4)
1203         .Case("secrel32", FK_SecRel_4)
1204         .Case("secidx", FK_SecRel_2)
1205         .Default(MCAsmBackend::getFixupKind(Name));
1206   }
1207 
1208   std::unique_ptr<MCObjectTargetWriter>
1209   createObjectTargetWriter() const override {
1210     return createX86WinCOFFObjectWriter(Is64Bit);
1211   }
1212 };
1213 
1214 namespace CU {
1215 
1216   /// Compact unwind encoding values.
1217   enum CompactUnwindEncodings {
1218     /// [RE]BP based frame where [RE]BP is pused on the stack immediately after
1219     /// the return address, then [RE]SP is moved to [RE]BP.
1220     UNWIND_MODE_BP_FRAME                   = 0x01000000,
1221 
1222     /// A frameless function with a small constant stack size.
1223     UNWIND_MODE_STACK_IMMD                 = 0x02000000,
1224 
1225     /// A frameless function with a large constant stack size.
1226     UNWIND_MODE_STACK_IND                  = 0x03000000,
1227 
1228     /// No compact unwind encoding is available.
1229     UNWIND_MODE_DWARF                      = 0x04000000,
1230 
1231     /// Mask for encoding the frame registers.
1232     UNWIND_BP_FRAME_REGISTERS              = 0x00007FFF,
1233 
1234     /// Mask for encoding the frameless registers.
1235     UNWIND_FRAMELESS_STACK_REG_PERMUTATION = 0x000003FF
1236   };
1237 
1238 } // end CU namespace
1239 
1240 class DarwinX86AsmBackend : public X86AsmBackend {
1241   const MCRegisterInfo &MRI;
1242 
1243   /// Number of registers that can be saved in a compact unwind encoding.
1244   enum { CU_NUM_SAVED_REGS = 6 };
1245 
1246   mutable unsigned SavedRegs[CU_NUM_SAVED_REGS];
1247   Triple TT;
1248   bool Is64Bit;
1249 
1250   unsigned OffsetSize;                   ///< Offset of a "push" instruction.
1251   unsigned MoveInstrSize;                ///< Size of a "move" instruction.
1252   unsigned StackDivide;                  ///< Amount to adjust stack size by.
1253 protected:
1254   /// Size of a "push" instruction for the given register.
1255   unsigned PushInstrSize(unsigned Reg) const {
1256     switch (Reg) {
1257       case X86::EBX:
1258       case X86::ECX:
1259       case X86::EDX:
1260       case X86::EDI:
1261       case X86::ESI:
1262       case X86::EBP:
1263       case X86::RBX:
1264       case X86::RBP:
1265         return 1;
1266       case X86::R12:
1267       case X86::R13:
1268       case X86::R14:
1269       case X86::R15:
1270         return 2;
1271     }
1272     return 1;
1273   }
1274 
1275 private:
1276   /// Get the compact unwind number for a given register. The number
1277   /// corresponds to the enum lists in compact_unwind_encoding.h.
1278   int getCompactUnwindRegNum(unsigned Reg) const {
1279     static const MCPhysReg CU32BitRegs[7] = {
1280       X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
1281     };
1282     static const MCPhysReg CU64BitRegs[] = {
1283       X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
1284     };
1285     const MCPhysReg *CURegs = Is64Bit ? CU64BitRegs : CU32BitRegs;
1286     for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
1287       if (*CURegs == Reg)
1288         return Idx;
1289 
1290     return -1;
1291   }
1292 
1293   /// Return the registers encoded for a compact encoding with a frame
1294   /// pointer.
1295   uint32_t encodeCompactUnwindRegistersWithFrame() const {
1296     // Encode the registers in the order they were saved --- 3-bits per
1297     // register. The list of saved registers is assumed to be in reverse
1298     // order. The registers are numbered from 1 to CU_NUM_SAVED_REGS.
1299     uint32_t RegEnc = 0;
1300     for (int i = 0, Idx = 0; i != CU_NUM_SAVED_REGS; ++i) {
1301       unsigned Reg = SavedRegs[i];
1302       if (Reg == 0) break;
1303 
1304       int CURegNum = getCompactUnwindRegNum(Reg);
1305       if (CURegNum == -1) return ~0U;
1306 
1307       // Encode the 3-bit register number in order, skipping over 3-bits for
1308       // each register.
1309       RegEnc |= (CURegNum & 0x7) << (Idx++ * 3);
1310     }
1311 
1312     assert((RegEnc & 0x3FFFF) == RegEnc &&
1313            "Invalid compact register encoding!");
1314     return RegEnc;
1315   }
1316 
1317   /// Create the permutation encoding used with frameless stacks. It is
1318   /// passed the number of registers to be saved and an array of the registers
1319   /// saved.
1320   uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned RegCount) const {
1321     // The saved registers are numbered from 1 to 6. In order to encode the
1322     // order in which they were saved, we re-number them according to their
1323     // place in the register order. The re-numbering is relative to the last
1324     // re-numbered register. E.g., if we have registers {6, 2, 4, 5} saved in
1325     // that order:
1326     //
1327     //    Orig  Re-Num
1328     //    ----  ------
1329     //     6       6
1330     //     2       2
1331     //     4       3
1332     //     5       3
1333     //
1334     for (unsigned i = 0; i < RegCount; ++i) {
1335       int CUReg = getCompactUnwindRegNum(SavedRegs[i]);
1336       if (CUReg == -1) return ~0U;
1337       SavedRegs[i] = CUReg;
1338     }
1339 
1340     // Reverse the list.
1341     std::reverse(&SavedRegs[0], &SavedRegs[CU_NUM_SAVED_REGS]);
1342 
1343     uint32_t RenumRegs[CU_NUM_SAVED_REGS];
1344     for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i){
1345       unsigned Countless = 0;
1346       for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
1347         if (SavedRegs[j] < SavedRegs[i])
1348           ++Countless;
1349 
1350       RenumRegs[i] = SavedRegs[i] - Countless - 1;
1351     }
1352 
1353     // Take the renumbered values and encode them into a 10-bit number.
1354     uint32_t permutationEncoding = 0;
1355     switch (RegCount) {
1356     case 6:
1357       permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
1358                              + 6 * RenumRegs[2] +  2 * RenumRegs[3]
1359                              +     RenumRegs[4];
1360       break;
1361     case 5:
1362       permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
1363                              + 6 * RenumRegs[3] +  2 * RenumRegs[4]
1364                              +     RenumRegs[5];
1365       break;
1366     case 4:
1367       permutationEncoding |=  60 * RenumRegs[2] + 12 * RenumRegs[3]
1368                              + 3 * RenumRegs[4] +      RenumRegs[5];
1369       break;
1370     case 3:
1371       permutationEncoding |=  20 * RenumRegs[3] +  4 * RenumRegs[4]
1372                              +     RenumRegs[5];
1373       break;
1374     case 2:
1375       permutationEncoding |=   5 * RenumRegs[4] +      RenumRegs[5];
1376       break;
1377     case 1:
1378       permutationEncoding |=       RenumRegs[5];
1379       break;
1380     }
1381 
1382     assert((permutationEncoding & 0x3FF) == permutationEncoding &&
1383            "Invalid compact register encoding!");
1384     return permutationEncoding;
1385   }
1386 
1387 public:
1388   DarwinX86AsmBackend(const Target &T, const MCRegisterInfo &MRI,
1389                       const MCSubtargetInfo &STI)
1390       : X86AsmBackend(T, STI), MRI(MRI), TT(STI.getTargetTriple()),
1391         Is64Bit(TT.isArch64Bit()) {
1392     memset(SavedRegs, 0, sizeof(SavedRegs));
1393     OffsetSize = Is64Bit ? 8 : 4;
1394     MoveInstrSize = Is64Bit ? 3 : 2;
1395     StackDivide = Is64Bit ? 8 : 4;
1396   }
1397 
1398   std::unique_ptr<MCObjectTargetWriter>
1399   createObjectTargetWriter() const override {
1400     uint32_t CPUType = cantFail(MachO::getCPUType(TT));
1401     uint32_t CPUSubType = cantFail(MachO::getCPUSubType(TT));
1402     return createX86MachObjectWriter(Is64Bit, CPUType, CPUSubType);
1403   }
1404 
1405   /// Implementation of algorithm to generate the compact unwind encoding
1406   /// for the CFI instructions.
1407   uint32_t
1408   generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const override {
1409     if (Instrs.empty()) return 0;
1410 
1411     // Reset the saved registers.
1412     unsigned SavedRegIdx = 0;
1413     memset(SavedRegs, 0, sizeof(SavedRegs));
1414 
1415     bool HasFP = false;
1416 
1417     // Encode that we are using EBP/RBP as the frame pointer.
1418     uint32_t CompactUnwindEncoding = 0;
1419 
1420     unsigned SubtractInstrIdx = Is64Bit ? 3 : 2;
1421     unsigned InstrOffset = 0;
1422     unsigned StackAdjust = 0;
1423     unsigned StackSize = 0;
1424     unsigned NumDefCFAOffsets = 0;
1425 
1426     for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1427       const MCCFIInstruction &Inst = Instrs[i];
1428 
1429       switch (Inst.getOperation()) {
1430       default:
1431         // Any other CFI directives indicate a frame that we aren't prepared
1432         // to represent via compact unwind, so just bail out.
1433         return 0;
1434       case MCCFIInstruction::OpDefCfaRegister: {
1435         // Defines a frame pointer. E.g.
1436         //
1437         //     movq %rsp, %rbp
1438         //  L0:
1439         //     .cfi_def_cfa_register %rbp
1440         //
1441         HasFP = true;
1442 
1443         // If the frame pointer is other than esp/rsp, we do not have a way to
1444         // generate a compact unwinding representation, so bail out.
1445         if (*MRI.getLLVMRegNum(Inst.getRegister(), true) !=
1446             (Is64Bit ? X86::RBP : X86::EBP))
1447           return 0;
1448 
1449         // Reset the counts.
1450         memset(SavedRegs, 0, sizeof(SavedRegs));
1451         StackAdjust = 0;
1452         SavedRegIdx = 0;
1453         InstrOffset += MoveInstrSize;
1454         break;
1455       }
1456       case MCCFIInstruction::OpDefCfaOffset: {
1457         // Defines a new offset for the CFA. E.g.
1458         //
1459         //  With frame:
1460         //
1461         //     pushq %rbp
1462         //  L0:
1463         //     .cfi_def_cfa_offset 16
1464         //
1465         //  Without frame:
1466         //
1467         //     subq $72, %rsp
1468         //  L0:
1469         //     .cfi_def_cfa_offset 80
1470         //
1471         StackSize = std::abs(Inst.getOffset()) / StackDivide;
1472         ++NumDefCFAOffsets;
1473         break;
1474       }
1475       case MCCFIInstruction::OpOffset: {
1476         // Defines a "push" of a callee-saved register. E.g.
1477         //
1478         //     pushq %r15
1479         //     pushq %r14
1480         //     pushq %rbx
1481         //  L0:
1482         //     subq $120, %rsp
1483         //  L1:
1484         //     .cfi_offset %rbx, -40
1485         //     .cfi_offset %r14, -32
1486         //     .cfi_offset %r15, -24
1487         //
1488         if (SavedRegIdx == CU_NUM_SAVED_REGS)
1489           // If there are too many saved registers, we cannot use a compact
1490           // unwind encoding.
1491           return CU::UNWIND_MODE_DWARF;
1492 
1493         unsigned Reg = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1494         SavedRegs[SavedRegIdx++] = Reg;
1495         StackAdjust += OffsetSize;
1496         InstrOffset += PushInstrSize(Reg);
1497         break;
1498       }
1499       }
1500     }
1501 
1502     StackAdjust /= StackDivide;
1503 
1504     if (HasFP) {
1505       if ((StackAdjust & 0xFF) != StackAdjust)
1506         // Offset was too big for a compact unwind encoding.
1507         return CU::UNWIND_MODE_DWARF;
1508 
1509       // Get the encoding of the saved registers when we have a frame pointer.
1510       uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame();
1511       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1512 
1513       CompactUnwindEncoding |= CU::UNWIND_MODE_BP_FRAME;
1514       CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
1515       CompactUnwindEncoding |= RegEnc & CU::UNWIND_BP_FRAME_REGISTERS;
1516     } else {
1517       SubtractInstrIdx += InstrOffset;
1518       ++StackAdjust;
1519 
1520       if ((StackSize & 0xFF) == StackSize) {
1521         // Frameless stack with a small stack size.
1522         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IMMD;
1523 
1524         // Encode the stack size.
1525         CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
1526       } else {
1527         if ((StackAdjust & 0x7) != StackAdjust)
1528           // The extra stack adjustments are too big for us to handle.
1529           return CU::UNWIND_MODE_DWARF;
1530 
1531         // Frameless stack with an offset too large for us to encode compactly.
1532         CompactUnwindEncoding |= CU::UNWIND_MODE_STACK_IND;
1533 
1534         // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
1535         // instruction.
1536         CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
1537 
1538         // Encode any extra stack adjustments (done via push instructions).
1539         CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
1540       }
1541 
1542       // Encode the number of registers saved. (Reverse the list first.)
1543       std::reverse(&SavedRegs[0], &SavedRegs[SavedRegIdx]);
1544       CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
1545 
1546       // Get the encoding of the saved registers when we don't have a frame
1547       // pointer.
1548       uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegIdx);
1549       if (RegEnc == ~0U) return CU::UNWIND_MODE_DWARF;
1550 
1551       // Encode the register encoding.
1552       CompactUnwindEncoding |=
1553         RegEnc & CU::UNWIND_FRAMELESS_STACK_REG_PERMUTATION;
1554     }
1555 
1556     return CompactUnwindEncoding;
1557   }
1558 };
1559 
1560 } // end anonymous namespace
1561 
1562 MCAsmBackend *llvm::createX86_32AsmBackend(const Target &T,
1563                                            const MCSubtargetInfo &STI,
1564                                            const MCRegisterInfo &MRI,
1565                                            const MCTargetOptions &Options) {
1566   const Triple &TheTriple = STI.getTargetTriple();
1567   if (TheTriple.isOSBinFormatMachO())
1568     return new DarwinX86AsmBackend(T, MRI, STI);
1569 
1570   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1571     return new WindowsX86AsmBackend(T, false, STI);
1572 
1573   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1574 
1575   if (TheTriple.isOSIAMCU())
1576     return new ELFX86_IAMCUAsmBackend(T, OSABI, STI);
1577 
1578   return new ELFX86_32AsmBackend(T, OSABI, STI);
1579 }
1580 
1581 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T,
1582                                            const MCSubtargetInfo &STI,
1583                                            const MCRegisterInfo &MRI,
1584                                            const MCTargetOptions &Options) {
1585   const Triple &TheTriple = STI.getTargetTriple();
1586   if (TheTriple.isOSBinFormatMachO())
1587     return new DarwinX86AsmBackend(T, MRI, STI);
1588 
1589   if (TheTriple.isOSWindows() && TheTriple.isOSBinFormatCOFF())
1590     return new WindowsX86AsmBackend(T, true, STI);
1591 
1592   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1593 
1594   if (TheTriple.getEnvironment() == Triple::GNUX32)
1595     return new ELFX86_X32AsmBackend(T, OSABI, STI);
1596   return new ELFX86_64AsmBackend(T, OSABI, STI);
1597 }
1598