blob: cde6a93a164729636b8671cd48634bbc028219aa [file] [log] [blame]
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001//===- 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
Chandler Carruthe3e43d92017-06-06 11:49:48 +000010#include "llvm/MC/MCAssembler.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000014#include "llvm/ADT/Statistic.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000015#include "llvm/ADT/StringRef.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCAsmBackend.h"
Lang Hames4c553e02015-01-09 18:55:42 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +000019#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbarb36052f2010-03-19 10:43:23 +000020#include "llvm/MC/MCCodeEmitter.h"
Reid Kleckner617bba82016-02-02 17:41:18 +000021#include "llvm/MC/MCCodeView.h"
Rafael Espindolafea753b2010-12-24 21:22:02 +000022#include "llvm/MC/MCContext.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/MC/MCDwarf.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000024#include "llvm/MC/MCExpr.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000025#include "llvm/MC/MCFixup.h"
Craig Topperf1d0f772012-03-26 06:58:25 +000026#include "llvm/MC/MCFixupKindInfo.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000027#include "llvm/MC/MCFragment.h"
28#include "llvm/MC/MCInst.h"
Daniel Dunbar53b23382010-03-19 09:28:59 +000029#include "llvm/MC/MCObjectWriter.h"
Kevin Enderbyc0957932010-09-30 16:52:03 +000030#include "llvm/MC/MCSection.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000031#include "llvm/MC/MCSectionELF.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000032#include "llvm/MC/MCSymbol.h"
33#include "llvm/MC/MCValue.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000034#include "llvm/Support/Casting.h"
Daniel Dunbarac2884a2010-03-25 22:49:09 +000035#include "llvm/Support/Debug.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000036#include "llvm/Support/ErrorHandling.h"
Jim Grosbach2d39a0e2012-08-08 23:56:06 +000037#include "llvm/Support/LEB128.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000038#include "llvm/Support/MathExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000039#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000040#include <cassert>
41#include <cstdint>
Chandler Carruthe3e43d92017-06-06 11:49:48 +000042#include <cstring>
Benjamin Kramerd17f5932014-04-29 23:46:48 +000043#include <tuple>
Eugene Zelenkof31871c2017-02-07 23:02:00 +000044#include <utility>
45
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000046using namespace llvm;
47
Chandler Carruth0d338a52014-04-22 03:04:17 +000048#define DEBUG_TYPE "assembler"
49
Daniel Dunbarff547842010-03-23 23:47:14 +000050namespace {
51namespace stats {
Eugene Zelenkof31871c2017-02-07 23:02:00 +000052
Eli Bendersky8ddc5a12012-12-07 17:59:21 +000053STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
Eli Bendersky6f6204f2013-01-08 17:41:59 +000054STATISTIC(EmittedRelaxableFragments,
55 "Number of emitted assembler fragments - relaxable");
Eli Bendersky6ac81f52012-12-10 18:59:39 +000056STATISTIC(EmittedDataFragments,
57 "Number of emitted assembler fragments - data");
Eli Bendersky9ccb7692013-01-15 23:22:09 +000058STATISTIC(EmittedCompactEncodedInstFragments,
59 "Number of emitted assembler fragments - compact encoded inst");
Eli Bendersky6ac81f52012-12-10 18:59:39 +000060STATISTIC(EmittedAlignFragments,
61 "Number of emitted assembler fragments - align");
62STATISTIC(EmittedFillFragments,
63 "Number of emitted assembler fragments - fill");
64STATISTIC(EmittedOrgFragments,
65 "Number of emitted assembler fragments - org");
Jim Grosbachf77d5b12011-12-06 00:03:48 +000066STATISTIC(evaluateFixup, "Number of evaluated fixups");
Daniel Dunbarac2884a2010-03-25 22:49:09 +000067STATISTIC(FragmentLayouts, "Number of fragment layouts");
Daniel Dunbarff547842010-03-23 23:47:14 +000068STATISTIC(ObjectBytes, "Number of emitted object file bytes");
Daniel Dunbarac2884a2010-03-25 22:49:09 +000069STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
70STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +000071STATISTIC(PaddingFragmentsRelaxations,
72 "Number of Padding Fragments relaxations");
73STATISTIC(PaddingFragmentsBytes,
74 "Total size of all padding from adding Fragments");
Eugene Zelenkof31871c2017-02-07 23:02:00 +000075
76} // end namespace stats
77} // end anonymous namespace
Daniel Dunbar0adcd352009-08-25 21:10:45 +000078
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000079// FIXME FIXME FIXME: There are number of places in this file where we convert
80// what is a 64-bit assembler value used for computation into a value in the
81// object file, which may truncate it. We should detect that truncation where
82// invalid and report errors back.
83
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000084/* *** */
85
Nirav Dave92f209b2018-04-27 15:45:27 +000086MCAssembler::MCAssembler(MCContext &Context,
87 std::unique_ptr<MCAsmBackend> Backend,
88 std::unique_ptr<MCCodeEmitter> Emitter,
89 std::unique_ptr<MCObjectWriter> Writer)
90 : Context(Context), Backend(std::move(Backend)),
91 Emitter(std::move(Emitter)), Writer(std::move(Writer)),
David Majnemerdc2d2162015-09-01 23:19:38 +000092 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
David Majnemer56afa6e2015-12-21 22:09:27 +000093 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
Matthias Braun177a4fc2017-12-14 00:12:46 +000094 VersionInfo.Major = 0; // Major version == 0 for "none specified"
Daniel Dunbar6009db42009-08-26 21:22:22 +000095}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000096
Eugene Zelenkof31871c2017-02-07 23:02:00 +000097MCAssembler::~MCAssembler() = default;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000098
Pedro Artigas5399d252012-12-12 22:59:46 +000099void MCAssembler::reset() {
100 Sections.clear();
101 Symbols.clear();
Pedro Artigas5399d252012-12-12 22:59:46 +0000102 IndirectSymbols.clear();
103 DataRegions.clear();
Yaron Kerenc63035a2014-09-17 09:25:36 +0000104 LinkerOptions.clear();
105 FileNames.clear();
Pedro Artigas5399d252012-12-12 22:59:46 +0000106 ThumbFuncs.clear();
Yaron Kerenc63035a2014-09-17 09:25:36 +0000107 BundleAlignSize = 0;
Pedro Artigas5399d252012-12-12 22:59:46 +0000108 RelaxAll = false;
Pedro Artigas5399d252012-12-12 22:59:46 +0000109 SubsectionsViaSymbols = false;
David Majnemer56afa6e2015-12-21 22:09:27 +0000110 IncrementalLinkerCompatible = false;
Jack Carter9a7bf432013-01-30 02:09:52 +0000111 ELFHeaderEFlags = 0;
Yaron Kerenc63035a2014-09-17 09:25:36 +0000112 LOHContainer.reset();
Matthias Braun177a4fc2017-12-14 00:12:46 +0000113 VersionInfo.Major = 0;
Alex Lorenz6592c092018-12-14 01:14:10 +0000114 VersionInfo.SDKVersion = VersionTuple();
Pedro Artigas99cbdde2012-12-14 18:52:11 +0000115
116 // reset objects owned by us
Nirav Dave92f209b2018-04-27 15:45:27 +0000117 if (getBackendPtr())
118 getBackendPtr()->reset();
119 if (getEmitterPtr())
120 getEmitterPtr()->reset();
121 if (getWriterPtr())
122 getWriterPtr()->reset();
Tim Northover1330ee32014-03-29 07:34:53 +0000123 getLOHContainer().reset();
Pedro Artigas5399d252012-12-12 22:59:46 +0000124}
125
Rafael Espindola8e4f5702015-10-03 18:28:40 +0000126bool MCAssembler::registerSection(MCSection &Section) {
127 if (Section.isRegistered())
128 return false;
129 Sections.push_back(&Section);
130 Section.setIsRegistered(true);
131 return true;
132}
133
Rafael Espindola1c5f4392014-04-29 12:46:50 +0000134bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
135 if (ThumbFuncs.count(Symbol))
136 return true;
137
138 if (!Symbol->isVariable())
139 return false;
140
Rafael Espindola1c5f4392014-04-29 12:46:50 +0000141 const MCExpr *Expr = Symbol->getVariableValue();
Evgeniy Stepanove2c31422017-01-19 20:04:11 +0000142
143 MCValue V;
144 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
145 return false;
146
147 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
148 return false;
149
150 const MCSymbolRefExpr *Ref = V.getSymA();
Rafael Espindola1c5f4392014-04-29 12:46:50 +0000151 if (!Ref)
152 return false;
153
154 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
155 return false;
156
157 const MCSymbol &Sym = Ref->getSymbol();
158 if (!isThumbFunc(&Sym))
159 return false;
160
161 ThumbFuncs.insert(Symbol); // Cache it.
162 return true;
163}
164
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000165bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
Daniel Dunbar23869852010-03-19 03:18:09 +0000166 // Non-temporary labels should always be visible to the linker.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000167 if (!Symbol.isTemporary())
Daniel Dunbar23869852010-03-19 03:18:09 +0000168 return true;
169
170 // Absolute temporary labels are never visible.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000171 if (!Symbol.isInSection())
Daniel Dunbar23869852010-03-19 03:18:09 +0000172 return false;
173
Rafael Espindolaa1e31b42015-06-17 20:08:20 +0000174 if (Symbol.isUsedInReloc())
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000175 return true;
176
177 return false;
Daniel Dunbar23869852010-03-19 03:18:09 +0000178}
179
Duncan P. N. Exon Smith20cf3f42015-05-20 16:02:11 +0000180const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000181 // Linker visible symbols define atoms.
Duncan P. N. Exon Smith20cf3f42015-05-20 16:02:11 +0000182 if (isSymbolLinkerVisible(S))
183 return &S;
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000184
185 // Absolute and undefined symbols have no defining atom.
Rafael Espindola0eba49c2015-10-05 12:07:05 +0000186 if (!S.isInSection())
Craig Topper4266ae82014-04-13 04:57:38 +0000187 return nullptr;
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000188
Daniel Dunbara5f1d572010-05-12 00:38:17 +0000189 // Non-linker visible symbols in sections which can't be atomized have no
190 // defining atom.
Lang Hames4c553e02015-01-09 18:55:42 +0000191 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000192 *S.getFragment()->getParent()))
Craig Topper4266ae82014-04-13 04:57:38 +0000193 return nullptr;
Daniel Dunbara5f1d572010-05-12 00:38:17 +0000194
Daniel Dunbar651804c2010-05-11 17:22:50 +0000195 // Otherwise, return the atom for the containing fragment.
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000196 return S.getFragment()->getAtom();
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000197}
198
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000199bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000200 const MCFixup &Fixup, const MCFragment *DF,
Shiva Chene2740152018-05-18 06:42:21 +0000201 MCValue &Target, uint64_t &Value,
202 bool &WasForced) const {
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000203 ++stats::evaluateFixup;
Daniel Dunbarff547842010-03-23 23:47:14 +0000204
Jim Grosbachbc812862015-06-04 22:24:41 +0000205 // FIXME: This code has some duplication with recordRelocation. We should
Rafael Espindola45516712014-07-01 14:34:30 +0000206 // probably merge the two into a single callback that tries to evaluate a
207 // fixup and records a relocation if one is needed.
Rafael Espindola6f1c76b2017-06-22 17:25:35 +0000208
209 // On error claim to have completely evaluated the fixup, to prevent any
210 // further processing from being done.
Rafael Espindola45516712014-07-01 14:34:30 +0000211 const MCExpr *Expr = Fixup.getValue();
Rafael Espindola6f1c76b2017-06-22 17:25:35 +0000212 MCContext &Ctx = getContext();
213 Value = 0;
Shiva Chene2740152018-05-18 06:42:21 +0000214 WasForced = false;
Oliver Stannard99ab1122015-11-17 10:00:43 +0000215 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
Rafael Espindola6f1c76b2017-06-22 17:25:35 +0000216 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
Oliver Stannard99ab1122015-11-17 10:00:43 +0000217 return true;
218 }
Rafael Espindola6f1c76b2017-06-22 17:25:35 +0000219 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
220 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
221 Ctx.reportError(Fixup.getLoc(),
222 "unsupported subtraction of qualified symbol");
223 return true;
224 }
225 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000226
Nirav Dave92f209b2018-04-27 15:45:27 +0000227 assert(getBackendPtr() && "Expected assembler backend");
228 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
229 MCFixupKindInfo::FKF_IsPCRel;
Rafael Espindolafea753b2010-12-24 21:22:02 +0000230
Nirav Daveb2d1a402018-04-27 16:11:24 +0000231 bool IsResolved = false;
Rafael Espindolafea753b2010-12-24 21:22:02 +0000232 if (IsPCRel) {
233 if (Target.getSymB()) {
234 IsResolved = false;
235 } else if (!Target.getSymA()) {
236 IsResolved = false;
237 } else {
Rafael Espindola908159b2011-02-16 03:25:55 +0000238 const MCSymbolRefExpr *A = Target.getSymA();
239 const MCSymbol &SA = A->getSymbol();
Rafael Espindolae17e7a22015-04-06 16:10:05 +0000240 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
Rafael Espindolafea753b2010-12-24 21:22:02 +0000241 IsResolved = false;
Nirav Dave80e97ed2018-04-27 15:45:54 +0000242 } else if (auto *Writer = getWriterPtr()) {
243 IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smith9e6378d2015-05-16 01:01:55 +0000244 *this, SA, *DF, false, true);
Rafael Espindolafea753b2010-12-24 21:22:02 +0000245 }
246 }
247 } else {
248 IsResolved = Target.isAbsolute();
249 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000250
251 Value = Target.getConstant();
252
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000253 if (const MCSymbolRefExpr *A = Target.getSymA()) {
Rafael Espindolae17e7a22015-04-06 16:10:05 +0000254 const MCSymbol &Sym = A->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000255 if (Sym.isDefined())
Duncan P. N. Exon Smithe1fce862015-05-19 23:53:20 +0000256 Value += Layout.getSymbolOffset(Sym);
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000257 }
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000258 if (const MCSymbolRefExpr *B = Target.getSymB()) {
Rafael Espindolae17e7a22015-04-06 16:10:05 +0000259 const MCSymbol &Sym = B->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000260 if (Sym.isDefined())
Duncan P. N. Exon Smithe1fce862015-05-19 23:53:20 +0000261 Value -= Layout.getSymbolOffset(Sym);
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000262 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000263
Nirav Dave92f209b2018-04-27 15:45:27 +0000264 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
265 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
Owen Anderson47dbd422010-12-15 18:48:27 +0000266 assert((ShouldAlignPC ? IsPCRel : true) &&
267 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
268
Owen Anderson05018c22010-12-09 20:27:52 +0000269 if (IsPCRel) {
Owen Anderson175fb362010-12-17 21:49:48 +0000270 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
Jim Grosbach684457d2011-10-26 22:44:41 +0000271
Owen Anderson47dbd422010-12-15 18:48:27 +0000272 // A number of ARM fixups in Thumb mode require that the effective PC
273 // address be determined as the 32-bit aligned version of the actual offset.
Owen Andersond18e0112010-12-15 19:24:24 +0000274 if (ShouldAlignPC) Offset &= ~0x3;
Owen Anderson175fb362010-12-17 21:49:48 +0000275 Value -= Offset;
Owen Anderson05018c22010-12-09 20:27:52 +0000276 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000277
Rafael Espindola42ad1632017-06-30 22:47:27 +0000278 // Let the backend force a relocation if needed.
Shiva Chene2740152018-05-18 06:42:21 +0000279 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
Rafael Espindola42ad1632017-06-30 22:47:27 +0000280 IsResolved = false;
Shiva Chene2740152018-05-18 06:42:21 +0000281 WasForced = true;
282 }
Jim Grosbach47500202010-12-14 18:46:57 +0000283
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000284 return IsResolved;
285}
286
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000287uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
Rafael Espindola7a459032010-12-21 20:35:18 +0000288 const MCFragment &F) const {
Nirav Dave92f209b2018-04-27 15:45:27 +0000289 assert(getBackendPtr() && "Requires assembler backend");
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000290 switch (F.getKind()) {
291 case MCFragment::FT_Data:
Pete Cooperc821cef2015-06-17 22:01:28 +0000292 return cast<MCDataFragment>(F).getContents().size();
Eli Bendersky0fdcef62013-01-08 22:05:10 +0000293 case MCFragment::FT_Relaxable:
Pete Cooperc821cef2015-06-17 22:01:28 +0000294 return cast<MCRelaxableFragment>(F).getContents().size();
Eli Bendersky9ccb7692013-01-15 23:22:09 +0000295 case MCFragment::FT_CompactEncodedInst:
Pete Cooperc821cef2015-06-17 22:01:28 +0000296 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
Rafael Espindola5d5caec2018-01-09 22:48:37 +0000297 case MCFragment::FT_Fill: {
298 auto &FF = cast<MCFillFragment>(F);
Nirav Davecdcd5e12018-05-18 17:45:48 +0000299 int64_t NumValues = 0;
300 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
Rafael Espindola5d5caec2018-01-09 22:48:37 +0000301 getContext().reportError(FF.getLoc(),
302 "expected assembly-time absolute expression");
Nirav Davecdcd5e12018-05-18 17:45:48 +0000303 return 0;
304 }
305 int64_t Size = NumValues * FF.getValueSize();
Rafael Espindola5d5caec2018-01-09 22:48:37 +0000306 if (Size < 0) {
307 getContext().reportError(FF.getLoc(), "invalid number of bytes");
308 return 0;
309 }
310 return Size;
311 }
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000312
Rafael Espindola3ff57092010-11-02 17:22:24 +0000313 case MCFragment::FT_LEB:
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000314 return cast<MCLEBFragment>(F).getContents().size();
Rafael Espindola3ff57092010-11-02 17:22:24 +0000315
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +0000316 case MCFragment::FT_Padding:
317 return cast<MCPaddingFragment>(F).getSize();
318
Adrian McCarthycf89e1c2017-11-08 18:57:02 +0000319 case MCFragment::FT_SymbolId:
David Majnemere0d2a292015-05-30 04:56:02 +0000320 return 4;
321
Rafael Espindola7a459032010-12-21 20:35:18 +0000322 case MCFragment::FT_Align: {
323 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
324 unsigned Offset = Layout.getFragmentOffset(&AF);
325 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
Owen Anderson15b7a982012-08-29 22:18:56 +0000326 // If we are padding with nops, force the padding to be larger than the
327 // minimum nop size.
328 if (Size > 0 && AF.hasEmitNops()) {
329 while (Size % getBackend().getMinimumNopSize())
330 Size += AF.getAlignment();
331 }
Rafael Espindola7a459032010-12-21 20:35:18 +0000332 if (Size > AF.getMaxBytesToEmit())
333 return 0;
334 return Size;
335 }
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000336
Rafael Espindola7a459032010-12-21 20:35:18 +0000337 case MCFragment::FT_Org: {
David Blaikief12b3792013-02-11 01:16:51 +0000338 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
Rafael Espindola036ec432015-11-04 23:50:29 +0000339 MCValue Value;
Oliver Stannardf4f85602016-12-14 10:43:58 +0000340 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
341 getContext().reportError(OF.getLoc(),
342 "expected assembly-time absolute expression");
343 return 0;
344 }
Rafael Espindola7a459032010-12-21 20:35:18 +0000345
Rafael Espindola7a459032010-12-21 20:35:18 +0000346 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
Rafael Espindola036ec432015-11-04 23:50:29 +0000347 int64_t TargetLocation = Value.getConstant();
348 if (const MCSymbolRefExpr *A = Value.getSymA()) {
349 uint64_t Val;
Oliver Stannardf4f85602016-12-14 10:43:58 +0000350 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
351 getContext().reportError(OF.getLoc(), "expected absolute expression");
352 return 0;
353 }
Rafael Espindola036ec432015-11-04 23:50:29 +0000354 TargetLocation += Val;
355 }
Rafael Espindola7a459032010-12-21 20:35:18 +0000356 int64_t Size = TargetLocation - FragmentOffset;
Oliver Stannardf4f85602016-12-14 10:43:58 +0000357 if (Size < 0 || Size >= 0x40000000) {
358 getContext().reportError(
359 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
360 "' (at offset '" + Twine(FragmentOffset) + "')");
361 return 0;
362 }
Rafael Espindola7a459032010-12-21 20:35:18 +0000363 return Size;
364 }
Kevin Enderbyc0957932010-09-30 16:52:03 +0000365
Rafael Espindola187d8332010-11-07 02:07:12 +0000366 case MCFragment::FT_Dwarf:
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000367 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
Rafael Espindola245a1e22010-12-28 05:39:27 +0000368 case MCFragment::FT_DwarfFrame:
369 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
Reid Kleckner617bba82016-02-02 17:41:18 +0000370 case MCFragment::FT_CVInlineLines:
371 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
David Majnemer7ddc5472016-02-05 01:55:49 +0000372 case MCFragment::FT_CVDefRange:
373 return cast<MCCVDefRangeFragment>(F).getContents().size();
Rafael Espindola0eba49c2015-10-05 12:07:05 +0000374 case MCFragment::FT_Dummy:
375 llvm_unreachable("Should not have been added");
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000376 }
377
Craig Topper85814382012-02-07 05:05:23 +0000378 llvm_unreachable("invalid fragment kind");
Daniel Dunbar2c18d3b2010-05-13 18:35:06 +0000379}
380
Eli Benderskyd52a2c02012-12-12 19:54:05 +0000381void MCAsmLayout::layoutFragment(MCFragment *F) {
Daniel Dunbar9005d452010-05-14 00:37:21 +0000382 MCFragment *Prev = F->getPrevNode();
Daniel Dunbarf0d17d22010-05-12 21:35:25 +0000383
Eli Benderskyd52a2c02012-12-12 19:54:05 +0000384 // We should never try to recompute something which is valid.
385 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
386 // We should never try to compute the fragment layout if its predecessor
387 // isn't valid.
388 assert((!Prev || isFragmentValid(Prev)) &&
389 "Attempt to compute fragment before its predecessor!");
Daniel Dunbarf0d17d22010-05-12 21:35:25 +0000390
391 ++stats::FragmentLayouts;
392
Daniel Dunbarb69fc042010-05-13 20:40:12 +0000393 // Compute fragment offset and size.
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000394 if (Prev)
Eli Bendersky4766ef42012-12-20 19:05:53 +0000395 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
396 else
397 F->Offset = 0;
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000398 LastValidFragment[F->getParent()] = F;
Eli Bendersky4766ef42012-12-20 19:05:53 +0000399
400 // If bundling is enabled and this fragment has instructions in it, it has to
401 // obey the bundling restrictions. With padding, we'll have:
402 //
403 //
404 // BundlePadding
Derek Schuffb11917c2013-01-31 17:00:03 +0000405 // |||
Eli Bendersky4766ef42012-12-20 19:05:53 +0000406 // -------------------------------------
407 // Prev |##########| F |
408 // -------------------------------------
409 // ^
410 // |
411 // F->Offset
412 //
413 // The fragment's offset will point to after the padding, and its computed
414 // size won't include the padding.
415 //
Petr Hosek054db7d2015-04-12 23:42:25 +0000416 // When the -mc-relax-all flag is used, we optimize bundling by writting the
Petr Hosek0aaf3282015-06-27 01:49:53 +0000417 // padding directly into fragments when the instructions are emitted inside
418 // the streamer. When the fragment is larger than the bundle size, we need to
419 // ensure that it's bundle aligned. This means that if we end up with
420 // multiple fragments, we must emit bundle padding between fragments.
Petr Hosek054db7d2015-04-12 23:42:25 +0000421 //
Petr Hosek0aaf3282015-06-27 01:49:53 +0000422 // ".align N" is an example of a directive that introduces multiple
423 // fragments. We could add a special case to handle ".align N" by emitting
424 // within-fragment padding (which would produce less padding when N is less
425 // than the bundle size), but for now we don't.
426 //
427 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
Eli Bendersky4766ef42012-12-20 19:05:53 +0000428 assert(isa<MCEncodedFragment>(F) &&
429 "Only MCEncodedFragment implementations have instructions");
Peter Smith565bf542018-06-15 09:48:18 +0000430 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
431 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
Eli Bendersky4766ef42012-12-20 19:05:53 +0000432
Petr Hosek0aaf3282015-06-27 01:49:53 +0000433 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
Eli Bendersky4766ef42012-12-20 19:05:53 +0000434 report_fatal_error("Fragment can't be larger than a bundle size");
435
Peter Smith565bf542018-06-15 09:48:18 +0000436 uint64_t RequiredBundlePadding =
437 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
Eli Bendersky4766ef42012-12-20 19:05:53 +0000438 if (RequiredBundlePadding > UINT8_MAX)
439 report_fatal_error("Padding cannot exceed 255 bytes");
Peter Smith565bf542018-06-15 09:48:18 +0000440 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
441 EF->Offset += RequiredBundlePadding;
Eli Bendersky4766ef42012-12-20 19:05:53 +0000442 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000443}
444
Rafael Espindolaba9e3282015-06-01 14:34:40 +0000445void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
446 bool New = !Symbol.isRegistered();
447 if (Created)
448 *Created = New;
449 if (New) {
450 Symbol.setIsRegistered(true);
451 Symbols.push_back(&Symbol);
452 }
453}
454
Peter Smith565bf542018-06-15 09:48:18 +0000455void MCAssembler::writeFragmentPadding(raw_ostream &OS,
456 const MCEncodedFragment &EF,
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000457 uint64_t FSize) const {
Nirav Dave92f209b2018-04-27 15:45:27 +0000458 assert(getBackendPtr() && "Expected assembler backend");
Eli Bendersky4766ef42012-12-20 19:05:53 +0000459 // Should NOP padding be written out before this fragment?
Peter Smith565bf542018-06-15 09:48:18 +0000460 unsigned BundlePadding = EF.getBundlePadding();
Eli Bendersky4766ef42012-12-20 19:05:53 +0000461 if (BundlePadding > 0) {
Petr Hosek054db7d2015-04-12 23:42:25 +0000462 assert(isBundlingEnabled() &&
Eli Bendersky4766ef42012-12-20 19:05:53 +0000463 "Writing bundle padding with disabled bundling");
Peter Smith565bf542018-06-15 09:48:18 +0000464 assert(EF.hasInstructions() &&
Eli Bendersky4766ef42012-12-20 19:05:53 +0000465 "Writing bundle padding for a fragment without instructions");
466
Petr Hosek054db7d2015-04-12 23:42:25 +0000467 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
Peter Smith565bf542018-06-15 09:48:18 +0000468 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
Derek Schuffb11917c2013-01-31 17:00:03 +0000469 // If the padding itself crosses a bundle boundary, it must be emitted
470 // in 2 pieces, since even nop instructions must not cross boundaries.
471 // v--------------v <- BundleAlignSize
472 // v---------v <- BundlePadding
473 // ----------------------------
474 // | Prev |####|####| F |
475 // ----------------------------
476 // ^-------------------^ <- TotalLength
Petr Hosek054db7d2015-04-12 23:42:25 +0000477 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000478 if (!getBackend().writeNopData(OS, DistanceToBoundary))
Peter Smith565bf542018-06-15 09:48:18 +0000479 report_fatal_error("unable to write NOP sequence of " +
480 Twine(DistanceToBoundary) + " bytes");
Derek Schuffb11917c2013-01-31 17:00:03 +0000481 BundlePadding -= DistanceToBoundary;
482 }
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000483 if (!getBackend().writeNopData(OS, BundlePadding))
Eli Bendersky4766ef42012-12-20 19:05:53 +0000484 report_fatal_error("unable to write NOP sequence of " +
485 Twine(BundlePadding) + " bytes");
486 }
Petr Hosek054db7d2015-04-12 23:42:25 +0000487}
488
Adrian Prantl26b584c2018-05-01 15:54:18 +0000489/// Write the fragment \p F to the output file.
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000490static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
491 const MCAsmLayout &Layout, const MCFragment &F) {
Petr Hosek054db7d2015-04-12 23:42:25 +0000492 // FIXME: Embed in fragments instead?
493 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
494
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000495 support::endianness Endian = Asm.getBackend().Endian;
496
Peter Smith565bf542018-06-15 09:48:18 +0000497 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
498 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
Eli Bendersky4766ef42012-12-20 19:05:53 +0000499
500 // This variable (and its dummy usage) is to participate in the assert at
501 // the end of the function.
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000502 uint64_t Start = OS.tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000503 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000504
Daniel Dunbarff547842010-03-23 23:47:14 +0000505 ++stats::EmittedFragments;
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000506
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000507 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000508 case MCFragment::FT_Align: {
Eli Bendersky6ac81f52012-12-10 18:59:39 +0000509 ++stats::EmittedAlignFragments;
David Blaikief12b3792013-02-11 01:16:51 +0000510 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbare73d49e2010-05-12 22:51:27 +0000511 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
512
Eric Christopheree0dcf42013-08-07 18:51:09 +0000513 uint64_t Count = FragmentSize / AF.getValueSize();
514
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000515 // FIXME: This error shouldn't actually occur (the front end should emit
516 // multiple .align directives to enforce the semantics it wants), but is
517 // severe enough that we want to report it. How to handle this?
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000518 if (Count * AF.getValueSize() != FragmentSize)
Chris Lattner75361b62010-04-07 22:58:41 +0000519 report_fatal_error("undefined .align directive, value size '" +
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000520 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000521 "' is not a divisor of padding size '" +
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000522 Twine(FragmentSize) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000523
Kevin Enderby6e720482010-02-23 18:26:34 +0000524 // See if we are aligning with nops, and if so do that first to try to fill
525 // the Count bytes. Then if that did not fill any bytes or there are any
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000526 // bytes left to fill use the Value and ValueSize to fill the rest.
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000527 // If we are aligning with nops, ask that target to emit the right data.
Daniel Dunbar1c154132010-05-12 22:56:23 +0000528 if (AF.hasEmitNops()) {
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000529 if (!Asm.getBackend().writeNopData(OS, Count))
Chris Lattner75361b62010-04-07 22:58:41 +0000530 report_fatal_error("unable to write nop sequence of " +
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000531 Twine(Count) + " bytes");
532 break;
Kevin Enderby6e720482010-02-23 18:26:34 +0000533 }
534
Daniel Dunbar8f9b80e2010-03-23 02:36:58 +0000535 // Otherwise, write out in multiples of the value size.
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000536 for (uint64_t i = 0; i != Count; ++i) {
537 switch (AF.getValueSize()) {
Craig Topper85814382012-02-07 05:05:23 +0000538 default: llvm_unreachable("Invalid size!");
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000539 case 1: OS << char(AF.getValue()); break;
540 case 2:
541 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
542 break;
543 case 4:
544 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
545 break;
546 case 8:
547 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
548 break;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000549 }
550 }
551 break;
552 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000553
Fangrui Songaf7b1832018-07-30 19:41:25 +0000554 case MCFragment::FT_Data:
Eli Bendersky8ddc5a12012-12-07 17:59:21 +0000555 ++stats::EmittedDataFragments;
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000556 OS << cast<MCDataFragment>(F).getContents();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000557 break;
Eli Bendersky64d9a322012-12-07 19:13:57 +0000558
Eli Bendersky251040b2013-01-08 00:22:56 +0000559 case MCFragment::FT_Relaxable:
Eli Bendersky6f6204f2013-01-08 17:41:59 +0000560 ++stats::EmittedRelaxableFragments;
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000561 OS << cast<MCRelaxableFragment>(F).getContents();
Eli Bendersky64d9a322012-12-07 19:13:57 +0000562 break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000563
Eli Bendersky9ccb7692013-01-15 23:22:09 +0000564 case MCFragment::FT_CompactEncodedInst:
565 ++stats::EmittedCompactEncodedInstFragments;
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000566 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
Eli Bendersky9ccb7692013-01-15 23:22:09 +0000567 break;
568
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000569 case MCFragment::FT_Fill: {
Eli Bendersky6ac81f52012-12-10 18:59:39 +0000570 ++stats::EmittedFillFragments;
David Blaikief12b3792013-02-11 01:16:51 +0000571 const MCFillFragment &FF = cast<MCFillFragment>(F);
Nirav Davecdcd5e12018-05-18 17:45:48 +0000572 uint64_t V = FF.getValue();
573 unsigned VSize = FF.getValueSize();
Rafael Espindolabe7a41b2016-01-19 17:47:48 +0000574 const unsigned MaxChunkSize = 16;
575 char Data[MaxChunkSize];
Nirav Davecdcd5e12018-05-18 17:45:48 +0000576 // Duplicate V into Data as byte vector to reduce number of
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000577 // writes done. As such, do endian conversion here.
Nirav Davecdcd5e12018-05-18 17:45:48 +0000578 for (unsigned I = 0; I != VSize; ++I) {
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000579 unsigned index = Endian == support::little ? I : (VSize - I - 1);
Nirav Davecdcd5e12018-05-18 17:45:48 +0000580 Data[I] = uint8_t(V >> (index * 8));
581 }
582 for (unsigned I = VSize; I < MaxChunkSize; ++I)
583 Data[I] = Data[I - VSize];
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000584
Nirav Davecdcd5e12018-05-18 17:45:48 +0000585 // Set to largest multiple of VSize in Data.
586 const unsigned NumPerChunk = MaxChunkSize / VSize;
587 // Set ChunkSize to largest multiple of VSize in Data
588 const unsigned ChunkSize = VSize * NumPerChunk;
589
590 // Do copies by chunk.
591 StringRef Ref(Data, ChunkSize);
592 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000593 OS << Ref;
Nirav Davecdcd5e12018-05-18 17:45:48 +0000594
595 // do remainder if needed.
596 unsigned TrailingCount = FragmentSize % ChunkSize;
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000597 if (TrailingCount)
598 OS.write(Data, TrailingCount);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000599 break;
600 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000601
Rafael Espindola3ff57092010-11-02 17:22:24 +0000602 case MCFragment::FT_LEB: {
David Blaikief12b3792013-02-11 01:16:51 +0000603 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000604 OS << LF.getContents();
Rafael Espindola3ff57092010-11-02 17:22:24 +0000605 break;
606 }
607
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +0000608 case MCFragment::FT_Padding: {
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000609 if (!Asm.getBackend().writeNopData(OS, FragmentSize))
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +0000610 report_fatal_error("unable to write nop sequence of " +
611 Twine(FragmentSize) + " bytes");
612 break;
613 }
614
Adrian McCarthycf89e1c2017-11-08 18:57:02 +0000615 case MCFragment::FT_SymbolId: {
616 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000617 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
David Majnemere0d2a292015-05-30 04:56:02 +0000618 break;
619 }
620
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000621 case MCFragment::FT_Org: {
Eli Bendersky6ac81f52012-12-10 18:59:39 +0000622 ++stats::EmittedOrgFragments;
David Blaikief12b3792013-02-11 01:16:51 +0000623 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000624
Daniel Dunbar432cd5f2010-03-25 02:00:02 +0000625 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000626 OS << char(OF.getValue());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000627
628 break;
629 }
Kevin Enderbyc0957932010-09-30 16:52:03 +0000630
631 case MCFragment::FT_Dwarf: {
632 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000633 OS << OF.getContents();
Kevin Enderbyc0957932010-09-30 16:52:03 +0000634 break;
635 }
Rafael Espindola245a1e22010-12-28 05:39:27 +0000636 case MCFragment::FT_DwarfFrame: {
637 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000638 OS << CF.getContents();
Rafael Espindola245a1e22010-12-28 05:39:27 +0000639 break;
640 }
Reid Kleckner617bba82016-02-02 17:41:18 +0000641 case MCFragment::FT_CVInlineLines: {
642 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000643 OS << OF.getContents();
Reid Kleckner617bba82016-02-02 17:41:18 +0000644 break;
645 }
David Majnemer7ddc5472016-02-05 01:55:49 +0000646 case MCFragment::FT_CVDefRange: {
647 const auto &DRF = cast<MCCVDefRangeFragment>(F);
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000648 OS << DRF.getContents();
David Majnemer7ddc5472016-02-05 01:55:49 +0000649 break;
650 }
Rafael Espindola0eba49c2015-10-05 12:07:05 +0000651 case MCFragment::FT_Dummy:
652 llvm_unreachable("Should not have been added");
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000653 }
654
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000655 assert(OS.tell() - Start == FragmentSize &&
Eli Bendersky4766ef42012-12-20 19:05:53 +0000656 "The stream should advance by fragment size");
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000657}
658
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000659void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
Daniel Dunbar5d2477c2010-12-17 02:45:59 +0000660 const MCAsmLayout &Layout) const {
Nirav Dave92f209b2018-04-27 15:45:27 +0000661 assert(getBackendPtr() && "Expected assembler backend");
662
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000663 // Ignore virtual sections.
Rafael Espindola2224f642015-05-26 02:17:21 +0000664 if (Sec->isVirtualSection()) {
665 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000666
667 // Check that contents are only things legal inside a virtual section.
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000668 for (const MCFragment &F : *Sec) {
669 switch (F.getKind()) {
Craig Topper85814382012-02-07 05:05:23 +0000670 default: llvm_unreachable("Invalid fragment in virtual section!");
Daniel Dunbarc983b202010-08-18 18:22:37 +0000671 case MCFragment::FT_Data: {
672 // Check that we aren't trying to write a non-zero contents (or fixups)
673 // into a virtual section. This is to support clients which use standard
674 // directives to fill the contents of virtual sections.
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000675 const MCDataFragment &DF = cast<MCDataFragment>(F);
Davide Italianoe20e4c12016-07-26 18:16:33 +0000676 if (DF.fixup_begin() != DF.fixup_end())
677 report_fatal_error("cannot have fixups in virtual section!");
Daniel Dunbarc983b202010-08-18 18:22:37 +0000678 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
Weiming Zhao09f104f2014-06-22 00:33:44 +0000679 if (DF.getContents()[i]) {
Rafael Espindola2224f642015-05-26 02:17:21 +0000680 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
Weiming Zhao09f104f2014-06-22 00:33:44 +0000681 report_fatal_error("non-zero initializer found in section '" +
682 ELFSec->getSectionName() + "'");
683 else
684 report_fatal_error("non-zero initializer found in virtual section");
685 }
Daniel Dunbarc983b202010-08-18 18:22:37 +0000686 break;
687 }
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000688 case MCFragment::FT_Align:
Daniel Dunbarc983b202010-08-18 18:22:37 +0000689 // Check that we aren't trying to write a non-zero value into a virtual
690 // section.
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000691 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
692 cast<MCAlignFragment>(F).getValue() == 0) &&
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000693 "Invalid align in virtual section!");
694 break;
695 case MCFragment::FT_Fill:
Rafael Espindola9f9435e2016-01-19 16:57:08 +0000696 assert((cast<MCFillFragment>(F).getValue() == 0) &&
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000697 "Invalid fill in virtual section!");
698 break;
Daniel Dunbare2fee5b2010-05-12 22:51:35 +0000699 }
700 }
701
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000702 return;
703 }
704
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000705 uint64_t Start = OS.tell();
Jim Grosbachb5762bf2012-09-18 23:05:18 +0000706 (void)Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000707
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000708 for (const MCFragment &F : *Sec)
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000709 writeFragment(OS, *this, Layout, F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000710
Peter Collingbourne74bda0b2018-05-21 18:11:35 +0000711 assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec));
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000712}
713
Rafael Espindola3d8b65f2017-06-23 22:52:36 +0000714std::tuple<MCValue, uint64_t, bool>
715MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
716 const MCFixup &Fixup) {
Joerg Sonnenberger286cc132014-01-13 15:50:36 +0000717 // Evaluate the fixup.
718 MCValue Target;
719 uint64_t FixedValue;
Shiva Chene2740152018-05-18 06:42:21 +0000720 bool WasForced;
721 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
722 WasForced);
Rafael Espindola4aebf832017-07-11 23:18:25 +0000723 if (!IsResolved) {
Joerg Sonnenberger286cc132014-01-13 15:50:36 +0000724 // The fixup was unresolved, we need a relocation. Inform the object
725 // writer of the relocation, and give it an opportunity to adjust the
726 // fixup value if need be.
Alex Bradburye54d5392018-05-23 12:36:18 +0000727 if (Target.getSymA() && Target.getSymB() &&
728 getBackend().requiresDiffExpressionRelocations()) {
729 // The fixup represents the difference between two symbols, which the
730 // backend has indicated must be resolved at link time. Split up the fixup
731 // into two relocations, one for the add, and one for the sub, and emit
732 // both of these. The constant will be associated with the add half of the
733 // expression.
734 MCFixup FixupAdd = MCFixup::createAddFor(Fixup);
735 MCValue TargetAdd =
736 MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
737 getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd,
738 FixedValue);
739 MCFixup FixupSub = MCFixup::createSubFor(Fixup);
740 MCValue TargetSub = MCValue::get(Target.getSymB());
741 getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub,
742 FixedValue);
743 } else {
744 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target,
745 FixedValue);
746 }
Joerg Sonnenberger286cc132014-01-13 15:50:36 +0000747 }
Rafael Espindola4aebf832017-07-11 23:18:25 +0000748 return std::make_tuple(Target, FixedValue, IsResolved);
Joerg Sonnenberger286cc132014-01-13 15:50:36 +0000749}
Rafael Espindola179821a2010-12-06 19:08:48 +0000750
Frederic Riss41426ae2015-08-26 05:09:49 +0000751void MCAssembler::layout(MCAsmLayout &Layout) {
Nirav Dave92f209b2018-04-27 15:45:27 +0000752 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000753 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenkof31871c2017-02-07 23:02:00 +0000754 errs() << "assembler backend - pre-layout\n--\n";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000755 dump(); });
756
Daniel Dunbar337718e2010-05-14 00:37:14 +0000757 // Create dummy fragments and assign section ordinals.
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000758 unsigned SectionIndex = 0;
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000759 for (MCSection &Sec : *this) {
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000760 // Create dummy fragments to eliminate any empty sections, this simplifies
761 // layout.
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000762 if (Sec.getFragmentList().empty())
763 new MCDataFragment(&Sec);
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000764
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000765 Sec.setOrdinal(SectionIndex++);
Daniel Dunbar337718e2010-05-14 00:37:14 +0000766 }
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000767
Daniel Dunbar337718e2010-05-14 00:37:14 +0000768 // Assign layout order indices to sections and fragments.
Daniel Dunbar337718e2010-05-14 00:37:14 +0000769 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000770 MCSection *Sec = Layout.getSectionOrder()[i];
771 Sec->setLayoutOrder(i);
Daniel Dunbar337718e2010-05-14 00:37:14 +0000772
Rafael Espindola4f4363a2010-12-07 23:32:26 +0000773 unsigned FragmentIndex = 0;
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000774 for (MCFragment &Frag : *Sec)
775 Frag.setLayoutOrder(FragmentIndex++);
Daniel Dunbar49ed9212010-05-13 08:43:37 +0000776 }
777
Daniel Dunbar61066db2010-05-13 02:34:14 +0000778 // Layout until everything fits.
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000779 while (layoutOnce(Layout))
Oliver Stannardf4f85602016-12-14 10:43:58 +0000780 if (getContext().hadError())
781 return;
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000782
783 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenkof31871c2017-02-07 23:02:00 +0000784 errs() << "assembler backend - post-relaxation\n--\n";
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000785 dump(); });
786
787 // Finalize the layout, including fragment lowering.
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000788 finishLayout(Layout);
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +0000789
790 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenkof31871c2017-02-07 23:02:00 +0000791 errs() << "assembler backend - final-layout\n--\n";
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000792 dump(); });
793
Daniel Dunbarbacba992010-03-19 07:09:33 +0000794 // Allow the object writer a chance to perform post-layout binding (for
795 // example, to set the index fields in the symbol data).
Jim Grosbacheafe4652015-06-04 23:25:54 +0000796 getWriter().executePostLayoutBinding(*this, Layout);
Daniel Dunbarbacba992010-03-19 07:09:33 +0000797
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000798 // Evaluate and apply the fixups, generating relocation entries as necessary.
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000799 for (MCSection &Sec : *this) {
800 for (MCFragment &Frag : Sec) {
Pete Cooperc821cef2015-06-17 22:01:28 +0000801 // Data and relaxable fragments both have fixups. So only process
802 // those here.
803 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
804 // being templated makes this tricky.
David Majnemer7ddc5472016-02-05 01:55:49 +0000805 if (isa<MCEncodedFragment>(&Frag) &&
806 isa<MCCompactEncodedInstFragment>(&Frag))
807 continue;
808 if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag))
Pete Cooperc821cef2015-06-17 22:01:28 +0000809 continue;
810 ArrayRef<MCFixup> Fixups;
811 MutableArrayRef<char> Contents;
Peter Smithe2b2a912018-06-06 09:40:06 +0000812 const MCSubtargetInfo *STI = nullptr;
David Majnemer7ddc5472016-02-05 01:55:49 +0000813 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
Pete Cooperc821cef2015-06-17 22:01:28 +0000814 Fixups = FragWithFixups->getFixups();
815 Contents = FragWithFixups->getContents();
Peter Smithe2b2a912018-06-06 09:40:06 +0000816 STI = FragWithFixups->getSubtargetInfo();
817 assert(!FragWithFixups->hasInstructions() || STI != nullptr);
David Majnemer7ddc5472016-02-05 01:55:49 +0000818 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) {
819 Fixups = FragWithFixups->getFixups();
820 Contents = FragWithFixups->getContents();
Peter Smithe2b2a912018-06-06 09:40:06 +0000821 STI = FragWithFixups->getSubtargetInfo();
822 assert(!FragWithFixups->hasInstructions() || STI != nullptr);
David Majnemer7ddc5472016-02-05 01:55:49 +0000823 } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
Pete Cooperc821cef2015-06-17 22:01:28 +0000824 Fixups = FragWithFixups->getFixups();
825 Contents = FragWithFixups->getContents();
Hsiangkai Wang2bdc8dd2018-08-01 02:18:06 +0000826 } else if (auto *FragWithFixups = dyn_cast<MCDwarfLineAddrFragment>(&Frag)) {
827 Fixups = FragWithFixups->getFixups();
828 Contents = FragWithFixups->getContents();
Pete Cooperc821cef2015-06-17 22:01:28 +0000829 } else
Yaron Keren57dee472015-07-04 05:48:52 +0000830 llvm_unreachable("Unknown fragment with fixups!");
Pete Cooperc821cef2015-06-17 22:01:28 +0000831 for (const MCFixup &Fixup : Fixups) {
832 uint64_t FixedValue;
Rafael Espindola4aebf832017-07-11 23:18:25 +0000833 bool IsResolved;
Rafael Espindola3d8b65f2017-06-23 22:52:36 +0000834 MCValue Target;
Rafael Espindola4aebf832017-07-11 23:18:25 +0000835 std::tie(Target, FixedValue, IsResolved) =
Rafael Espindola3d8b65f2017-06-23 22:52:36 +0000836 handleFixup(Layout, Frag, Fixup);
837 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
Peter Smithe2b2a912018-06-06 09:40:06 +0000838 IsResolved, STI);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000839 }
840 }
841 }
Frederic Riss41426ae2015-08-26 05:09:49 +0000842}
843
844void MCAssembler::Finish() {
845 // Create the layout object.
846 MCAsmLayout Layout(*this);
847 layout(Layout);
848
Daniel Dunbarbacba992010-03-19 07:09:33 +0000849 // Write the object file.
Peter Collingbourne0d4292f2018-05-21 18:23:50 +0000850 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000851}
852
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000853bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
Eli Bendersky251040b2013-01-08 00:22:56 +0000854 const MCRelaxableFragment *DF,
Daniel Dunbar8d39eb42010-03-22 20:35:35 +0000855 const MCAsmLayout &Layout) const {
Nirav Dave92f209b2018-04-27 15:45:27 +0000856 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000857 MCValue Target;
858 uint64_t Value;
Shiva Chene2740152018-05-18 06:42:21 +0000859 bool WasForced;
860 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
Peter Collingbourne043d1a92017-01-31 18:28:44 +0000861 if (Target.getSymA() &&
862 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
863 Fixup.getKind() == FK_Data_1)
864 return false;
Colin LeMahieu32de7d72015-05-30 18:42:22 +0000865 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
Shiva Chene2740152018-05-18 06:42:21 +0000866 Layout, WasForced);
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000867}
868
Eli Bendersky251040b2013-01-08 00:22:56 +0000869bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000870 const MCAsmLayout &Layout) const {
Nirav Dave92f209b2018-04-27 15:45:27 +0000871 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000872 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
873 // are intentionally pushing out inst fragments, or because we relaxed a
874 // previous instruction to one that doesn't need relaxation.
Peter Smithe2b2a912018-06-06 09:40:06 +0000875 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000876 return false;
877
Craig Topperdc8bd0c2015-08-02 22:34:02 +0000878 for (const MCFixup &Fixup : F->getFixups())
879 if (fixupNeedsRelaxation(Fixup, F, Layout))
Daniel Dunbard8036fb2010-03-23 05:09:03 +0000880 return true;
881
882 return false;
883}
884
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000885bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
Eli Bendersky251040b2013-01-08 00:22:56 +0000886 MCRelaxableFragment &F) {
Nirav Dave92f209b2018-04-27 15:45:27 +0000887 assert(getEmitterPtr() &&
888 "Expected CodeEmitter defined for relaxInstruction");
Eli Bendersky251040b2013-01-08 00:22:56 +0000889 if (!fragmentNeedsRelaxation(&F, Layout))
Rafael Espindola3ff57092010-11-02 17:22:24 +0000890 return false;
891
892 ++stats::RelaxedInstructions;
893
894 // FIXME-PERF: We could immediately lower out instructions if we can tell
895 // they are fully resolved, to avoid retesting on later passes.
896
897 // Relax the fragment.
898
899 MCInst Relaxed;
Peter Smithe2b2a912018-06-06 09:40:06 +0000900 getBackend().relaxInstruction(F.getInst(), *F.getSubtargetInfo(), Relaxed);
Rafael Espindola3ff57092010-11-02 17:22:24 +0000901
902 // Encode the new instruction.
903 //
904 // FIXME-PERF: If it matters, we could let the target do this. It can
905 // probably do so more efficiently in many cases.
906 SmallVector<MCFixup, 4> Fixups;
907 SmallString<256> Code;
908 raw_svector_ostream VecOS(Code);
Peter Smithe2b2a912018-06-06 09:40:06 +0000909 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
Rafael Espindola3ff57092010-11-02 17:22:24 +0000910
Eli Bendersky251040b2013-01-08 00:22:56 +0000911 // Update the fragment.
912 F.setInst(Relaxed);
913 F.getContents() = Code;
914 F.getFixups() = Fixups;
Rafael Espindola3ff57092010-11-02 17:22:24 +0000915
Rafael Espindola3ff57092010-11-02 17:22:24 +0000916 return true;
917}
918
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +0000919bool MCAssembler::relaxPaddingFragment(MCAsmLayout &Layout,
920 MCPaddingFragment &PF) {
Nirav Dave92f209b2018-04-27 15:45:27 +0000921 assert(getBackendPtr() && "Expected assembler backend");
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +0000922 uint64_t OldSize = PF.getSize();
923 if (!getBackend().relaxFragment(&PF, Layout))
924 return false;
925 uint64_t NewSize = PF.getSize();
926
927 ++stats::PaddingFragmentsRelaxations;
928 stats::PaddingFragmentsBytes += NewSize;
929 stats::PaddingFragmentsBytes -= OldSize;
930 return true;
931}
932
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000933bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000934 uint64_t OldSize = LF.getContents().size();
Rafael Espindola49dba992015-03-25 00:25:37 +0000935 int64_t Value;
936 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
937 if (!Abs)
938 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000939 SmallString<8> &Data = LF.getContents();
940 Data.clear();
941 raw_svector_ostream OSE(Data);
Rafael Espindolaea9d3ea2018-02-01 00:25:19 +0000942 // The compiler can generate EH table assembly that is impossible to assemble
943 // without either adding padding to an LEB fragment or adding extra padding
944 // to a later alignment fragment. To accommodate such tables, relaxation can
945 // only increase an LEB fragment size here, not decrease it. See PR35809.
Rafael Espindola3ff57092010-11-02 17:22:24 +0000946 if (LF.isSigned())
Rafael Espindolaea9d3ea2018-02-01 00:25:19 +0000947 encodeSLEB128(Value, OSE, OldSize);
Rafael Espindola3ff57092010-11-02 17:22:24 +0000948 else
Rafael Espindolaea9d3ea2018-02-01 00:25:19 +0000949 encodeULEB128(Value, OSE, OldSize);
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000950 return OldSize != LF.getContents().size();
Rafael Espindola3ff57092010-11-02 17:22:24 +0000951}
952
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000953bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000954 MCDwarfLineAddrFragment &DF) {
Ulrich Weigandc1f4a4b2013-06-12 14:46:54 +0000955 MCContext &Context = Layout.getAssembler().getContext();
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000956 uint64_t OldSize = DF.getContents().size();
Rafael Espindola49dba992015-03-25 00:25:37 +0000957 int64_t AddrDelta;
Hsiangkai Wangc8a83002018-08-01 04:17:41 +0000958 bool Abs;
959 if (getBackend().requiresDiffExpressionRelocations())
960 Abs = DF.getAddrDelta().evaluateAsAbsolute(AddrDelta, Layout);
961 else {
962 Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
963 assert(Abs && "We created a line delta with an invalid expression");
964 }
Rafael Espindola187d8332010-11-07 02:07:12 +0000965 int64_t LineDelta;
966 LineDelta = DF.getLineDelta();
Hsiangkai Wang2bdc8dd2018-08-01 02:18:06 +0000967 SmallVectorImpl<char> &Data = DF.getContents();
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000968 Data.clear();
969 raw_svector_ostream OSE(Data);
Hsiangkai Wang2bdc8dd2018-08-01 02:18:06 +0000970 DF.getFixups().clear();
971
972 if (Abs) {
973 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
974 AddrDelta, OSE);
975 } else {
976 uint32_t Offset;
977 uint32_t Size;
978 bool SetDelta = MCDwarfLineAddr::FixedEncode(Context,
979 getDWARFLinetableParams(),
980 LineDelta, AddrDelta,
981 OSE, &Offset, &Size);
982 // Add Fixups for address delta or new address.
983 const MCExpr *FixupExpr;
984 if (SetDelta) {
985 FixupExpr = &DF.getAddrDelta();
986 } else {
987 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta());
988 FixupExpr = ABE->getLHS();
989 }
990 DF.getFixups().push_back(
991 MCFixup::create(Offset, FixupExpr,
992 MCFixup::getKindForSize(Size, false /*isPCRel*/)));
993 }
994
Rafael Espindoladb74aea2010-12-04 21:58:52 +0000995 return OldSize != Data.size();
Rafael Espindola187d8332010-11-07 02:07:12 +0000996}
997
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000998bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
Rafael Espindola245a1e22010-12-28 05:39:27 +0000999 MCDwarfCallFrameFragment &DF) {
Ulrich Weigandc1f4a4b2013-06-12 14:46:54 +00001000 MCContext &Context = Layout.getAssembler().getContext();
Rafael Espindola245a1e22010-12-28 05:39:27 +00001001 uint64_t OldSize = DF.getContents().size();
Rafael Espindola49dba992015-03-25 00:25:37 +00001002 int64_t AddrDelta;
1003 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1004 assert(Abs && "We created call frame with an invalid expression");
Rafael Espindola41509f42015-03-25 00:45:41 +00001005 (void) Abs;
Rafael Espindola245a1e22010-12-28 05:39:27 +00001006 SmallString<8> &Data = DF.getContents();
1007 Data.clear();
1008 raw_svector_ostream OSE(Data);
Ulrich Weigandc1f4a4b2013-06-12 14:46:54 +00001009 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
Rafael Espindola245a1e22010-12-28 05:39:27 +00001010 return OldSize != Data.size();
1011}
1012
Reid Kleckner617bba82016-02-02 17:41:18 +00001013bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1014 MCCVInlineLineTableFragment &F) {
1015 unsigned OldSize = F.getContents().size();
1016 getContext().getCVContext().encodeInlineLineTable(Layout, F);
1017 return OldSize != F.getContents().size();
1018}
1019
David Majnemer7ddc5472016-02-05 01:55:49 +00001020bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1021 MCCVDefRangeFragment &F) {
1022 unsigned OldSize = F.getContents().size();
1023 getContext().getCVContext().encodeDefRange(Layout, F);
1024 return OldSize != F.getContents().size();
1025}
1026
Rafael Espindola2224f642015-05-26 02:17:21 +00001027bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001028 // Holds the first fragment which needed relaxing during this layout. It will
1029 // remain NULL if none were relaxed.
Eli Benderskyd52a2c02012-12-12 19:54:05 +00001030 // When a fragment is relaxed, all the fragments following it should get
1031 // invalidated because their offset is going to change.
Craig Topper4266ae82014-04-13 04:57:38 +00001032 MCFragment *FirstRelaxedFragment = nullptr;
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001033
Eli Benderskyd52a2c02012-12-12 19:54:05 +00001034 // Attempt to relax all the fragments in the section.
Rafael Espindola899cab62015-05-27 15:14:11 +00001035 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001036 // Check if this is a fragment that needs relaxation.
1037 bool RelaxedFrag = false;
1038 switch(I->getKind()) {
Rafael Espindola62b83b62010-12-21 04:22:09 +00001039 default:
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001040 break;
Eli Bendersky251040b2013-01-08 00:22:56 +00001041 case MCFragment::FT_Relaxable:
Eli Bendersky37a98302012-12-11 17:16:00 +00001042 assert(!getRelaxAll() &&
Eli Bendersky251040b2013-01-08 00:22:56 +00001043 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1044 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
Rafael Espindola62b83b62010-12-21 04:22:09 +00001045 break;
Rafael Espindola62b83b62010-12-21 04:22:09 +00001046 case MCFragment::FT_Dwarf:
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001047 RelaxedFrag = relaxDwarfLineAddr(Layout,
1048 *cast<MCDwarfLineAddrFragment>(I));
Rafael Espindola62b83b62010-12-21 04:22:09 +00001049 break;
Rafael Espindola245a1e22010-12-28 05:39:27 +00001050 case MCFragment::FT_DwarfFrame:
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001051 RelaxedFrag =
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001052 relaxDwarfCallFrameFragment(Layout,
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001053 *cast<MCDwarfCallFrameFragment>(I));
Rafael Espindola245a1e22010-12-28 05:39:27 +00001054 break;
1055 case MCFragment::FT_LEB:
Eli Benderskyf43e3fd2012-12-10 20:13:43 +00001056 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
Rafael Espindola245a1e22010-12-28 05:39:27 +00001057 break;
Omer Paparo Bivas1be670d2017-10-24 06:16:03 +00001058 case MCFragment::FT_Padding:
1059 RelaxedFrag = relaxPaddingFragment(Layout, *cast<MCPaddingFragment>(I));
1060 break;
Reid Kleckner617bba82016-02-02 17:41:18 +00001061 case MCFragment::FT_CVInlineLines:
1062 RelaxedFrag =
1063 relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
1064 break;
David Majnemer7ddc5472016-02-05 01:55:49 +00001065 case MCFragment::FT_CVDefRange:
1066 RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
1067 break;
Rafael Espindola62b83b62010-12-21 04:22:09 +00001068 }
Eli Benderskyd52a2c02012-12-12 19:54:05 +00001069 if (RelaxedFrag && !FirstRelaxedFragment)
Duncan P. N. Exon Smith5d8fcb92015-10-10 00:13:11 +00001070 FirstRelaxedFragment = &*I;
Rafael Espindola62b83b62010-12-21 04:22:09 +00001071 }
Eli Benderskyd52a2c02012-12-12 19:54:05 +00001072 if (FirstRelaxedFragment) {
Derek Schufff918d7f2013-02-05 17:55:27 +00001073 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
Rafael Espindola62b83b62010-12-21 04:22:09 +00001074 return true;
1075 }
1076 return false;
1077}
1078
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001079bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
Daniel Dunbarff547842010-03-23 23:47:14 +00001080 ++stats::RelaxationSteps;
1081
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +00001082 bool WasRelaxed = false;
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001083 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Rafael Espindolae86bc462015-05-25 23:14:17 +00001084 MCSection &Sec = *it;
Rafael Espindola2224f642015-05-26 02:17:21 +00001085 while (layoutSectionOnce(Layout, Sec))
Rafael Espindola62b83b62010-12-21 04:22:09 +00001086 WasRelaxed = true;
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001087 }
1088
Daniel Dunbar0cc8bd42010-03-25 19:35:56 +00001089 return WasRelaxed;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001090}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001091
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001092void MCAssembler::finishLayout(MCAsmLayout &Layout) {
Nirav Dave92f209b2018-04-27 15:45:27 +00001093 assert(getBackendPtr() && "Expected assembler backend");
Rafael Espindolab4172fa2010-12-04 22:47:22 +00001094 // The layout is done. Mark every fragment as valid.
Rafael Espindola4f4363a2010-12-07 23:32:26 +00001095 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
Oliver Stannardf4f85602016-12-14 10:43:58 +00001096 MCSection &Section = *Layout.getSectionOrder()[i];
1097 Layout.getFragmentOffset(&*Section.rbegin());
1098 computeFragmentSize(Layout, *Section.rbegin());
Rafael Espindola4f4363a2010-12-07 23:32:26 +00001099 }
Colin LeMahieua6e18c12016-04-27 21:26:13 +00001100 getBackend().finishLayout(*this, Layout);
Daniel Dunbar3f4dcd92010-03-22 23:16:48 +00001101}
Sam Clegg28809c02018-06-14 14:04:23 +00001102
1103#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1104LLVM_DUMP_METHOD void MCAssembler::dump() const{
1105 raw_ostream &OS = errs();
1106
1107 OS << "<MCAssembler\n";
1108 OS << " Sections:[\n ";
1109 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1110 if (it != begin()) OS << ",\n ";
1111 it->dump();
1112 }
1113 OS << "],\n";
1114 OS << " Symbols:[";
1115
1116 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1117 if (it != symbol_begin()) OS << ",\n ";
1118 OS << "(";
1119 it->dump();
1120 OS << ", Index:" << it->getIndex() << ", ";
1121 OS << ")";
1122 }
1123 OS << "]>\n";
1124}
1125#endif