1 //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef LLVM_MC_MCCONTEXT_H 11 #define LLVM_MC_MCCONTEXT_H 12 13 #include "llvm/ADT/DenseMap.h" 14 #include "llvm/ADT/SetVector.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/MC/MCDwarf.h" 20 #include "llvm/MC/SectionKind.h" 21 #include "llvm/Support/Allocator.h" 22 #include "llvm/Support/Compiler.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include <map> 25 #include <tuple> 26 #include <vector> // FIXME: Shouldn't be needed. 27 28 namespace llvm { 29 class MCAsmInfo; 30 class MCExpr; 31 class MCSection; 32 class MCSymbol; 33 class MCLabel; 34 struct MCDwarfFile; 35 class MCDwarfLoc; 36 class MCObjectFileInfo; 37 class MCRegisterInfo; 38 class MCLineSection; 39 class SMLoc; 40 class MCSectionMachO; 41 class MCSectionELF; 42 class MCSectionCOFF; 43 44 /// Context object for machine code objects. This class owns all of the 45 /// sections that it creates. 46 /// 47 class MCContext { 48 MCContext(const MCContext&) = delete; 49 MCContext &operator=(const MCContext&) = delete; 50 public: 51 typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable; 52 private: 53 /// The SourceMgr for this object, if any. 54 const SourceMgr *SrcMgr; 55 56 /// The MCAsmInfo for this target. 57 const MCAsmInfo *MAI; 58 59 /// The MCRegisterInfo for this target. 60 const MCRegisterInfo *MRI; 61 62 /// The MCObjectFileInfo for this target. 63 const MCObjectFileInfo *MOFI; 64 65 /// Allocator object used for creating machine code objects. 66 /// 67 /// We use a bump pointer allocator to avoid the need to track all allocated 68 /// objects. 69 BumpPtrAllocator Allocator; 70 71 /// Bindings of names to symbols. 72 SymbolTable Symbols; 73 74 /// ELF sections can have a corresponding symbol. This maps one to the 75 /// other. 76 DenseMap<const MCSectionELF*, MCSymbol*> SectionSymbols; 77 78 /// A maping from a local label number and an instance count to a symbol. 79 /// For example, in the assembly 80 /// 1: 81 /// 2: 82 /// 1: 83 /// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1) 84 DenseMap<std::pair<unsigned, unsigned>, MCSymbol*> LocalSymbols; 85 86 /// Keeps tracks of names that were used both for used declared and 87 /// artificial symbols. 88 StringMap<bool, BumpPtrAllocator&> UsedNames; 89 90 /// The next ID to dole out to an unnamed assembler temporary symbol with 91 /// a given prefix. 92 StringMap<unsigned> NextID; 93 94 /// Instances of directional local labels. 95 DenseMap<unsigned, MCLabel *> Instances; 96 /// NextInstance() creates the next instance of the directional local label 97 /// for the LocalLabelVal and adds it to the map if needed. 98 unsigned NextInstance(unsigned LocalLabelVal); 99 /// GetInstance() gets the current instance of the directional local label 100 /// for the LocalLabelVal and adds it to the map if needed. 101 unsigned GetInstance(unsigned LocalLabelVal); 102 103 /// The file name of the log file from the environment variable 104 /// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique 105 /// directive is used or it is an error. 106 char *SecureLogFile; 107 /// The stream that gets written to for the .secure_log_unique directive. 108 raw_ostream *SecureLog; 109 /// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to 110 /// catch errors if .secure_log_unique appears twice without 111 /// .secure_log_reset appearing between them. 112 bool SecureLogUsed; 113 114 /// The compilation directory to use for DW_AT_comp_dir. 115 SmallString<128> CompilationDir; 116 117 /// The main file name if passed in explicitly. 118 std::string MainFileName; 119 120 /// The dwarf file and directory tables from the dwarf .file directive. 121 /// We now emit a line table for each compile unit. To reduce the prologue 122 /// size of each line table, the files and directories used by each compile 123 /// unit are separated. 124 std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap; 125 126 /// The current dwarf line information from the last dwarf .loc directive. 127 MCDwarfLoc CurrentDwarfLoc; 128 bool DwarfLocSeen; 129 130 /// Generate dwarf debugging info for assembly source files. 131 bool GenDwarfForAssembly; 132 133 /// The current dwarf file number when generate dwarf debugging info for 134 /// assembly source files. 135 unsigned GenDwarfFileNumber; 136 137 /// Symbols created for the start and end of each section, used for 138 /// generating the .debug_ranges and .debug_aranges sections. 139 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > 140 SectionStartEndSyms; 141 142 /// The information gathered from labels that will have dwarf label 143 /// entries when generating dwarf assembly source files. 144 std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries; 145 146 /// The string to embed in the debug information for the compile unit, if 147 /// non-empty. 148 StringRef DwarfDebugFlags; 149 150 /// The string to embed in as the dwarf AT_producer for the compile unit, if 151 /// non-empty. 152 StringRef DwarfDebugProducer; 153 154 /// The maximum version of dwarf that we should emit. 155 uint16_t DwarfVersion; 156 157 /// Honor temporary labels, this is useful for debugging semantic 158 /// differences between temporary and non-temporary labels (primarily on 159 /// Darwin). 160 bool AllowTemporaryLabels; 161 162 /// The Compile Unit ID that we are currently processing. 163 unsigned DwarfCompileUnitID; 164 165 struct ELFSectionKey { 166 std::string SectionName; 167 StringRef GroupName; 168 unsigned UniqueID; 169 ELFSectionKey(StringRef SectionName, StringRef GroupName, 170 unsigned UniqueID) 171 : SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) { 172 } 173 bool operator<(const ELFSectionKey &Other) const { 174 if (SectionName != Other.SectionName) 175 return SectionName < Other.SectionName; 176 if (GroupName != Other.GroupName) 177 return GroupName < Other.GroupName; 178 return UniqueID < Other.UniqueID; 179 } 180 }; 181 182 struct COFFSectionKey { 183 std::string SectionName; 184 StringRef GroupName; 185 int SelectionKey; 186 COFFSectionKey(StringRef SectionName, StringRef GroupName, 187 int SelectionKey) 188 : SectionName(SectionName), GroupName(GroupName), 189 SelectionKey(SelectionKey) {} 190 bool operator<(const COFFSectionKey &Other) const { 191 if (SectionName != Other.SectionName) 192 return SectionName < Other.SectionName; 193 if (GroupName != Other.GroupName) 194 return GroupName < Other.GroupName; 195 return SelectionKey < Other.SelectionKey; 196 } 197 }; 198 199 StringMap<const MCSectionMachO*> MachOUniquingMap; 200 std::map<ELFSectionKey, const MCSectionELF *> ELFUniquingMap; 201 std::map<COFFSectionKey, const MCSectionCOFF *> COFFUniquingMap; 202 StringMap<bool> ELFRelSecNames; 203 204 /// Do automatic reset in destructor 205 bool AutoReset; 206 207 MCSymbol *CreateSymbol(StringRef Name, bool AlwaysAddSuffix); 208 209 MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal, 210 unsigned Instance); 211 212 public: 213 explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI, 214 const MCObjectFileInfo *MOFI, 215 const SourceMgr *Mgr = nullptr, bool DoAutoReset = true); 216 ~MCContext(); 217 218 const SourceMgr *getSourceManager() const { return SrcMgr; } 219 220 const MCAsmInfo *getAsmInfo() const { return MAI; } 221 222 const MCRegisterInfo *getRegisterInfo() const { return MRI; } 223 224 const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; } 225 226 void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; } 227 228 /// @name Module Lifetime Management 229 /// @{ 230 231 /// reset - return object to right after construction state to prepare 232 /// to process a new module 233 void reset(); 234 235 /// @} 236 237 /// @name Symbol Management 238 /// @{ 239 240 /// Create and return a new linker temporary symbol with a unique but 241 /// unspecified name. 242 MCSymbol *CreateLinkerPrivateTempSymbol(); 243 244 /// Create and return a new assembler temporary symbol with a unique but 245 /// unspecified name. 246 MCSymbol *CreateTempSymbol(); 247 248 MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix); 249 250 /// Create the definition of a directional local symbol for numbered label 251 /// (used for "1:" definitions). 252 MCSymbol *CreateDirectionalLocalSymbol(unsigned LocalLabelVal); 253 254 /// Create and return a directional local symbol for numbered label (used 255 /// for "1b" or 1f" references). 256 MCSymbol *GetDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before); 257 258 /// Lookup the symbol inside with the specified @p Name. If it exists, 259 /// return it. If not, create a forward reference and return it. 260 /// 261 /// @param Name - The symbol name, which must be unique across all symbols. 262 MCSymbol *GetOrCreateSymbol(const Twine &Name); 263 264 MCSymbol *getOrCreateSectionSymbol(const MCSectionELF &Section); 265 266 /// Gets a symbol that will be defined to the final stack offset of a local 267 /// variable after codegen. 268 /// 269 /// @param Idx - The index of a local variable passed to @llvm.frameescape. 270 MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx); 271 272 MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName); 273 274 /// Get the symbol for \p Name, or null. 275 MCSymbol *LookupSymbol(const Twine &Name) const; 276 277 /// getSymbols - Get a reference for the symbol table for clients that 278 /// want to, for example, iterate over all symbols. 'const' because we 279 /// still want any modifications to the table itself to use the MCContext 280 /// APIs. 281 const SymbolTable &getSymbols() const { 282 return Symbols; 283 } 284 285 /// @} 286 287 /// @name Section Management 288 /// @{ 289 290 /// Return the MCSection for the specified mach-o section. This requires 291 /// the operands to be valid. 292 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section, 293 unsigned TypeAndAttributes, 294 unsigned Reserved2, SectionKind K, 295 const char *BeginSymName = nullptr); 296 297 const MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section, 298 unsigned TypeAndAttributes, 299 SectionKind K, 300 const char *BeginSymName = nullptr) { 301 return getMachOSection(Segment, Section, TypeAndAttributes, 0, K, 302 BeginSymName); 303 } 304 305 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 306 unsigned Flags) { 307 return getELFSection(Section, Type, Flags, nullptr); 308 } 309 310 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 311 unsigned Flags, 312 const char *BeginSymName) { 313 return getELFSection(Section, Type, Flags, 0, "", BeginSymName); 314 } 315 316 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 317 unsigned Flags, unsigned EntrySize, 318 StringRef Group) { 319 return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr); 320 } 321 322 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 323 unsigned Flags, unsigned EntrySize, 324 StringRef Group, 325 const char *BeginSymName) { 326 return getELFSection(Section, Type, Flags, EntrySize, Group, ~0, 327 BeginSymName); 328 } 329 330 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 331 unsigned Flags, unsigned EntrySize, 332 StringRef Group, unsigned UniqueID) { 333 return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID, 334 nullptr); 335 } 336 337 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 338 unsigned Flags, unsigned EntrySize, 339 StringRef Group, unsigned UniqueID, 340 const char *BeginSymName); 341 342 const MCSectionELF *getELFSection(StringRef Section, unsigned Type, 343 unsigned Flags, unsigned EntrySize, 344 const MCSymbol *Group, unsigned UniqueID, 345 const char *BeginSymName, 346 const MCSectionELF *Associated); 347 348 const MCSectionELF *createELFRelSection(StringRef Name, unsigned Type, 349 unsigned Flags, unsigned EntrySize, 350 const MCSymbol *Group, 351 const MCSectionELF *Associated); 352 353 void renameELFSection(const MCSectionELF *Section, StringRef Name); 354 355 const MCSectionELF *CreateELFGroupSection(); 356 357 const MCSectionCOFF *getCOFFSection(StringRef Section, 358 unsigned Characteristics, 359 SectionKind Kind, 360 StringRef COMDATSymName, int Selection, 361 const char *BeginSymName = nullptr); 362 363 const MCSectionCOFF *getCOFFSection(StringRef Section, 364 unsigned Characteristics, 365 SectionKind Kind, 366 const char *BeginSymName = nullptr); 367 368 const MCSectionCOFF *getCOFFSection(StringRef Section); 369 370 /// Gets or creates a section equivalent to Sec that is associated with the 371 /// section containing KeySym. For example, to create a debug info section 372 /// associated with an inline function, pass the normal debug info section 373 /// as Sec and the function symbol as KeySym. 374 const MCSectionCOFF *getAssociativeCOFFSection(const MCSectionCOFF *Sec, 375 const MCSymbol *KeySym); 376 377 /// @} 378 379 /// @name Dwarf Management 380 /// @{ 381 382 /// \brief Get the compilation directory for DW_AT_comp_dir 383 /// This can be overridden by clients which want to control the reported 384 /// compilation directory and have it be something other than the current 385 /// working directory. 386 /// Returns an empty string if the current directory cannot be determined. 387 StringRef getCompilationDir() const { return CompilationDir; } 388 389 /// \brief Set the compilation directory for DW_AT_comp_dir 390 /// Override the default (CWD) compilation directory. 391 void setCompilationDir(StringRef S) { CompilationDir = S.str(); } 392 393 /// \brief Get the main file name for use in error messages and debug 394 /// info. This can be set to ensure we've got the correct file name 395 /// after preprocessing or for -save-temps. 396 const std::string &getMainFileName() const { return MainFileName; } 397 398 /// \brief Set the main file name and override the default. 399 void setMainFileName(StringRef S) { MainFileName = S; } 400 401 /// Creates an entry in the dwarf file and directory tables. 402 unsigned GetDwarfFile(StringRef Directory, StringRef FileName, 403 unsigned FileNumber, unsigned CUID); 404 405 bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0); 406 407 const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const { 408 return MCDwarfLineTablesCUMap; 409 } 410 411 MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) { 412 return MCDwarfLineTablesCUMap[CUID]; 413 } 414 415 const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const { 416 auto I = MCDwarfLineTablesCUMap.find(CUID); 417 assert(I != MCDwarfLineTablesCUMap.end()); 418 return I->second; 419 } 420 421 const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) { 422 return getMCDwarfLineTable(CUID).getMCDwarfFiles(); 423 } 424 const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) { 425 return getMCDwarfLineTable(CUID).getMCDwarfDirs(); 426 } 427 428 bool hasMCLineSections() const { 429 for (const auto &Table : MCDwarfLineTablesCUMap) 430 if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel()) 431 return true; 432 return false; 433 } 434 unsigned getDwarfCompileUnitID() { 435 return DwarfCompileUnitID; 436 } 437 void setDwarfCompileUnitID(unsigned CUIndex) { 438 DwarfCompileUnitID = CUIndex; 439 } 440 void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) { 441 getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir); 442 } 443 444 /// Saves the information from the currently parsed dwarf .loc directive 445 /// and sets DwarfLocSeen. When the next instruction is assembled an entry 446 /// in the line number table with this information and the address of the 447 /// instruction will be created. 448 void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column, 449 unsigned Flags, unsigned Isa, 450 unsigned Discriminator) { 451 CurrentDwarfLoc.setFileNum(FileNum); 452 CurrentDwarfLoc.setLine(Line); 453 CurrentDwarfLoc.setColumn(Column); 454 CurrentDwarfLoc.setFlags(Flags); 455 CurrentDwarfLoc.setIsa(Isa); 456 CurrentDwarfLoc.setDiscriminator(Discriminator); 457 DwarfLocSeen = true; 458 } 459 void ClearDwarfLocSeen() { DwarfLocSeen = false; } 460 461 bool getDwarfLocSeen() { return DwarfLocSeen; } 462 const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; } 463 464 bool getGenDwarfForAssembly() { return GenDwarfForAssembly; } 465 void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; } 466 unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; } 467 void setGenDwarfFileNumber(unsigned FileNumber) { 468 GenDwarfFileNumber = FileNumber; 469 } 470 MapVector<const MCSection *, std::pair<MCSymbol *, MCSymbol *> > & 471 getGenDwarfSectionSyms() { 472 return SectionStartEndSyms; 473 } 474 std::pair<MapVector<const MCSection *, 475 std::pair<MCSymbol *, MCSymbol *> >::iterator, 476 bool> 477 addGenDwarfSection(const MCSection *Sec) { 478 return SectionStartEndSyms.insert( 479 std::make_pair(Sec, std::make_pair(nullptr, nullptr))); 480 } 481 void finalizeDwarfSections(MCStreamer &MCOS); 482 const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const { 483 return MCGenDwarfLabelEntries; 484 } 485 void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) { 486 MCGenDwarfLabelEntries.push_back(E); 487 } 488 489 void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; } 490 StringRef getDwarfDebugFlags() { return DwarfDebugFlags; } 491 492 void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; } 493 StringRef getDwarfDebugProducer() { return DwarfDebugProducer; } 494 495 void setDwarfVersion(uint16_t v) { DwarfVersion = v; } 496 uint16_t getDwarfVersion() const { return DwarfVersion; } 497 498 /// @} 499 500 char *getSecureLogFile() { return SecureLogFile; } 501 raw_ostream *getSecureLog() { return SecureLog; } 502 bool getSecureLogUsed() { return SecureLogUsed; } 503 void setSecureLog(raw_ostream *Value) { 504 SecureLog = Value; 505 } 506 void setSecureLogUsed(bool Value) { 507 SecureLogUsed = Value; 508 } 509 510 void *Allocate(unsigned Size, unsigned Align = 8) { 511 return Allocator.Allocate(Size, Align); 512 } 513 void Deallocate(void *Ptr) { 514 } 515 516 // Unrecoverable error has occurred. Display the best diagnostic we can 517 // and bail via exit(1). For now, most MC backend errors are unrecoverable. 518 // FIXME: We should really do something about that. 519 LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg) const; 520 }; 521 522 } // end namespace llvm 523 524 // operator new and delete aren't allowed inside namespaces. 525 // The throw specifications are mandated by the standard. 526 /// @brief Placement new for using the MCContext's allocator. 527 /// 528 /// This placement form of operator new uses the MCContext's allocator for 529 /// obtaining memory. It is a non-throwing new, which means that it returns 530 /// null on error. (If that is what the allocator does. The current does, so if 531 /// this ever changes, this operator will have to be changed, too.) 532 /// Usage looks like this (assuming there's an MCContext 'Context' in scope): 533 /// @code 534 /// // Default alignment (16) 535 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments); 536 /// // Specific alignment 537 /// IntegerLiteral *Ex2 = new (Context, 8) IntegerLiteral(arguments); 538 /// @endcode 539 /// Please note that you cannot use delete on the pointer; it must be 540 /// deallocated using an explicit destructor call followed by 541 /// @c Context.Deallocate(Ptr). 542 /// 543 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 544 /// @param C The MCContext that provides the allocator. 545 /// @param Alignment The alignment of the allocated memory (if the underlying 546 /// allocator supports it). 547 /// @return The allocated memory. Could be NULL. 548 inline void *operator new(size_t Bytes, llvm::MCContext &C, 549 size_t Alignment = 16) throw () { 550 return C.Allocate(Bytes, Alignment); 551 } 552 /// @brief Placement delete companion to the new above. 553 /// 554 /// This operator is just a companion to the new above. There is no way of 555 /// invoking it directly; see the new operator for more details. This operator 556 /// is called implicitly by the compiler if a placement new expression using 557 /// the MCContext throws in the object constructor. 558 inline void operator delete(void *Ptr, llvm::MCContext &C, size_t) 559 throw () { 560 C.Deallocate(Ptr); 561 } 562 563 /// This placement form of operator new[] uses the MCContext's allocator for 564 /// obtaining memory. It is a non-throwing new[], which means that it returns 565 /// null on error. 566 /// Usage looks like this (assuming there's an MCContext 'Context' in scope): 567 /// @code 568 /// // Default alignment (16) 569 /// char *data = new (Context) char[10]; 570 /// // Specific alignment 571 /// char *data = new (Context, 8) char[10]; 572 /// @endcode 573 /// Please note that you cannot use delete on the pointer; it must be 574 /// deallocated using an explicit destructor call followed by 575 /// @c Context.Deallocate(Ptr). 576 /// 577 /// @param Bytes The number of bytes to allocate. Calculated by the compiler. 578 /// @param C The MCContext that provides the allocator. 579 /// @param Alignment The alignment of the allocated memory (if the underlying 580 /// allocator supports it). 581 /// @return The allocated memory. Could be NULL. 582 inline void *operator new[](size_t Bytes, llvm::MCContext& C, 583 size_t Alignment = 16) throw () { 584 return C.Allocate(Bytes, Alignment); 585 } 586 587 /// @brief Placement delete[] companion to the new[] above. 588 /// 589 /// This operator is just a companion to the new[] above. There is no way of 590 /// invoking it directly; see the new[] operator for more details. This operator 591 /// is called implicitly by the compiler if a placement new[] expression using 592 /// the MCContext throws in the object constructor. 593 inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () { 594 C.Deallocate(Ptr); 595 } 596 597 #endif 598