1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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 "llvm/MC/MCAssembler.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCCodeView.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Alignment.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/EndianStream.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <cstring>
44 #include <tuple>
45 #include <utility>
46
47 using namespace llvm;
48
49 #define DEBUG_TYPE "assembler"
50
51 namespace {
52 namespace stats {
53
54 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
55 STATISTIC(EmittedRelaxableFragments,
56 "Number of emitted assembler fragments - relaxable");
57 STATISTIC(EmittedDataFragments,
58 "Number of emitted assembler fragments - data");
59 STATISTIC(EmittedCompactEncodedInstFragments,
60 "Number of emitted assembler fragments - compact encoded inst");
61 STATISTIC(EmittedAlignFragments,
62 "Number of emitted assembler fragments - align");
63 STATISTIC(EmittedFillFragments,
64 "Number of emitted assembler fragments - fill");
65 STATISTIC(EmittedOrgFragments,
66 "Number of emitted assembler fragments - org");
67 STATISTIC(evaluateFixup, "Number of evaluated fixups");
68 STATISTIC(FragmentLayouts, "Number of fragment layouts");
69 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
70 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
71 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
72
73 } // end namespace stats
74 } // end anonymous namespace
75
76 // FIXME FIXME FIXME: There are number of places in this file where we convert
77 // what is a 64-bit assembler value used for computation into a value in the
78 // object file, which may truncate it. We should detect that truncation where
79 // invalid and report errors back.
80
81 /* *** */
82
MCAssembler(MCContext & Context,std::unique_ptr<MCAsmBackend> Backend,std::unique_ptr<MCCodeEmitter> Emitter,std::unique_ptr<MCObjectWriter> Writer)83 MCAssembler::MCAssembler(MCContext &Context,
84 std::unique_ptr<MCAsmBackend> Backend,
85 std::unique_ptr<MCCodeEmitter> Emitter,
86 std::unique_ptr<MCObjectWriter> Writer)
87 : Context(Context), Backend(std::move(Backend)),
88 Emitter(std::move(Emitter)), Writer(std::move(Writer)),
89 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
90 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
91 VersionInfo.Major = 0; // Major version == 0 for "none specified"
92 }
93
94 MCAssembler::~MCAssembler() = default;
95
reset()96 void MCAssembler::reset() {
97 Sections.clear();
98 Symbols.clear();
99 IndirectSymbols.clear();
100 DataRegions.clear();
101 LinkerOptions.clear();
102 FileNames.clear();
103 ThumbFuncs.clear();
104 BundleAlignSize = 0;
105 RelaxAll = false;
106 SubsectionsViaSymbols = false;
107 IncrementalLinkerCompatible = false;
108 ELFHeaderEFlags = 0;
109 LOHContainer.reset();
110 VersionInfo.Major = 0;
111 VersionInfo.SDKVersion = VersionTuple();
112
113 // reset objects owned by us
114 if (getBackendPtr())
115 getBackendPtr()->reset();
116 if (getEmitterPtr())
117 getEmitterPtr()->reset();
118 if (getWriterPtr())
119 getWriterPtr()->reset();
120 getLOHContainer().reset();
121 }
122
registerSection(MCSection & Section)123 bool MCAssembler::registerSection(MCSection &Section) {
124 if (Section.isRegistered())
125 return false;
126 Sections.push_back(&Section);
127 Section.setIsRegistered(true);
128 return true;
129 }
130
isThumbFunc(const MCSymbol * Symbol) const131 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
132 if (ThumbFuncs.count(Symbol))
133 return true;
134
135 if (!Symbol->isVariable())
136 return false;
137
138 const MCExpr *Expr = Symbol->getVariableValue();
139
140 MCValue V;
141 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
142 return false;
143
144 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
145 return false;
146
147 const MCSymbolRefExpr *Ref = V.getSymA();
148 if (!Ref)
149 return false;
150
151 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
152 return false;
153
154 const MCSymbol &Sym = Ref->getSymbol();
155 if (!isThumbFunc(&Sym))
156 return false;
157
158 ThumbFuncs.insert(Symbol); // Cache it.
159 return true;
160 }
161
isSymbolLinkerVisible(const MCSymbol & Symbol) const162 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
163 // Non-temporary labels should always be visible to the linker.
164 if (!Symbol.isTemporary())
165 return true;
166
167 if (Symbol.isUsedInReloc())
168 return true;
169
170 return false;
171 }
172
getAtom(const MCSymbol & S) const173 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
174 // Linker visible symbols define atoms.
175 if (isSymbolLinkerVisible(S))
176 return &S;
177
178 // Absolute and undefined symbols have no defining atom.
179 if (!S.isInSection())
180 return nullptr;
181
182 // Non-linker visible symbols in sections which can't be atomized have no
183 // defining atom.
184 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
185 *S.getFragment()->getParent()))
186 return nullptr;
187
188 // Otherwise, return the atom for the containing fragment.
189 return S.getFragment()->getAtom();
190 }
191
evaluateFixup(const MCAsmLayout & Layout,const MCFixup & Fixup,const MCFragment * DF,MCValue & Target,uint64_t & Value,bool & WasForced) const192 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
193 const MCFixup &Fixup, const MCFragment *DF,
194 MCValue &Target, uint64_t &Value,
195 bool &WasForced) const {
196 ++stats::evaluateFixup;
197
198 // FIXME: This code has some duplication with recordRelocation. We should
199 // probably merge the two into a single callback that tries to evaluate a
200 // fixup and records a relocation if one is needed.
201
202 // On error claim to have completely evaluated the fixup, to prevent any
203 // further processing from being done.
204 const MCExpr *Expr = Fixup.getValue();
205 MCContext &Ctx = getContext();
206 Value = 0;
207 WasForced = false;
208 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
209 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
210 return true;
211 }
212 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
213 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
214 Ctx.reportError(Fixup.getLoc(),
215 "unsupported subtraction of qualified symbol");
216 return true;
217 }
218 }
219
220 assert(getBackendPtr() && "Expected assembler backend");
221 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
222 MCFixupKindInfo::FKF_IsTarget;
223
224 if (IsTarget)
225 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
226 Value, WasForced);
227
228 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
229 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
230 MCFixupKindInfo::FKF_IsPCRel;
231
232 bool IsResolved = false;
233 if (IsPCRel) {
234 if (Target.getSymB()) {
235 IsResolved = false;
236 } else if (!Target.getSymA()) {
237 IsResolved = false;
238 } else {
239 const MCSymbolRefExpr *A = Target.getSymA();
240 const MCSymbol &SA = A->getSymbol();
241 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
242 IsResolved = false;
243 } else if (auto *Writer = getWriterPtr()) {
244 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
245 Writer->isSymbolRefDifferenceFullyResolvedImpl(
246 *this, SA, *DF, false, true);
247 }
248 }
249 } else {
250 IsResolved = Target.isAbsolute();
251 }
252
253 Value = Target.getConstant();
254
255 if (const MCSymbolRefExpr *A = Target.getSymA()) {
256 const MCSymbol &Sym = A->getSymbol();
257 if (Sym.isDefined())
258 Value += Layout.getSymbolOffset(Sym);
259 }
260 if (const MCSymbolRefExpr *B = Target.getSymB()) {
261 const MCSymbol &Sym = B->getSymbol();
262 if (Sym.isDefined())
263 Value -= Layout.getSymbolOffset(Sym);
264 }
265
266 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
267 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
268 assert((ShouldAlignPC ? IsPCRel : true) &&
269 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
270
271 if (IsPCRel) {
272 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
273
274 // A number of ARM fixups in Thumb mode require that the effective PC
275 // address be determined as the 32-bit aligned version of the actual offset.
276 if (ShouldAlignPC) Offset &= ~0x3;
277 Value -= Offset;
278 }
279
280 // Let the backend force a relocation if needed.
281 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
282 IsResolved = false;
283 WasForced = true;
284 }
285
286 return IsResolved;
287 }
288
computeFragmentSize(const MCAsmLayout & Layout,const MCFragment & F) const289 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
290 const MCFragment &F) const {
291 assert(getBackendPtr() && "Requires assembler backend");
292 switch (F.getKind()) {
293 case MCFragment::FT_Data:
294 return cast<MCDataFragment>(F).getContents().size();
295 case MCFragment::FT_Relaxable:
296 return cast<MCRelaxableFragment>(F).getContents().size();
297 case MCFragment::FT_CompactEncodedInst:
298 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
299 case MCFragment::FT_Fill: {
300 auto &FF = cast<MCFillFragment>(F);
301 int64_t NumValues = 0;
302 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
303 getContext().reportError(FF.getLoc(),
304 "expected assembly-time absolute expression");
305 return 0;
306 }
307 int64_t Size = NumValues * FF.getValueSize();
308 if (Size < 0) {
309 getContext().reportError(FF.getLoc(), "invalid number of bytes");
310 return 0;
311 }
312 return Size;
313 }
314
315 case MCFragment::FT_LEB:
316 return cast<MCLEBFragment>(F).getContents().size();
317
318 case MCFragment::FT_BoundaryAlign:
319 return cast<MCBoundaryAlignFragment>(F).getSize();
320
321 case MCFragment::FT_SymbolId:
322 return 4;
323
324 case MCFragment::FT_Align: {
325 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
326 unsigned Offset = Layout.getFragmentOffset(&AF);
327 unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment()));
328
329 // Insert extra Nops for code alignment if the target define
330 // shouldInsertExtraNopBytesForCodeAlign target hook.
331 if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() &&
332 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
333 return Size;
334
335 // If we are padding with nops, force the padding to be larger than the
336 // minimum nop size.
337 if (Size > 0 && AF.hasEmitNops()) {
338 while (Size % getBackend().getMinimumNopSize())
339 Size += AF.getAlignment();
340 }
341 if (Size > AF.getMaxBytesToEmit())
342 return 0;
343 return Size;
344 }
345
346 case MCFragment::FT_Org: {
347 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
348 MCValue Value;
349 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
350 getContext().reportError(OF.getLoc(),
351 "expected assembly-time absolute expression");
352 return 0;
353 }
354
355 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
356 int64_t TargetLocation = Value.getConstant();
357 if (const MCSymbolRefExpr *A = Value.getSymA()) {
358 uint64_t Val;
359 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
360 getContext().reportError(OF.getLoc(), "expected absolute expression");
361 return 0;
362 }
363 TargetLocation += Val;
364 }
365 int64_t Size = TargetLocation - FragmentOffset;
366 if (Size < 0 || Size >= 0x40000000) {
367 getContext().reportError(
368 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
369 "' (at offset '" + Twine(FragmentOffset) + "')");
370 return 0;
371 }
372 return Size;
373 }
374
375 case MCFragment::FT_Dwarf:
376 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
377 case MCFragment::FT_DwarfFrame:
378 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
379 case MCFragment::FT_CVInlineLines:
380 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
381 case MCFragment::FT_CVDefRange:
382 return cast<MCCVDefRangeFragment>(F).getContents().size();
383 case MCFragment::FT_Dummy:
384 llvm_unreachable("Should not have been added");
385 }
386
387 llvm_unreachable("invalid fragment kind");
388 }
389
layoutFragment(MCFragment * F)390 void MCAsmLayout::layoutFragment(MCFragment *F) {
391 MCFragment *Prev = F->getPrevNode();
392
393 // We should never try to recompute something which is valid.
394 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
395 // We should never try to compute the fragment layout if its predecessor
396 // isn't valid.
397 assert((!Prev || isFragmentValid(Prev)) &&
398 "Attempt to compute fragment before its predecessor!");
399
400 assert(!F->IsBeingLaidOut && "Already being laid out!");
401 F->IsBeingLaidOut = true;
402
403 ++stats::FragmentLayouts;
404
405 // Compute fragment offset and size.
406 if (Prev)
407 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
408 else
409 F->Offset = 0;
410 F->IsBeingLaidOut = false;
411 LastValidFragment[F->getParent()] = F;
412
413 // If bundling is enabled and this fragment has instructions in it, it has to
414 // obey the bundling restrictions. With padding, we'll have:
415 //
416 //
417 // BundlePadding
418 // |||
419 // -------------------------------------
420 // Prev |##########| F |
421 // -------------------------------------
422 // ^
423 // |
424 // F->Offset
425 //
426 // The fragment's offset will point to after the padding, and its computed
427 // size won't include the padding.
428 //
429 // When the -mc-relax-all flag is used, we optimize bundling by writting the
430 // padding directly into fragments when the instructions are emitted inside
431 // the streamer. When the fragment is larger than the bundle size, we need to
432 // ensure that it's bundle aligned. This means that if we end up with
433 // multiple fragments, we must emit bundle padding between fragments.
434 //
435 // ".align N" is an example of a directive that introduces multiple
436 // fragments. We could add a special case to handle ".align N" by emitting
437 // within-fragment padding (which would produce less padding when N is less
438 // than the bundle size), but for now we don't.
439 //
440 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
441 assert(isa<MCEncodedFragment>(F) &&
442 "Only MCEncodedFragment implementations have instructions");
443 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
444 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
445
446 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
447 report_fatal_error("Fragment can't be larger than a bundle size");
448
449 uint64_t RequiredBundlePadding =
450 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
451 if (RequiredBundlePadding > UINT8_MAX)
452 report_fatal_error("Padding cannot exceed 255 bytes");
453 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
454 EF->Offset += RequiredBundlePadding;
455 }
456 }
457
registerSymbol(const MCSymbol & Symbol,bool * Created)458 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
459 bool New = !Symbol.isRegistered();
460 if (Created)
461 *Created = New;
462 if (New) {
463 Symbol.setIsRegistered(true);
464 Symbols.push_back(&Symbol);
465 }
466 }
467
writeFragmentPadding(raw_ostream & OS,const MCEncodedFragment & EF,uint64_t FSize) const468 void MCAssembler::writeFragmentPadding(raw_ostream &OS,
469 const MCEncodedFragment &EF,
470 uint64_t FSize) const {
471 assert(getBackendPtr() && "Expected assembler backend");
472 // Should NOP padding be written out before this fragment?
473 unsigned BundlePadding = EF.getBundlePadding();
474 if (BundlePadding > 0) {
475 assert(isBundlingEnabled() &&
476 "Writing bundle padding with disabled bundling");
477 assert(EF.hasInstructions() &&
478 "Writing bundle padding for a fragment without instructions");
479
480 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
481 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
482 // If the padding itself crosses a bundle boundary, it must be emitted
483 // in 2 pieces, since even nop instructions must not cross boundaries.
484 // v--------------v <- BundleAlignSize
485 // v---------v <- BundlePadding
486 // ----------------------------
487 // | Prev |####|####| F |
488 // ----------------------------
489 // ^-------------------^ <- TotalLength
490 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
491 if (!getBackend().writeNopData(OS, DistanceToBoundary))
492 report_fatal_error("unable to write NOP sequence of " +
493 Twine(DistanceToBoundary) + " bytes");
494 BundlePadding -= DistanceToBoundary;
495 }
496 if (!getBackend().writeNopData(OS, BundlePadding))
497 report_fatal_error("unable to write NOP sequence of " +
498 Twine(BundlePadding) + " bytes");
499 }
500 }
501
502 /// Write the fragment \p F to the output file.
writeFragment(raw_ostream & OS,const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment & F)503 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
504 const MCAsmLayout &Layout, const MCFragment &F) {
505 // FIXME: Embed in fragments instead?
506 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
507
508 support::endianness Endian = Asm.getBackend().Endian;
509
510 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
511 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
512
513 // This variable (and its dummy usage) is to participate in the assert at
514 // the end of the function.
515 uint64_t Start = OS.tell();
516 (void) Start;
517
518 ++stats::EmittedFragments;
519
520 switch (F.getKind()) {
521 case MCFragment::FT_Align: {
522 ++stats::EmittedAlignFragments;
523 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
524 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
525
526 uint64_t Count = FragmentSize / AF.getValueSize();
527
528 // FIXME: This error shouldn't actually occur (the front end should emit
529 // multiple .align directives to enforce the semantics it wants), but is
530 // severe enough that we want to report it. How to handle this?
531 if (Count * AF.getValueSize() != FragmentSize)
532 report_fatal_error("undefined .align directive, value size '" +
533 Twine(AF.getValueSize()) +
534 "' is not a divisor of padding size '" +
535 Twine(FragmentSize) + "'");
536
537 // See if we are aligning with nops, and if so do that first to try to fill
538 // the Count bytes. Then if that did not fill any bytes or there are any
539 // bytes left to fill use the Value and ValueSize to fill the rest.
540 // If we are aligning with nops, ask that target to emit the right data.
541 if (AF.hasEmitNops()) {
542 if (!Asm.getBackend().writeNopData(OS, Count))
543 report_fatal_error("unable to write nop sequence of " +
544 Twine(Count) + " bytes");
545 break;
546 }
547
548 // Otherwise, write out in multiples of the value size.
549 for (uint64_t i = 0; i != Count; ++i) {
550 switch (AF.getValueSize()) {
551 default: llvm_unreachable("Invalid size!");
552 case 1: OS << char(AF.getValue()); break;
553 case 2:
554 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
555 break;
556 case 4:
557 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
558 break;
559 case 8:
560 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
561 break;
562 }
563 }
564 break;
565 }
566
567 case MCFragment::FT_Data:
568 ++stats::EmittedDataFragments;
569 OS << cast<MCDataFragment>(F).getContents();
570 break;
571
572 case MCFragment::FT_Relaxable:
573 ++stats::EmittedRelaxableFragments;
574 OS << cast<MCRelaxableFragment>(F).getContents();
575 break;
576
577 case MCFragment::FT_CompactEncodedInst:
578 ++stats::EmittedCompactEncodedInstFragments;
579 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
580 break;
581
582 case MCFragment::FT_Fill: {
583 ++stats::EmittedFillFragments;
584 const MCFillFragment &FF = cast<MCFillFragment>(F);
585 uint64_t V = FF.getValue();
586 unsigned VSize = FF.getValueSize();
587 const unsigned MaxChunkSize = 16;
588 char Data[MaxChunkSize];
589 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
590 // Duplicate V into Data as byte vector to reduce number of
591 // writes done. As such, do endian conversion here.
592 for (unsigned I = 0; I != VSize; ++I) {
593 unsigned index = Endian == support::little ? I : (VSize - I - 1);
594 Data[I] = uint8_t(V >> (index * 8));
595 }
596 for (unsigned I = VSize; I < MaxChunkSize; ++I)
597 Data[I] = Data[I - VSize];
598
599 // Set to largest multiple of VSize in Data.
600 const unsigned NumPerChunk = MaxChunkSize / VSize;
601 // Set ChunkSize to largest multiple of VSize in Data
602 const unsigned ChunkSize = VSize * NumPerChunk;
603
604 // Do copies by chunk.
605 StringRef Ref(Data, ChunkSize);
606 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
607 OS << Ref;
608
609 // do remainder if needed.
610 unsigned TrailingCount = FragmentSize % ChunkSize;
611 if (TrailingCount)
612 OS.write(Data, TrailingCount);
613 break;
614 }
615
616 case MCFragment::FT_LEB: {
617 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
618 OS << LF.getContents();
619 break;
620 }
621
622 case MCFragment::FT_BoundaryAlign: {
623 if (!Asm.getBackend().writeNopData(OS, FragmentSize))
624 report_fatal_error("unable to write nop sequence of " +
625 Twine(FragmentSize) + " bytes");
626 break;
627 }
628
629 case MCFragment::FT_SymbolId: {
630 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
631 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
632 break;
633 }
634
635 case MCFragment::FT_Org: {
636 ++stats::EmittedOrgFragments;
637 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
638
639 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
640 OS << char(OF.getValue());
641
642 break;
643 }
644
645 case MCFragment::FT_Dwarf: {
646 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
647 OS << OF.getContents();
648 break;
649 }
650 case MCFragment::FT_DwarfFrame: {
651 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
652 OS << CF.getContents();
653 break;
654 }
655 case MCFragment::FT_CVInlineLines: {
656 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
657 OS << OF.getContents();
658 break;
659 }
660 case MCFragment::FT_CVDefRange: {
661 const auto &DRF = cast<MCCVDefRangeFragment>(F);
662 OS << DRF.getContents();
663 break;
664 }
665 case MCFragment::FT_Dummy:
666 llvm_unreachable("Should not have been added");
667 }
668
669 assert(OS.tell() - Start == FragmentSize &&
670 "The stream should advance by fragment size");
671 }
672
writeSectionData(raw_ostream & OS,const MCSection * Sec,const MCAsmLayout & Layout) const673 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
674 const MCAsmLayout &Layout) const {
675 assert(getBackendPtr() && "Expected assembler backend");
676
677 // Ignore virtual sections.
678 if (Sec->isVirtualSection()) {
679 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
680
681 // Check that contents are only things legal inside a virtual section.
682 for (const MCFragment &F : *Sec) {
683 switch (F.getKind()) {
684 default: llvm_unreachable("Invalid fragment in virtual section!");
685 case MCFragment::FT_Data: {
686 // Check that we aren't trying to write a non-zero contents (or fixups)
687 // into a virtual section. This is to support clients which use standard
688 // directives to fill the contents of virtual sections.
689 const MCDataFragment &DF = cast<MCDataFragment>(F);
690 if (DF.fixup_begin() != DF.fixup_end())
691 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
692 " section '" + Sec->getName() +
693 "' cannot have fixups");
694 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
695 if (DF.getContents()[i]) {
696 getContext().reportError(SMLoc(),
697 Sec->getVirtualSectionKind() +
698 " section '" + Sec->getName() +
699 "' cannot have non-zero initializers");
700 break;
701 }
702 break;
703 }
704 case MCFragment::FT_Align:
705 // Check that we aren't trying to write a non-zero value into a virtual
706 // section.
707 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
708 cast<MCAlignFragment>(F).getValue() == 0) &&
709 "Invalid align in virtual section!");
710 break;
711 case MCFragment::FT_Fill:
712 assert((cast<MCFillFragment>(F).getValue() == 0) &&
713 "Invalid fill in virtual section!");
714 break;
715 }
716 }
717
718 return;
719 }
720
721 uint64_t Start = OS.tell();
722 (void)Start;
723
724 for (const MCFragment &F : *Sec)
725 writeFragment(OS, *this, Layout, F);
726
727 assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec));
728 }
729
730 std::tuple<MCValue, uint64_t, bool>
handleFixup(const MCAsmLayout & Layout,MCFragment & F,const MCFixup & Fixup)731 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
732 const MCFixup &Fixup) {
733 // Evaluate the fixup.
734 MCValue Target;
735 uint64_t FixedValue;
736 bool WasForced;
737 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
738 WasForced);
739 if (!IsResolved) {
740 // The fixup was unresolved, we need a relocation. Inform the object
741 // writer of the relocation, and give it an opportunity to adjust the
742 // fixup value if need be.
743 if (Target.getSymA() && Target.getSymB() &&
744 getBackend().requiresDiffExpressionRelocations()) {
745 // The fixup represents the difference between two symbols, which the
746 // backend has indicated must be resolved at link time. Split up the fixup
747 // into two relocations, one for the add, and one for the sub, and emit
748 // both of these. The constant will be associated with the add half of the
749 // expression.
750 MCFixup FixupAdd = MCFixup::createAddFor(Fixup);
751 MCValue TargetAdd =
752 MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
753 getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd,
754 FixedValue);
755 MCFixup FixupSub = MCFixup::createSubFor(Fixup);
756 MCValue TargetSub = MCValue::get(Target.getSymB());
757 getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub,
758 FixedValue);
759 } else {
760 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target,
761 FixedValue);
762 }
763 }
764 return std::make_tuple(Target, FixedValue, IsResolved);
765 }
766
layout(MCAsmLayout & Layout)767 void MCAssembler::layout(MCAsmLayout &Layout) {
768 assert(getBackendPtr() && "Expected assembler backend");
769 DEBUG_WITH_TYPE("mc-dump", {
770 errs() << "assembler backend - pre-layout\n--\n";
771 dump(); });
772
773 // Create dummy fragments and assign section ordinals.
774 unsigned SectionIndex = 0;
775 for (MCSection &Sec : *this) {
776 // Create dummy fragments to eliminate any empty sections, this simplifies
777 // layout.
778 if (Sec.getFragmentList().empty())
779 new MCDataFragment(&Sec);
780
781 Sec.setOrdinal(SectionIndex++);
782 }
783
784 // Assign layout order indices to sections and fragments.
785 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
786 MCSection *Sec = Layout.getSectionOrder()[i];
787 Sec->setLayoutOrder(i);
788
789 unsigned FragmentIndex = 0;
790 for (MCFragment &Frag : *Sec)
791 Frag.setLayoutOrder(FragmentIndex++);
792 }
793
794 // Layout until everything fits.
795 while (layoutOnce(Layout)) {
796 if (getContext().hadError())
797 return;
798 // Size of fragments in one section can depend on the size of fragments in
799 // another. If any fragment has changed size, we have to re-layout (and
800 // as a result possibly further relax) all.
801 for (MCSection &Sec : *this)
802 Layout.invalidateFragmentsFrom(&*Sec.begin());
803 }
804
805 DEBUG_WITH_TYPE("mc-dump", {
806 errs() << "assembler backend - post-relaxation\n--\n";
807 dump(); });
808
809 // Finalize the layout, including fragment lowering.
810 finishLayout(Layout);
811
812 DEBUG_WITH_TYPE("mc-dump", {
813 errs() << "assembler backend - final-layout\n--\n";
814 dump(); });
815
816 // Allow the object writer a chance to perform post-layout binding (for
817 // example, to set the index fields in the symbol data).
818 getWriter().executePostLayoutBinding(*this, Layout);
819
820 // Evaluate and apply the fixups, generating relocation entries as necessary.
821 for (MCSection &Sec : *this) {
822 for (MCFragment &Frag : Sec) {
823 ArrayRef<MCFixup> Fixups;
824 MutableArrayRef<char> Contents;
825 const MCSubtargetInfo *STI = nullptr;
826
827 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
828 switch (Frag.getKind()) {
829 default:
830 continue;
831 case MCFragment::FT_Align: {
832 MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
833 // Insert fixup type for code alignment if the target define
834 // shouldInsertFixupForCodeAlign target hook.
835 if (Sec.UseCodeAlign() && AF.hasEmitNops())
836 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
837 continue;
838 }
839 case MCFragment::FT_Data: {
840 MCDataFragment &DF = cast<MCDataFragment>(Frag);
841 Fixups = DF.getFixups();
842 Contents = DF.getContents();
843 STI = DF.getSubtargetInfo();
844 assert(!DF.hasInstructions() || STI != nullptr);
845 break;
846 }
847 case MCFragment::FT_Relaxable: {
848 MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
849 Fixups = RF.getFixups();
850 Contents = RF.getContents();
851 STI = RF.getSubtargetInfo();
852 assert(!RF.hasInstructions() || STI != nullptr);
853 break;
854 }
855 case MCFragment::FT_CVDefRange: {
856 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
857 Fixups = CF.getFixups();
858 Contents = CF.getContents();
859 break;
860 }
861 case MCFragment::FT_Dwarf: {
862 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
863 Fixups = DF.getFixups();
864 Contents = DF.getContents();
865 break;
866 }
867 case MCFragment::FT_DwarfFrame: {
868 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
869 Fixups = DF.getFixups();
870 Contents = DF.getContents();
871 break;
872 }
873 }
874 for (const MCFixup &Fixup : Fixups) {
875 uint64_t FixedValue;
876 bool IsResolved;
877 MCValue Target;
878 std::tie(Target, FixedValue, IsResolved) =
879 handleFixup(Layout, Frag, Fixup);
880 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
881 IsResolved, STI);
882 }
883 }
884 }
885 }
886
Finish()887 void MCAssembler::Finish() {
888 // Create the layout object.
889 MCAsmLayout Layout(*this);
890 layout(Layout);
891
892 // Write the object file.
893 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
894 }
895
fixupNeedsRelaxation(const MCFixup & Fixup,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const896 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
897 const MCRelaxableFragment *DF,
898 const MCAsmLayout &Layout) const {
899 assert(getBackendPtr() && "Expected assembler backend");
900 MCValue Target;
901 uint64_t Value;
902 bool WasForced;
903 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
904 if (Target.getSymA() &&
905 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
906 Fixup.getKind() == FK_Data_1)
907 return false;
908 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
909 Layout, WasForced);
910 }
911
fragmentNeedsRelaxation(const MCRelaxableFragment * F,const MCAsmLayout & Layout) const912 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
913 const MCAsmLayout &Layout) const {
914 assert(getBackendPtr() && "Expected assembler backend");
915 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
916 // are intentionally pushing out inst fragments, or because we relaxed a
917 // previous instruction to one that doesn't need relaxation.
918 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
919 return false;
920
921 for (const MCFixup &Fixup : F->getFixups())
922 if (fixupNeedsRelaxation(Fixup, F, Layout))
923 return true;
924
925 return false;
926 }
927
relaxInstruction(MCAsmLayout & Layout,MCRelaxableFragment & F)928 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
929 MCRelaxableFragment &F) {
930 assert(getEmitterPtr() &&
931 "Expected CodeEmitter defined for relaxInstruction");
932 if (!fragmentNeedsRelaxation(&F, Layout))
933 return false;
934
935 ++stats::RelaxedInstructions;
936
937 // FIXME-PERF: We could immediately lower out instructions if we can tell
938 // they are fully resolved, to avoid retesting on later passes.
939
940 // Relax the fragment.
941
942 MCInst Relaxed = F.getInst();
943 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
944
945 // Encode the new instruction.
946 //
947 // FIXME-PERF: If it matters, we could let the target do this. It can
948 // probably do so more efficiently in many cases.
949 SmallVector<MCFixup, 4> Fixups;
950 SmallString<256> Code;
951 raw_svector_ostream VecOS(Code);
952 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
953
954 // Update the fragment.
955 F.setInst(Relaxed);
956 F.getContents() = Code;
957 F.getFixups() = Fixups;
958
959 return true;
960 }
961
relaxLEB(MCAsmLayout & Layout,MCLEBFragment & LF)962 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
963 uint64_t OldSize = LF.getContents().size();
964 int64_t Value;
965 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
966 if (!Abs)
967 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
968 SmallString<8> &Data = LF.getContents();
969 Data.clear();
970 raw_svector_ostream OSE(Data);
971 // The compiler can generate EH table assembly that is impossible to assemble
972 // without either adding padding to an LEB fragment or adding extra padding
973 // to a later alignment fragment. To accommodate such tables, relaxation can
974 // only increase an LEB fragment size here, not decrease it. See PR35809.
975 if (LF.isSigned())
976 encodeSLEB128(Value, OSE, OldSize);
977 else
978 encodeULEB128(Value, OSE, OldSize);
979 return OldSize != LF.getContents().size();
980 }
981
982 /// Check if the branch crosses the boundary.
983 ///
984 /// \param StartAddr start address of the fused/unfused branch.
985 /// \param Size size of the fused/unfused branch.
986 /// \param BoundaryAlignment alignment requirement of the branch.
987 /// \returns true if the branch cross the boundary.
mayCrossBoundary(uint64_t StartAddr,uint64_t Size,Align BoundaryAlignment)988 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
989 Align BoundaryAlignment) {
990 uint64_t EndAddr = StartAddr + Size;
991 return (StartAddr >> Log2(BoundaryAlignment)) !=
992 ((EndAddr - 1) >> Log2(BoundaryAlignment));
993 }
994
995 /// Check if the branch is against the boundary.
996 ///
997 /// \param StartAddr start address of the fused/unfused branch.
998 /// \param Size size of the fused/unfused branch.
999 /// \param BoundaryAlignment alignment requirement of the branch.
1000 /// \returns true if the branch is against the boundary.
isAgainstBoundary(uint64_t StartAddr,uint64_t Size,Align BoundaryAlignment)1001 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
1002 Align BoundaryAlignment) {
1003 uint64_t EndAddr = StartAddr + Size;
1004 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1005 }
1006
1007 /// Check if the branch needs padding.
1008 ///
1009 /// \param StartAddr start address of the fused/unfused branch.
1010 /// \param Size size of the fused/unfused branch.
1011 /// \param BoundaryAlignment alignment requirement of the branch.
1012 /// \returns true if the branch needs padding.
needPadding(uint64_t StartAddr,uint64_t Size,Align BoundaryAlignment)1013 static bool needPadding(uint64_t StartAddr, uint64_t Size,
1014 Align BoundaryAlignment) {
1015 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1016 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1017 }
1018
relaxBoundaryAlign(MCAsmLayout & Layout,MCBoundaryAlignFragment & BF)1019 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1020 MCBoundaryAlignFragment &BF) {
1021 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1022 // relaxed.
1023 if (!BF.getLastFragment())
1024 return false;
1025
1026 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1027 uint64_t AlignedSize = 0;
1028 for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1029 F = F->getPrevNode())
1030 AlignedSize += computeFragmentSize(Layout, *F);
1031
1032 Align BoundaryAlignment = BF.getAlignment();
1033 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1034 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1035 : 0U;
1036 if (NewSize == BF.getSize())
1037 return false;
1038 BF.setSize(NewSize);
1039 Layout.invalidateFragmentsFrom(&BF);
1040 return true;
1041 }
1042
relaxDwarfLineAddr(MCAsmLayout & Layout,MCDwarfLineAddrFragment & DF)1043 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1044 MCDwarfLineAddrFragment &DF) {
1045 MCContext &Context = Layout.getAssembler().getContext();
1046 uint64_t OldSize = DF.getContents().size();
1047 int64_t AddrDelta;
1048 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1049 assert(Abs && "We created a line delta with an invalid expression");
1050 (void)Abs;
1051 int64_t LineDelta;
1052 LineDelta = DF.getLineDelta();
1053 SmallVectorImpl<char> &Data = DF.getContents();
1054 Data.clear();
1055 raw_svector_ostream OSE(Data);
1056 DF.getFixups().clear();
1057
1058 if (!getBackend().requiresDiffExpressionRelocations()) {
1059 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1060 AddrDelta, OSE);
1061 } else {
1062 uint32_t Offset;
1063 uint32_t Size;
1064 bool SetDelta = MCDwarfLineAddr::FixedEncode(Context,
1065 getDWARFLinetableParams(),
1066 LineDelta, AddrDelta,
1067 OSE, &Offset, &Size);
1068 // Add Fixups for address delta or new address.
1069 const MCExpr *FixupExpr;
1070 if (SetDelta) {
1071 FixupExpr = &DF.getAddrDelta();
1072 } else {
1073 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta());
1074 FixupExpr = ABE->getLHS();
1075 }
1076 DF.getFixups().push_back(
1077 MCFixup::create(Offset, FixupExpr,
1078 MCFixup::getKindForSize(Size, false /*isPCRel*/)));
1079 }
1080
1081 return OldSize != Data.size();
1082 }
1083
relaxDwarfCallFrameFragment(MCAsmLayout & Layout,MCDwarfCallFrameFragment & DF)1084 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1085 MCDwarfCallFrameFragment &DF) {
1086 MCContext &Context = Layout.getAssembler().getContext();
1087 uint64_t OldSize = DF.getContents().size();
1088 int64_t AddrDelta;
1089 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1090 assert(Abs && "We created call frame with an invalid expression");
1091 (void) Abs;
1092 SmallVectorImpl<char> &Data = DF.getContents();
1093 Data.clear();
1094 raw_svector_ostream OSE(Data);
1095 DF.getFixups().clear();
1096
1097 if (getBackend().requiresDiffExpressionRelocations()) {
1098 uint32_t Offset;
1099 uint32_t Size;
1100 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE, &Offset,
1101 &Size);
1102 if (Size) {
1103 DF.getFixups().push_back(MCFixup::create(
1104 Offset, &DF.getAddrDelta(),
1105 MCFixup::getKindForSizeInBits(Size /*In bits.*/, false /*isPCRel*/)));
1106 }
1107 } else {
1108 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1109 }
1110
1111 return OldSize != Data.size();
1112 }
1113
relaxCVInlineLineTable(MCAsmLayout & Layout,MCCVInlineLineTableFragment & F)1114 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1115 MCCVInlineLineTableFragment &F) {
1116 unsigned OldSize = F.getContents().size();
1117 getContext().getCVContext().encodeInlineLineTable(Layout, F);
1118 return OldSize != F.getContents().size();
1119 }
1120
relaxCVDefRange(MCAsmLayout & Layout,MCCVDefRangeFragment & F)1121 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1122 MCCVDefRangeFragment &F) {
1123 unsigned OldSize = F.getContents().size();
1124 getContext().getCVContext().encodeDefRange(Layout, F);
1125 return OldSize != F.getContents().size();
1126 }
1127
relaxFragment(MCAsmLayout & Layout,MCFragment & F)1128 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1129 switch(F.getKind()) {
1130 default:
1131 return false;
1132 case MCFragment::FT_Relaxable:
1133 assert(!getRelaxAll() &&
1134 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1135 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1136 case MCFragment::FT_Dwarf:
1137 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1138 case MCFragment::FT_DwarfFrame:
1139 return relaxDwarfCallFrameFragment(Layout,
1140 cast<MCDwarfCallFrameFragment>(F));
1141 case MCFragment::FT_LEB:
1142 return relaxLEB(Layout, cast<MCLEBFragment>(F));
1143 case MCFragment::FT_BoundaryAlign:
1144 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1145 case MCFragment::FT_CVInlineLines:
1146 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1147 case MCFragment::FT_CVDefRange:
1148 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1149 }
1150 }
1151
layoutSectionOnce(MCAsmLayout & Layout,MCSection & Sec)1152 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1153 // Holds the first fragment which needed relaxing during this layout. It will
1154 // remain NULL if none were relaxed.
1155 // When a fragment is relaxed, all the fragments following it should get
1156 // invalidated because their offset is going to change.
1157 MCFragment *FirstRelaxedFragment = nullptr;
1158
1159 // Attempt to relax all the fragments in the section.
1160 for (MCFragment &Frag : Sec) {
1161 // Check if this is a fragment that needs relaxation.
1162 bool RelaxedFrag = relaxFragment(Layout, Frag);
1163 if (RelaxedFrag && !FirstRelaxedFragment)
1164 FirstRelaxedFragment = &Frag;
1165 }
1166 if (FirstRelaxedFragment) {
1167 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1168 return true;
1169 }
1170 return false;
1171 }
1172
layoutOnce(MCAsmLayout & Layout)1173 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1174 ++stats::RelaxationSteps;
1175
1176 bool WasRelaxed = false;
1177 for (MCSection &Sec : *this) {
1178 while (layoutSectionOnce(Layout, Sec))
1179 WasRelaxed = true;
1180 }
1181
1182 return WasRelaxed;
1183 }
1184
finishLayout(MCAsmLayout & Layout)1185 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1186 assert(getBackendPtr() && "Expected assembler backend");
1187 // The layout is done. Mark every fragment as valid.
1188 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1189 MCSection &Section = *Layout.getSectionOrder()[i];
1190 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1191 computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1192 }
1193 getBackend().finishLayout(*this, Layout);
1194 }
1195
1196 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1197 LLVM_DUMP_METHOD void MCAssembler::dump() const{
1198 raw_ostream &OS = errs();
1199
1200 OS << "<MCAssembler\n";
1201 OS << " Sections:[\n ";
1202 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1203 if (it != begin()) OS << ",\n ";
1204 it->dump();
1205 }
1206 OS << "],\n";
1207 OS << " Symbols:[";
1208
1209 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1210 if (it != symbol_begin()) OS << ",\n ";
1211 OS << "(";
1212 it->dump();
1213 OS << ", Index:" << it->getIndex() << ", ";
1214 OS << ")";
1215 }
1216 OS << "]>\n";
1217 }
1218 #endif
1219