Break circular dependency between FIR dialect and utilities
[llvm-project.git] / lld / ELF / Config.h
blob249fe3c30eceba1c3db27efe5af8e3fbb23d71e6
1 //===- Config.h -------------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef LLD_ELF_CONFIG_H
10 #define LLD_ELF_CONFIG_H
12 #include "lld/Common/ErrorHandler.h"
13 #include "llvm/ADT/CachedHashString.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/BinaryFormat/ELF.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Support/CachePruning.h"
22 #include "llvm/Support/CodeGen.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/GlobPattern.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include <atomic>
29 #include <memory>
30 #include <optional>
31 #include <vector>
33 namespace lld::elf {
35 class InputFile;
36 class BinaryFile;
37 class BitcodeFile;
38 class ELFFileBase;
39 class SharedFile;
40 class InputSectionBase;
41 class EhInputSection;
42 class Symbol;
43 class BitcodeCompiler;
45 enum ELFKind : uint8_t {
46 ELFNoneKind,
47 ELF32LEKind,
48 ELF32BEKind,
49 ELF64LEKind,
50 ELF64BEKind
53 // For -Bno-symbolic, -Bsymbolic-non-weak-functions, -Bsymbolic-functions,
54 // -Bsymbolic.
55 enum class BsymbolicKind { None, NonWeakFunctions, Functions, All };
57 // For --build-id.
58 enum class BuildIdKind { None, Fast, Md5, Sha1, Hexstring, Uuid };
60 // For --discard-{all,locals,none}.
61 enum class DiscardPolicy { Default, All, Locals, None };
63 // For --icf={none,safe,all}.
64 enum class ICFLevel { None, Safe, All };
66 // For --strip-{all,debug}.
67 enum class StripPolicy { None, All, Debug };
69 // For --unresolved-symbols.
70 enum class UnresolvedPolicy { ReportError, Warn, Ignore };
72 // For --orphan-handling.
73 enum class OrphanHandlingPolicy { Place, Warn, Error };
75 // For --sort-section and linkerscript sorting rules.
76 enum class SortSectionPolicy {
77 Default,
78 None,
79 Alignment,
80 Name,
81 Priority,
82 Reverse,
85 // For --target2
86 enum class Target2Policy { Abs, Rel, GotRel };
88 // For tracking ARM Float Argument PCS
89 enum class ARMVFPArgKind { Default, Base, VFP, ToolChain };
91 // For -z noseparate-code, -z separate-code and -z separate-loadable-segments.
92 enum class SeparateSegmentKind { None, Code, Loadable };
94 // For -z *stack
95 enum class GnuStackKind { None, Exec, NoExec };
97 struct SymbolVersion {
98 llvm::StringRef name;
99 bool isExternCpp;
100 bool hasWildcard;
103 // This struct contains symbols version definition that
104 // can be found in version script if it is used for link.
105 struct VersionDefinition {
106 llvm::StringRef name;
107 uint16_t id;
108 SmallVector<SymbolVersion, 0> nonLocalPatterns;
109 SmallVector<SymbolVersion, 0> localPatterns;
112 class LinkerDriver {
113 public:
114 void linkerMain(ArrayRef<const char *> args);
115 void addFile(StringRef path, bool withLOption);
116 void addLibrary(StringRef name);
118 private:
119 void createFiles(llvm::opt::InputArgList &args);
120 void inferMachineType();
121 void link(llvm::opt::InputArgList &args);
122 template <class ELFT> void compileBitcodeFiles(bool skipLinkedOutput);
124 // True if we are in --whole-archive and --no-whole-archive.
125 bool inWholeArchive = false;
127 // True if we are in --start-lib and --end-lib.
128 bool inLib = false;
130 std::unique_ptr<BitcodeCompiler> lto;
131 std::vector<InputFile *> files;
133 public:
134 SmallVector<std::pair<StringRef, unsigned>, 0> archiveFiles;
137 // This struct contains the global configuration for the linker.
138 // Most fields are direct mapping from the command line options
139 // and such fields have the same name as the corresponding options.
140 // Most fields are initialized by the ctx.driver.
141 struct Config {
142 uint8_t osabi = 0;
143 uint32_t andFeatures = 0;
144 llvm::CachePruningPolicy thinLTOCachePolicy;
145 llvm::SetVector<llvm::CachedHashString> dependencyFiles; // for --dependency-file
146 llvm::StringMap<uint64_t> sectionStartMap;
147 llvm::StringRef bfdname;
148 llvm::StringRef chroot;
149 llvm::StringRef dependencyFile;
150 llvm::StringRef dwoDir;
151 llvm::StringRef dynamicLinker;
152 llvm::StringRef entry;
153 llvm::StringRef emulation;
154 llvm::StringRef fini;
155 llvm::StringRef init;
156 llvm::StringRef ltoAAPipeline;
157 llvm::StringRef ltoCSProfileFile;
158 llvm::StringRef ltoNewPmPasses;
159 llvm::StringRef ltoObjPath;
160 llvm::StringRef ltoSampleProfile;
161 llvm::StringRef mapFile;
162 llvm::StringRef outputFile;
163 llvm::StringRef optRemarksFilename;
164 std::optional<uint64_t> optRemarksHotnessThreshold = 0;
165 llvm::StringRef optRemarksPasses;
166 llvm::StringRef optRemarksFormat;
167 llvm::StringRef optStatsFilename;
168 llvm::StringRef progName;
169 llvm::StringRef printArchiveStats;
170 llvm::StringRef printSymbolOrder;
171 llvm::StringRef soName;
172 llvm::StringRef sysroot;
173 llvm::StringRef thinLTOCacheDir;
174 llvm::StringRef thinLTOIndexOnlyArg;
175 llvm::StringRef whyExtract;
176 StringRef zBtiReport = "none";
177 StringRef zCetReport = "none";
178 llvm::StringRef ltoBasicBlockSections;
179 std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;
180 std::pair<llvm::StringRef, llvm::StringRef> thinLTOPrefixReplace;
181 std::string rpath;
182 llvm::SmallVector<VersionDefinition, 0> versionDefinitions;
183 llvm::SmallVector<llvm::StringRef, 0> auxiliaryList;
184 llvm::SmallVector<llvm::StringRef, 0> filterList;
185 llvm::SmallVector<llvm::StringRef, 0> passPlugins;
186 llvm::SmallVector<llvm::StringRef, 0> searchPaths;
187 llvm::SmallVector<llvm::StringRef, 0> symbolOrderingFile;
188 llvm::SmallVector<llvm::StringRef, 0> thinLTOModulesToCompile;
189 llvm::SmallVector<llvm::StringRef, 0> undefined;
190 llvm::SmallVector<SymbolVersion, 0> dynamicList;
191 llvm::SmallVector<uint8_t, 0> buildIdVector;
192 llvm::SmallVector<llvm::StringRef, 0> mllvmOpts;
193 llvm::MapVector<std::pair<const InputSectionBase *, const InputSectionBase *>,
194 uint64_t>
195 callGraphProfile;
196 bool allowMultipleDefinition;
197 bool androidPackDynRelocs = false;
198 bool armHasBlx = false;
199 bool armHasMovtMovw = false;
200 bool armJ1J2BranchEncoding = false;
201 bool asNeeded = false;
202 BsymbolicKind bsymbolic = BsymbolicKind::None;
203 bool callGraphProfileSort;
204 bool checkSections;
205 bool checkDynamicRelocs;
206 llvm::DebugCompressionType compressDebugSections;
207 bool cref;
208 llvm::SmallVector<std::pair<llvm::GlobPattern, uint64_t>, 0>
209 deadRelocInNonAlloc;
210 bool demangle = true;
211 bool dependentLibraries;
212 bool disableVerify;
213 bool ehFrameHdr;
214 bool emitLLVM;
215 bool emitRelocs;
216 bool enableNewDtags;
217 bool executeOnly;
218 bool exportDynamic;
219 bool fixCortexA53Errata843419;
220 bool fixCortexA8;
221 bool formatBinary = false;
222 bool fortranCommon;
223 bool gcSections;
224 bool gdbIndex;
225 bool gnuHash = false;
226 bool gnuUnique;
227 bool hasDynSymTab;
228 bool ignoreDataAddressEquality;
229 bool ignoreFunctionAddressEquality;
230 bool ltoCSProfileGenerate;
231 bool ltoPGOWarnMismatch;
232 bool ltoDebugPassManager;
233 bool ltoEmitAsm;
234 bool ltoUniqueBasicBlockSectionNames;
235 bool ltoWholeProgramVisibility;
236 bool mergeArmExidx;
237 bool mipsN32Abi = false;
238 bool mmapOutputFile;
239 bool nmagic;
240 bool noDynamicLinker = false;
241 bool noinhibitExec;
242 bool nostdlib;
243 bool oFormatBinary;
244 bool omagic;
245 bool optEB = false;
246 bool optEL = false;
247 bool optimizeBBJumps;
248 bool optRemarksWithHotness;
249 bool picThunk;
250 bool pie;
251 bool printGcSections;
252 bool printIcfSections;
253 bool relax;
254 bool relocatable;
255 bool relrGlibc = false;
256 bool relrPackDynRelocs = false;
257 llvm::DenseSet<llvm::StringRef> saveTempsArgs;
258 llvm::SmallVector<std::pair<llvm::GlobPattern, uint32_t>, 0> shuffleSections;
259 bool singleRoRx;
260 bool shared;
261 bool symbolic;
262 bool isStatic = false;
263 bool sysvHash = false;
264 bool target1Rel;
265 bool trace;
266 bool thinLTOEmitImportsFiles;
267 bool thinLTOEmitIndexFiles;
268 bool thinLTOIndexOnly;
269 bool timeTraceEnabled;
270 bool tocOptimize;
271 bool pcRelOptimize;
272 bool undefinedVersion;
273 bool unique;
274 bool useAndroidRelrTags = false;
275 bool warnBackrefs;
276 llvm::SmallVector<llvm::GlobPattern, 0> warnBackrefsExclude;
277 bool warnCommon;
278 bool warnMissingEntry;
279 bool warnSymbolOrdering;
280 bool writeAddends;
281 bool zCombreloc;
282 bool zCopyreloc;
283 bool zForceBti;
284 bool zForceIbt;
285 bool zGlobal;
286 bool zHazardplt;
287 bool zIfuncNoplt;
288 bool zInitfirst;
289 bool zInterpose;
290 bool zKeepTextSectionPrefix;
291 bool zNodefaultlib;
292 bool zNodelete;
293 bool zNodlopen;
294 bool zNow;
295 bool zOrigin;
296 bool zPacPlt;
297 bool zRelro;
298 bool zRodynamic;
299 bool zShstk;
300 bool zStartStopGC;
301 uint8_t zStartStopVisibility;
302 bool zText;
303 bool zRetpolineplt;
304 bool zWxneeded;
305 DiscardPolicy discard;
306 GnuStackKind zGnustack;
307 ICFLevel icf;
308 OrphanHandlingPolicy orphanHandling;
309 SortSectionPolicy sortSection;
310 StripPolicy strip;
311 UnresolvedPolicy unresolvedSymbols;
312 UnresolvedPolicy unresolvedSymbolsInShlib;
313 Target2Policy target2;
314 bool power10Stubs;
315 ARMVFPArgKind armVFPArgs = ARMVFPArgKind::Default;
316 BuildIdKind buildId = BuildIdKind::None;
317 SeparateSegmentKind zSeparate;
318 ELFKind ekind = ELFNoneKind;
319 uint16_t emachine = llvm::ELF::EM_NONE;
320 std::optional<uint64_t> imageBase;
321 uint64_t commonPageSize;
322 uint64_t maxPageSize;
323 uint64_t mipsGotSize;
324 uint64_t zStackSize;
325 unsigned ltoPartitions;
326 unsigned ltoo;
327 llvm::CodeGenOpt::Level ltoCgo;
328 unsigned optimize;
329 StringRef thinLTOJobs;
330 unsigned timeTraceGranularity;
331 int32_t splitStackAdjustSize;
332 StringRef packageMetadata;
334 // The following config options do not directly correspond to any
335 // particular command line options.
337 // True if we need to pass through relocations in input files to the
338 // output file. Usually false because we consume relocations.
339 bool copyRelocs;
341 // True if the target is ELF64. False if ELF32.
342 bool is64;
344 // True if the target is little-endian. False if big-endian.
345 bool isLE;
347 // endianness::little if isLE is true. endianness::big otherwise.
348 llvm::support::endianness endianness;
350 // True if the target is the little-endian MIPS64.
352 // The reason why we have this variable only for the MIPS is because
353 // we use this often. Some ELF headers for MIPS64EL are in a
354 // mixed-endian (which is horrible and I'd say that's a serious spec
355 // bug), and we need to know whether we are reading MIPS ELF files or
356 // not in various places.
358 // (Note that MIPS64EL is not a typo for MIPS64LE. This is the official
359 // name whatever that means. A fun hypothesis is that "EL" is short for
360 // little-endian written in the little-endian order, but I don't know
361 // if that's true.)
362 bool isMips64EL;
364 // True if we need to set the DF_STATIC_TLS flag to an output file, which
365 // works as a hint to the dynamic loader that the shared object contains code
366 // compiled with the initial-exec TLS model.
367 bool hasTlsIe = false;
369 // Holds set of ELF header flags for the target.
370 uint32_t eflags = 0;
372 // The ELF spec defines two types of relocation table entries, RELA and
373 // REL. RELA is a triplet of (offset, info, addend) while REL is a
374 // tuple of (offset, info). Addends for REL are implicit and read from
375 // the location where the relocations are applied. So, REL is more
376 // compact than RELA but requires a bit of more work to process.
378 // (From the linker writer's view, this distinction is not necessary.
379 // If the ELF had chosen whichever and sticked with it, it would have
380 // been easier to write code to process relocations, but it's too late
381 // to change the spec.)
383 // Each ABI defines its relocation type. IsRela is true if target
384 // uses RELA. As far as we know, all 64-bit ABIs are using RELA. A
385 // few 32-bit ABIs are using RELA too.
386 bool isRela;
388 // True if we are creating position-independent code.
389 bool isPic;
391 // 4 for ELF32, 8 for ELF64.
392 int wordsize;
394 // Mode of MTE to write to the ELF note. Should be one of NT_MEMTAG_ASYNC (for
395 // async), NT_MEMTAG_SYNC (for sync), or NT_MEMTAG_LEVEL_NONE (for none). If
396 // async or sync is enabled, write the ELF note specifying the default MTE
397 // mode.
398 int androidMemtagMode;
399 // Signal to the dynamic loader to enable heap MTE.
400 bool androidMemtagHeap;
401 // Signal to the dynamic loader that this binary expects stack MTE. Generally,
402 // this means to map the primary and thread stacks as PROT_MTE. Note: This is
403 // not supported on Android 11 & 12.
404 bool androidMemtagStack;
406 unsigned threadCount;
408 struct ConfigWrapper {
409 Config c;
410 Config *operator->() { return &c; }
413 LLVM_LIBRARY_VISIBILITY extern ConfigWrapper config;
415 struct DuplicateSymbol {
416 const Symbol *sym;
417 const InputFile *file;
418 InputSectionBase *section;
419 uint64_t value;
422 struct Ctx {
423 LinkerDriver driver;
424 SmallVector<std::unique_ptr<MemoryBuffer>> memoryBuffers;
425 SmallVector<ELFFileBase *, 0> objectFiles;
426 SmallVector<SharedFile *, 0> sharedFiles;
427 SmallVector<BinaryFile *, 0> binaryFiles;
428 SmallVector<BitcodeFile *, 0> bitcodeFiles;
429 SmallVector<BitcodeFile *, 0> lazyBitcodeFiles;
430 SmallVector<InputSectionBase *, 0> inputSections;
431 SmallVector<EhInputSection *, 0> ehInputSections;
432 // Duplicate symbol candidates.
433 SmallVector<DuplicateSymbol, 0> duplicates;
434 // Symbols in a non-prevailing COMDAT group which should be changed to an
435 // Undefined.
436 SmallVector<std::pair<Symbol *, unsigned>, 0> nonPrevailingSyms;
437 // A tuple of (reference, extractedFile, sym). Used by --why-extract=.
438 SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
439 whyExtractRecords;
440 // A mapping from a symbol to an InputFile referencing it backward. Used by
441 // --warn-backrefs.
442 llvm::DenseMap<const Symbol *,
443 std::pair<const InputFile *, const InputFile *>>
444 backwardReferences;
445 // True if SHT_LLVM_SYMPART is used.
446 std::atomic<bool> hasSympart{false};
447 // True if there are TLS IE relocations. Set DF_STATIC_TLS if -shared.
448 std::atomic<bool> hasTlsIe{false};
449 // True if we need to reserve two .got entries for local-dynamic TLS model.
450 std::atomic<bool> needsTlsLd{false};
452 void reset();
455 LLVM_LIBRARY_VISIBILITY extern Ctx ctx;
457 // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
458 // VER_NDX_GLOBAL. This helper returns other elements.
459 static inline ArrayRef<VersionDefinition> namedVersionDefs() {
460 return llvm::ArrayRef(config->versionDefinitions).slice(2);
463 void errorOrWarn(const Twine &msg);
465 static inline void internalLinkerError(StringRef loc, const Twine &msg) {
466 errorOrWarn(loc + "internal linker error: " + msg + "\n" +
467 llvm::getBugReportMsg());
470 } // namespace lld::elf
472 #endif