1 //===- MCAssembler.h - Object File Generation -------------------*- 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 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_MC_MCASSEMBLER_H 10 #define LLVM_MC_MCASSEMBLER_H 11 12 #include "llvm/ADT/ArrayRef.h" 13 #include "llvm/ADT/SmallPtrSet.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/iterator.h" 16 #include "llvm/ADT/iterator_range.h" 17 #include "llvm/BinaryFormat/MachO.h" 18 #include "llvm/MC/MCDirectives.h" 19 #include "llvm/MC/MCDwarf.h" 20 #include "llvm/MC/MCLinkerOptimizationHint.h" 21 #include "llvm/MC/MCSymbol.h" 22 #include "llvm/Support/SMLoc.h" 23 #include "llvm/Support/VersionTuple.h" 24 #include <algorithm> 25 #include <cassert> 26 #include <cstddef> 27 #include <cstdint> 28 #include <memory> 29 #include <string> 30 #include <tuple> 31 #include <utility> 32 #include <vector> 33 34 namespace llvm { 35 36 class MCBoundaryAlignFragment; 37 class MCCVDefRangeFragment; 38 class MCCVInlineLineTableFragment; 39 class MCDwarfCallFrameFragment; 40 class MCDwarfLineAddrFragment; 41 class MCEncodedFragment; 42 class MCFixup; 43 class MCLEBFragment; 44 class MCPseudoProbeAddrFragment; 45 class MCRelaxableFragment; 46 class MCSymbolRefExpr; 47 class raw_ostream; 48 class MCAsmBackend; 49 class MCAsmLayout; 50 class MCContext; 51 class MCCodeEmitter; 52 class MCFragment; 53 class MCObjectWriter; 54 class MCSection; 55 class MCValue; 56 57 // FIXME: This really doesn't belong here. See comments below. 58 struct IndirectSymbolData { 59 MCSymbol *Symbol; 60 MCSection *Section; 61 }; 62 63 // FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk 64 // to one another. 65 struct DataRegionData { 66 // This enum should be kept in sync w/ the mach-o definition in 67 // llvm/Object/MachOFormat.h. 68 enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind; 69 MCSymbol *Start; 70 MCSymbol *End; 71 }; 72 73 class MCAssembler { 74 friend class MCAsmLayout; 75 76 public: 77 using SectionListType = std::vector<MCSection *>; 78 using SymbolDataListType = std::vector<const MCSymbol *>; 79 80 using const_iterator = pointee_iterator<SectionListType::const_iterator>; 81 using iterator = pointee_iterator<SectionListType::iterator>; 82 83 using const_symbol_iterator = 84 pointee_iterator<SymbolDataListType::const_iterator>; 85 using symbol_iterator = pointee_iterator<SymbolDataListType::iterator>; 86 87 using symbol_range = iterator_range<symbol_iterator>; 88 using const_symbol_range = iterator_range<const_symbol_iterator>; 89 90 using const_indirect_symbol_iterator = 91 std::vector<IndirectSymbolData>::const_iterator; 92 using indirect_symbol_iterator = std::vector<IndirectSymbolData>::iterator; 93 94 using const_data_region_iterator = 95 std::vector<DataRegionData>::const_iterator; 96 using data_region_iterator = std::vector<DataRegionData>::iterator; 97 98 /// MachO specific deployment target version info. 99 // A Major version of 0 indicates that no version information was supplied 100 // and so the corresponding load command should not be emitted. 101 using VersionInfoType = struct { 102 bool EmitBuildVersion; 103 union { 104 MCVersionMinType Type; ///< Used when EmitBuildVersion==false. 105 MachO::PlatformType Platform; ///< Used when EmitBuildVersion==true. 106 } TypeOrPlatform; 107 unsigned Major; 108 unsigned Minor; 109 unsigned Update; 110 /// An optional version of the SDK that was used to build the source. 111 VersionTuple SDKVersion; 112 }; 113 114 private: 115 MCContext &Context; 116 117 std::unique_ptr<MCAsmBackend> Backend; 118 119 std::unique_ptr<MCCodeEmitter> Emitter; 120 121 std::unique_ptr<MCObjectWriter> Writer; 122 123 SectionListType Sections; 124 125 SymbolDataListType Symbols; 126 127 std::vector<IndirectSymbolData> IndirectSymbols; 128 129 std::vector<DataRegionData> DataRegions; 130 131 /// The list of linker options to propagate into the object file. 132 std::vector<std::vector<std::string>> LinkerOptions; 133 134 /// List of declared file names 135 std::vector<std::pair<std::string, size_t>> FileNames; 136 137 MCDwarfLineTableParams LTParams; 138 139 /// The set of function symbols for which a .thumb_func directive has 140 /// been seen. 141 // 142 // FIXME: We really would like this in target specific code rather than 143 // here. Maybe when the relocation stuff moves to target specific, 144 // this can go with it? The streamer would need some target specific 145 // refactoring too. 146 mutable SmallPtrSet<const MCSymbol *, 32> ThumbFuncs; 147 148 /// The bundle alignment size currently set in the assembler. 149 /// 150 /// By default it's 0, which means bundling is disabled. 151 unsigned BundleAlignSize; 152 153 bool RelaxAll : 1; 154 bool SubsectionsViaSymbols : 1; 155 bool IncrementalLinkerCompatible : 1; 156 157 /// ELF specific e_header flags 158 // It would be good if there were an MCELFAssembler class to hold this. 159 // ELF header flags are used both by the integrated and standalone assemblers. 160 // Access to the flags is necessary in cases where assembler directives affect 161 // which flags to be set. 162 unsigned ELFHeaderEFlags; 163 164 /// Used to communicate Linker Optimization Hint information between 165 /// the Streamer and the .o writer 166 MCLOHContainer LOHContainer; 167 168 VersionInfoType VersionInfo; 169 VersionInfoType DarwinTargetVariantVersionInfo; 170 171 /// Evaluate a fixup to a relocatable expression and the value which should be 172 /// placed into the fixup. 173 /// 174 /// \param Layout The layout to use for evaluation. 175 /// \param Fixup The fixup to evaluate. 176 /// \param DF The fragment the fixup is inside. 177 /// \param Target [out] On return, the relocatable expression the fixup 178 /// evaluates to. 179 /// \param Value [out] On return, the value of the fixup as currently laid 180 /// out. 181 /// \param WasForced [out] On return, the value in the fixup is set to the 182 /// correct value if WasForced is true, even if evaluateFixup returns false. 183 /// \return Whether the fixup value was fully resolved. This is true if the 184 /// \p Value result is fixed, otherwise the value may change due to 185 /// relocation. 186 bool evaluateFixup(const MCAsmLayout &Layout, const MCFixup &Fixup, 187 const MCFragment *DF, MCValue &Target, 188 const MCSubtargetInfo *STI, uint64_t &Value, 189 bool &WasForced) const; 190 191 /// Check whether a fixup can be satisfied, or whether it needs to be relaxed 192 /// (increased in size, in order to hold its value correctly). 193 bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF, 194 const MCAsmLayout &Layout) const; 195 196 /// Check whether the given fragment needs relaxation. 197 bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF, 198 const MCAsmLayout &Layout) const; 199 200 /// Perform one layout iteration and return true if any offsets 201 /// were adjusted. 202 bool layoutOnce(MCAsmLayout &Layout); 203 204 /// Perform one layout iteration of the given section and return true 205 /// if any offsets were adjusted. 206 bool layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec); 207 208 /// Perform relaxation on a single fragment - returns true if the fragment 209 /// changes as a result of relaxation. 210 bool relaxFragment(MCAsmLayout &Layout, MCFragment &F); 211 bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF); 212 bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF); 213 bool relaxBoundaryAlign(MCAsmLayout &Layout, MCBoundaryAlignFragment &BF); 214 bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF); 215 bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout, 216 MCDwarfCallFrameFragment &DF); 217 bool relaxCVInlineLineTable(MCAsmLayout &Layout, 218 MCCVInlineLineTableFragment &DF); 219 bool relaxCVDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &DF); 220 bool relaxPseudoProbeAddr(MCAsmLayout &Layout, MCPseudoProbeAddrFragment &DF); 221 222 /// finishLayout - Finalize a layout, including fragment lowering. 223 void finishLayout(MCAsmLayout &Layout); 224 225 std::tuple<MCValue, uint64_t, bool> handleFixup(const MCAsmLayout &Layout, 226 MCFragment &F, 227 const MCFixup &Fixup, 228 const MCSubtargetInfo *STI); 229 230 public: 231 struct Symver { 232 SMLoc Loc; 233 const MCSymbol *Sym; 234 StringRef Name; 235 // True if .symver *, *@@@* or .symver *, *, remove. 236 bool KeepOriginalSym; 237 }; 238 std::vector<Symver> Symvers; 239 240 /// Construct a new assembler instance. 241 // 242 // FIXME: How are we going to parameterize this? Two obvious options are stay 243 // concrete and require clients to pass in a target like object. The other 244 // option is to make this abstract, and have targets provide concrete 245 // implementations as we do with AsmParser. 246 MCAssembler(MCContext &Context, std::unique_ptr<MCAsmBackend> Backend, 247 std::unique_ptr<MCCodeEmitter> Emitter, 248 std::unique_ptr<MCObjectWriter> Writer); 249 MCAssembler(const MCAssembler &) = delete; 250 MCAssembler &operator=(const MCAssembler &) = delete; 251 ~MCAssembler(); 252 253 /// Compute the effective fragment size assuming it is laid out at the given 254 /// \p SectionAddress and \p FragmentOffset. 255 uint64_t computeFragmentSize(const MCAsmLayout &Layout, 256 const MCFragment &F) const; 257 258 /// Find the symbol which defines the atom containing the given symbol, or 259 /// null if there is no such symbol. 260 const MCSymbol *getAtom(const MCSymbol &S) const; 261 262 /// Check whether a particular symbol is visible to the linker and is required 263 /// in the symbol table, or whether it can be discarded by the assembler. This 264 /// also effects whether the assembler treats the label as potentially 265 /// defining a separate atom. 266 bool isSymbolLinkerVisible(const MCSymbol &SD) const; 267 268 /// Emit the section contents to \p OS. 269 void writeSectionData(raw_ostream &OS, const MCSection *Section, 270 const MCAsmLayout &Layout) const; 271 272 /// Check whether a given symbol has been flagged with .thumb_func. 273 bool isThumbFunc(const MCSymbol *Func) const; 274 275 /// Flag a function symbol as the target of a .thumb_func directive. setIsThumbFunc(const MCSymbol * Func)276 void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); } 277 278 /// ELF e_header flags getELFHeaderEFlags()279 unsigned getELFHeaderEFlags() const { return ELFHeaderEFlags; } setELFHeaderEFlags(unsigned Flags)280 void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags; } 281 282 /// MachO deployment target version information. getVersionInfo()283 const VersionInfoType &getVersionInfo() const { return VersionInfo; } 284 void setVersionMin(MCVersionMinType Type, unsigned Major, unsigned Minor, 285 unsigned Update, 286 VersionTuple SDKVersion = VersionTuple()) { 287 VersionInfo.EmitBuildVersion = false; 288 VersionInfo.TypeOrPlatform.Type = Type; 289 VersionInfo.Major = Major; 290 VersionInfo.Minor = Minor; 291 VersionInfo.Update = Update; 292 VersionInfo.SDKVersion = SDKVersion; 293 } 294 void setBuildVersion(MachO::PlatformType Platform, unsigned Major, 295 unsigned Minor, unsigned Update, 296 VersionTuple SDKVersion = VersionTuple()) { 297 VersionInfo.EmitBuildVersion = true; 298 VersionInfo.TypeOrPlatform.Platform = Platform; 299 VersionInfo.Major = Major; 300 VersionInfo.Minor = Minor; 301 VersionInfo.Update = Update; 302 VersionInfo.SDKVersion = SDKVersion; 303 } 304 getDarwinTargetVariantVersionInfo()305 const VersionInfoType &getDarwinTargetVariantVersionInfo() const { 306 return DarwinTargetVariantVersionInfo; 307 } setDarwinTargetVariantBuildVersion(MachO::PlatformType Platform,unsigned Major,unsigned Minor,unsigned Update,VersionTuple SDKVersion)308 void setDarwinTargetVariantBuildVersion(MachO::PlatformType Platform, 309 unsigned Major, unsigned Minor, 310 unsigned Update, 311 VersionTuple SDKVersion) { 312 DarwinTargetVariantVersionInfo.EmitBuildVersion = true; 313 DarwinTargetVariantVersionInfo.TypeOrPlatform.Platform = Platform; 314 DarwinTargetVariantVersionInfo.Major = Major; 315 DarwinTargetVariantVersionInfo.Minor = Minor; 316 DarwinTargetVariantVersionInfo.Update = Update; 317 DarwinTargetVariantVersionInfo.SDKVersion = SDKVersion; 318 } 319 320 /// Reuse an assembler instance 321 /// 322 void reset(); 323 getContext()324 MCContext &getContext() const { return Context; } 325 getBackendPtr()326 MCAsmBackend *getBackendPtr() const { return Backend.get(); } 327 getEmitterPtr()328 MCCodeEmitter *getEmitterPtr() const { return Emitter.get(); } 329 getWriterPtr()330 MCObjectWriter *getWriterPtr() const { return Writer.get(); } 331 getBackend()332 MCAsmBackend &getBackend() const { return *Backend; } 333 getEmitter()334 MCCodeEmitter &getEmitter() const { return *Emitter; } 335 getWriter()336 MCObjectWriter &getWriter() const { return *Writer; } 337 getDWARFLinetableParams()338 MCDwarfLineTableParams getDWARFLinetableParams() const { return LTParams; } setDWARFLinetableParams(MCDwarfLineTableParams P)339 void setDWARFLinetableParams(MCDwarfLineTableParams P) { LTParams = P; } 340 341 /// Finish - Do final processing and write the object to the output stream. 342 /// \p Writer is used for custom object writer (as the MCJIT does), 343 /// if not specified it is automatically created from backend. 344 void Finish(); 345 346 // Layout all section and prepare them for emission. 347 void layout(MCAsmLayout &Layout); 348 349 // FIXME: This does not belong here. getSubsectionsViaSymbols()350 bool getSubsectionsViaSymbols() const { return SubsectionsViaSymbols; } setSubsectionsViaSymbols(bool Value)351 void setSubsectionsViaSymbols(bool Value) { SubsectionsViaSymbols = Value; } 352 isIncrementalLinkerCompatible()353 bool isIncrementalLinkerCompatible() const { 354 return IncrementalLinkerCompatible; 355 } setIncrementalLinkerCompatible(bool Value)356 void setIncrementalLinkerCompatible(bool Value) { 357 IncrementalLinkerCompatible = Value; 358 } 359 getRelaxAll()360 bool getRelaxAll() const { return RelaxAll; } setRelaxAll(bool Value)361 void setRelaxAll(bool Value) { RelaxAll = Value; } 362 isBundlingEnabled()363 bool isBundlingEnabled() const { return BundleAlignSize != 0; } 364 getBundleAlignSize()365 unsigned getBundleAlignSize() const { return BundleAlignSize; } 366 setBundleAlignSize(unsigned Size)367 void setBundleAlignSize(unsigned Size) { 368 assert((Size == 0 || !(Size & (Size - 1))) && 369 "Expect a power-of-two bundle align size"); 370 BundleAlignSize = Size; 371 } 372 373 /// \name Section List Access 374 /// @{ 375 begin()376 iterator begin() { return Sections.begin(); } begin()377 const_iterator begin() const { return Sections.begin(); } 378 end()379 iterator end() { return Sections.end(); } end()380 const_iterator end() const { return Sections.end(); } 381 size()382 size_t size() const { return Sections.size(); } 383 384 /// @} 385 /// \name Symbol List Access 386 /// @{ symbol_begin()387 symbol_iterator symbol_begin() { return Symbols.begin(); } symbol_begin()388 const_symbol_iterator symbol_begin() const { return Symbols.begin(); } 389 symbol_end()390 symbol_iterator symbol_end() { return Symbols.end(); } symbol_end()391 const_symbol_iterator symbol_end() const { return Symbols.end(); } 392 symbols()393 symbol_range symbols() { return make_range(symbol_begin(), symbol_end()); } symbols()394 const_symbol_range symbols() const { 395 return make_range(symbol_begin(), symbol_end()); 396 } 397 symbol_size()398 size_t symbol_size() const { return Symbols.size(); } 399 400 /// @} 401 /// \name Indirect Symbol List Access 402 /// @{ 403 404 // FIXME: This is a total hack, this should not be here. Once things are 405 // factored so that the streamer has direct access to the .o writer, it can 406 // disappear. getIndirectSymbols()407 std::vector<IndirectSymbolData> &getIndirectSymbols() { 408 return IndirectSymbols; 409 } 410 indirect_symbol_begin()411 indirect_symbol_iterator indirect_symbol_begin() { 412 return IndirectSymbols.begin(); 413 } indirect_symbol_begin()414 const_indirect_symbol_iterator indirect_symbol_begin() const { 415 return IndirectSymbols.begin(); 416 } 417 indirect_symbol_end()418 indirect_symbol_iterator indirect_symbol_end() { 419 return IndirectSymbols.end(); 420 } indirect_symbol_end()421 const_indirect_symbol_iterator indirect_symbol_end() const { 422 return IndirectSymbols.end(); 423 } 424 indirect_symbol_size()425 size_t indirect_symbol_size() const { return IndirectSymbols.size(); } 426 427 /// @} 428 /// \name Linker Option List Access 429 /// @{ 430 getLinkerOptions()431 std::vector<std::vector<std::string>> &getLinkerOptions() { 432 return LinkerOptions; 433 } 434 435 /// @} 436 /// \name Data Region List Access 437 /// @{ 438 439 // FIXME: This is a total hack, this should not be here. Once things are 440 // factored so that the streamer has direct access to the .o writer, it can 441 // disappear. getDataRegions()442 std::vector<DataRegionData> &getDataRegions() { return DataRegions; } 443 data_region_begin()444 data_region_iterator data_region_begin() { return DataRegions.begin(); } data_region_begin()445 const_data_region_iterator data_region_begin() const { 446 return DataRegions.begin(); 447 } 448 data_region_end()449 data_region_iterator data_region_end() { return DataRegions.end(); } data_region_end()450 const_data_region_iterator data_region_end() const { 451 return DataRegions.end(); 452 } 453 data_region_size()454 size_t data_region_size() const { return DataRegions.size(); } 455 456 /// @} 457 /// \name Data Region List Access 458 /// @{ 459 460 // FIXME: This is a total hack, this should not be here. Once things are 461 // factored so that the streamer has direct access to the .o writer, it can 462 // disappear. getLOHContainer()463 MCLOHContainer &getLOHContainer() { return LOHContainer; } getLOHContainer()464 const MCLOHContainer &getLOHContainer() const { 465 return const_cast<MCAssembler *>(this)->getLOHContainer(); 466 } 467 468 struct CGProfileEntry { 469 const MCSymbolRefExpr *From; 470 const MCSymbolRefExpr *To; 471 uint64_t Count; 472 }; 473 std::vector<CGProfileEntry> CGProfile; 474 /// @} 475 /// \name Backend Data Access 476 /// @{ 477 478 bool registerSection(MCSection &Section); 479 bool registerSymbol(const MCSymbol &Symbol); 480 getFileNames()481 MutableArrayRef<std::pair<std::string, size_t>> getFileNames() { 482 return FileNames; 483 } 484 addFileName(StringRef FileName)485 void addFileName(StringRef FileName) { 486 FileNames.emplace_back(std::string(FileName), Symbols.size()); 487 } 488 489 /// Write the necessary bundle padding to \p OS. 490 /// Expects a fragment \p F containing instructions and its size \p FSize. 491 void writeFragmentPadding(raw_ostream &OS, const MCEncodedFragment &F, 492 uint64_t FSize) const; 493 494 /// @} 495 496 void dump() const; 497 }; 498 499 /// Compute the amount of padding required before the fragment \p F to 500 /// obey bundling restrictions, where \p FOffset is the fragment's offset in 501 /// its section and \p FSize is the fragment's size. 502 uint64_t computeBundlePadding(const MCAssembler &Assembler, 503 const MCEncodedFragment *F, uint64_t FOffset, 504 uint64_t FSize); 505 506 } // end namespace llvm 507 508 #endif // LLVM_MC_MCASSEMBLER_H 509