1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetAsmBackend.h"
36 STATISTIC(EmittedFragments
, "Number of emitted assembler fragments");
37 STATISTIC(EvaluateFixup
, "Number of evaluated fixups");
38 STATISTIC(FragmentLayouts
, "Number of fragment layouts");
39 STATISTIC(ObjectBytes
, "Number of emitted object file bytes");
40 STATISTIC(RelaxationSteps
, "Number of assembler layout and relaxation steps");
41 STATISTIC(RelaxedInstructions
, "Number of relaxed instructions");
45 // FIXME FIXME FIXME: There are number of places in this file where we convert
46 // what is a 64-bit assembler value used for computation into a value in the
47 // object file, which may truncate it. We should detect that truncation where
48 // invalid and report errors back.
52 MCAsmLayout::MCAsmLayout(MCAssembler
&Asm
)
53 : Assembler(Asm
), LastValidFragment()
55 // Compute the section layout order. Virtual sections must go last.
56 for (MCAssembler::iterator it
= Asm
.begin(), ie
= Asm
.end(); it
!= ie
; ++it
)
57 if (!it
->getSection().isVirtualSection())
58 SectionOrder
.push_back(&*it
);
59 for (MCAssembler::iterator it
= Asm
.begin(), ie
= Asm
.end(); it
!= ie
; ++it
)
60 if (it
->getSection().isVirtualSection())
61 SectionOrder
.push_back(&*it
);
64 bool MCAsmLayout::isFragmentUpToDate(const MCFragment
*F
) const {
65 const MCSectionData
&SD
= *F
->getParent();
66 const MCFragment
*LastValid
= LastValidFragment
.lookup(&SD
);
69 assert(LastValid
->getParent() == F
->getParent());
70 return F
->getLayoutOrder() <= LastValid
->getLayoutOrder();
73 void MCAsmLayout::Invalidate(MCFragment
*F
) {
74 // If this fragment wasn't already up-to-date, we don't need to do anything.
75 if (!isFragmentUpToDate(F
))
78 // Otherwise, reset the last valid fragment to this fragment.
79 const MCSectionData
&SD
= *F
->getParent();
80 LastValidFragment
[&SD
] = F
;
83 void MCAsmLayout::EnsureValid(const MCFragment
*F
) const {
84 MCSectionData
&SD
= *F
->getParent();
86 MCFragment
*Cur
= LastValidFragment
[&SD
];
90 Cur
= Cur
->getNextNode();
92 // Advance the layout position until the fragment is up-to-date.
93 while (!isFragmentUpToDate(F
)) {
94 const_cast<MCAsmLayout
*>(this)->LayoutFragment(Cur
);
95 Cur
= Cur
->getNextNode();
99 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment
*F
) const {
101 assert(F
->Offset
!= ~UINT64_C(0) && "Address not set!");
105 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData
*SD
) const {
106 assert(SD
->getFragment() && "Invalid getOffset() on undefined symbol!");
107 return getFragmentOffset(SD
->getFragment()) + SD
->getOffset();
110 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData
*SD
) const {
111 // The size is the last fragment's end offset.
112 const MCFragment
&F
= SD
->getFragmentList().back();
113 return getFragmentOffset(&F
) + getAssembler().ComputeFragmentSize(*this, F
);
116 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData
*SD
) const {
117 // Virtual sections have no file size.
118 if (SD
->getSection().isVirtualSection())
121 // Otherwise, the file size is the same as the address space size.
122 return getSectionAddressSize(SD
);
127 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
130 MCFragment::~MCFragment() {
133 MCFragment::MCFragment(FragmentType _Kind
, MCSectionData
*_Parent
)
134 : Kind(_Kind
), Parent(_Parent
), Atom(0), Offset(~UINT64_C(0))
137 Parent
->getFragmentList().push_back(this);
142 MCSectionData::MCSectionData() : Section(0) {}
144 MCSectionData::MCSectionData(const MCSection
&_Section
, MCAssembler
*A
)
145 : Section(&_Section
),
146 Ordinal(~UINT32_C(0)),
148 HasInstructions(false)
151 A
->getSectionList().push_back(this);
156 MCSymbolData::MCSymbolData() : Symbol(0) {}
158 MCSymbolData::MCSymbolData(const MCSymbol
&_Symbol
, MCFragment
*_Fragment
,
159 uint64_t _Offset
, MCAssembler
*A
)
160 : Symbol(&_Symbol
), Fragment(_Fragment
), Offset(_Offset
),
161 IsExternal(false), IsPrivateExtern(false),
162 CommonSize(0), SymbolSize(0), CommonAlign(0),
166 A
->getSymbolList().push_back(this);
171 MCAssembler::MCAssembler(MCContext
&Context_
, TargetAsmBackend
&Backend_
,
172 MCCodeEmitter
&Emitter_
, MCObjectWriter
&Writer_
,
174 : Context(Context_
), Backend(Backend_
), Emitter(Emitter_
), Writer(Writer_
),
175 OS(OS_
), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false)
179 MCAssembler::~MCAssembler() {
182 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol
&Symbol
) const {
183 // Non-temporary labels should always be visible to the linker.
184 if (!Symbol
.isTemporary())
187 // Absolute temporary labels are never visible.
188 if (!Symbol
.isInSection())
191 // Otherwise, check if the section requires symbols even for temporary labels.
192 return getBackend().doesSectionRequireSymbols(Symbol
.getSection());
195 const MCSymbolData
*MCAssembler::getAtom(const MCSymbolData
*SD
) const {
196 // Linker visible symbols define atoms.
197 if (isSymbolLinkerVisible(SD
->getSymbol()))
200 // Absolute and undefined symbols have no defining atom.
201 if (!SD
->getFragment())
204 // Non-linker visible symbols in sections which can't be atomized have no
206 if (!getBackend().isSectionAtomizable(
207 SD
->getFragment()->getParent()->getSection()))
210 // Otherwise, return the atom for the containing fragment.
211 return SD
->getFragment()->getAtom();
214 bool MCAssembler::EvaluateFixup(const MCAsmLayout
&Layout
,
215 const MCFixup
&Fixup
, const MCFragment
*DF
,
216 MCValue
&Target
, uint64_t &Value
) const {
217 ++stats::EvaluateFixup
;
219 if (!Fixup
.getValue()->EvaluateAsRelocatable(Target
, Layout
))
220 report_fatal_error("expected relocatable expression");
222 bool IsPCRel
= Backend
.getFixupKindInfo(
223 Fixup
.getKind()).Flags
& MCFixupKindInfo::FKF_IsPCRel
;
227 if (Target
.getSymB()) {
229 } else if (!Target
.getSymA()) {
232 const MCSymbol
&SA
= Target
.getSymA()->getSymbol();
233 if (SA
.AliasedSymbol().isUndefined()) {
236 const MCSymbolData
&DataA
= getSymbolData(SA
);
238 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA
,
243 IsResolved
= Target
.isAbsolute();
246 Value
= Target
.getConstant();
248 bool IsThumb
= false;
249 if (const MCSymbolRefExpr
*A
= Target
.getSymA()) {
250 const MCSymbol
&Sym
= A
->getSymbol().AliasedSymbol();
252 Value
+= Layout
.getSymbolOffset(&getSymbolData(Sym
));
253 if (isThumbFunc(&Sym
))
256 if (const MCSymbolRefExpr
*B
= Target
.getSymB()) {
257 const MCSymbol
&Sym
= B
->getSymbol().AliasedSymbol();
259 Value
-= Layout
.getSymbolOffset(&getSymbolData(Sym
));
263 bool ShouldAlignPC
= Backend
.getFixupKindInfo(Fixup
.getKind()).Flags
&
264 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits
;
265 assert((ShouldAlignPC
? IsPCRel
: true) &&
266 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
269 uint32_t Offset
= Layout
.getFragmentOffset(DF
) + Fixup
.getOffset();
271 // A number of ARM fixups in Thumb mode require that the effective PC
272 // address be determined as the 32-bit aligned version of the actual offset.
273 if (ShouldAlignPC
) Offset
&= ~0x3;
277 // ARM fixups based from a thumb function address need to have the low
278 // bit set. The actual value is always at least 16-bit aligned, so the
279 // low bit is normally clear and available for use as an ISA flag for
287 uint64_t MCAssembler::ComputeFragmentSize(const MCAsmLayout
&Layout
,
288 const MCFragment
&F
) const {
289 switch (F
.getKind()) {
290 case MCFragment::FT_Data
:
291 return cast
<MCDataFragment
>(F
).getContents().size();
292 case MCFragment::FT_Fill
:
293 return cast
<MCFillFragment
>(F
).getSize();
294 case MCFragment::FT_Inst
:
295 return cast
<MCInstFragment
>(F
).getInstSize();
297 case MCFragment::FT_LEB
:
298 return cast
<MCLEBFragment
>(F
).getContents().size();
300 case MCFragment::FT_Align
: {
301 const MCAlignFragment
&AF
= cast
<MCAlignFragment
>(F
);
302 unsigned Offset
= Layout
.getFragmentOffset(&AF
);
303 unsigned Size
= OffsetToAlignment(Offset
, AF
.getAlignment());
304 if (Size
> AF
.getMaxBytesToEmit())
309 case MCFragment::FT_Org
: {
310 MCOrgFragment
&OF
= cast
<MCOrgFragment
>(F
);
311 int64_t TargetLocation
;
312 if (!OF
.getOffset().EvaluateAsAbsolute(TargetLocation
, Layout
))
313 report_fatal_error("expected assembly-time absolute expression");
315 // FIXME: We need a way to communicate this error.
316 uint64_t FragmentOffset
= Layout
.getFragmentOffset(&OF
);
317 int64_t Size
= TargetLocation
- FragmentOffset
;
318 if (Size
< 0 || Size
>= 0x40000000)
319 report_fatal_error("invalid .org offset '" + Twine(TargetLocation
) +
320 "' (at offset '" + Twine(FragmentOffset
) + "')");
324 case MCFragment::FT_Dwarf
:
325 return cast
<MCDwarfLineAddrFragment
>(F
).getContents().size();
326 case MCFragment::FT_DwarfFrame
:
327 return cast
<MCDwarfCallFrameFragment
>(F
).getContents().size();
330 assert(0 && "invalid fragment kind");
334 void MCAsmLayout::LayoutFragment(MCFragment
*F
) {
335 MCFragment
*Prev
= F
->getPrevNode();
337 // We should never try to recompute something which is up-to-date.
338 assert(!isFragmentUpToDate(F
) && "Attempt to recompute up-to-date fragment!");
339 // We should never try to compute the fragment layout if it's predecessor
341 assert((!Prev
|| isFragmentUpToDate(Prev
)) &&
342 "Attempt to compute fragment before it's predecessor!");
344 ++stats::FragmentLayouts
;
346 // Compute fragment offset and size.
349 Offset
+= Prev
->Offset
+ getAssembler().ComputeFragmentSize(*this, *Prev
);
352 LastValidFragment
[F
->getParent()] = F
;
355 /// WriteFragmentData - Write the \arg F data to the output file.
356 static void WriteFragmentData(const MCAssembler
&Asm
, const MCAsmLayout
&Layout
,
357 const MCFragment
&F
) {
358 MCObjectWriter
*OW
= &Asm
.getWriter();
359 uint64_t Start
= OW
->getStream().tell();
362 ++stats::EmittedFragments
;
364 // FIXME: Embed in fragments instead?
365 uint64_t FragmentSize
= Asm
.ComputeFragmentSize(Layout
, F
);
366 switch (F
.getKind()) {
367 case MCFragment::FT_Align
: {
368 MCAlignFragment
&AF
= cast
<MCAlignFragment
>(F
);
369 uint64_t Count
= FragmentSize
/ AF
.getValueSize();
371 assert(AF
.getValueSize() && "Invalid virtual align in concrete fragment!");
373 // FIXME: This error shouldn't actually occur (the front end should emit
374 // multiple .align directives to enforce the semantics it wants), but is
375 // severe enough that we want to report it. How to handle this?
376 if (Count
* AF
.getValueSize() != FragmentSize
)
377 report_fatal_error("undefined .align directive, value size '" +
378 Twine(AF
.getValueSize()) +
379 "' is not a divisor of padding size '" +
380 Twine(FragmentSize
) + "'");
382 // See if we are aligning with nops, and if so do that first to try to fill
383 // the Count bytes. Then if that did not fill any bytes or there are any
384 // bytes left to fill use the the Value and ValueSize to fill the rest.
385 // If we are aligning with nops, ask that target to emit the right data.
386 if (AF
.hasEmitNops()) {
387 if (!Asm
.getBackend().WriteNopData(Count
, OW
))
388 report_fatal_error("unable to write nop sequence of " +
389 Twine(Count
) + " bytes");
393 // Otherwise, write out in multiples of the value size.
394 for (uint64_t i
= 0; i
!= Count
; ++i
) {
395 switch (AF
.getValueSize()) {
397 assert(0 && "Invalid size!");
398 case 1: OW
->Write8 (uint8_t (AF
.getValue())); break;
399 case 2: OW
->Write16(uint16_t(AF
.getValue())); break;
400 case 4: OW
->Write32(uint32_t(AF
.getValue())); break;
401 case 8: OW
->Write64(uint64_t(AF
.getValue())); break;
407 case MCFragment::FT_Data
: {
408 MCDataFragment
&DF
= cast
<MCDataFragment
>(F
);
409 assert(FragmentSize
== DF
.getContents().size() && "Invalid size!");
410 OW
->WriteBytes(DF
.getContents().str());
414 case MCFragment::FT_Fill
: {
415 MCFillFragment
&FF
= cast
<MCFillFragment
>(F
);
417 assert(FF
.getValueSize() && "Invalid virtual align in concrete fragment!");
419 for (uint64_t i
= 0, e
= FF
.getSize() / FF
.getValueSize(); i
!= e
; ++i
) {
420 switch (FF
.getValueSize()) {
422 assert(0 && "Invalid size!");
423 case 1: OW
->Write8 (uint8_t (FF
.getValue())); break;
424 case 2: OW
->Write16(uint16_t(FF
.getValue())); break;
425 case 4: OW
->Write32(uint32_t(FF
.getValue())); break;
426 case 8: OW
->Write64(uint64_t(FF
.getValue())); break;
432 case MCFragment::FT_Inst
: {
433 MCInstFragment
&IF
= cast
<MCInstFragment
>(F
);
434 OW
->WriteBytes(StringRef(IF
.getCode().begin(), IF
.getCode().size()));
438 case MCFragment::FT_LEB
: {
439 MCLEBFragment
&LF
= cast
<MCLEBFragment
>(F
);
440 OW
->WriteBytes(LF
.getContents().str());
444 case MCFragment::FT_Org
: {
445 MCOrgFragment
&OF
= cast
<MCOrgFragment
>(F
);
447 for (uint64_t i
= 0, e
= FragmentSize
; i
!= e
; ++i
)
448 OW
->Write8(uint8_t(OF
.getValue()));
453 case MCFragment::FT_Dwarf
: {
454 const MCDwarfLineAddrFragment
&OF
= cast
<MCDwarfLineAddrFragment
>(F
);
455 OW
->WriteBytes(OF
.getContents().str());
458 case MCFragment::FT_DwarfFrame
: {
459 const MCDwarfCallFrameFragment
&CF
= cast
<MCDwarfCallFrameFragment
>(F
);
460 OW
->WriteBytes(CF
.getContents().str());
465 assert(OW
->getStream().tell() - Start
== FragmentSize
);
468 void MCAssembler::WriteSectionData(const MCSectionData
*SD
,
469 const MCAsmLayout
&Layout
) const {
470 // Ignore virtual sections.
471 if (SD
->getSection().isVirtualSection()) {
472 assert(Layout
.getSectionFileSize(SD
) == 0 && "Invalid size for section!");
474 // Check that contents are only things legal inside a virtual section.
475 for (MCSectionData::const_iterator it
= SD
->begin(),
476 ie
= SD
->end(); it
!= ie
; ++it
) {
477 switch (it
->getKind()) {
479 assert(0 && "Invalid fragment in virtual section!");
480 case MCFragment::FT_Data
: {
481 // Check that we aren't trying to write a non-zero contents (or fixups)
482 // into a virtual section. This is to support clients which use standard
483 // directives to fill the contents of virtual sections.
484 MCDataFragment
&DF
= cast
<MCDataFragment
>(*it
);
485 assert(DF
.fixup_begin() == DF
.fixup_end() &&
486 "Cannot have fixups in virtual section!");
487 for (unsigned i
= 0, e
= DF
.getContents().size(); i
!= e
; ++i
)
488 assert(DF
.getContents()[i
] == 0 &&
489 "Invalid data value for virtual section!");
492 case MCFragment::FT_Align
:
493 // Check that we aren't trying to write a non-zero value into a virtual
495 assert((!cast
<MCAlignFragment
>(it
)->getValueSize() ||
496 !cast
<MCAlignFragment
>(it
)->getValue()) &&
497 "Invalid align in virtual section!");
499 case MCFragment::FT_Fill
:
500 assert(!cast
<MCFillFragment
>(it
)->getValueSize() &&
501 "Invalid fill in virtual section!");
509 uint64_t Start
= getWriter().getStream().tell();
512 for (MCSectionData::const_iterator it
= SD
->begin(),
513 ie
= SD
->end(); it
!= ie
; ++it
)
514 WriteFragmentData(*this, Layout
, *it
);
516 assert(getWriter().getStream().tell() - Start
==
517 Layout
.getSectionAddressSize(SD
));
521 uint64_t MCAssembler::HandleFixup(const MCAsmLayout
&Layout
,
523 const MCFixup
&Fixup
) {
524 // Evaluate the fixup.
527 if (!EvaluateFixup(Layout
, Fixup
, &F
, Target
, FixedValue
)) {
528 // The fixup was unresolved, we need a relocation. Inform the object
529 // writer of the relocation, and give it an opportunity to adjust the
530 // fixup value if need be.
531 getWriter().RecordRelocation(*this, Layout
, &F
, Fixup
, Target
, FixedValue
);
536 void MCAssembler::Finish() {
537 DEBUG_WITH_TYPE("mc-dump", {
538 llvm::errs() << "assembler backend - pre-layout\n--\n";
541 // Create the layout object.
542 MCAsmLayout
Layout(*this);
544 // Create dummy fragments and assign section ordinals.
545 unsigned SectionIndex
= 0;
546 for (MCAssembler::iterator it
= begin(), ie
= end(); it
!= ie
; ++it
) {
547 // Create dummy fragments to eliminate any empty sections, this simplifies
549 if (it
->getFragmentList().empty())
550 new MCDataFragment(it
);
552 it
->setOrdinal(SectionIndex
++);
555 // Assign layout order indices to sections and fragments.
556 for (unsigned i
= 0, e
= Layout
.getSectionOrder().size(); i
!= e
; ++i
) {
557 MCSectionData
*SD
= Layout
.getSectionOrder()[i
];
558 SD
->setLayoutOrder(i
);
560 unsigned FragmentIndex
= 0;
561 for (MCSectionData::iterator it2
= SD
->begin(),
562 ie2
= SD
->end(); it2
!= ie2
; ++it2
)
563 it2
->setLayoutOrder(FragmentIndex
++);
566 // Layout until everything fits.
567 while (LayoutOnce(Layout
))
570 DEBUG_WITH_TYPE("mc-dump", {
571 llvm::errs() << "assembler backend - post-relaxation\n--\n";
574 // Finalize the layout, including fragment lowering.
575 FinishLayout(Layout
);
577 DEBUG_WITH_TYPE("mc-dump", {
578 llvm::errs() << "assembler backend - final-layout\n--\n";
581 uint64_t StartOffset
= OS
.tell();
583 // Allow the object writer a chance to perform post-layout binding (for
584 // example, to set the index fields in the symbol data).
585 getWriter().ExecutePostLayoutBinding(*this, Layout
);
587 // Evaluate and apply the fixups, generating relocation entries as necessary.
588 for (MCAssembler::iterator it
= begin(), ie
= end(); it
!= ie
; ++it
) {
589 for (MCSectionData::iterator it2
= it
->begin(),
590 ie2
= it
->end(); it2
!= ie2
; ++it2
) {
591 MCDataFragment
*DF
= dyn_cast
<MCDataFragment
>(it2
);
593 for (MCDataFragment::fixup_iterator it3
= DF
->fixup_begin(),
594 ie3
= DF
->fixup_end(); it3
!= ie3
; ++it3
) {
595 MCFixup
&Fixup
= *it3
;
596 uint64_t FixedValue
= HandleFixup(Layout
, *DF
, Fixup
);
597 getBackend().ApplyFixup(Fixup
, DF
->getContents().data(),
598 DF
->getContents().size(), FixedValue
);
601 MCInstFragment
*IF
= dyn_cast
<MCInstFragment
>(it2
);
603 for (MCInstFragment::fixup_iterator it3
= IF
->fixup_begin(),
604 ie3
= IF
->fixup_end(); it3
!= ie3
; ++it3
) {
605 MCFixup
&Fixup
= *it3
;
606 uint64_t FixedValue
= HandleFixup(Layout
, *IF
, Fixup
);
607 getBackend().ApplyFixup(Fixup
, IF
->getCode().data(),
608 IF
->getCode().size(), FixedValue
);
614 // Write the object file.
615 getWriter().WriteObject(*this, Layout
);
617 stats::ObjectBytes
+= OS
.tell() - StartOffset
;
620 bool MCAssembler::FixupNeedsRelaxation(const MCFixup
&Fixup
,
621 const MCFragment
*DF
,
622 const MCAsmLayout
&Layout
) const {
626 // If we cannot resolve the fixup value, it requires relaxation.
629 if (!EvaluateFixup(Layout
, Fixup
, DF
, Target
, Value
))
632 // Otherwise, relax if the value is too big for a (signed) i8.
634 // FIXME: This is target dependent!
635 return int64_t(Value
) != int64_t(int8_t(Value
));
638 bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment
*IF
,
639 const MCAsmLayout
&Layout
) const {
640 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
641 // are intentionally pushing out inst fragments, or because we relaxed a
642 // previous instruction to one that doesn't need relaxation.
643 if (!getBackend().MayNeedRelaxation(IF
->getInst()))
646 for (MCInstFragment::const_fixup_iterator it
= IF
->fixup_begin(),
647 ie
= IF
->fixup_end(); it
!= ie
; ++it
)
648 if (FixupNeedsRelaxation(*it
, IF
, Layout
))
654 bool MCAssembler::RelaxInstruction(MCAsmLayout
&Layout
,
655 MCInstFragment
&IF
) {
656 if (!FragmentNeedsRelaxation(&IF
, Layout
))
659 ++stats::RelaxedInstructions
;
661 // FIXME-PERF: We could immediately lower out instructions if we can tell
662 // they are fully resolved, to avoid retesting on later passes.
664 // Relax the fragment.
667 getBackend().RelaxInstruction(IF
.getInst(), Relaxed
);
669 // Encode the new instruction.
671 // FIXME-PERF: If it matters, we could let the target do this. It can
672 // probably do so more efficiently in many cases.
673 SmallVector
<MCFixup
, 4> Fixups
;
674 SmallString
<256> Code
;
675 raw_svector_ostream
VecOS(Code
);
676 getEmitter().EncodeInstruction(Relaxed
, VecOS
, Fixups
);
679 // Update the instruction fragment.
682 IF
.getFixups().clear();
683 // FIXME: Eliminate copy.
684 for (unsigned i
= 0, e
= Fixups
.size(); i
!= e
; ++i
)
685 IF
.getFixups().push_back(Fixups
[i
]);
690 bool MCAssembler::RelaxLEB(MCAsmLayout
&Layout
, MCLEBFragment
&LF
) {
692 uint64_t OldSize
= LF
.getContents().size();
693 LF
.getValue().EvaluateAsAbsolute(Value
, Layout
);
694 SmallString
<8> &Data
= LF
.getContents();
696 raw_svector_ostream
OSE(Data
);
698 MCObjectWriter::EncodeSLEB128(Value
, OSE
);
700 MCObjectWriter::EncodeULEB128(Value
, OSE
);
702 return OldSize
!= LF
.getContents().size();
705 bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout
&Layout
,
706 MCDwarfLineAddrFragment
&DF
) {
707 int64_t AddrDelta
= 0;
708 uint64_t OldSize
= DF
.getContents().size();
709 bool IsAbs
= DF
.getAddrDelta().EvaluateAsAbsolute(AddrDelta
, Layout
);
713 LineDelta
= DF
.getLineDelta();
714 SmallString
<8> &Data
= DF
.getContents();
716 raw_svector_ostream
OSE(Data
);
717 MCDwarfLineAddr::Encode(LineDelta
, AddrDelta
, OSE
);
719 return OldSize
!= Data
.size();
722 bool MCAssembler::RelaxDwarfCallFrameFragment(MCAsmLayout
&Layout
,
723 MCDwarfCallFrameFragment
&DF
) {
724 int64_t AddrDelta
= 0;
725 uint64_t OldSize
= DF
.getContents().size();
726 bool IsAbs
= DF
.getAddrDelta().EvaluateAsAbsolute(AddrDelta
, Layout
);
729 SmallString
<8> &Data
= DF
.getContents();
731 raw_svector_ostream
OSE(Data
);
732 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta
, OSE
);
734 return OldSize
!= Data
.size();
737 bool MCAssembler::LayoutSectionOnce(MCAsmLayout
&Layout
,
739 MCFragment
*FirstInvalidFragment
= NULL
;
740 // Scan for fragments that need relaxation.
741 for (MCSectionData::iterator it2
= SD
.begin(),
742 ie2
= SD
.end(); it2
!= ie2
; ++it2
) {
743 // Check if this is an fragment that needs relaxation.
744 bool relaxedFrag
= false;
745 switch(it2
->getKind()) {
748 case MCFragment::FT_Inst
:
749 relaxedFrag
= RelaxInstruction(Layout
, *cast
<MCInstFragment
>(it2
));
751 case MCFragment::FT_Dwarf
:
752 relaxedFrag
= RelaxDwarfLineAddr(Layout
,
753 *cast
<MCDwarfLineAddrFragment
>(it2
));
755 case MCFragment::FT_DwarfFrame
:
757 RelaxDwarfCallFrameFragment(Layout
,
758 *cast
<MCDwarfCallFrameFragment
>(it2
));
760 case MCFragment::FT_LEB
:
761 relaxedFrag
= RelaxLEB(Layout
, *cast
<MCLEBFragment
>(it2
));
764 // Update the layout, and remember that we relaxed.
765 if (relaxedFrag
&& !FirstInvalidFragment
)
766 FirstInvalidFragment
= it2
;
768 if (FirstInvalidFragment
) {
769 Layout
.Invalidate(FirstInvalidFragment
);
775 bool MCAssembler::LayoutOnce(MCAsmLayout
&Layout
) {
776 ++stats::RelaxationSteps
;
778 bool WasRelaxed
= false;
779 for (iterator it
= begin(), ie
= end(); it
!= ie
; ++it
) {
780 MCSectionData
&SD
= *it
;
781 while(LayoutSectionOnce(Layout
, SD
))
788 void MCAssembler::FinishLayout(MCAsmLayout
&Layout
) {
789 // The layout is done. Mark every fragment as valid.
790 for (unsigned int i
= 0, n
= Layout
.getSectionOrder().size(); i
!= n
; ++i
) {
791 Layout
.getFragmentOffset(&*Layout
.getSectionOrder()[i
]->rbegin());
799 raw_ostream
&operator<<(raw_ostream
&OS
, const MCFixup
&AF
) {
800 OS
<< "<MCFixup" << " Offset:" << AF
.getOffset()
801 << " Value:" << *AF
.getValue()
802 << " Kind:" << AF
.getKind() << ">";
808 void MCFragment::dump() {
809 raw_ostream
&OS
= llvm::errs();
813 case MCFragment::FT_Align
: OS
<< "MCAlignFragment"; break;
814 case MCFragment::FT_Data
: OS
<< "MCDataFragment"; break;
815 case MCFragment::FT_Fill
: OS
<< "MCFillFragment"; break;
816 case MCFragment::FT_Inst
: OS
<< "MCInstFragment"; break;
817 case MCFragment::FT_Org
: OS
<< "MCOrgFragment"; break;
818 case MCFragment::FT_Dwarf
: OS
<< "MCDwarfFragment"; break;
819 case MCFragment::FT_DwarfFrame
: OS
<< "MCDwarfCallFrameFragment"; break;
820 case MCFragment::FT_LEB
: OS
<< "MCLEBFragment"; break;
823 OS
<< "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
824 << " Offset:" << Offset
<< ">";
827 case MCFragment::FT_Align
: {
828 const MCAlignFragment
*AF
= cast
<MCAlignFragment
>(this);
829 if (AF
->hasEmitNops())
830 OS
<< " (emit nops)";
832 OS
<< " Alignment:" << AF
->getAlignment()
833 << " Value:" << AF
->getValue() << " ValueSize:" << AF
->getValueSize()
834 << " MaxBytesToEmit:" << AF
->getMaxBytesToEmit() << ">";
837 case MCFragment::FT_Data
: {
838 const MCDataFragment
*DF
= cast
<MCDataFragment
>(this);
841 const SmallVectorImpl
<char> &Contents
= DF
->getContents();
842 for (unsigned i
= 0, e
= Contents
.size(); i
!= e
; ++i
) {
844 OS
<< hexdigit((Contents
[i
] >> 4) & 0xF) << hexdigit(Contents
[i
] & 0xF);
846 OS
<< "] (" << Contents
.size() << " bytes)";
848 if (!DF
->getFixups().empty()) {
851 for (MCDataFragment::const_fixup_iterator it
= DF
->fixup_begin(),
852 ie
= DF
->fixup_end(); it
!= ie
; ++it
) {
853 if (it
!= DF
->fixup_begin()) OS
<< ",\n ";
860 case MCFragment::FT_Fill
: {
861 const MCFillFragment
*FF
= cast
<MCFillFragment
>(this);
862 OS
<< " Value:" << FF
->getValue() << " ValueSize:" << FF
->getValueSize()
863 << " Size:" << FF
->getSize();
866 case MCFragment::FT_Inst
: {
867 const MCInstFragment
*IF
= cast
<MCInstFragment
>(this);
870 IF
->getInst().dump_pretty(OS
);
873 case MCFragment::FT_Org
: {
874 const MCOrgFragment
*OF
= cast
<MCOrgFragment
>(this);
876 OS
<< " Offset:" << OF
->getOffset() << " Value:" << OF
->getValue();
879 case MCFragment::FT_Dwarf
: {
880 const MCDwarfLineAddrFragment
*OF
= cast
<MCDwarfLineAddrFragment
>(this);
882 OS
<< " AddrDelta:" << OF
->getAddrDelta()
883 << " LineDelta:" << OF
->getLineDelta();
886 case MCFragment::FT_DwarfFrame
: {
887 const MCDwarfCallFrameFragment
*CF
= cast
<MCDwarfCallFrameFragment
>(this);
889 OS
<< " AddrDelta:" << CF
->getAddrDelta();
892 case MCFragment::FT_LEB
: {
893 const MCLEBFragment
*LF
= cast
<MCLEBFragment
>(this);
895 OS
<< " Value:" << LF
->getValue() << " Signed:" << LF
->isSigned();
902 void MCSectionData::dump() {
903 raw_ostream
&OS
= llvm::errs();
905 OS
<< "<MCSectionData";
906 OS
<< " Alignment:" << getAlignment() << " Fragments:[\n ";
907 for (iterator it
= begin(), ie
= end(); it
!= ie
; ++it
) {
908 if (it
!= begin()) OS
<< ",\n ";
914 void MCSymbolData::dump() {
915 raw_ostream
&OS
= llvm::errs();
917 OS
<< "<MCSymbolData Symbol:" << getSymbol()
918 << " Fragment:" << getFragment() << " Offset:" << getOffset()
919 << " Flags:" << getFlags() << " Index:" << getIndex();
921 OS
<< " (common, size:" << getCommonSize()
922 << " align: " << getCommonAlignment() << ")";
925 if (isPrivateExtern())
926 OS
<< " (private extern)";
930 void MCAssembler::dump() {
931 raw_ostream
&OS
= llvm::errs();
933 OS
<< "<MCAssembler\n";
934 OS
<< " Sections:[\n ";
935 for (iterator it
= begin(), ie
= end(); it
!= ie
; ++it
) {
936 if (it
!= begin()) OS
<< ",\n ";
942 for (symbol_iterator it
= symbol_begin(), ie
= symbol_end(); it
!= ie
; ++it
) {
943 if (it
!= symbol_begin()) OS
<< ",\n ";