blob: cf42fe85b8e5df584d1c1952591f26630345e71b [file] [log] [blame]
Daniel Dunbar3016db32009-08-21 09:11:24 +00001//===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar3016db32009-08-21 09:11:24 +00006//
7//===----------------------------------------------------------------------===//
8
Chandler Carruth6bda14b2017-06-06 11:49:48 +00009#include "llvm/MC/MCAssembler.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000010#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/ADT/Statistic.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000014#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Twine.h"
16#include "llvm/MC/MCAsmBackend.h"
Lang Hames1e923ec2015-01-09 18:55:42 +000017#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarcf55f962010-03-11 05:53:33 +000018#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbareaa367f2010-03-19 10:43:23 +000019#include "llvm/MC/MCCodeEmitter.h"
Reid Kleckner1fcd6102016-02-02 17:41:18 +000020#include "llvm/MC/MCCodeView.h"
Rafael Espindola0f8abeb2010-12-24 21:22:02 +000021#include "llvm/MC/MCContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/MC/MCDwarf.h"
Daniel Dunbar8e6d8892009-10-16 01:58:03 +000023#include "llvm/MC/MCExpr.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000024#include "llvm/MC/MCFixup.h"
Craig Topper6e80c282012-03-26 06:58:25 +000025#include "llvm/MC/MCFixupKindInfo.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000026#include "llvm/MC/MCFragment.h"
27#include "llvm/MC/MCInst.h"
Daniel Dunbarf027abf2010-03-19 09:28:59 +000028#include "llvm/MC/MCObjectWriter.h"
Kevin Enderbye46564a2010-09-30 16:52:03 +000029#include "llvm/MC/MCSection.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000030#include "llvm/MC/MCSectionELF.h"
Daniel Dunbar8e6d8892009-10-16 01:58:03 +000031#include "llvm/MC/MCSymbol.h"
32#include "llvm/MC/MCValue.h"
Guillaume Chateletaf11cc72019-09-12 15:20:36 +000033#include "llvm/Support/Alignment.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000034#include "llvm/Support/Casting.h"
Daniel Dunbard821f4a2010-03-25 22:49:09 +000035#include "llvm/Support/Debug.h"
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +000036#include "llvm/Support/ErrorHandling.h"
Jim Grosbachbf387df2012-08-08 23:56:06 +000037#include "llvm/Support/LEB128.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000038#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000040#include <cassert>
41#include <cstdint>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include <cstring>
Benjamin Kramerb2459272014-04-29 23:46:48 +000043#include <tuple>
Eugene Zelenko1d435522017-02-07 23:02:00 +000044#include <utility>
45
Daniel Dunbar3016db32009-08-21 09:11:24 +000046using namespace llvm;
47
Chandler Carruthf58e3762014-04-22 03:04:17 +000048#define DEBUG_TYPE "assembler"
49
Daniel Dunbar5376c2a2010-03-23 23:47:14 +000050namespace {
51namespace stats {
Eugene Zelenko1d435522017-02-07 23:02:00 +000052
Eli Bendersky2ccd0442012-12-07 17:59:21 +000053STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
Eli Bendersky0652dfd2013-01-08 17:41:59 +000054STATISTIC(EmittedRelaxableFragments,
55 "Number of emitted assembler fragments - relaxable");
Eli Benderskyc01322e2012-12-10 18:59:39 +000056STATISTIC(EmittedDataFragments,
57 "Number of emitted assembler fragments - data");
Eli Benderskycf6009b2013-01-15 23:22:09 +000058STATISTIC(EmittedCompactEncodedInstFragments,
59 "Number of emitted assembler fragments - compact encoded inst");
Eli Benderskyc01322e2012-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 Grosbach18e2fe42011-12-06 00:03:48 +000066STATISTIC(evaluateFixup, "Number of evaluated fixups");
Daniel Dunbard821f4a2010-03-25 22:49:09 +000067STATISTIC(FragmentLayouts, "Number of fragment layouts");
Daniel Dunbar5376c2a2010-03-23 23:47:14 +000068STATISTIC(ObjectBytes, "Number of emitted object file bytes");
Daniel Dunbard821f4a2010-03-25 22:49:09 +000069STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
70STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
Omer Paparo Bivas2251c792017-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 Zelenko1d435522017-02-07 23:02:00 +000075
76} // end namespace stats
77} // end anonymous namespace
Daniel Dunbar5a07d6a2009-08-25 21:10:45 +000078
Daniel Dunbar2701eee2009-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 Dunbar3016db32009-08-21 09:11:24 +000084/* *** */
85
Nirav Dave8728e092018-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 Majnemer83c862a2015-09-01 23:19:38 +000092 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
David Majnemer03e2cc32015-12-21 22:09:27 +000093 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
Matthias Braun0148c882017-12-14 00:12:46 +000094 VersionInfo.Major = 0; // Major version == 0 for "none specified"
Daniel Dunbare2697732009-08-26 21:22:22 +000095}
Daniel Dunbar3016db32009-08-21 09:11:24 +000096
Eugene Zelenko1d435522017-02-07 23:02:00 +000097MCAssembler::~MCAssembler() = default;
Daniel Dunbar3016db32009-08-21 09:11:24 +000098
Pedro Artigas7212ee42012-12-12 22:59:46 +000099void MCAssembler::reset() {
100 Sections.clear();
101 Symbols.clear();
Pedro Artigas7212ee42012-12-12 22:59:46 +0000102 IndirectSymbols.clear();
103 DataRegions.clear();
Yaron Keren559b47d2014-09-17 09:25:36 +0000104 LinkerOptions.clear();
105 FileNames.clear();
Pedro Artigas7212ee42012-12-12 22:59:46 +0000106 ThumbFuncs.clear();
Yaron Keren559b47d2014-09-17 09:25:36 +0000107 BundleAlignSize = 0;
Pedro Artigas7212ee42012-12-12 22:59:46 +0000108 RelaxAll = false;
Pedro Artigas7212ee42012-12-12 22:59:46 +0000109 SubsectionsViaSymbols = false;
David Majnemer03e2cc32015-12-21 22:09:27 +0000110 IncrementalLinkerCompatible = false;
Jack Carter1bd90ff2013-01-30 02:09:52 +0000111 ELFHeaderEFlags = 0;
Yaron Keren559b47d2014-09-17 09:25:36 +0000112 LOHContainer.reset();
Matthias Braun0148c882017-12-14 00:12:46 +0000113 VersionInfo.Major = 0;
Alex Lorenzafa75d72018-12-14 01:14:10 +0000114 VersionInfo.SDKVersion = VersionTuple();
Pedro Artigasb95c53e2012-12-14 18:52:11 +0000115
116 // reset objects owned by us
Nirav Dave8728e092018-04-27 15:45:27 +0000117 if (getBackendPtr())
118 getBackendPtr()->reset();
119 if (getEmitterPtr())
120 getEmitterPtr()->reset();
121 if (getWriterPtr())
122 getWriterPtr()->reset();
Tim Northover53d32512014-03-29 07:34:53 +0000123 getLOHContainer().reset();
Pedro Artigas7212ee42012-12-12 22:59:46 +0000124}
125
Rafael Espindola28de2242015-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 Espindolab60c8292014-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 Espindolab60c8292014-04-29 12:46:50 +0000141 const MCExpr *Expr = Symbol->getVariableValue();
Evgeniy Stepanovf2d9a462017-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 Espindolab60c8292014-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 Dunbaraa627c32010-06-16 20:04:29 +0000165bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
Daniel Dunbarc558ec22010-03-19 03:18:09 +0000166 // Non-temporary labels should always be visible to the linker.
Daniel Dunbaraa627c32010-06-16 20:04:29 +0000167 if (!Symbol.isTemporary())
Daniel Dunbarc558ec22010-03-19 03:18:09 +0000168 return true;
169
170 // Absolute temporary labels are never visible.
Daniel Dunbaraa627c32010-06-16 20:04:29 +0000171 if (!Symbol.isInSection())
Daniel Dunbarc558ec22010-03-19 03:18:09 +0000172 return false;
173
Rafael Espindoladfe2d352015-06-17 20:08:20 +0000174 if (Symbol.isUsedInReloc())
Rafael Espindola26585542015-01-19 21:11:14 +0000175 return true;
176
177 return false;
Daniel Dunbarc558ec22010-03-19 03:18:09 +0000178}
179
Duncan P. N. Exon Smithfd27a1d2015-05-20 16:02:11 +0000180const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
Daniel Dunbar6e13bb02010-03-19 03:18:15 +0000181 // Linker visible symbols define atoms.
Duncan P. N. Exon Smithfd27a1d2015-05-20 16:02:11 +0000182 if (isSymbolLinkerVisible(S))
183 return &S;
Daniel Dunbar6e13bb02010-03-19 03:18:15 +0000184
185 // Absolute and undefined symbols have no defining atom.
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000186 if (!S.isInSection())
Craig Topperbb694de2014-04-13 04:57:38 +0000187 return nullptr;
Daniel Dunbar6e13bb02010-03-19 03:18:15 +0000188
Daniel Dunbarba2f4c32010-05-12 00:38:17 +0000189 // Non-linker visible symbols in sections which can't be atomized have no
190 // defining atom.
Lang Hames1e923ec2015-01-09 18:55:42 +0000191 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000192 *S.getFragment()->getParent()))
Craig Topperbb694de2014-04-13 04:57:38 +0000193 return nullptr;
Daniel Dunbarba2f4c32010-05-12 00:38:17 +0000194
Daniel Dunbar3937e282010-05-11 17:22:50 +0000195 // Otherwise, return the atom for the containing fragment.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000196 return S.getFragment()->getAtom();
Daniel Dunbar6e13bb02010-03-19 03:18:15 +0000197}
198
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000199bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
Daniel Dunbarb34440a2010-05-26 15:18:56 +0000200 const MCFixup &Fixup, const MCFragment *DF,
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000201 MCValue &Target, uint64_t &Value,
202 bool &WasForced) const {
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000203 ++stats::evaluateFixup;
Daniel Dunbar5376c2a2010-03-23 23:47:14 +0000204
Jim Grosbach36e60e92015-06-04 22:24:41 +0000205 // FIXME: This code has some duplication with recordRelocation. We should
Rafael Espindola83120cd2014-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 Espindola8a261c22017-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 Espindola83120cd2014-07-01 14:34:30 +0000211 const MCExpr *Expr = Fixup.getValue();
Rafael Espindola8a261c22017-06-22 17:25:35 +0000212 MCContext &Ctx = getContext();
213 Value = 0;
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000214 WasForced = false;
Oliver Stannard9be59af2015-11-17 10:00:43 +0000215 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
Rafael Espindola8a261c22017-06-22 17:25:35 +0000216 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
Oliver Stannard9be59af2015-11-17 10:00:43 +0000217 return true;
218 }
Rafael Espindola8a261c22017-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 Dunbarea9e2f82010-03-12 21:00:49 +0000226
Nirav Dave8728e092018-04-27 15:45:27 +0000227 assert(getBackendPtr() && "Expected assembler backend");
228 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
229 MCFixupKindInfo::FKF_IsPCRel;
Rafael Espindola0f8abeb2010-12-24 21:22:02 +0000230
Nirav Dave38b4b542018-04-27 16:11:24 +0000231 bool IsResolved = false;
Rafael Espindola0f8abeb2010-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 Espindola490d02a2011-02-16 03:25:55 +0000238 const MCSymbolRefExpr *A = Target.getSymA();
239 const MCSymbol &SA = A->getSymbol();
Rafael Espindola972756b2015-04-06 16:10:05 +0000240 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
Rafael Espindola0f8abeb2010-12-24 21:22:02 +0000241 IsResolved = false;
Nirav Dave1b5533c2018-04-27 15:45:54 +0000242 } else if (auto *Writer = getWriterPtr()) {
243 IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000244 *this, SA, *DF, false, true);
Rafael Espindola0f8abeb2010-12-24 21:22:02 +0000245 }
246 }
247 } else {
248 IsResolved = Target.isAbsolute();
249 }
Daniel Dunbarea9e2f82010-03-12 21:00:49 +0000250
251 Value = Target.getConstant();
252
Daniel Dunbar9c64ec02010-03-18 00:59:10 +0000253 if (const MCSymbolRefExpr *A = Target.getSymA()) {
Rafael Espindola972756b2015-04-06 16:10:05 +0000254 const MCSymbol &Sym = A->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000255 if (Sym.isDefined())
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000256 Value += Layout.getSymbolOffset(Sym);
Daniel Dunbarea9e2f82010-03-12 21:00:49 +0000257 }
Daniel Dunbar9c64ec02010-03-18 00:59:10 +0000258 if (const MCSymbolRefExpr *B = Target.getSymB()) {
Rafael Espindola972756b2015-04-06 16:10:05 +0000259 const MCSymbol &Sym = B->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000260 if (Sym.isDefined())
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000261 Value -= Layout.getSymbolOffset(Sym);
Daniel Dunbar5ec4bdd2010-03-19 03:18:12 +0000262 }
Daniel Dunbarea9e2f82010-03-12 21:00:49 +0000263
Nirav Dave8728e092018-04-27 15:45:27 +0000264 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
265 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
Owen Anderson622ad512010-12-15 18:48:27 +0000266 assert((ShouldAlignPC ? IsPCRel : true) &&
267 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
268
Owen Anderson3ef19d92010-12-09 20:27:52 +0000269 if (IsPCRel) {
Owen Anderson79855292010-12-17 21:49:48 +0000270 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
Jim Grosbach6485a792011-10-26 22:44:41 +0000271
Owen Anderson622ad512010-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 Andersonc8fa5fc2010-12-15 19:24:24 +0000274 if (ShouldAlignPC) Offset &= ~0x3;
Owen Anderson79855292010-12-17 21:49:48 +0000275 Value -= Offset;
Owen Anderson3ef19d92010-12-09 20:27:52 +0000276 }
Daniel Dunbarea9e2f82010-03-12 21:00:49 +0000277
Rafael Espindola76287ab2017-06-30 22:47:27 +0000278 // Let the backend force a relocation if needed.
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000279 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
Rafael Espindola76287ab2017-06-30 22:47:27 +0000280 IsResolved = false;
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000281 WasForced = true;
282 }
Jim Grosbach41955ff2010-12-14 18:46:57 +0000283
Daniel Dunbarea9e2f82010-03-12 21:00:49 +0000284 return IsResolved;
285}
286
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000287uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000288 const MCFragment &F) const {
Nirav Dave8728e092018-04-27 15:45:27 +0000289 assert(getBackendPtr() && "Requires assembler backend");
Daniel Dunbar454ea712010-05-13 18:35:06 +0000290 switch (F.getKind()) {
291 case MCFragment::FT_Data:
Pete Coopere0d40372015-06-17 22:01:28 +0000292 return cast<MCDataFragment>(F).getContents().size();
Eli Bendersky52771202013-01-08 22:05:10 +0000293 case MCFragment::FT_Relaxable:
Pete Coopere0d40372015-06-17 22:01:28 +0000294 return cast<MCRelaxableFragment>(F).getContents().size();
Eli Benderskycf6009b2013-01-15 23:22:09 +0000295 case MCFragment::FT_CompactEncodedInst:
Pete Coopere0d40372015-06-17 22:01:28 +0000296 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
Rafael Espindolad707c372018-01-09 22:48:37 +0000297 case MCFragment::FT_Fill: {
298 auto &FF = cast<MCFillFragment>(F);
Nirav Dave588fad42018-05-18 17:45:48 +0000299 int64_t NumValues = 0;
300 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000301 getContext().reportError(FF.getLoc(),
302 "expected assembly-time absolute expression");
Nirav Dave588fad42018-05-18 17:45:48 +0000303 return 0;
304 }
305 int64_t Size = NumValues * FF.getValueSize();
Rafael Espindolad707c372018-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 Dunbar454ea712010-05-13 18:35:06 +0000312
Rafael Espindola5e874982010-11-02 17:22:24 +0000313 case MCFragment::FT_LEB:
Rafael Espindola99e026d2010-12-04 21:58:52 +0000314 return cast<MCLEBFragment>(F).getContents().size();
Rafael Espindola5e874982010-11-02 17:22:24 +0000315
Omer Paparo Bivas2251c792017-10-24 06:16:03 +0000316 case MCFragment::FT_Padding:
317 return cast<MCPaddingFragment>(F).getSize();
318
Adrian McCarthy75248a72017-11-08 18:57:02 +0000319 case MCFragment::FT_SymbolId:
David Majnemer4eecd302015-05-30 04:56:02 +0000320 return 4;
321
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000322 case MCFragment::FT_Align: {
323 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
324 unsigned Offset = Layout.getFragmentOffset(&AF);
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000325 unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment()));
Shiva Chen5af037f2019-01-30 11:16:59 +0000326
327 // Insert extra Nops for code alignment if the target define
328 // shouldInsertExtraNopBytesForCodeAlign target hook.
329 if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() &&
330 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
331 return Size;
332
Owen Anderson9d0f9232012-08-29 22:18:56 +0000333 // If we are padding with nops, force the padding to be larger than the
334 // minimum nop size.
335 if (Size > 0 && AF.hasEmitNops()) {
336 while (Size % getBackend().getMinimumNopSize())
337 Size += AF.getAlignment();
338 }
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000339 if (Size > AF.getMaxBytesToEmit())
340 return 0;
341 return Size;
342 }
Daniel Dunbar454ea712010-05-13 18:35:06 +0000343
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000344 case MCFragment::FT_Org: {
David Blaikieb78e9e52013-02-11 01:16:51 +0000345 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
Rafael Espindola04d39262015-11-04 23:50:29 +0000346 MCValue Value;
Oliver Stannard268f42f2016-12-14 10:43:58 +0000347 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
348 getContext().reportError(OF.getLoc(),
349 "expected assembly-time absolute expression");
350 return 0;
351 }
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000352
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000353 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
Rafael Espindola04d39262015-11-04 23:50:29 +0000354 int64_t TargetLocation = Value.getConstant();
355 if (const MCSymbolRefExpr *A = Value.getSymA()) {
356 uint64_t Val;
Oliver Stannard268f42f2016-12-14 10:43:58 +0000357 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
358 getContext().reportError(OF.getLoc(), "expected absolute expression");
359 return 0;
360 }
Rafael Espindola04d39262015-11-04 23:50:29 +0000361 TargetLocation += Val;
362 }
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000363 int64_t Size = TargetLocation - FragmentOffset;
Oliver Stannard268f42f2016-12-14 10:43:58 +0000364 if (Size < 0 || Size >= 0x40000000) {
365 getContext().reportError(
366 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
367 "' (at offset '" + Twine(FragmentOffset) + "')");
368 return 0;
369 }
Rafael Espindola6bdb49d2010-12-21 20:35:18 +0000370 return Size;
371 }
Kevin Enderbye46564a2010-09-30 16:52:03 +0000372
Rafael Espindola5665a932010-11-07 02:07:12 +0000373 case MCFragment::FT_Dwarf:
Rafael Espindola99e026d2010-12-04 21:58:52 +0000374 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
Rafael Espindola736a35d2010-12-28 05:39:27 +0000375 case MCFragment::FT_DwarfFrame:
376 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000377 case MCFragment::FT_CVInlineLines:
378 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
David Majnemer408b5e62016-02-05 01:55:49 +0000379 case MCFragment::FT_CVDefRange:
380 return cast<MCCVDefRangeFragment>(F).getContents().size();
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000381 case MCFragment::FT_Dummy:
382 llvm_unreachable("Should not have been added");
Daniel Dunbar454ea712010-05-13 18:35:06 +0000383 }
384
Craig Toppera2886c22012-02-07 05:05:23 +0000385 llvm_unreachable("invalid fragment kind");
Daniel Dunbar454ea712010-05-13 18:35:06 +0000386}
387
Eli Benderskye11ab3a2012-12-12 19:54:05 +0000388void MCAsmLayout::layoutFragment(MCFragment *F) {
Daniel Dunbar9abade12010-05-14 00:37:21 +0000389 MCFragment *Prev = F->getPrevNode();
Daniel Dunbara7cc32a2010-05-12 21:35:25 +0000390
Eli Benderskye11ab3a2012-12-12 19:54:05 +0000391 // We should never try to recompute something which is valid.
392 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
393 // We should never try to compute the fragment layout if its predecessor
394 // isn't valid.
395 assert((!Prev || isFragmentValid(Prev)) &&
396 "Attempt to compute fragment before its predecessor!");
Daniel Dunbara7cc32a2010-05-12 21:35:25 +0000397
398 ++stats::FragmentLayouts;
399
Daniel Dunbarb9f6ac02010-05-13 20:40:12 +0000400 // Compute fragment offset and size.
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000401 if (Prev)
Eli Benderskyf483ff92012-12-20 19:05:53 +0000402 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
403 else
404 F->Offset = 0;
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000405 LastValidFragment[F->getParent()] = F;
Eli Benderskyf483ff92012-12-20 19:05:53 +0000406
407 // If bundling is enabled and this fragment has instructions in it, it has to
408 // obey the bundling restrictions. With padding, we'll have:
409 //
410 //
411 // BundlePadding
Derek Schuffb76ec3b2013-01-31 17:00:03 +0000412 // |||
Eli Benderskyf483ff92012-12-20 19:05:53 +0000413 // -------------------------------------
414 // Prev |##########| F |
415 // -------------------------------------
416 // ^
417 // |
418 // F->Offset
419 //
420 // The fragment's offset will point to after the padding, and its computed
421 // size won't include the padding.
422 //
Petr Hosek9e0c8902015-04-12 23:42:25 +0000423 // When the -mc-relax-all flag is used, we optimize bundling by writting the
Petr Hosek4bbf5632015-06-27 01:49:53 +0000424 // padding directly into fragments when the instructions are emitted inside
425 // the streamer. When the fragment is larger than the bundle size, we need to
426 // ensure that it's bundle aligned. This means that if we end up with
427 // multiple fragments, we must emit bundle padding between fragments.
Petr Hosek9e0c8902015-04-12 23:42:25 +0000428 //
Petr Hosek4bbf5632015-06-27 01:49:53 +0000429 // ".align N" is an example of a directive that introduces multiple
430 // fragments. We could add a special case to handle ".align N" by emitting
431 // within-fragment padding (which would produce less padding when N is less
432 // than the bundle size), but for now we don't.
433 //
434 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
Eli Benderskyf483ff92012-12-20 19:05:53 +0000435 assert(isa<MCEncodedFragment>(F) &&
436 "Only MCEncodedFragment implementations have instructions");
Peter Smith1503fc02018-06-15 09:48:18 +0000437 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
438 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000439
Petr Hosek4bbf5632015-06-27 01:49:53 +0000440 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
Eli Benderskyf483ff92012-12-20 19:05:53 +0000441 report_fatal_error("Fragment can't be larger than a bundle size");
442
Peter Smith1503fc02018-06-15 09:48:18 +0000443 uint64_t RequiredBundlePadding =
444 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000445 if (RequiredBundlePadding > UINT8_MAX)
446 report_fatal_error("Padding cannot exceed 255 bytes");
Peter Smith1503fc02018-06-15 09:48:18 +0000447 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
448 EF->Offset += RequiredBundlePadding;
Eli Benderskyf483ff92012-12-20 19:05:53 +0000449 }
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000450}
451
Rafael Espindola499c99c2015-06-01 14:34:40 +0000452void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
453 bool New = !Symbol.isRegistered();
454 if (Created)
455 *Created = New;
456 if (New) {
457 Symbol.setIsRegistered(true);
458 Symbols.push_back(&Symbol);
459 }
460}
461
Peter Smith1503fc02018-06-15 09:48:18 +0000462void MCAssembler::writeFragmentPadding(raw_ostream &OS,
463 const MCEncodedFragment &EF,
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000464 uint64_t FSize) const {
Nirav Dave8728e092018-04-27 15:45:27 +0000465 assert(getBackendPtr() && "Expected assembler backend");
Eli Benderskyf483ff92012-12-20 19:05:53 +0000466 // Should NOP padding be written out before this fragment?
Peter Smith1503fc02018-06-15 09:48:18 +0000467 unsigned BundlePadding = EF.getBundlePadding();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000468 if (BundlePadding > 0) {
Petr Hosek9e0c8902015-04-12 23:42:25 +0000469 assert(isBundlingEnabled() &&
Eli Benderskyf483ff92012-12-20 19:05:53 +0000470 "Writing bundle padding with disabled bundling");
Peter Smith1503fc02018-06-15 09:48:18 +0000471 assert(EF.hasInstructions() &&
Eli Benderskyf483ff92012-12-20 19:05:53 +0000472 "Writing bundle padding for a fragment without instructions");
473
Petr Hosek9e0c8902015-04-12 23:42:25 +0000474 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
Peter Smith1503fc02018-06-15 09:48:18 +0000475 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
Derek Schuffb76ec3b2013-01-31 17:00:03 +0000476 // If the padding itself crosses a bundle boundary, it must be emitted
477 // in 2 pieces, since even nop instructions must not cross boundaries.
478 // v--------------v <- BundleAlignSize
479 // v---------v <- BundlePadding
480 // ----------------------------
481 // | Prev |####|####| F |
482 // ----------------------------
483 // ^-------------------^ <- TotalLength
Petr Hosek9e0c8902015-04-12 23:42:25 +0000484 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000485 if (!getBackend().writeNopData(OS, DistanceToBoundary))
Peter Smith1503fc02018-06-15 09:48:18 +0000486 report_fatal_error("unable to write NOP sequence of " +
487 Twine(DistanceToBoundary) + " bytes");
Derek Schuffb76ec3b2013-01-31 17:00:03 +0000488 BundlePadding -= DistanceToBoundary;
489 }
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000490 if (!getBackend().writeNopData(OS, BundlePadding))
Eli Benderskyf483ff92012-12-20 19:05:53 +0000491 report_fatal_error("unable to write NOP sequence of " +
492 Twine(BundlePadding) + " bytes");
493 }
Petr Hosek9e0c8902015-04-12 23:42:25 +0000494}
495
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000496/// Write the fragment \p F to the output file.
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000497static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
498 const MCAsmLayout &Layout, const MCFragment &F) {
Petr Hosek9e0c8902015-04-12 23:42:25 +0000499 // FIXME: Embed in fragments instead?
500 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
501
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000502 support::endianness Endian = Asm.getBackend().Endian;
503
Peter Smith1503fc02018-06-15 09:48:18 +0000504 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
505 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000506
507 // This variable (and its dummy usage) is to participate in the assert at
508 // the end of the function.
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000509 uint64_t Start = OS.tell();
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000510 (void) Start;
Daniel Dunbare024def2009-10-16 01:58:15 +0000511
Daniel Dunbar5376c2a2010-03-23 23:47:14 +0000512 ++stats::EmittedFragments;
Daniel Dunbar5a07d6a2009-08-25 21:10:45 +0000513
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000514 switch (F.getKind()) {
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000515 case MCFragment::FT_Align: {
Eli Benderskyc01322e2012-12-10 18:59:39 +0000516 ++stats::EmittedAlignFragments;
David Blaikieb78e9e52013-02-11 01:16:51 +0000517 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar51402b72010-05-12 22:51:27 +0000518 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
519
Eric Christophered420bb2013-08-07 18:51:09 +0000520 uint64_t Count = FragmentSize / AF.getValueSize();
521
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000522 // FIXME: This error shouldn't actually occur (the front end should emit
523 // multiple .align directives to enforce the semantics it wants), but is
524 // severe enough that we want to report it. How to handle this?
Daniel Dunbar2522dd12010-03-25 02:00:02 +0000525 if (Count * AF.getValueSize() != FragmentSize)
Chris Lattner2104b8d2010-04-07 22:58:41 +0000526 report_fatal_error("undefined .align directive, value size '" +
Daniel Dunbare024def2009-10-16 01:58:15 +0000527 Twine(AF.getValueSize()) +
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000528 "' is not a divisor of padding size '" +
Daniel Dunbar2522dd12010-03-25 02:00:02 +0000529 Twine(FragmentSize) + "'");
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000530
Kevin Enderbye83d74f2010-02-23 18:26:34 +0000531 // See if we are aligning with nops, and if so do that first to try to fill
532 // the Count bytes. Then if that did not fill any bytes or there are any
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000533 // bytes left to fill use the Value and ValueSize to fill the rest.
Daniel Dunbara9ae3ae2010-03-23 02:36:58 +0000534 // If we are aligning with nops, ask that target to emit the right data.
Daniel Dunbarb76df222010-05-12 22:56:23 +0000535 if (AF.hasEmitNops()) {
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000536 if (!Asm.getBackend().writeNopData(OS, Count))
Chris Lattner2104b8d2010-04-07 22:58:41 +0000537 report_fatal_error("unable to write nop sequence of " +
Daniel Dunbara9ae3ae2010-03-23 02:36:58 +0000538 Twine(Count) + " bytes");
539 break;
Kevin Enderbye83d74f2010-02-23 18:26:34 +0000540 }
541
Daniel Dunbara9ae3ae2010-03-23 02:36:58 +0000542 // Otherwise, write out in multiples of the value size.
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000543 for (uint64_t i = 0; i != Count; ++i) {
544 switch (AF.getValueSize()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000545 default: llvm_unreachable("Invalid size!");
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000546 case 1: OS << char(AF.getValue()); break;
547 case 2:
548 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
549 break;
550 case 4:
551 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
552 break;
553 case 8:
554 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
555 break;
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000556 }
557 }
558 break;
559 }
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000560
Fangrui Songf78650a2018-07-30 19:41:25 +0000561 case MCFragment::FT_Data:
Eli Bendersky2ccd0442012-12-07 17:59:21 +0000562 ++stats::EmittedDataFragments;
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000563 OS << cast<MCDataFragment>(F).getContents();
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000564 break;
Eli Benderskya31a8942012-12-07 19:13:57 +0000565
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000566 case MCFragment::FT_Relaxable:
Eli Bendersky0652dfd2013-01-08 17:41:59 +0000567 ++stats::EmittedRelaxableFragments;
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000568 OS << cast<MCRelaxableFragment>(F).getContents();
Eli Benderskya31a8942012-12-07 19:13:57 +0000569 break;
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000570
Eli Benderskycf6009b2013-01-15 23:22:09 +0000571 case MCFragment::FT_CompactEncodedInst:
572 ++stats::EmittedCompactEncodedInstFragments;
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000573 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
Eli Benderskycf6009b2013-01-15 23:22:09 +0000574 break;
575
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000576 case MCFragment::FT_Fill: {
Eli Benderskyc01322e2012-12-10 18:59:39 +0000577 ++stats::EmittedFillFragments;
David Blaikieb78e9e52013-02-11 01:16:51 +0000578 const MCFillFragment &FF = cast<MCFillFragment>(F);
Nirav Dave588fad42018-05-18 17:45:48 +0000579 uint64_t V = FF.getValue();
580 unsigned VSize = FF.getValueSize();
Rafael Espindolaa39d3052016-01-19 17:47:48 +0000581 const unsigned MaxChunkSize = 16;
582 char Data[MaxChunkSize];
Nirav Dave588fad42018-05-18 17:45:48 +0000583 // Duplicate V into Data as byte vector to reduce number of
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000584 // writes done. As such, do endian conversion here.
Nirav Dave588fad42018-05-18 17:45:48 +0000585 for (unsigned I = 0; I != VSize; ++I) {
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000586 unsigned index = Endian == support::little ? I : (VSize - I - 1);
Nirav Dave588fad42018-05-18 17:45:48 +0000587 Data[I] = uint8_t(V >> (index * 8));
588 }
589 for (unsigned I = VSize; I < MaxChunkSize; ++I)
590 Data[I] = Data[I - VSize];
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000591
Nirav Dave588fad42018-05-18 17:45:48 +0000592 // Set to largest multiple of VSize in Data.
593 const unsigned NumPerChunk = MaxChunkSize / VSize;
594 // Set ChunkSize to largest multiple of VSize in Data
595 const unsigned ChunkSize = VSize * NumPerChunk;
596
597 // Do copies by chunk.
598 StringRef Ref(Data, ChunkSize);
599 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000600 OS << Ref;
Nirav Dave588fad42018-05-18 17:45:48 +0000601
602 // do remainder if needed.
603 unsigned TrailingCount = FragmentSize % ChunkSize;
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000604 if (TrailingCount)
605 OS.write(Data, TrailingCount);
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000606 break;
607 }
Daniel Dunbare024def2009-10-16 01:58:15 +0000608
Rafael Espindola5e874982010-11-02 17:22:24 +0000609 case MCFragment::FT_LEB: {
David Blaikieb78e9e52013-02-11 01:16:51 +0000610 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000611 OS << LF.getContents();
Rafael Espindola5e874982010-11-02 17:22:24 +0000612 break;
613 }
614
Omer Paparo Bivas2251c792017-10-24 06:16:03 +0000615 case MCFragment::FT_Padding: {
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000616 if (!Asm.getBackend().writeNopData(OS, FragmentSize))
Omer Paparo Bivas2251c792017-10-24 06:16:03 +0000617 report_fatal_error("unable to write nop sequence of " +
618 Twine(FragmentSize) + " bytes");
619 break;
620 }
621
Adrian McCarthy75248a72017-11-08 18:57:02 +0000622 case MCFragment::FT_SymbolId: {
623 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000624 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
David Majnemer4eecd302015-05-30 04:56:02 +0000625 break;
626 }
627
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000628 case MCFragment::FT_Org: {
Eli Benderskyc01322e2012-12-10 18:59:39 +0000629 ++stats::EmittedOrgFragments;
David Blaikieb78e9e52013-02-11 01:16:51 +0000630 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000631
Daniel Dunbar2522dd12010-03-25 02:00:02 +0000632 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000633 OS << char(OF.getValue());
Daniel Dunbarb1068e42009-08-21 23:07:38 +0000634
635 break;
636 }
Kevin Enderbye46564a2010-09-30 16:52:03 +0000637
638 case MCFragment::FT_Dwarf: {
639 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000640 OS << OF.getContents();
Kevin Enderbye46564a2010-09-30 16:52:03 +0000641 break;
642 }
Rafael Espindola736a35d2010-12-28 05:39:27 +0000643 case MCFragment::FT_DwarfFrame: {
644 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000645 OS << CF.getContents();
Rafael Espindola736a35d2010-12-28 05:39:27 +0000646 break;
647 }
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000648 case MCFragment::FT_CVInlineLines: {
649 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000650 OS << OF.getContents();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000651 break;
652 }
David Majnemer408b5e62016-02-05 01:55:49 +0000653 case MCFragment::FT_CVDefRange: {
654 const auto &DRF = cast<MCCVDefRangeFragment>(F);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000655 OS << DRF.getContents();
David Majnemer408b5e62016-02-05 01:55:49 +0000656 break;
657 }
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000658 case MCFragment::FT_Dummy:
659 llvm_unreachable("Should not have been added");
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000660 }
661
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000662 assert(OS.tell() - Start == FragmentSize &&
Eli Benderskyf483ff92012-12-20 19:05:53 +0000663 "The stream should advance by fragment size");
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000664}
665
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000666void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
Daniel Dunbar50269282010-12-17 02:45:59 +0000667 const MCAsmLayout &Layout) const {
Nirav Dave8728e092018-04-27 15:45:27 +0000668 assert(getBackendPtr() && "Expected assembler backend");
669
Daniel Dunbar42a39d02009-08-28 05:49:21 +0000670 // Ignore virtual sections.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000671 if (Sec->isVirtualSection()) {
672 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000673
674 // Check that contents are only things legal inside a virtual section.
Craig Topper1cd693c2015-08-02 22:34:02 +0000675 for (const MCFragment &F : *Sec) {
676 switch (F.getKind()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000677 default: llvm_unreachable("Invalid fragment in virtual section!");
Daniel Dunbar8e92d9b2010-08-18 18:22:37 +0000678 case MCFragment::FT_Data: {
679 // Check that we aren't trying to write a non-zero contents (or fixups)
680 // into a virtual section. This is to support clients which use standard
681 // directives to fill the contents of virtual sections.
Craig Topper1cd693c2015-08-02 22:34:02 +0000682 const MCDataFragment &DF = cast<MCDataFragment>(F);
Davide Italianof17d48e2016-07-26 18:16:33 +0000683 if (DF.fixup_begin() != DF.fixup_end())
684 report_fatal_error("cannot have fixups in virtual section!");
Daniel Dunbar8e92d9b2010-08-18 18:22:37 +0000685 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
Weiming Zhao58eb5ab2014-06-22 00:33:44 +0000686 if (DF.getContents()[i]) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000687 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
Weiming Zhao58eb5ab2014-06-22 00:33:44 +0000688 report_fatal_error("non-zero initializer found in section '" +
689 ELFSec->getSectionName() + "'");
690 else
691 report_fatal_error("non-zero initializer found in virtual section");
692 }
Daniel Dunbar8e92d9b2010-08-18 18:22:37 +0000693 break;
694 }
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000695 case MCFragment::FT_Align:
Daniel Dunbar8e92d9b2010-08-18 18:22:37 +0000696 // Check that we aren't trying to write a non-zero value into a virtual
697 // section.
Craig Topper1cd693c2015-08-02 22:34:02 +0000698 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
699 cast<MCAlignFragment>(F).getValue() == 0) &&
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000700 "Invalid align in virtual section!");
701 break;
702 case MCFragment::FT_Fill:
Rafael Espindola1a7e8b42016-01-19 16:57:08 +0000703 assert((cast<MCFillFragment>(F).getValue() == 0) &&
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000704 "Invalid fill in virtual section!");
705 break;
Daniel Dunbar7cd309f2010-05-12 22:51:35 +0000706 }
707 }
708
Daniel Dunbar42a39d02009-08-28 05:49:21 +0000709 return;
710 }
711
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000712 uint64_t Start = OS.tell();
Jim Grosbach0aac6ce2012-09-18 23:05:18 +0000713 (void)Start;
Daniel Dunbare024def2009-10-16 01:58:15 +0000714
Craig Topper1cd693c2015-08-02 22:34:02 +0000715 for (const MCFragment &F : *Sec)
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000716 writeFragment(OS, *this, Layout, F);
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000717
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000718 assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec));
Daniel Dunbar4ef7fb92009-08-21 18:29:01 +0000719}
720
Rafael Espindola801b42d2017-06-23 22:52:36 +0000721std::tuple<MCValue, uint64_t, bool>
722MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
723 const MCFixup &Fixup) {
Joerg Sonnenberger808df672014-01-13 15:50:36 +0000724 // Evaluate the fixup.
725 MCValue Target;
726 uint64_t FixedValue;
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000727 bool WasForced;
728 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
729 WasForced);
Rafael Espindola1beb7022017-07-11 23:18:25 +0000730 if (!IsResolved) {
Joerg Sonnenberger808df672014-01-13 15:50:36 +0000731 // The fixup was unresolved, we need a relocation. Inform the object
732 // writer of the relocation, and give it an opportunity to adjust the
733 // fixup value if need be.
Alex Bradbury257d5b52018-05-23 12:36:18 +0000734 if (Target.getSymA() && Target.getSymB() &&
735 getBackend().requiresDiffExpressionRelocations()) {
736 // The fixup represents the difference between two symbols, which the
737 // backend has indicated must be resolved at link time. Split up the fixup
738 // into two relocations, one for the add, and one for the sub, and emit
739 // both of these. The constant will be associated with the add half of the
740 // expression.
741 MCFixup FixupAdd = MCFixup::createAddFor(Fixup);
742 MCValue TargetAdd =
743 MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
744 getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd,
745 FixedValue);
746 MCFixup FixupSub = MCFixup::createSubFor(Fixup);
747 MCValue TargetSub = MCValue::get(Target.getSymB());
748 getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub,
749 FixedValue);
750 } else {
751 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target,
752 FixedValue);
753 }
Joerg Sonnenberger808df672014-01-13 15:50:36 +0000754 }
Rafael Espindola1beb7022017-07-11 23:18:25 +0000755 return std::make_tuple(Target, FixedValue, IsResolved);
Joerg Sonnenberger808df672014-01-13 15:50:36 +0000756}
Rafael Espindola0f30fec2010-12-06 19:08:48 +0000757
Frederic Riss74b98822015-08-26 05:09:49 +0000758void MCAssembler::layout(MCAsmLayout &Layout) {
Nirav Dave8728e092018-04-27 15:45:27 +0000759 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbarbedf1d42010-02-13 09:28:03 +0000760 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenko1d435522017-02-07 23:02:00 +0000761 errs() << "assembler backend - pre-layout\n--\n";
Daniel Dunbarbedf1d42010-02-13 09:28:03 +0000762 dump(); });
763
Daniel Dunbar8f9d2262010-05-14 00:37:14 +0000764 // Create dummy fragments and assign section ordinals.
Daniel Dunbaraa8bd692010-05-13 08:43:37 +0000765 unsigned SectionIndex = 0;
Craig Topper1cd693c2015-08-02 22:34:02 +0000766 for (MCSection &Sec : *this) {
Daniel Dunbaraa8bd692010-05-13 08:43:37 +0000767 // Create dummy fragments to eliminate any empty sections, this simplifies
768 // layout.
Craig Topper1cd693c2015-08-02 22:34:02 +0000769 if (Sec.getFragmentList().empty())
770 new MCDataFragment(&Sec);
Daniel Dunbaraa8bd692010-05-13 08:43:37 +0000771
Craig Topper1cd693c2015-08-02 22:34:02 +0000772 Sec.setOrdinal(SectionIndex++);
Daniel Dunbar8f9d2262010-05-14 00:37:14 +0000773 }
Daniel Dunbaraa8bd692010-05-13 08:43:37 +0000774
Daniel Dunbar8f9d2262010-05-14 00:37:14 +0000775 // Assign layout order indices to sections and fragments.
Daniel Dunbar8f9d2262010-05-14 00:37:14 +0000776 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000777 MCSection *Sec = Layout.getSectionOrder()[i];
778 Sec->setLayoutOrder(i);
Daniel Dunbar8f9d2262010-05-14 00:37:14 +0000779
Rafael Espindola6624f472010-12-07 23:32:26 +0000780 unsigned FragmentIndex = 0;
Craig Topper1cd693c2015-08-02 22:34:02 +0000781 for (MCFragment &Frag : *Sec)
782 Frag.setLayoutOrder(FragmentIndex++);
Daniel Dunbaraa8bd692010-05-13 08:43:37 +0000783 }
784
Daniel Dunbarc7c53ea2010-05-13 02:34:14 +0000785 // Layout until everything fits.
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000786 while (layoutOnce(Layout))
Oliver Stannard268f42f2016-12-14 10:43:58 +0000787 if (getContext().hadError())
788 return;
Daniel Dunbar12f1e322010-03-12 22:07:14 +0000789
790 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenko1d435522017-02-07 23:02:00 +0000791 errs() << "assembler backend - post-relaxation\n--\n";
Daniel Dunbarb31c49a2010-03-22 23:16:48 +0000792 dump(); });
793
794 // Finalize the layout, including fragment lowering.
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000795 finishLayout(Layout);
Daniel Dunbarb31c49a2010-03-22 23:16:48 +0000796
797 DEBUG_WITH_TYPE("mc-dump", {
Eugene Zelenko1d435522017-02-07 23:02:00 +0000798 errs() << "assembler backend - final-layout\n--\n";
Daniel Dunbar12f1e322010-03-12 22:07:14 +0000799 dump(); });
800
Daniel Dunbard84d1962010-03-19 07:09:33 +0000801 // Allow the object writer a chance to perform post-layout binding (for
802 // example, to set the index fields in the symbol data).
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000803 getWriter().executePostLayoutBinding(*this, Layout);
Daniel Dunbard84d1962010-03-19 07:09:33 +0000804
Daniel Dunbar3cab2752010-03-19 07:09:47 +0000805 // Evaluate and apply the fixups, generating relocation entries as necessary.
Craig Topper1cd693c2015-08-02 22:34:02 +0000806 for (MCSection &Sec : *this) {
807 for (MCFragment &Frag : Sec) {
Pete Coopere0d40372015-06-17 22:01:28 +0000808 // Data and relaxable fragments both have fixups. So only process
809 // those here.
810 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
811 // being templated makes this tricky.
David Majnemer408b5e62016-02-05 01:55:49 +0000812 if (isa<MCEncodedFragment>(&Frag) &&
813 isa<MCCompactEncodedInstFragment>(&Frag))
814 continue;
Shiva Chen5af037f2019-01-30 11:16:59 +0000815 if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag) &&
816 !isa<MCAlignFragment>(&Frag))
Pete Coopere0d40372015-06-17 22:01:28 +0000817 continue;
818 ArrayRef<MCFixup> Fixups;
819 MutableArrayRef<char> Contents;
Peter Smith57f661b2018-06-06 09:40:06 +0000820 const MCSubtargetInfo *STI = nullptr;
David Majnemer408b5e62016-02-05 01:55:49 +0000821 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
Pete Coopere0d40372015-06-17 22:01:28 +0000822 Fixups = FragWithFixups->getFixups();
823 Contents = FragWithFixups->getContents();
Peter Smith57f661b2018-06-06 09:40:06 +0000824 STI = FragWithFixups->getSubtargetInfo();
825 assert(!FragWithFixups->hasInstructions() || STI != nullptr);
David Majnemer408b5e62016-02-05 01:55:49 +0000826 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) {
827 Fixups = FragWithFixups->getFixups();
828 Contents = FragWithFixups->getContents();
Peter Smith57f661b2018-06-06 09:40:06 +0000829 STI = FragWithFixups->getSubtargetInfo();
830 assert(!FragWithFixups->hasInstructions() || STI != nullptr);
David Majnemer408b5e62016-02-05 01:55:49 +0000831 } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
Pete Coopere0d40372015-06-17 22:01:28 +0000832 Fixups = FragWithFixups->getFixups();
833 Contents = FragWithFixups->getContents();
Hsiangkai Wang5c63af02018-08-01 02:18:06 +0000834 } else if (auto *FragWithFixups = dyn_cast<MCDwarfLineAddrFragment>(&Frag)) {
835 Fixups = FragWithFixups->getFixups();
836 Contents = FragWithFixups->getContents();
Shiva Chen5af037f2019-01-30 11:16:59 +0000837 } else if (auto *AF = dyn_cast<MCAlignFragment>(&Frag)) {
838 // Insert fixup type for code alignment if the target define
839 // shouldInsertFixupForCodeAlign target hook.
840 if (Sec.UseCodeAlign() && AF->hasEmitNops()) {
841 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, *AF);
842 }
843 continue;
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000844 } else if (auto *FragWithFixups =
845 dyn_cast<MCDwarfCallFrameFragment>(&Frag)) {
846 Fixups = FragWithFixups->getFixups();
847 Contents = FragWithFixups->getContents();
Pete Coopere0d40372015-06-17 22:01:28 +0000848 } else
Yaron Kerenfffc0682015-07-04 05:48:52 +0000849 llvm_unreachable("Unknown fragment with fixups!");
Pete Coopere0d40372015-06-17 22:01:28 +0000850 for (const MCFixup &Fixup : Fixups) {
851 uint64_t FixedValue;
Rafael Espindola1beb7022017-07-11 23:18:25 +0000852 bool IsResolved;
Rafael Espindola801b42d2017-06-23 22:52:36 +0000853 MCValue Target;
Rafael Espindola1beb7022017-07-11 23:18:25 +0000854 std::tie(Target, FixedValue, IsResolved) =
Rafael Espindola801b42d2017-06-23 22:52:36 +0000855 handleFixup(Layout, Frag, Fixup);
856 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
Peter Smith57f661b2018-06-06 09:40:06 +0000857 IsResolved, STI);
Daniel Dunbar3cab2752010-03-19 07:09:47 +0000858 }
859 }
860 }
Frederic Riss74b98822015-08-26 05:09:49 +0000861}
862
863void MCAssembler::Finish() {
864 // Create the layout object.
865 MCAsmLayout Layout(*this);
866 layout(Layout);
867
Daniel Dunbard84d1962010-03-19 07:09:33 +0000868 // Write the object file.
Peter Collingbourne438390f2018-05-21 18:23:50 +0000869 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
Daniel Dunbar12f1e322010-03-12 22:07:14 +0000870}
871
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000872bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000873 const MCRelaxableFragment *DF,
Daniel Dunbar32ffc582010-03-22 20:35:35 +0000874 const MCAsmLayout &Layout) const {
Nirav Dave8728e092018-04-27 15:45:27 +0000875 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbar12f1e322010-03-12 22:07:14 +0000876 MCValue Target;
877 uint64_t Value;
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000878 bool WasForced;
879 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
Peter Collingbourned763c4c2017-01-31 18:28:44 +0000880 if (Target.getSymA() &&
881 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
882 Fixup.getKind() == FK_Data_1)
883 return false;
Colin LeMahieua01780f2015-05-30 18:42:22 +0000884 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
Shiva Chen6e07dfb2018-05-18 06:42:21 +0000885 Layout, WasForced);
Daniel Dunbar12f1e322010-03-12 22:07:14 +0000886}
887
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000888bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
Daniel Dunbarde04b3f2010-03-23 05:09:03 +0000889 const MCAsmLayout &Layout) const {
Nirav Dave8728e092018-04-27 15:45:27 +0000890 assert(getBackendPtr() && "Expected assembler backend");
Daniel Dunbarde04b3f2010-03-23 05:09:03 +0000891 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
892 // are intentionally pushing out inst fragments, or because we relaxed a
893 // previous instruction to one that doesn't need relaxation.
Peter Smith57f661b2018-06-06 09:40:06 +0000894 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
Daniel Dunbarde04b3f2010-03-23 05:09:03 +0000895 return false;
896
Craig Topper1cd693c2015-08-02 22:34:02 +0000897 for (const MCFixup &Fixup : F->getFixups())
898 if (fixupNeedsRelaxation(Fixup, F, Layout))
Daniel Dunbarde04b3f2010-03-23 05:09:03 +0000899 return true;
900
901 return false;
902}
903
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000904bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000905 MCRelaxableFragment &F) {
Nirav Dave8728e092018-04-27 15:45:27 +0000906 assert(getEmitterPtr() &&
907 "Expected CodeEmitter defined for relaxInstruction");
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000908 if (!fragmentNeedsRelaxation(&F, Layout))
Rafael Espindola5e874982010-11-02 17:22:24 +0000909 return false;
910
911 ++stats::RelaxedInstructions;
912
913 // FIXME-PERF: We could immediately lower out instructions if we can tell
914 // they are fully resolved, to avoid retesting on later passes.
915
916 // Relax the fragment.
917
918 MCInst Relaxed;
Peter Smith57f661b2018-06-06 09:40:06 +0000919 getBackend().relaxInstruction(F.getInst(), *F.getSubtargetInfo(), Relaxed);
Rafael Espindola5e874982010-11-02 17:22:24 +0000920
921 // Encode the new instruction.
922 //
923 // FIXME-PERF: If it matters, we could let the target do this. It can
924 // probably do so more efficiently in many cases.
925 SmallVector<MCFixup, 4> Fixups;
926 SmallString<256> Code;
927 raw_svector_ostream VecOS(Code);
Peter Smith57f661b2018-06-06 09:40:06 +0000928 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
Rafael Espindola5e874982010-11-02 17:22:24 +0000929
Eli Bendersky4d9ada02013-01-08 00:22:56 +0000930 // Update the fragment.
931 F.setInst(Relaxed);
932 F.getContents() = Code;
933 F.getFixups() = Fixups;
Rafael Espindola5e874982010-11-02 17:22:24 +0000934
Rafael Espindola5e874982010-11-02 17:22:24 +0000935 return true;
936}
937
Omer Paparo Bivas2251c792017-10-24 06:16:03 +0000938bool MCAssembler::relaxPaddingFragment(MCAsmLayout &Layout,
939 MCPaddingFragment &PF) {
Nirav Dave8728e092018-04-27 15:45:27 +0000940 assert(getBackendPtr() && "Expected assembler backend");
Omer Paparo Bivas2251c792017-10-24 06:16:03 +0000941 uint64_t OldSize = PF.getSize();
942 if (!getBackend().relaxFragment(&PF, Layout))
943 return false;
944 uint64_t NewSize = PF.getSize();
945
946 ++stats::PaddingFragmentsRelaxations;
947 stats::PaddingFragmentsBytes += NewSize;
948 stats::PaddingFragmentsBytes -= OldSize;
949 return true;
950}
951
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000952bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
Rafael Espindola99e026d2010-12-04 21:58:52 +0000953 uint64_t OldSize = LF.getContents().size();
Rafael Espindoladbb40212015-03-25 00:25:37 +0000954 int64_t Value;
955 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
956 if (!Abs)
957 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
Rafael Espindola99e026d2010-12-04 21:58:52 +0000958 SmallString<8> &Data = LF.getContents();
959 Data.clear();
960 raw_svector_ostream OSE(Data);
Rafael Espindola45b12f12018-02-01 00:25:19 +0000961 // The compiler can generate EH table assembly that is impossible to assemble
962 // without either adding padding to an LEB fragment or adding extra padding
963 // to a later alignment fragment. To accommodate such tables, relaxation can
964 // only increase an LEB fragment size here, not decrease it. See PR35809.
Rafael Espindola5e874982010-11-02 17:22:24 +0000965 if (LF.isSigned())
Rafael Espindola45b12f12018-02-01 00:25:19 +0000966 encodeSLEB128(Value, OSE, OldSize);
Rafael Espindola5e874982010-11-02 17:22:24 +0000967 else
Rafael Espindola45b12f12018-02-01 00:25:19 +0000968 encodeULEB128(Value, OSE, OldSize);
Rafael Espindola99e026d2010-12-04 21:58:52 +0000969 return OldSize != LF.getContents().size();
Rafael Espindola5e874982010-11-02 17:22:24 +0000970}
971
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000972bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
Jim Grosbach46be3012011-12-06 00:13:09 +0000973 MCDwarfLineAddrFragment &DF) {
Ulrich Weigand32d725b2013-06-12 14:46:54 +0000974 MCContext &Context = Layout.getAssembler().getContext();
Rafael Espindola99e026d2010-12-04 21:58:52 +0000975 uint64_t OldSize = DF.getContents().size();
Rafael Espindoladbb40212015-03-25 00:25:37 +0000976 int64_t AddrDelta;
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000977 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
978 assert(Abs && "We created a line delta with an invalid expression");
979 (void)Abs;
Rafael Espindola5665a932010-11-07 02:07:12 +0000980 int64_t LineDelta;
981 LineDelta = DF.getLineDelta();
Hsiangkai Wang5c63af02018-08-01 02:18:06 +0000982 SmallVectorImpl<char> &Data = DF.getContents();
Rafael Espindola99e026d2010-12-04 21:58:52 +0000983 Data.clear();
984 raw_svector_ostream OSE(Data);
Hsiangkai Wang5c63af02018-08-01 02:18:06 +0000985 DF.getFixups().clear();
986
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000987 if (!getBackend().requiresDiffExpressionRelocations()) {
Hsiangkai Wang5c63af02018-08-01 02:18:06 +0000988 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
989 AddrDelta, OSE);
990 } else {
991 uint32_t Offset;
992 uint32_t Size;
993 bool SetDelta = MCDwarfLineAddr::FixedEncode(Context,
994 getDWARFLinetableParams(),
995 LineDelta, AddrDelta,
996 OSE, &Offset, &Size);
997 // Add Fixups for address delta or new address.
998 const MCExpr *FixupExpr;
999 if (SetDelta) {
1000 FixupExpr = &DF.getAddrDelta();
1001 } else {
1002 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta());
1003 FixupExpr = ABE->getLHS();
1004 }
1005 DF.getFixups().push_back(
1006 MCFixup::create(Offset, FixupExpr,
1007 MCFixup::getKindForSize(Size, false /*isPCRel*/)));
1008 }
1009
Rafael Espindola99e026d2010-12-04 21:58:52 +00001010 return OldSize != Data.size();
Rafael Espindola5665a932010-11-07 02:07:12 +00001011}
1012
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001013bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
Rafael Espindola736a35d2010-12-28 05:39:27 +00001014 MCDwarfCallFrameFragment &DF) {
Ulrich Weigand32d725b2013-06-12 14:46:54 +00001015 MCContext &Context = Layout.getAssembler().getContext();
Rafael Espindola736a35d2010-12-28 05:39:27 +00001016 uint64_t OldSize = DF.getContents().size();
Rafael Espindoladbb40212015-03-25 00:25:37 +00001017 int64_t AddrDelta;
1018 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1019 assert(Abs && "We created call frame with an invalid expression");
Rafael Espindola44cc6542015-03-25 00:45:41 +00001020 (void) Abs;
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +00001021 SmallVectorImpl<char> &Data = DF.getContents();
Rafael Espindola736a35d2010-12-28 05:39:27 +00001022 Data.clear();
1023 raw_svector_ostream OSE(Data);
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +00001024 DF.getFixups().clear();
1025
1026 if (getBackend().requiresDiffExpressionRelocations()) {
1027 uint32_t Offset;
1028 uint32_t Size;
1029 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE, &Offset,
1030 &Size);
1031 if (Size) {
1032 DF.getFixups().push_back(MCFixup::create(
1033 Offset, &DF.getAddrDelta(),
1034 MCFixup::getKindForSizeInBits(Size /*In bits.*/, false /*isPCRel*/)));
1035 }
1036 } else {
1037 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1038 }
1039
Rafael Espindola736a35d2010-12-28 05:39:27 +00001040 return OldSize != Data.size();
1041}
1042
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001043bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1044 MCCVInlineLineTableFragment &F) {
1045 unsigned OldSize = F.getContents().size();
1046 getContext().getCVContext().encodeInlineLineTable(Layout, F);
1047 return OldSize != F.getContents().size();
1048}
1049
David Majnemer408b5e62016-02-05 01:55:49 +00001050bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1051 MCCVDefRangeFragment &F) {
1052 unsigned OldSize = F.getContents().size();
1053 getContext().getCVContext().encodeDefRange(Layout, F);
1054 return OldSize != F.getContents().size();
1055}
1056
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001057bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001058 // Holds the first fragment which needed relaxing during this layout. It will
1059 // remain NULL if none were relaxed.
Eli Benderskye11ab3a2012-12-12 19:54:05 +00001060 // When a fragment is relaxed, all the fragments following it should get
1061 // invalidated because their offset is going to change.
Craig Topperbb694de2014-04-13 04:57:38 +00001062 MCFragment *FirstRelaxedFragment = nullptr;
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001063
Eli Benderskye11ab3a2012-12-12 19:54:05 +00001064 // Attempt to relax all the fragments in the section.
Rafael Espindolaa32d0e92015-05-27 15:14:11 +00001065 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001066 // Check if this is a fragment that needs relaxation.
1067 bool RelaxedFrag = false;
1068 switch(I->getKind()) {
Rafael Espindola98d93c52010-12-21 04:22:09 +00001069 default:
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001070 break;
Eli Bendersky4d9ada02013-01-08 00:22:56 +00001071 case MCFragment::FT_Relaxable:
Eli Bendersky0f74f172012-12-11 17:16:00 +00001072 assert(!getRelaxAll() &&
Eli Bendersky4d9ada02013-01-08 00:22:56 +00001073 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1074 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
Rafael Espindola98d93c52010-12-21 04:22:09 +00001075 break;
Rafael Espindola98d93c52010-12-21 04:22:09 +00001076 case MCFragment::FT_Dwarf:
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001077 RelaxedFrag = relaxDwarfLineAddr(Layout,
1078 *cast<MCDwarfLineAddrFragment>(I));
Rafael Espindola98d93c52010-12-21 04:22:09 +00001079 break;
Rafael Espindola736a35d2010-12-28 05:39:27 +00001080 case MCFragment::FT_DwarfFrame:
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001081 RelaxedFrag =
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001082 relaxDwarfCallFrameFragment(Layout,
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001083 *cast<MCDwarfCallFrameFragment>(I));
Rafael Espindola736a35d2010-12-28 05:39:27 +00001084 break;
1085 case MCFragment::FT_LEB:
Eli Bendersky4c7296f2012-12-10 20:13:43 +00001086 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
Rafael Espindola736a35d2010-12-28 05:39:27 +00001087 break;
Omer Paparo Bivas2251c792017-10-24 06:16:03 +00001088 case MCFragment::FT_Padding:
1089 RelaxedFrag = relaxPaddingFragment(Layout, *cast<MCPaddingFragment>(I));
1090 break;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001091 case MCFragment::FT_CVInlineLines:
1092 RelaxedFrag =
1093 relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
1094 break;
David Majnemer408b5e62016-02-05 01:55:49 +00001095 case MCFragment::FT_CVDefRange:
1096 RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
1097 break;
Rafael Espindola98d93c52010-12-21 04:22:09 +00001098 }
Eli Benderskye11ab3a2012-12-12 19:54:05 +00001099 if (RelaxedFrag && !FirstRelaxedFragment)
Duncan P. N. Exon Smitha5f45da2015-10-10 00:13:11 +00001100 FirstRelaxedFragment = &*I;
Rafael Espindola98d93c52010-12-21 04:22:09 +00001101 }
Eli Benderskye11ab3a2012-12-12 19:54:05 +00001102 if (FirstRelaxedFragment) {
Derek Schuff90aa1d82013-02-05 17:55:27 +00001103 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
Rafael Espindola98d93c52010-12-21 04:22:09 +00001104 return true;
1105 }
1106 return false;
1107}
1108
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001109bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
Daniel Dunbar5376c2a2010-03-23 23:47:14 +00001110 ++stats::RelaxationSteps;
1111
Daniel Dunbar6432bd72010-03-25 19:35:56 +00001112 bool WasRelaxed = false;
Daniel Dunbar12f1e322010-03-12 22:07:14 +00001113 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Rafael Espindolaa554c052015-05-25 23:14:17 +00001114 MCSection &Sec = *it;
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001115 while (layoutSectionOnce(Layout, Sec))
Rafael Espindola98d93c52010-12-21 04:22:09 +00001116 WasRelaxed = true;
Daniel Dunbar12f1e322010-03-12 22:07:14 +00001117 }
1118
Daniel Dunbar6432bd72010-03-25 19:35:56 +00001119 return WasRelaxed;
Daniel Dunbar3016db32009-08-21 09:11:24 +00001120}
Daniel Dunbarbedf1d42010-02-13 09:28:03 +00001121
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001122void MCAssembler::finishLayout(MCAsmLayout &Layout) {
Nirav Dave8728e092018-04-27 15:45:27 +00001123 assert(getBackendPtr() && "Expected assembler backend");
Rafael Espindola88673902010-12-04 22:47:22 +00001124 // The layout is done. Mark every fragment as valid.
Rafael Espindola6624f472010-12-07 23:32:26 +00001125 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
Oliver Stannard268f42f2016-12-14 10:43:58 +00001126 MCSection &Section = *Layout.getSectionOrder()[i];
1127 Layout.getFragmentOffset(&*Section.rbegin());
1128 computeFragmentSize(Layout, *Section.rbegin());
Rafael Espindola6624f472010-12-07 23:32:26 +00001129 }
Colin LeMahieu485d9052016-04-27 21:26:13 +00001130 getBackend().finishLayout(*this, Layout);
Daniel Dunbarb31c49a2010-03-22 23:16:48 +00001131}
Sam Clegg8c32e912018-06-14 14:04:23 +00001132
1133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1134LLVM_DUMP_METHOD void MCAssembler::dump() const{
1135 raw_ostream &OS = errs();
1136
1137 OS << "<MCAssembler\n";
1138 OS << " Sections:[\n ";
1139 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1140 if (it != begin()) OS << ",\n ";
1141 it->dump();
1142 }
1143 OS << "],\n";
1144 OS << " Symbols:[";
1145
1146 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1147 if (it != symbol_begin()) OS << ",\n ";
1148 OS << "(";
1149 it->dump();
1150 OS << ", Index:" << it->getIndex() << ", ";
1151 OS << ")";
1152 }
1153 OS << "]>\n";
1154}
1155#endif