Taints the non-acquire RMW's store address with the load part
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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 "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <tuple>
33 using namespace llvm;
34
35 #define DEBUG_TYPE "assembler"
36
37 namespace {
38 namespace stats {
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41           "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43           "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45           "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47           "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49           "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51           "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
57 }
58 }
59
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
64
65 /* *** */
66
67 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
68                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
69     : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
70       BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
71       IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
72   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
73 }
74
75 MCAssembler::~MCAssembler() {
76 }
77
78 void MCAssembler::reset() {
79   Sections.clear();
80   Symbols.clear();
81   IndirectSymbols.clear();
82   DataRegions.clear();
83   LinkerOptions.clear();
84   FileNames.clear();
85   ThumbFuncs.clear();
86   BundleAlignSize = 0;
87   RelaxAll = false;
88   SubsectionsViaSymbols = false;
89   IncrementalLinkerCompatible = false;
90   ELFHeaderEFlags = 0;
91   LOHContainer.reset();
92   VersionMinInfo.Major = 0;
93
94   // reset objects owned by us
95   getBackend().reset();
96   getEmitter().reset();
97   getWriter().reset();
98   getLOHContainer().reset();
99 }
100
101 bool MCAssembler::registerSection(MCSection &Section) {
102   if (Section.isRegistered())
103     return false;
104   Sections.push_back(&Section);
105   Section.setIsRegistered(true);
106   return true;
107 }
108
109 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
110   if (ThumbFuncs.count(Symbol))
111     return true;
112
113   if (!Symbol->isVariable())
114     return false;
115
116   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
117   // is not clear if that is a bug or a feature.
118   const MCExpr *Expr = Symbol->getVariableValue();
119   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
120   if (!Ref)
121     return false;
122
123   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
124     return false;
125
126   const MCSymbol &Sym = Ref->getSymbol();
127   if (!isThumbFunc(&Sym))
128     return false;
129
130   ThumbFuncs.insert(Symbol); // Cache it.
131   return true;
132 }
133
134 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
135   // Non-temporary labels should always be visible to the linker.
136   if (!Symbol.isTemporary())
137     return true;
138
139   // Absolute temporary labels are never visible.
140   if (!Symbol.isInSection())
141     return false;
142
143   if (Symbol.isUsedInReloc())
144     return true;
145
146   return false;
147 }
148
149 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
150   // Linker visible symbols define atoms.
151   if (isSymbolLinkerVisible(S))
152     return &S;
153
154   // Absolute and undefined symbols have no defining atom.
155   if (!S.isInSection())
156     return nullptr;
157
158   // Non-linker visible symbols in sections which can't be atomized have no
159   // defining atom.
160   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
161           *S.getFragment()->getParent()))
162     return nullptr;
163
164   // Otherwise, return the atom for the containing fragment.
165   return S.getFragment()->getAtom();
166 }
167
168 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
169                                 const MCFixup &Fixup, const MCFragment *DF,
170                                 MCValue &Target, uint64_t &Value) const {
171   ++stats::evaluateFixup;
172
173   // FIXME: This code has some duplication with recordRelocation. We should
174   // probably merge the two into a single callback that tries to evaluate a
175   // fixup and records a relocation if one is needed.
176   const MCExpr *Expr = Fixup.getValue();
177   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
178     getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
179     // Claim to have completely evaluated the fixup, to prevent any further
180     // processing from being done.
181     Value = 0;
182     return true;
183   }
184
185   bool IsPCRel = Backend.getFixupKindInfo(
186     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
187
188   bool IsResolved;
189   if (IsPCRel) {
190     if (Target.getSymB()) {
191       IsResolved = false;
192     } else if (!Target.getSymA()) {
193       IsResolved = false;
194     } else {
195       const MCSymbolRefExpr *A = Target.getSymA();
196       const MCSymbol &SA = A->getSymbol();
197       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
198         IsResolved = false;
199       } else {
200         IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
201             *this, SA, *DF, false, true);
202       }
203     }
204   } else {
205     IsResolved = Target.isAbsolute();
206   }
207
208   Value = Target.getConstant();
209
210   if (const MCSymbolRefExpr *A = Target.getSymA()) {
211     const MCSymbol &Sym = A->getSymbol();
212     if (Sym.isDefined())
213       Value += Layout.getSymbolOffset(Sym);
214   }
215   if (const MCSymbolRefExpr *B = Target.getSymB()) {
216     const MCSymbol &Sym = B->getSymbol();
217     if (Sym.isDefined())
218       Value -= Layout.getSymbolOffset(Sym);
219   }
220
221
222   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
223                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
224   assert((ShouldAlignPC ? IsPCRel : true) &&
225     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
226
227   if (IsPCRel) {
228     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
229
230     // A number of ARM fixups in Thumb mode require that the effective PC
231     // address be determined as the 32-bit aligned version of the actual offset.
232     if (ShouldAlignPC) Offset &= ~0x3;
233     Value -= Offset;
234   }
235
236   // Let the backend adjust the fixup value if necessary, including whether
237   // we need a relocation.
238   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
239                             IsResolved);
240
241   return IsResolved;
242 }
243
244 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
245                                           const MCFragment &F) const {
246   switch (F.getKind()) {
247   case MCFragment::FT_Data:
248     return cast<MCDataFragment>(F).getContents().size();
249   case MCFragment::FT_Relaxable:
250     return cast<MCRelaxableFragment>(F).getContents().size();
251   case MCFragment::FT_CompactEncodedInst:
252     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
253   case MCFragment::FT_Fill:
254     return cast<MCFillFragment>(F).getSize();
255
256   case MCFragment::FT_LEB:
257     return cast<MCLEBFragment>(F).getContents().size();
258
259   case MCFragment::FT_SafeSEH:
260     return 4;
261
262   case MCFragment::FT_Align: {
263     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
264     unsigned Offset = Layout.getFragmentOffset(&AF);
265     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
266     // If we are padding with nops, force the padding to be larger than the
267     // minimum nop size.
268     if (Size > 0 && AF.hasEmitNops()) {
269       while (Size % getBackend().getMinimumNopSize())
270         Size += AF.getAlignment();
271     }
272     if (Size > AF.getMaxBytesToEmit())
273       return 0;
274     return Size;
275   }
276
277   case MCFragment::FT_Org: {
278     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
279     MCValue Value;
280     if (!OF.getOffset().evaluateAsValue(Value, Layout))
281       report_fatal_error("expected assembly-time absolute expression");
282
283     // FIXME: We need a way to communicate this error.
284     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
285     int64_t TargetLocation = Value.getConstant();
286     if (const MCSymbolRefExpr *A = Value.getSymA()) {
287       uint64_t Val;
288       if (!Layout.getSymbolOffset(A->getSymbol(), Val))
289         report_fatal_error("expected absolute expression");
290       TargetLocation += Val;
291     }
292     int64_t Size = TargetLocation - FragmentOffset;
293     if (Size < 0 || Size >= 0x40000000)
294       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
295                          "' (at offset '" + Twine(FragmentOffset) + "')");
296     return Size;
297   }
298
299   case MCFragment::FT_Dwarf:
300     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
301   case MCFragment::FT_DwarfFrame:
302     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
303   case MCFragment::FT_Dummy:
304     llvm_unreachable("Should not have been added");
305   }
306
307   llvm_unreachable("invalid fragment kind");
308 }
309
310 void MCAsmLayout::layoutFragment(MCFragment *F) {
311   MCFragment *Prev = F->getPrevNode();
312
313   // We should never try to recompute something which is valid.
314   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
315   // We should never try to compute the fragment layout if its predecessor
316   // isn't valid.
317   assert((!Prev || isFragmentValid(Prev)) &&
318          "Attempt to compute fragment before its predecessor!");
319
320   ++stats::FragmentLayouts;
321
322   // Compute fragment offset and size.
323   if (Prev)
324     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
325   else
326     F->Offset = 0;
327   LastValidFragment[F->getParent()] = F;
328
329   // If bundling is enabled and this fragment has instructions in it, it has to
330   // obey the bundling restrictions. With padding, we'll have:
331   //
332   //
333   //        BundlePadding
334   //             |||
335   // -------------------------------------
336   //   Prev  |##########|       F        |
337   // -------------------------------------
338   //                    ^
339   //                    |
340   //                    F->Offset
341   //
342   // The fragment's offset will point to after the padding, and its computed
343   // size won't include the padding.
344   //
345   // When the -mc-relax-all flag is used, we optimize bundling by writting the
346   // padding directly into fragments when the instructions are emitted inside
347   // the streamer. When the fragment is larger than the bundle size, we need to
348   // ensure that it's bundle aligned. This means that if we end up with
349   // multiple fragments, we must emit bundle padding between fragments.
350   //
351   // ".align N" is an example of a directive that introduces multiple
352   // fragments. We could add a special case to handle ".align N" by emitting
353   // within-fragment padding (which would produce less padding when N is less
354   // than the bundle size), but for now we don't.
355   //
356   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
357     assert(isa<MCEncodedFragment>(F) &&
358            "Only MCEncodedFragment implementations have instructions");
359     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
360
361     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
362       report_fatal_error("Fragment can't be larger than a bundle size");
363
364     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
365                                                           F->Offset, FSize);
366     if (RequiredBundlePadding > UINT8_MAX)
367       report_fatal_error("Padding cannot exceed 255 bytes");
368     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
369     F->Offset += RequiredBundlePadding;
370   }
371 }
372
373 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
374   bool New = !Symbol.isRegistered();
375   if (Created)
376     *Created = New;
377   if (New) {
378     Symbol.setIsRegistered(true);
379     Symbols.push_back(&Symbol);
380   }
381 }
382
383 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
384                                        MCObjectWriter *OW) const {
385   // Should NOP padding be written out before this fragment?
386   unsigned BundlePadding = F.getBundlePadding();
387   if (BundlePadding > 0) {
388     assert(isBundlingEnabled() &&
389            "Writing bundle padding with disabled bundling");
390     assert(F.hasInstructions() &&
391            "Writing bundle padding for a fragment without instructions");
392
393     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
394     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
395       // If the padding itself crosses a bundle boundary, it must be emitted
396       // in 2 pieces, since even nop instructions must not cross boundaries.
397       //             v--------------v   <- BundleAlignSize
398       //        v---------v             <- BundlePadding
399       // ----------------------------
400       // | Prev |####|####|    F    |
401       // ----------------------------
402       //        ^-------------------^   <- TotalLength
403       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
404       if (!getBackend().writeNopData(DistanceToBoundary, OW))
405           report_fatal_error("unable to write NOP sequence of " +
406                              Twine(DistanceToBoundary) + " bytes");
407       BundlePadding -= DistanceToBoundary;
408     }
409     if (!getBackend().writeNopData(BundlePadding, OW))
410       report_fatal_error("unable to write NOP sequence of " +
411                          Twine(BundlePadding) + " bytes");
412   }
413 }
414
415 /// \brief Write the fragment \p F to the output file.
416 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
417                           const MCFragment &F) {
418   MCObjectWriter *OW = &Asm.getWriter();
419
420   // FIXME: Embed in fragments instead?
421   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
422
423   Asm.writeFragmentPadding(F, FragmentSize, OW);
424
425   // This variable (and its dummy usage) is to participate in the assert at
426   // the end of the function.
427   uint64_t Start = OW->getStream().tell();
428   (void) Start;
429
430   ++stats::EmittedFragments;
431
432   switch (F.getKind()) {
433   case MCFragment::FT_Align: {
434     ++stats::EmittedAlignFragments;
435     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
436     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
437
438     uint64_t Count = FragmentSize / AF.getValueSize();
439
440     // FIXME: This error shouldn't actually occur (the front end should emit
441     // multiple .align directives to enforce the semantics it wants), but is
442     // severe enough that we want to report it. How to handle this?
443     if (Count * AF.getValueSize() != FragmentSize)
444       report_fatal_error("undefined .align directive, value size '" +
445                         Twine(AF.getValueSize()) +
446                         "' is not a divisor of padding size '" +
447                         Twine(FragmentSize) + "'");
448
449     // See if we are aligning with nops, and if so do that first to try to fill
450     // the Count bytes.  Then if that did not fill any bytes or there are any
451     // bytes left to fill use the Value and ValueSize to fill the rest.
452     // If we are aligning with nops, ask that target to emit the right data.
453     if (AF.hasEmitNops()) {
454       if (!Asm.getBackend().writeNopData(Count, OW))
455         report_fatal_error("unable to write nop sequence of " +
456                           Twine(Count) + " bytes");
457       break;
458     }
459
460     // Otherwise, write out in multiples of the value size.
461     for (uint64_t i = 0; i != Count; ++i) {
462       switch (AF.getValueSize()) {
463       default: llvm_unreachable("Invalid size!");
464       case 1: OW->write8 (uint8_t (AF.getValue())); break;
465       case 2: OW->write16(uint16_t(AF.getValue())); break;
466       case 4: OW->write32(uint32_t(AF.getValue())); break;
467       case 8: OW->write64(uint64_t(AF.getValue())); break;
468       }
469     }
470     break;
471   }
472
473   case MCFragment::FT_Data: 
474     ++stats::EmittedDataFragments;
475     OW->writeBytes(cast<MCDataFragment>(F).getContents());
476     break;
477
478   case MCFragment::FT_Relaxable:
479     ++stats::EmittedRelaxableFragments;
480     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
481     break;
482
483   case MCFragment::FT_CompactEncodedInst:
484     ++stats::EmittedCompactEncodedInstFragments;
485     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
486     break;
487
488   case MCFragment::FT_Fill: {
489     ++stats::EmittedFillFragments;
490     const MCFillFragment &FF = cast<MCFillFragment>(F);
491
492     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
493
494     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
495       switch (FF.getValueSize()) {
496       default: llvm_unreachable("Invalid size!");
497       case 1: OW->write8 (uint8_t (FF.getValue())); break;
498       case 2: OW->write16(uint16_t(FF.getValue())); break;
499       case 4: OW->write32(uint32_t(FF.getValue())); break;
500       case 8: OW->write64(uint64_t(FF.getValue())); break;
501       }
502     }
503     break;
504   }
505
506   case MCFragment::FT_LEB: {
507     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
508     OW->writeBytes(LF.getContents());
509     break;
510   }
511
512   case MCFragment::FT_SafeSEH: {
513     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
514     OW->write32(SF.getSymbol()->getIndex());
515     break;
516   }
517
518   case MCFragment::FT_Org: {
519     ++stats::EmittedOrgFragments;
520     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
521
522     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
523       OW->write8(uint8_t(OF.getValue()));
524
525     break;
526   }
527
528   case MCFragment::FT_Dwarf: {
529     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
530     OW->writeBytes(OF.getContents());
531     break;
532   }
533   case MCFragment::FT_DwarfFrame: {
534     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
535     OW->writeBytes(CF.getContents());
536     break;
537   }
538   case MCFragment::FT_Dummy:
539     llvm_unreachable("Should not have been added");
540   }
541
542   assert(OW->getStream().tell() - Start == FragmentSize &&
543          "The stream should advance by fragment size");
544 }
545
546 void MCAssembler::writeSectionData(const MCSection *Sec,
547                                    const MCAsmLayout &Layout) const {
548   // Ignore virtual sections.
549   if (Sec->isVirtualSection()) {
550     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
551
552     // Check that contents are only things legal inside a virtual section.
553     for (const MCFragment &F : *Sec) {
554       switch (F.getKind()) {
555       default: llvm_unreachable("Invalid fragment in virtual section!");
556       case MCFragment::FT_Data: {
557         // Check that we aren't trying to write a non-zero contents (or fixups)
558         // into a virtual section. This is to support clients which use standard
559         // directives to fill the contents of virtual sections.
560         const MCDataFragment &DF = cast<MCDataFragment>(F);
561         assert(DF.fixup_begin() == DF.fixup_end() &&
562                "Cannot have fixups in virtual section!");
563         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
564           if (DF.getContents()[i]) {
565             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
566               report_fatal_error("non-zero initializer found in section '" +
567                   ELFSec->getSectionName() + "'");
568             else
569               report_fatal_error("non-zero initializer found in virtual section");
570           }
571         break;
572       }
573       case MCFragment::FT_Align:
574         // Check that we aren't trying to write a non-zero value into a virtual
575         // section.
576         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
577                 cast<MCAlignFragment>(F).getValue() == 0) &&
578                "Invalid align in virtual section!");
579         break;
580       case MCFragment::FT_Fill:
581         assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
582                 cast<MCFillFragment>(F).getValue() == 0) &&
583                "Invalid fill in virtual section!");
584         break;
585       }
586     }
587
588     return;
589   }
590
591   uint64_t Start = getWriter().getStream().tell();
592   (void)Start;
593
594   for (const MCFragment &F : *Sec)
595     writeFragment(*this, Layout, F);
596
597   assert(getWriter().getStream().tell() - Start ==
598          Layout.getSectionAddressSize(Sec));
599 }
600
601 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
602                                                    MCFragment &F,
603                                                    const MCFixup &Fixup) {
604   // Evaluate the fixup.
605   MCValue Target;
606   uint64_t FixedValue;
607   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
608                  MCFixupKindInfo::FKF_IsPCRel;
609   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
610     // The fixup was unresolved, we need a relocation. Inform the object
611     // writer of the relocation, and give it an opportunity to adjust the
612     // fixup value if need be.
613     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
614                                  FixedValue);
615   }
616   return std::make_pair(FixedValue, IsPCRel);
617 }
618
619 void MCAssembler::layout(MCAsmLayout &Layout) {
620   DEBUG_WITH_TYPE("mc-dump", {
621       llvm::errs() << "assembler backend - pre-layout\n--\n";
622       dump(); });
623
624   // Create dummy fragments and assign section ordinals.
625   unsigned SectionIndex = 0;
626   for (MCSection &Sec : *this) {
627     // Create dummy fragments to eliminate any empty sections, this simplifies
628     // layout.
629     if (Sec.getFragmentList().empty())
630       new MCDataFragment(&Sec);
631
632     Sec.setOrdinal(SectionIndex++);
633   }
634
635   // Assign layout order indices to sections and fragments.
636   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
637     MCSection *Sec = Layout.getSectionOrder()[i];
638     Sec->setLayoutOrder(i);
639
640     unsigned FragmentIndex = 0;
641     for (MCFragment &Frag : *Sec)
642       Frag.setLayoutOrder(FragmentIndex++);
643   }
644
645   // Layout until everything fits.
646   while (layoutOnce(Layout))
647     continue;
648
649   DEBUG_WITH_TYPE("mc-dump", {
650       llvm::errs() << "assembler backend - post-relaxation\n--\n";
651       dump(); });
652
653   // Finalize the layout, including fragment lowering.
654   finishLayout(Layout);
655
656   DEBUG_WITH_TYPE("mc-dump", {
657       llvm::errs() << "assembler backend - final-layout\n--\n";
658       dump(); });
659
660   // Allow the object writer a chance to perform post-layout binding (for
661   // example, to set the index fields in the symbol data).
662   getWriter().executePostLayoutBinding(*this, Layout);
663
664   // Evaluate and apply the fixups, generating relocation entries as necessary.
665   for (MCSection &Sec : *this) {
666     for (MCFragment &Frag : Sec) {
667       MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
668       // Data and relaxable fragments both have fixups.  So only process
669       // those here.
670       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
671       // being templated makes this tricky.
672       if (!F || isa<MCCompactEncodedInstFragment>(F))
673         continue;
674       ArrayRef<MCFixup> Fixups;
675       MutableArrayRef<char> Contents;
676       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
677         Fixups = FragWithFixups->getFixups();
678         Contents = FragWithFixups->getContents();
679       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
680         Fixups = FragWithFixups->getFixups();
681         Contents = FragWithFixups->getContents();
682       } else
683         llvm_unreachable("Unknown fragment with fixups!");
684       for (const MCFixup &Fixup : Fixups) {
685         uint64_t FixedValue;
686         bool IsPCRel;
687         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
688         getBackend().applyFixup(Fixup, Contents.data(),
689                                 Contents.size(), FixedValue, IsPCRel);
690       }
691     }
692   }
693 }
694
695 void MCAssembler::Finish() {
696   // Create the layout object.
697   MCAsmLayout Layout(*this);
698   layout(Layout);
699
700   raw_ostream &OS = getWriter().getStream();
701   uint64_t StartOffset = OS.tell();
702
703   // Write the object file.
704   getWriter().writeObject(*this, Layout);
705
706   stats::ObjectBytes += OS.tell() - StartOffset;
707 }
708
709 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
710                                        const MCRelaxableFragment *DF,
711                                        const MCAsmLayout &Layout) const {
712   MCValue Target;
713   uint64_t Value;
714   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
715   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
716                                                    Layout);
717 }
718
719 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
720                                           const MCAsmLayout &Layout) const {
721   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
722   // are intentionally pushing out inst fragments, or because we relaxed a
723   // previous instruction to one that doesn't need relaxation.
724   if (!getBackend().mayNeedRelaxation(F->getInst()))
725     return false;
726
727   for (const MCFixup &Fixup : F->getFixups())
728     if (fixupNeedsRelaxation(Fixup, F, Layout))
729       return true;
730
731   return false;
732 }
733
734 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
735                                    MCRelaxableFragment &F) {
736   if (!fragmentNeedsRelaxation(&F, Layout))
737     return false;
738
739   ++stats::RelaxedInstructions;
740
741   // FIXME-PERF: We could immediately lower out instructions if we can tell
742   // they are fully resolved, to avoid retesting on later passes.
743
744   // Relax the fragment.
745
746   MCInst Relaxed;
747   getBackend().relaxInstruction(F.getInst(), Relaxed);
748
749   // Encode the new instruction.
750   //
751   // FIXME-PERF: If it matters, we could let the target do this. It can
752   // probably do so more efficiently in many cases.
753   SmallVector<MCFixup, 4> Fixups;
754   SmallString<256> Code;
755   raw_svector_ostream VecOS(Code);
756   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
757
758   // Update the fragment.
759   F.setInst(Relaxed);
760   F.getContents() = Code;
761   F.getFixups() = Fixups;
762
763   return true;
764 }
765
766 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
767   uint64_t OldSize = LF.getContents().size();
768   int64_t Value;
769   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
770   if (!Abs)
771     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
772   SmallString<8> &Data = LF.getContents();
773   Data.clear();
774   raw_svector_ostream OSE(Data);
775   if (LF.isSigned())
776     encodeSLEB128(Value, OSE);
777   else
778     encodeULEB128(Value, OSE);
779   return OldSize != LF.getContents().size();
780 }
781
782 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
783                                      MCDwarfLineAddrFragment &DF) {
784   MCContext &Context = Layout.getAssembler().getContext();
785   uint64_t OldSize = DF.getContents().size();
786   int64_t AddrDelta;
787   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
788   assert(Abs && "We created a line delta with an invalid expression");
789   (void) Abs;
790   int64_t LineDelta;
791   LineDelta = DF.getLineDelta();
792   SmallString<8> &Data = DF.getContents();
793   Data.clear();
794   raw_svector_ostream OSE(Data);
795   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
796                           AddrDelta, OSE);
797   return OldSize != Data.size();
798 }
799
800 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
801                                               MCDwarfCallFrameFragment &DF) {
802   MCContext &Context = Layout.getAssembler().getContext();
803   uint64_t OldSize = DF.getContents().size();
804   int64_t AddrDelta;
805   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
806   assert(Abs && "We created call frame with an invalid expression");
807   (void) Abs;
808   SmallString<8> &Data = DF.getContents();
809   Data.clear();
810   raw_svector_ostream OSE(Data);
811   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
812   return OldSize != Data.size();
813 }
814
815 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
816   // Holds the first fragment which needed relaxing during this layout. It will
817   // remain NULL if none were relaxed.
818   // When a fragment is relaxed, all the fragments following it should get
819   // invalidated because their offset is going to change.
820   MCFragment *FirstRelaxedFragment = nullptr;
821
822   // Attempt to relax all the fragments in the section.
823   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
824     // Check if this is a fragment that needs relaxation.
825     bool RelaxedFrag = false;
826     switch(I->getKind()) {
827     default:
828       break;
829     case MCFragment::FT_Relaxable:
830       assert(!getRelaxAll() &&
831              "Did not expect a MCRelaxableFragment in RelaxAll mode");
832       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
833       break;
834     case MCFragment::FT_Dwarf:
835       RelaxedFrag = relaxDwarfLineAddr(Layout,
836                                        *cast<MCDwarfLineAddrFragment>(I));
837       break;
838     case MCFragment::FT_DwarfFrame:
839       RelaxedFrag =
840         relaxDwarfCallFrameFragment(Layout,
841                                     *cast<MCDwarfCallFrameFragment>(I));
842       break;
843     case MCFragment::FT_LEB:
844       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
845       break;
846     }
847     if (RelaxedFrag && !FirstRelaxedFragment)
848       FirstRelaxedFragment = &*I;
849   }
850   if (FirstRelaxedFragment) {
851     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
852     return true;
853   }
854   return false;
855 }
856
857 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
858   ++stats::RelaxationSteps;
859
860   bool WasRelaxed = false;
861   for (iterator it = begin(), ie = end(); it != ie; ++it) {
862     MCSection &Sec = *it;
863     while (layoutSectionOnce(Layout, Sec))
864       WasRelaxed = true;
865   }
866
867   return WasRelaxed;
868 }
869
870 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
871   // The layout is done. Mark every fragment as valid.
872   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
873     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
874   }
875 }