xref: /llvm-project/llvm/lib/MC/XCOFFObjectWriter.cpp (revision a40ca78bb926d8c596036fc93b1c6ca7731c795b)
1 //===-- lib/MC/XCOFFObjectWriter.cpp - XCOFF file writer ------------------===//
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 // This file implements XCOFF object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/BinaryFormat/XCOFF.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCFixup.h"
18 #include "llvm/MC/MCFixupKindInfo.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSectionXCOFF.h"
21 #include "llvm/MC/MCSymbolXCOFF.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/MC/MCXCOFFObjectWriter.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/EndianStream.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 
30 #include <deque>
31 #include <map>
32 
33 using namespace llvm;
34 
35 // An XCOFF object file has a limited set of predefined sections. The most
36 // important ones for us (right now) are:
37 // .text --> contains program code and read-only data.
38 // .data --> contains initialized data, function descriptors, and the TOC.
39 // .bss  --> contains uninitialized data.
40 // Each of these sections is composed of 'Control Sections'. A Control Section
41 // is more commonly referred to as a csect. A csect is an indivisible unit of
42 // code or data, and acts as a container for symbols. A csect is mapped
43 // into a section based on its storage-mapping class, with the exception of
44 // XMC_RW which gets mapped to either .data or .bss based on whether it's
45 // explicitly initialized or not.
46 //
47 // We don't represent the sections in the MC layer as there is nothing
48 // interesting about them at at that level: they carry information that is
49 // only relevant to the ObjectWriter, so we materialize them in this class.
50 namespace {
51 
52 constexpr unsigned DefaultSectionAlign = 4;
53 constexpr int16_t MaxSectionIndex = INT16_MAX;
54 
55 // Packs the csect's alignment and type into a byte.
56 uint8_t getEncodedType(const MCSectionXCOFF *);
57 
58 struct XCOFFRelocation {
59   uint32_t SymbolTableIndex;
60   uint32_t FixupOffsetInCsect;
61   uint8_t SignAndSize;
62   uint8_t Type;
63 };
64 
65 // Wrapper around an MCSymbolXCOFF.
66 struct Symbol {
67   const MCSymbolXCOFF *const MCSym;
68   uint32_t SymbolTableIndex;
69 
70   XCOFF::VisibilityType getVisibilityType() const {
71     return MCSym->getVisibilityType();
72   }
73 
74   XCOFF::StorageClass getStorageClass() const {
75     return MCSym->getStorageClass();
76   }
77   StringRef getSymbolTableName() const { return MCSym->getSymbolTableName(); }
78   Symbol(const MCSymbolXCOFF *MCSym) : MCSym(MCSym), SymbolTableIndex(-1) {}
79 };
80 
81 // Wrapper for an MCSectionXCOFF.
82 // It can be a Csect or debug section or DWARF section and so on.
83 struct XCOFFSection {
84   const MCSectionXCOFF *const MCSec;
85   uint32_t SymbolTableIndex;
86   uint64_t Address;
87   uint64_t Size;
88 
89   SmallVector<Symbol, 1> Syms;
90   SmallVector<XCOFFRelocation, 1> Relocations;
91   StringRef getSymbolTableName() const { return MCSec->getSymbolTableName(); }
92   XCOFF::VisibilityType getVisibilityType() const {
93     return MCSec->getVisibilityType();
94   }
95   XCOFFSection(const MCSectionXCOFF *MCSec)
96       : MCSec(MCSec), SymbolTableIndex(-1), Address(-1), Size(0) {}
97 };
98 
99 // Type to be used for a container representing a set of csects with
100 // (approximately) the same storage mapping class. For example all the csects
101 // with a storage mapping class of `xmc_pr` will get placed into the same
102 // container.
103 using CsectGroup = std::deque<XCOFFSection>;
104 using CsectGroups = std::deque<CsectGroup *>;
105 
106 // The basic section entry defination. This Section represents a section entry
107 // in XCOFF section header table.
108 struct SectionEntry {
109   char Name[XCOFF::NameSize];
110   // The physical/virtual address of the section. For an object file these
111   // values are equivalent, except for in the overflow section header, where
112   // the physical address specifies the number of relocation entries and the
113   // virtual address specifies the number of line number entries.
114   // TODO: Divide Address into PhysicalAddress and VirtualAddress when line
115   // number entries are supported.
116   uint64_t Address;
117   uint64_t Size;
118   uint64_t FileOffsetToData;
119   uint64_t FileOffsetToRelocations;
120   uint32_t RelocationCount;
121   int32_t Flags;
122 
123   int16_t Index;
124 
125   virtual uint64_t advanceFileOffset(const uint64_t MaxRawDataSize,
126                                      const uint64_t RawPointer) {
127     FileOffsetToData = RawPointer;
128     uint64_t NewPointer = RawPointer + Size;
129     if (NewPointer > MaxRawDataSize)
130       report_fatal_error("Section raw data overflowed this object file.");
131     return NewPointer;
132   }
133 
134   // XCOFF has special section numbers for symbols:
135   // -2 Specifies N_DEBUG, a special symbolic debugging symbol.
136   // -1 Specifies N_ABS, an absolute symbol. The symbol has a value but is not
137   // relocatable.
138   //  0 Specifies N_UNDEF, an undefined external symbol.
139   // Therefore, we choose -3 (N_DEBUG - 1) to represent a section index that
140   // hasn't been initialized.
141   static constexpr int16_t UninitializedIndex =
142       XCOFF::ReservedSectionNum::N_DEBUG - 1;
143 
144   SectionEntry(StringRef N, int32_t Flags)
145       : Name(), Address(0), Size(0), FileOffsetToData(0),
146         FileOffsetToRelocations(0), RelocationCount(0), Flags(Flags),
147         Index(UninitializedIndex) {
148     assert(N.size() <= XCOFF::NameSize && "section name too long");
149     memcpy(Name, N.data(), N.size());
150   }
151 
152   virtual void reset() {
153     Address = 0;
154     Size = 0;
155     FileOffsetToData = 0;
156     FileOffsetToRelocations = 0;
157     RelocationCount = 0;
158     Index = UninitializedIndex;
159   }
160 
161   virtual ~SectionEntry() = default;
162 };
163 
164 // Represents the data related to a section excluding the csects that make up
165 // the raw data of the section. The csects are stored separately as not all
166 // sections contain csects, and some sections contain csects which are better
167 // stored separately, e.g. the .data section containing read-write, descriptor,
168 // TOCBase and TOC-entry csects.
169 struct CsectSectionEntry : public SectionEntry {
170   // Virtual sections do not need storage allocated in the object file.
171   const bool IsVirtual;
172 
173   // This is a section containing csect groups.
174   CsectGroups Groups;
175 
176   CsectSectionEntry(StringRef N, XCOFF::SectionTypeFlags Flags, bool IsVirtual,
177                     CsectGroups Groups)
178       : SectionEntry(N, Flags), IsVirtual(IsVirtual), Groups(Groups) {
179     assert(N.size() <= XCOFF::NameSize && "section name too long");
180     memcpy(Name, N.data(), N.size());
181   }
182 
183   void reset() override {
184     SectionEntry::reset();
185     // Clear any csects we have stored.
186     for (auto *Group : Groups)
187       Group->clear();
188   }
189 
190   virtual ~CsectSectionEntry() = default;
191 };
192 
193 struct DwarfSectionEntry : public SectionEntry {
194   // For DWARF section entry.
195   std::unique_ptr<XCOFFSection> DwarfSect;
196 
197   // For DWARF section, we must use real size in the section header. MemorySize
198   // is for the size the DWARF section occupies including paddings.
199   uint32_t MemorySize;
200 
201   // TODO: Remove this override. Loadable sections (e.g., .text, .data) may need
202   // to be aligned. Other sections generally don't need any alignment, but if
203   // they're aligned, the RawPointer should be adjusted before writing the
204   // section. Then a dwarf-specific function wouldn't be needed.
205   uint64_t advanceFileOffset(const uint64_t MaxRawDataSize,
206                              const uint64_t RawPointer) override {
207     FileOffsetToData = RawPointer;
208     uint64_t NewPointer = RawPointer + MemorySize;
209     assert(NewPointer <= MaxRawDataSize &&
210            "Section raw data overflowed this object file.");
211     return NewPointer;
212   }
213 
214   DwarfSectionEntry(StringRef N, int32_t Flags,
215                     std::unique_ptr<XCOFFSection> Sect)
216       : SectionEntry(N, Flags | XCOFF::STYP_DWARF), DwarfSect(std::move(Sect)),
217         MemorySize(0) {
218     assert(DwarfSect->MCSec->isDwarfSect() &&
219            "This should be a DWARF section!");
220     assert(N.size() <= XCOFF::NameSize && "section name too long");
221     memcpy(Name, N.data(), N.size());
222   }
223 
224   DwarfSectionEntry(DwarfSectionEntry &&s) = default;
225 
226   virtual ~DwarfSectionEntry() = default;
227 };
228 
229 struct ExceptionTableEntry {
230   const MCSymbol *Trap;
231   uint64_t TrapAddress = ~0ul;
232   unsigned Lang;
233   unsigned Reason;
234 
235   ExceptionTableEntry(const MCSymbol *Trap, unsigned Lang, unsigned Reason)
236       : Trap(Trap), Lang(Lang), Reason(Reason) {}
237 };
238 
239 struct ExceptionInfo {
240   const MCSymbol *FunctionSymbol;
241   unsigned FunctionSize;
242   std::vector<ExceptionTableEntry> Entries;
243 };
244 
245 struct ExceptionSectionEntry : public SectionEntry {
246   std::map<const StringRef, ExceptionInfo> ExceptionTable;
247   bool isDebugEnabled = false;
248 
249   ExceptionSectionEntry(StringRef N, int32_t Flags)
250       : SectionEntry(N, Flags | XCOFF::STYP_EXCEPT) {
251     assert(N.size() <= XCOFF::NameSize && "Section too long.");
252     memcpy(Name, N.data(), N.size());
253   }
254 
255   virtual ~ExceptionSectionEntry() = default;
256 };
257 
258 struct CInfoSymInfo {
259   // Name of the C_INFO symbol associated with the section
260   std::string Name;
261   std::string Metadata;
262   // Offset into the start of the metadata in the section
263   uint64_t Offset;
264 
265   CInfoSymInfo(std::string Name, std::string Metadata)
266       : Name(Name), Metadata(Metadata) {}
267   // Metadata needs to be padded out to an even word size.
268   uint32_t paddingSize() const {
269     return alignTo(Metadata.size(), sizeof(uint32_t)) - Metadata.size();
270   };
271 
272   // Total size of the entry, including the 4 byte length
273   uint32_t size() const {
274     return Metadata.size() + paddingSize() + sizeof(uint32_t);
275   };
276 };
277 
278 struct CInfoSymSectionEntry : public SectionEntry {
279   std::unique_ptr<CInfoSymInfo> Entry;
280 
281   CInfoSymSectionEntry(StringRef N, int32_t Flags) : SectionEntry(N, Flags) {}
282   virtual ~CInfoSymSectionEntry() = default;
283   void addEntry(std::unique_ptr<CInfoSymInfo> NewEntry) {
284     Entry = std::move(NewEntry);
285     Entry->Offset = sizeof(uint32_t);
286     Size += Entry->size();
287   }
288   void reset() override {
289     SectionEntry::reset();
290     Entry.reset();
291   }
292 };
293 
294 class XCOFFObjectWriter : public MCObjectWriter {
295 
296   uint32_t SymbolTableEntryCount = 0;
297   uint64_t SymbolTableOffset = 0;
298   uint16_t SectionCount = 0;
299   uint32_t PaddingsBeforeDwarf = 0;
300   std::vector<std::pair<std::string, size_t>> FileNames;
301   bool HasVisibility = false;
302 
303   support::endian::Writer W;
304   std::unique_ptr<MCXCOFFObjectTargetWriter> TargetObjectWriter;
305   StringTableBuilder Strings;
306 
307   const uint64_t MaxRawDataSize =
308       TargetObjectWriter->is64Bit() ? UINT64_MAX : UINT32_MAX;
309 
310   // Maps the MCSection representation to its corresponding XCOFFSection
311   // wrapper. Needed for finding the XCOFFSection to insert an MCSymbol into
312   // from its containing MCSectionXCOFF.
313   DenseMap<const MCSectionXCOFF *, XCOFFSection *> SectionMap;
314 
315   // Maps the MCSymbol representation to its corrresponding symbol table index.
316   // Needed for relocation.
317   DenseMap<const MCSymbol *, uint32_t> SymbolIndexMap;
318 
319   // CsectGroups. These store the csects which make up different parts of
320   // the sections. Should have one for each set of csects that get mapped into
321   // the same section and get handled in a 'similar' way.
322   CsectGroup UndefinedCsects;
323   CsectGroup ProgramCodeCsects;
324   CsectGroup ReadOnlyCsects;
325   CsectGroup DataCsects;
326   CsectGroup FuncDSCsects;
327   CsectGroup TOCCsects;
328   CsectGroup BSSCsects;
329   CsectGroup TDataCsects;
330   CsectGroup TBSSCsects;
331 
332   // The Predefined sections.
333   CsectSectionEntry Text;
334   CsectSectionEntry Data;
335   CsectSectionEntry BSS;
336   CsectSectionEntry TData;
337   CsectSectionEntry TBSS;
338 
339   // All the XCOFF sections, in the order they will appear in the section header
340   // table.
341   std::array<CsectSectionEntry *const, 5> Sections{
342       {&Text, &Data, &BSS, &TData, &TBSS}};
343 
344   std::vector<DwarfSectionEntry> DwarfSections;
345   std::vector<SectionEntry> OverflowSections;
346 
347   ExceptionSectionEntry ExceptionSection;
348   CInfoSymSectionEntry CInfoSymSection;
349 
350   CsectGroup &getCsectGroup(const MCSectionXCOFF *MCSec);
351 
352   void reset() override;
353 
354   void executePostLayoutBinding(MCAssembler &) override;
355 
356   void recordRelocation(MCAssembler &, const MCFragment *, const MCFixup &,
357                         MCValue, uint64_t &) override;
358 
359   uint64_t writeObject(MCAssembler &) override;
360 
361   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
362   bool nameShouldBeInStringTable(const StringRef &);
363   void writeSymbolName(const StringRef &);
364   bool auxFileSymNameShouldBeInStringTable(const StringRef &);
365   void writeAuxFileSymName(const StringRef &);
366 
367   void writeSymbolEntryForCsectMemberLabel(const Symbol &SymbolRef,
368                                            const XCOFFSection &CSectionRef,
369                                            int16_t SectionIndex,
370                                            uint64_t SymbolOffset);
371   void writeSymbolEntryForControlSection(const XCOFFSection &CSectionRef,
372                                          int16_t SectionIndex,
373                                          XCOFF::StorageClass StorageClass);
374   void writeSymbolEntryForDwarfSection(const XCOFFSection &DwarfSectionRef,
375                                        int16_t SectionIndex);
376   void writeFileHeader();
377   void writeAuxFileHeader();
378   void writeSectionHeader(const SectionEntry *Sec);
379   void writeSectionHeaderTable();
380   void writeSections(const MCAssembler &Asm);
381   void writeSectionForControlSectionEntry(const MCAssembler &Asm,
382                                           const MCAsmLayout &Layout,
383                                           const CsectSectionEntry &CsectEntry,
384                                           uint64_t &CurrentAddressLocation);
385   void writeSectionForDwarfSectionEntry(const MCAssembler &Asm,
386                                         const MCAsmLayout &Layout,
387                                         const DwarfSectionEntry &DwarfEntry,
388                                         uint64_t &CurrentAddressLocation);
389   void writeSectionForExceptionSectionEntry(
390       const MCAssembler &Asm, const MCAsmLayout &Layout,
391       ExceptionSectionEntry &ExceptionEntry, uint64_t &CurrentAddressLocation);
392   void writeSectionForCInfoSymSectionEntry(const MCAssembler &Asm,
393                                            const MCAsmLayout &Layout,
394                                            CInfoSymSectionEntry &CInfoSymEntry,
395                                            uint64_t &CurrentAddressLocation);
396   void writeSymbolTable(MCAssembler &Asm);
397   void writeSymbolAuxFileEntry(StringRef &Name, uint8_t ftype);
398   void writeSymbolAuxDwarfEntry(uint64_t LengthOfSectionPortion,
399                                 uint64_t NumberOfRelocEnt = 0);
400   void writeSymbolAuxCsectEntry(uint64_t SectionOrLength,
401                                 uint8_t SymbolAlignmentAndType,
402                                 uint8_t StorageMappingClass);
403   void writeSymbolAuxFunctionEntry(uint32_t EntryOffset, uint32_t FunctionSize,
404                                    uint64_t LineNumberPointer,
405                                    uint32_t EndIndex);
406   void writeSymbolAuxExceptionEntry(uint64_t EntryOffset, uint32_t FunctionSize,
407                                     uint32_t EndIndex);
408   void writeSymbolEntry(StringRef SymbolName, uint64_t Value,
409                         int16_t SectionNumber, uint16_t SymbolType,
410                         uint8_t StorageClass, uint8_t NumberOfAuxEntries = 1);
411   void writeRelocations();
412   void writeRelocation(XCOFFRelocation Reloc, const XCOFFSection &Section);
413 
414   // Called after all the csects and symbols have been processed by
415   // `executePostLayoutBinding`, this function handles building up the majority
416   // of the structures in the object file representation. Namely:
417   // *) Calculates physical/virtual addresses, raw-pointer offsets, and section
418   //    sizes.
419   // *) Assigns symbol table indices.
420   // *) Builds up the section header table by adding any non-empty sections to
421   //    `Sections`.
422   void assignAddressesAndIndices(MCAssembler &Asm, const MCAsmLayout &);
423   // Called after relocations are recorded.
424   void finalizeSectionInfo();
425   void finalizeRelocationInfo(SectionEntry *Sec, uint64_t RelCount);
426   void calcOffsetToRelocations(SectionEntry *Sec, uint64_t &RawPointer);
427 
428   void addExceptionEntry(const MCSymbol *Symbol, const MCSymbol *Trap,
429                          unsigned LanguageCode, unsigned ReasonCode,
430                          unsigned FunctionSize, bool hasDebug) override;
431   bool hasExceptionSection() {
432     return !ExceptionSection.ExceptionTable.empty();
433   }
434   unsigned getExceptionSectionSize();
435   unsigned getExceptionOffset(const MCSymbol *Symbol);
436 
437   void addCInfoSymEntry(StringRef Name, StringRef Metadata) override;
438   size_t auxiliaryHeaderSize() const {
439     // 64-bit object files have no auxiliary header.
440     return HasVisibility && !is64Bit() ? XCOFF::AuxFileHeaderSizeShort : 0;
441   }
442 
443 public:
444   XCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
445                     raw_pwrite_stream &OS);
446 
447   void writeWord(uint64_t Word) {
448     is64Bit() ? W.write<uint64_t>(Word) : W.write<uint32_t>(Word);
449   }
450 };
451 
452 XCOFFObjectWriter::XCOFFObjectWriter(
453     std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
454     : W(OS, llvm::endianness::big), TargetObjectWriter(std::move(MOTW)),
455       Strings(StringTableBuilder::XCOFF),
456       Text(".text", XCOFF::STYP_TEXT, /* IsVirtual */ false,
457            CsectGroups{&ProgramCodeCsects, &ReadOnlyCsects}),
458       Data(".data", XCOFF::STYP_DATA, /* IsVirtual */ false,
459            CsectGroups{&DataCsects, &FuncDSCsects, &TOCCsects}),
460       BSS(".bss", XCOFF::STYP_BSS, /* IsVirtual */ true,
461           CsectGroups{&BSSCsects}),
462       TData(".tdata", XCOFF::STYP_TDATA, /* IsVirtual */ false,
463             CsectGroups{&TDataCsects}),
464       TBSS(".tbss", XCOFF::STYP_TBSS, /* IsVirtual */ true,
465            CsectGroups{&TBSSCsects}),
466       ExceptionSection(".except", XCOFF::STYP_EXCEPT),
467       CInfoSymSection(".info", XCOFF::STYP_INFO) {}
468 
469 void XCOFFObjectWriter::reset() {
470   // Clear the mappings we created.
471   SymbolIndexMap.clear();
472   SectionMap.clear();
473 
474   UndefinedCsects.clear();
475   // Reset any sections we have written to, and empty the section header table.
476   for (auto *Sec : Sections)
477     Sec->reset();
478   for (auto &DwarfSec : DwarfSections)
479     DwarfSec.reset();
480   for (auto &OverflowSec : OverflowSections)
481     OverflowSec.reset();
482   ExceptionSection.reset();
483   CInfoSymSection.reset();
484 
485   // Reset states in XCOFFObjectWriter.
486   SymbolTableEntryCount = 0;
487   SymbolTableOffset = 0;
488   SectionCount = 0;
489   PaddingsBeforeDwarf = 0;
490   Strings.clear();
491 
492   MCObjectWriter::reset();
493 }
494 
495 CsectGroup &XCOFFObjectWriter::getCsectGroup(const MCSectionXCOFF *MCSec) {
496   switch (MCSec->getMappingClass()) {
497   case XCOFF::XMC_PR:
498     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
499            "Only an initialized csect can contain program code.");
500     return ProgramCodeCsects;
501   case XCOFF::XMC_RO:
502     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
503            "Only an initialized csect can contain read only data.");
504     return ReadOnlyCsects;
505   case XCOFF::XMC_RW:
506     if (XCOFF::XTY_CM == MCSec->getCSectType())
507       return BSSCsects;
508 
509     if (XCOFF::XTY_SD == MCSec->getCSectType())
510       return DataCsects;
511 
512     report_fatal_error("Unhandled mapping of read-write csect to section.");
513   case XCOFF::XMC_DS:
514     return FuncDSCsects;
515   case XCOFF::XMC_BS:
516     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
517            "Mapping invalid csect. CSECT with bss storage class must be "
518            "common type.");
519     return BSSCsects;
520   case XCOFF::XMC_TL:
521     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
522            "Mapping invalid csect. CSECT with tdata storage class must be "
523            "an initialized csect.");
524     return TDataCsects;
525   case XCOFF::XMC_UL:
526     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
527            "Mapping invalid csect. CSECT with tbss storage class must be "
528            "an uninitialized csect.");
529     return TBSSCsects;
530   case XCOFF::XMC_TC0:
531     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
532            "Only an initialized csect can contain TOC-base.");
533     assert(TOCCsects.empty() &&
534            "We should have only one TOC-base, and it should be the first csect "
535            "in this CsectGroup.");
536     return TOCCsects;
537   case XCOFF::XMC_TC:
538   case XCOFF::XMC_TE:
539     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
540            "A TOC symbol must be an initialized csect.");
541     assert(!TOCCsects.empty() &&
542            "We should at least have a TOC-base in this CsectGroup.");
543     return TOCCsects;
544   case XCOFF::XMC_TD:
545     assert((XCOFF::XTY_SD == MCSec->getCSectType() ||
546             XCOFF::XTY_CM == MCSec->getCSectType()) &&
547            "Symbol type incompatible with toc-data.");
548     assert(!TOCCsects.empty() &&
549            "We should at least have a TOC-base in this CsectGroup.");
550     return TOCCsects;
551   default:
552     report_fatal_error("Unhandled mapping of csect to section.");
553   }
554 }
555 
556 static MCSectionXCOFF *getContainingCsect(const MCSymbolXCOFF *XSym) {
557   if (XSym->isDefined())
558     return cast<MCSectionXCOFF>(XSym->getFragment()->getParent());
559   return XSym->getRepresentedCsect();
560 }
561 
562 void XCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm) {
563   for (const auto &S : Asm) {
564     const auto *MCSec = cast<const MCSectionXCOFF>(&S);
565     assert(!SectionMap.contains(MCSec) && "Cannot add a section twice.");
566 
567     // If the name does not fit in the storage provided in the symbol table
568     // entry, add it to the string table.
569     if (nameShouldBeInStringTable(MCSec->getSymbolTableName()))
570       Strings.add(MCSec->getSymbolTableName());
571     if (MCSec->isCsect()) {
572       // A new control section. Its CsectSectionEntry should already be staticly
573       // generated as Text/Data/BSS/TDATA/TBSS. Add this section to the group of
574       // the CsectSectionEntry.
575       assert(XCOFF::XTY_ER != MCSec->getCSectType() &&
576              "An undefined csect should not get registered.");
577       CsectGroup &Group = getCsectGroup(MCSec);
578       Group.emplace_back(MCSec);
579       SectionMap[MCSec] = &Group.back();
580     } else if (MCSec->isDwarfSect()) {
581       // A new DwarfSectionEntry.
582       std::unique_ptr<XCOFFSection> DwarfSec =
583           std::make_unique<XCOFFSection>(MCSec);
584       SectionMap[MCSec] = DwarfSec.get();
585 
586       DwarfSectionEntry SecEntry(MCSec->getName(),
587                                  *MCSec->getDwarfSubtypeFlags(),
588                                  std::move(DwarfSec));
589       DwarfSections.push_back(std::move(SecEntry));
590     } else
591       llvm_unreachable("unsupport section type!");
592   }
593 
594   for (const MCSymbol &S : Asm.symbols()) {
595     // Nothing to do for temporary symbols.
596     if (S.isTemporary())
597       continue;
598 
599     const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(&S);
600     const MCSectionXCOFF *ContainingCsect = getContainingCsect(XSym);
601 
602     if (XSym->getVisibilityType() != XCOFF::SYM_V_UNSPECIFIED)
603       HasVisibility = true;
604 
605     if (ContainingCsect->getCSectType() == XCOFF::XTY_ER) {
606       // Handle undefined symbol.
607       UndefinedCsects.emplace_back(ContainingCsect);
608       SectionMap[ContainingCsect] = &UndefinedCsects.back();
609       if (nameShouldBeInStringTable(ContainingCsect->getSymbolTableName()))
610         Strings.add(ContainingCsect->getSymbolTableName());
611       continue;
612     }
613 
614     // If the symbol is the csect itself, we don't need to put the symbol
615     // into csect's Syms.
616     if (XSym == ContainingCsect->getQualNameSymbol())
617       continue;
618 
619     // Only put a label into the symbol table when it is an external label.
620     if (!XSym->isExternal())
621       continue;
622 
623     assert(SectionMap.contains(ContainingCsect) &&
624            "Expected containing csect to exist in map");
625     XCOFFSection *Csect = SectionMap[ContainingCsect];
626     // Lookup the containing csect and add the symbol to it.
627     assert(Csect->MCSec->isCsect() && "only csect is supported now!");
628     Csect->Syms.emplace_back(XSym);
629 
630     // If the name does not fit in the storage provided in the symbol table
631     // entry, add it to the string table.
632     if (nameShouldBeInStringTable(XSym->getSymbolTableName()))
633       Strings.add(XSym->getSymbolTableName());
634   }
635 
636   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymSection.Entry;
637   if (CISI && nameShouldBeInStringTable(CISI->Name))
638     Strings.add(CISI->Name);
639 
640   FileNames = Asm.getFileNames();
641   // Emit ".file" as the source file name when there is no file name.
642   if (FileNames.empty())
643     FileNames.emplace_back(".file", 0);
644   for (const std::pair<std::string, size_t> &F : FileNames) {
645     if (auxFileSymNameShouldBeInStringTable(F.first))
646       Strings.add(F.first);
647   }
648 
649   // Always add ".file" to the symbol table. The actual file name will be in
650   // the AUX_FILE auxiliary entry.
651   if (nameShouldBeInStringTable(".file"))
652     Strings.add(".file");
653   StringRef Vers = Asm.getCompilerVersion();
654   if (auxFileSymNameShouldBeInStringTable(Vers))
655     Strings.add(Vers);
656 
657   Strings.finalize();
658   assignAddressesAndIndices(Asm, *Asm.getLayout());
659 }
660 
661 void XCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
662                                          const MCFragment *Fragment,
663                                          const MCFixup &Fixup, MCValue Target,
664                                          uint64_t &FixedValue) {
665   auto getIndex = [this](const MCSymbol *Sym,
666                          const MCSectionXCOFF *ContainingCsect) {
667     // If we could not find the symbol directly in SymbolIndexMap, this symbol
668     // could either be a temporary symbol or an undefined symbol. In this case,
669     // we would need to have the relocation reference its csect instead.
670     return SymbolIndexMap.contains(Sym)
671                ? SymbolIndexMap[Sym]
672                : SymbolIndexMap[ContainingCsect->getQualNameSymbol()];
673   };
674 
675   auto getVirtualAddress =
676       [this, &Asm](const MCSymbol *Sym,
677                    const MCSectionXCOFF *ContainingSect) -> uint64_t {
678     // A DWARF section.
679     if (ContainingSect->isDwarfSect())
680       return Asm.getSymbolOffset(*Sym);
681 
682     // A csect.
683     if (!Sym->isDefined())
684       return SectionMap[ContainingSect]->Address;
685 
686     // A label.
687     assert(Sym->isDefined() && "not a valid object that has address!");
688     return SectionMap[ContainingSect]->Address + Asm.getSymbolOffset(*Sym);
689   };
690 
691   const MCSymbol *const SymA = &Target.getSymA()->getSymbol();
692 
693   MCAsmBackend &Backend = Asm.getBackend();
694   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
695                  MCFixupKindInfo::FKF_IsPCRel;
696 
697   uint8_t Type;
698   uint8_t SignAndSize;
699   std::tie(Type, SignAndSize) =
700       TargetObjectWriter->getRelocTypeAndSignSize(Target, Fixup, IsPCRel);
701 
702   const MCSectionXCOFF *SymASec = getContainingCsect(cast<MCSymbolXCOFF>(SymA));
703   assert(SectionMap.contains(SymASec) &&
704          "Expected containing csect to exist in map.");
705 
706   assert((Fixup.getOffset() <=
707           MaxRawDataSize - Asm.getFragmentOffset(*Fragment)) &&
708          "Fragment offset + fixup offset is overflowed.");
709   uint32_t FixupOffsetInCsect =
710       Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
711 
712   const uint32_t Index = getIndex(SymA, SymASec);
713   if (Type == XCOFF::RelocationType::R_POS ||
714       Type == XCOFF::RelocationType::R_TLS ||
715       Type == XCOFF::RelocationType::R_TLS_LE ||
716       Type == XCOFF::RelocationType::R_TLS_IE ||
717       Type == XCOFF::RelocationType::R_TLS_LD)
718     // The FixedValue should be symbol's virtual address in this object file
719     // plus any constant value that we might get.
720     FixedValue = getVirtualAddress(SymA, SymASec) + Target.getConstant();
721   else if (Type == XCOFF::RelocationType::R_TLSM)
722     // The FixedValue should always be zero since the region handle is only
723     // known at load time.
724     FixedValue = 0;
725   else if (Type == XCOFF::RelocationType::R_TOC ||
726            Type == XCOFF::RelocationType::R_TOCL) {
727     // For non toc-data external symbols, R_TOC type relocation will relocate to
728     // data symbols that have XCOFF::XTY_SD type csect. For toc-data external
729     // symbols, R_TOC type relocation will relocate to data symbols that have
730     // XCOFF_ER type csect. For XCOFF_ER kind symbols, there will be no TOC
731     // entry for them, so the FixedValue should always be 0.
732     if (SymASec->getCSectType() == XCOFF::XTY_ER) {
733       FixedValue = 0;
734     } else {
735       // The FixedValue should be the TOC entry offset from the TOC-base plus
736       // any constant offset value.
737       int64_t TOCEntryOffset = SectionMap[SymASec]->Address -
738                                TOCCsects.front().Address + Target.getConstant();
739       // For small code model, if the TOCEntryOffset overflows the 16-bit value,
740       // we truncate it back down to 16 bits. The linker will be able to insert
741       // fix-up code when needed.
742       // For non toc-data symbols, we already did the truncation in
743       // PPCAsmPrinter.cpp through setting Target.getConstant() in the
744       // expression above by calling getTOCEntryLoadingExprForXCOFF for the
745       // various TOC PseudoOps.
746       // For toc-data symbols, we were not able to calculate the offset from
747       // the TOC in PPCAsmPrinter.cpp since the TOC has not been finalized at
748       // that point, so we are adjusting it here though
749       // llvm::SignExtend64<16>(TOCEntryOffset);
750       // TODO: Since the time that the handling for offsets over 16-bits was
751       // added in PPCAsmPrinter.cpp using getTOCEntryLoadingExprForXCOFF, the
752       // system assembler and linker have been updated to be able to handle the
753       // overflowing offsets, so we no longer need to keep
754       // getTOCEntryLoadingExprForXCOFF.
755       if (Type == XCOFF::RelocationType::R_TOC && !isInt<16>(TOCEntryOffset))
756         TOCEntryOffset = llvm::SignExtend64<16>(TOCEntryOffset);
757 
758       FixedValue = TOCEntryOffset;
759     }
760   } else if (Type == XCOFF::RelocationType::R_RBR) {
761     MCSectionXCOFF *ParentSec = cast<MCSectionXCOFF>(Fragment->getParent());
762     assert((SymASec->getMappingClass() == XCOFF::XMC_PR &&
763             ParentSec->getMappingClass() == XCOFF::XMC_PR) &&
764            "Only XMC_PR csect may have the R_RBR relocation.");
765 
766     // The address of the branch instruction should be the sum of section
767     // address, fragment offset and Fixup offset.
768     uint64_t BRInstrAddress =
769         SectionMap[ParentSec]->Address + FixupOffsetInCsect;
770     // The FixedValue should be the difference between symbol's virtual address
771     // and BR instr address plus any constant value.
772     FixedValue = getVirtualAddress(SymA, SymASec) - BRInstrAddress +
773                  Target.getConstant();
774   } else if (Type == XCOFF::RelocationType::R_REF) {
775     // The FixedValue and FixupOffsetInCsect should always be 0 since it
776     // specifies a nonrelocating reference.
777     FixedValue = 0;
778     FixupOffsetInCsect = 0;
779   }
780 
781   XCOFFRelocation Reloc = {Index, FixupOffsetInCsect, SignAndSize, Type};
782   MCSectionXCOFF *RelocationSec = cast<MCSectionXCOFF>(Fragment->getParent());
783   assert(SectionMap.contains(RelocationSec) &&
784          "Expected containing csect to exist in map.");
785   SectionMap[RelocationSec]->Relocations.push_back(Reloc);
786 
787   if (!Target.getSymB())
788     return;
789 
790   const MCSymbol *const SymB = &Target.getSymB()->getSymbol();
791   if (SymA == SymB)
792     report_fatal_error("relocation for opposite term is not yet supported");
793 
794   const MCSectionXCOFF *SymBSec = getContainingCsect(cast<MCSymbolXCOFF>(SymB));
795   assert(SectionMap.contains(SymBSec) &&
796          "Expected containing csect to exist in map.");
797   if (SymASec == SymBSec)
798     report_fatal_error(
799         "relocation for paired relocatable term is not yet supported");
800 
801   assert(Type == XCOFF::RelocationType::R_POS &&
802          "SymA must be R_POS here if it's not opposite term or paired "
803          "relocatable term.");
804   const uint32_t IndexB = getIndex(SymB, SymBSec);
805   // SymB must be R_NEG here, given the general form of Target(MCValue) is
806   // "SymbolA - SymbolB + imm64".
807   const uint8_t TypeB = XCOFF::RelocationType::R_NEG;
808   XCOFFRelocation RelocB = {IndexB, FixupOffsetInCsect, SignAndSize, TypeB};
809   SectionMap[RelocationSec]->Relocations.push_back(RelocB);
810   // We already folded "SymbolA + imm64" above when Type is R_POS for SymbolA,
811   // now we just need to fold "- SymbolB" here.
812   FixedValue -= getVirtualAddress(SymB, SymBSec);
813 }
814 
815 void XCOFFObjectWriter::writeSections(const MCAssembler &Asm) {
816   auto &Layout = *Asm.getLayout();
817   uint64_t CurrentAddressLocation = 0;
818   for (const auto *Section : Sections)
819     writeSectionForControlSectionEntry(Asm, Layout, *Section,
820                                        CurrentAddressLocation);
821   for (const auto &DwarfSection : DwarfSections)
822     writeSectionForDwarfSectionEntry(Asm, Layout, DwarfSection,
823                                      CurrentAddressLocation);
824   writeSectionForExceptionSectionEntry(Asm, Layout, ExceptionSection,
825                                        CurrentAddressLocation);
826   writeSectionForCInfoSymSectionEntry(Asm, Layout, CInfoSymSection,
827                                       CurrentAddressLocation);
828 }
829 
830 uint64_t XCOFFObjectWriter::writeObject(MCAssembler &Asm) {
831   // We always emit a timestamp of 0 for reproducibility, so ensure incremental
832   // linking is not enabled, in case, like with Windows COFF, such a timestamp
833   // is incompatible with incremental linking of XCOFF.
834   if (Asm.isIncrementalLinkerCompatible())
835     report_fatal_error("Incremental linking not supported for XCOFF.");
836 
837   finalizeSectionInfo();
838   uint64_t StartOffset = W.OS.tell();
839 
840   writeFileHeader();
841   writeAuxFileHeader();
842   writeSectionHeaderTable();
843   writeSections(Asm);
844   writeRelocations();
845   writeSymbolTable(Asm);
846   // Write the string table.
847   Strings.write(W.OS);
848 
849   return W.OS.tell() - StartOffset;
850 }
851 
852 bool XCOFFObjectWriter::nameShouldBeInStringTable(const StringRef &SymbolName) {
853   return SymbolName.size() > XCOFF::NameSize || is64Bit();
854 }
855 
856 void XCOFFObjectWriter::writeSymbolName(const StringRef &SymbolName) {
857   // Magic, Offset or SymbolName.
858   if (nameShouldBeInStringTable(SymbolName)) {
859     W.write<int32_t>(0);
860     W.write<uint32_t>(Strings.getOffset(SymbolName));
861   } else {
862     char Name[XCOFF::NameSize + 1];
863     std::strncpy(Name, SymbolName.data(), XCOFF::NameSize);
864     ArrayRef<char> NameRef(Name, XCOFF::NameSize);
865     W.write(NameRef);
866   }
867 }
868 
869 void XCOFFObjectWriter::writeSymbolEntry(StringRef SymbolName, uint64_t Value,
870                                          int16_t SectionNumber,
871                                          uint16_t SymbolType,
872                                          uint8_t StorageClass,
873                                          uint8_t NumberOfAuxEntries) {
874   if (is64Bit()) {
875     W.write<uint64_t>(Value);
876     W.write<uint32_t>(Strings.getOffset(SymbolName));
877   } else {
878     writeSymbolName(SymbolName);
879     W.write<uint32_t>(Value);
880   }
881   W.write<int16_t>(SectionNumber);
882   W.write<uint16_t>(SymbolType);
883   W.write<uint8_t>(StorageClass);
884   W.write<uint8_t>(NumberOfAuxEntries);
885 }
886 
887 void XCOFFObjectWriter::writeSymbolAuxCsectEntry(uint64_t SectionOrLength,
888                                                  uint8_t SymbolAlignmentAndType,
889                                                  uint8_t StorageMappingClass) {
890   W.write<uint32_t>(is64Bit() ? Lo_32(SectionOrLength) : SectionOrLength);
891   W.write<uint32_t>(0); // ParameterHashIndex
892   W.write<uint16_t>(0); // TypeChkSectNum
893   W.write<uint8_t>(SymbolAlignmentAndType);
894   W.write<uint8_t>(StorageMappingClass);
895   if (is64Bit()) {
896     W.write<uint32_t>(Hi_32(SectionOrLength));
897     W.OS.write_zeros(1); // Reserved
898     W.write<uint8_t>(XCOFF::AUX_CSECT);
899   } else {
900     W.write<uint32_t>(0); // StabInfoIndex
901     W.write<uint16_t>(0); // StabSectNum
902   }
903 }
904 
905 bool XCOFFObjectWriter::auxFileSymNameShouldBeInStringTable(
906     const StringRef &SymbolName) {
907   return SymbolName.size() > XCOFF::AuxFileEntNameSize;
908 }
909 
910 void XCOFFObjectWriter::writeAuxFileSymName(const StringRef &SymbolName) {
911   // Magic, Offset or SymbolName.
912   if (auxFileSymNameShouldBeInStringTable(SymbolName)) {
913     W.write<int32_t>(0);
914     W.write<uint32_t>(Strings.getOffset(SymbolName));
915     W.OS.write_zeros(XCOFF::FileNamePadSize);
916   } else {
917     char Name[XCOFF::AuxFileEntNameSize + 1];
918     std::strncpy(Name, SymbolName.data(), XCOFF::AuxFileEntNameSize);
919     ArrayRef<char> NameRef(Name, XCOFF::AuxFileEntNameSize);
920     W.write(NameRef);
921   }
922 }
923 
924 void XCOFFObjectWriter::writeSymbolAuxFileEntry(StringRef &Name,
925                                                 uint8_t ftype) {
926   writeAuxFileSymName(Name);
927   W.write<uint8_t>(ftype);
928   W.OS.write_zeros(2);
929   if (is64Bit())
930     W.write<uint8_t>(XCOFF::AUX_FILE);
931   else
932     W.OS.write_zeros(1);
933 }
934 
935 void XCOFFObjectWriter::writeSymbolAuxDwarfEntry(
936     uint64_t LengthOfSectionPortion, uint64_t NumberOfRelocEnt) {
937   writeWord(LengthOfSectionPortion);
938   if (!is64Bit())
939     W.OS.write_zeros(4); // Reserved
940   writeWord(NumberOfRelocEnt);
941   if (is64Bit()) {
942     W.OS.write_zeros(1); // Reserved
943     W.write<uint8_t>(XCOFF::AUX_SECT);
944   } else {
945     W.OS.write_zeros(6); // Reserved
946   }
947 }
948 
949 void XCOFFObjectWriter::writeSymbolEntryForCsectMemberLabel(
950     const Symbol &SymbolRef, const XCOFFSection &CSectionRef,
951     int16_t SectionIndex, uint64_t SymbolOffset) {
952   assert(SymbolOffset <= MaxRawDataSize - CSectionRef.Address &&
953          "Symbol address overflowed.");
954 
955   auto Entry = ExceptionSection.ExceptionTable.find(SymbolRef.MCSym->getName());
956   if (Entry != ExceptionSection.ExceptionTable.end()) {
957     writeSymbolEntry(SymbolRef.getSymbolTableName(),
958                      CSectionRef.Address + SymbolOffset, SectionIndex,
959                      // In the old version of the 32-bit XCOFF interpretation,
960                      // symbols may require bit 10 (0x0020) to be set if the
961                      // symbol is a function, otherwise the bit should be 0.
962                      is64Bit() ? SymbolRef.getVisibilityType()
963                                : SymbolRef.getVisibilityType() | 0x0020,
964                      SymbolRef.getStorageClass(),
965                      (is64Bit() && ExceptionSection.isDebugEnabled) ? 3 : 2);
966     if (is64Bit() && ExceptionSection.isDebugEnabled) {
967       // On 64 bit with debugging enabled, we have a csect, exception, and
968       // function auxilliary entries, so we must increment symbol index by 4.
969       writeSymbolAuxExceptionEntry(
970           ExceptionSection.FileOffsetToData +
971               getExceptionOffset(Entry->second.FunctionSymbol),
972           Entry->second.FunctionSize,
973           SymbolIndexMap[Entry->second.FunctionSymbol] + 4);
974     }
975     // For exception section entries, csect and function auxilliary entries
976     // must exist. On 64-bit there is also an exception auxilliary entry.
977     writeSymbolAuxFunctionEntry(
978         ExceptionSection.FileOffsetToData +
979             getExceptionOffset(Entry->second.FunctionSymbol),
980         Entry->second.FunctionSize, 0,
981         (is64Bit() && ExceptionSection.isDebugEnabled)
982             ? SymbolIndexMap[Entry->second.FunctionSymbol] + 4
983             : SymbolIndexMap[Entry->second.FunctionSymbol] + 3);
984   } else {
985     writeSymbolEntry(SymbolRef.getSymbolTableName(),
986                      CSectionRef.Address + SymbolOffset, SectionIndex,
987                      SymbolRef.getVisibilityType(),
988                      SymbolRef.getStorageClass());
989   }
990   writeSymbolAuxCsectEntry(CSectionRef.SymbolTableIndex, XCOFF::XTY_LD,
991                            CSectionRef.MCSec->getMappingClass());
992 }
993 
994 void XCOFFObjectWriter::writeSymbolEntryForDwarfSection(
995     const XCOFFSection &DwarfSectionRef, int16_t SectionIndex) {
996   assert(DwarfSectionRef.MCSec->isDwarfSect() && "Not a DWARF section!");
997 
998   writeSymbolEntry(DwarfSectionRef.getSymbolTableName(), /*Value=*/0,
999                    SectionIndex, /*SymbolType=*/0, XCOFF::C_DWARF);
1000 
1001   writeSymbolAuxDwarfEntry(DwarfSectionRef.Size);
1002 }
1003 
1004 void XCOFFObjectWriter::writeSymbolEntryForControlSection(
1005     const XCOFFSection &CSectionRef, int16_t SectionIndex,
1006     XCOFF::StorageClass StorageClass) {
1007   writeSymbolEntry(CSectionRef.getSymbolTableName(), CSectionRef.Address,
1008                    SectionIndex, CSectionRef.getVisibilityType(), StorageClass);
1009 
1010   writeSymbolAuxCsectEntry(CSectionRef.Size, getEncodedType(CSectionRef.MCSec),
1011                            CSectionRef.MCSec->getMappingClass());
1012 }
1013 
1014 void XCOFFObjectWriter::writeSymbolAuxFunctionEntry(uint32_t EntryOffset,
1015                                                     uint32_t FunctionSize,
1016                                                     uint64_t LineNumberPointer,
1017                                                     uint32_t EndIndex) {
1018   if (is64Bit())
1019     writeWord(LineNumberPointer);
1020   else
1021     W.write<uint32_t>(EntryOffset);
1022   W.write<uint32_t>(FunctionSize);
1023   if (!is64Bit())
1024     writeWord(LineNumberPointer);
1025   W.write<uint32_t>(EndIndex);
1026   if (is64Bit()) {
1027     W.OS.write_zeros(1);
1028     W.write<uint8_t>(XCOFF::AUX_FCN);
1029   } else {
1030     W.OS.write_zeros(2);
1031   }
1032 }
1033 
1034 void XCOFFObjectWriter::writeSymbolAuxExceptionEntry(uint64_t EntryOffset,
1035                                                      uint32_t FunctionSize,
1036                                                      uint32_t EndIndex) {
1037   assert(is64Bit() && "Exception auxilliary entries are 64-bit only.");
1038   W.write<uint64_t>(EntryOffset);
1039   W.write<uint32_t>(FunctionSize);
1040   W.write<uint32_t>(EndIndex);
1041   W.OS.write_zeros(1); // Pad (unused)
1042   W.write<uint8_t>(XCOFF::AUX_EXCEPT);
1043 }
1044 
1045 void XCOFFObjectWriter::writeFileHeader() {
1046   W.write<uint16_t>(is64Bit() ? XCOFF::XCOFF64 : XCOFF::XCOFF32);
1047   W.write<uint16_t>(SectionCount);
1048   W.write<int32_t>(0); // TimeStamp
1049   writeWord(SymbolTableOffset);
1050   if (is64Bit()) {
1051     W.write<uint16_t>(auxiliaryHeaderSize());
1052     W.write<uint16_t>(0); // Flags
1053     W.write<int32_t>(SymbolTableEntryCount);
1054   } else {
1055     W.write<int32_t>(SymbolTableEntryCount);
1056     W.write<uint16_t>(auxiliaryHeaderSize());
1057     W.write<uint16_t>(0); // Flags
1058   }
1059 }
1060 
1061 void XCOFFObjectWriter::writeAuxFileHeader() {
1062   if (!auxiliaryHeaderSize())
1063     return;
1064   W.write<uint16_t>(0); // Magic
1065   W.write<uint16_t>(
1066       XCOFF::NEW_XCOFF_INTERPRET); // Version. The new interpretation of the
1067                                    // n_type field in the symbol table entry is
1068                                    // used in XCOFF32.
1069   W.write<uint32_t>(Sections[0]->Size);    // TextSize
1070   W.write<uint32_t>(Sections[1]->Size);    // InitDataSize
1071   W.write<uint32_t>(Sections[2]->Size);    // BssDataSize
1072   W.write<uint32_t>(0);                    // EntryPointAddr
1073   W.write<uint32_t>(Sections[0]->Address); // TextStartAddr
1074   W.write<uint32_t>(Sections[1]->Address); // DataStartAddr
1075 }
1076 
1077 void XCOFFObjectWriter::writeSectionHeader(const SectionEntry *Sec) {
1078   bool IsDwarf = (Sec->Flags & XCOFF::STYP_DWARF) != 0;
1079   bool IsOvrflo = (Sec->Flags & XCOFF::STYP_OVRFLO) != 0;
1080   // Nothing to write for this Section.
1081   if (Sec->Index == SectionEntry::UninitializedIndex)
1082     return;
1083 
1084   // Write Name.
1085   ArrayRef<char> NameRef(Sec->Name, XCOFF::NameSize);
1086   W.write(NameRef);
1087 
1088   // Write the Physical Address and Virtual Address.
1089   // We use 0 for DWARF sections' Physical and Virtual Addresses.
1090   writeWord(IsDwarf ? 0 : Sec->Address);
1091   // Since line number is not supported, we set it to 0 for overflow sections.
1092   writeWord((IsDwarf || IsOvrflo) ? 0 : Sec->Address);
1093 
1094   writeWord(Sec->Size);
1095   writeWord(Sec->FileOffsetToData);
1096   writeWord(Sec->FileOffsetToRelocations);
1097   writeWord(0); // FileOffsetToLineNumberInfo. Not supported yet.
1098 
1099   if (is64Bit()) {
1100     W.write<uint32_t>(Sec->RelocationCount);
1101     W.write<uint32_t>(0); // NumberOfLineNumbers. Not supported yet.
1102     W.write<int32_t>(Sec->Flags);
1103     W.OS.write_zeros(4);
1104   } else {
1105     // For the overflow section header, s_nreloc provides a reference to the
1106     // primary section header and s_nlnno must have the same value.
1107     // For common section headers, if either of s_nreloc or s_nlnno are set to
1108     // 65535, the other one must also be set to 65535.
1109     W.write<uint16_t>(Sec->RelocationCount);
1110     W.write<uint16_t>((IsOvrflo || Sec->RelocationCount == XCOFF::RelocOverflow)
1111                           ? Sec->RelocationCount
1112                           : 0); // NumberOfLineNumbers. Not supported yet.
1113     W.write<int32_t>(Sec->Flags);
1114   }
1115 }
1116 
1117 void XCOFFObjectWriter::writeSectionHeaderTable() {
1118   for (const auto *CsectSec : Sections)
1119     writeSectionHeader(CsectSec);
1120   for (const auto &DwarfSec : DwarfSections)
1121     writeSectionHeader(&DwarfSec);
1122   for (const auto &OverflowSec : OverflowSections)
1123     writeSectionHeader(&OverflowSec);
1124   if (hasExceptionSection())
1125     writeSectionHeader(&ExceptionSection);
1126   if (CInfoSymSection.Entry)
1127     writeSectionHeader(&CInfoSymSection);
1128 }
1129 
1130 void XCOFFObjectWriter::writeRelocation(XCOFFRelocation Reloc,
1131                                         const XCOFFSection &Section) {
1132   if (Section.MCSec->isCsect())
1133     writeWord(Section.Address + Reloc.FixupOffsetInCsect);
1134   else {
1135     // DWARF sections' address is set to 0.
1136     assert(Section.MCSec->isDwarfSect() && "unsupport section type!");
1137     writeWord(Reloc.FixupOffsetInCsect);
1138   }
1139   W.write<uint32_t>(Reloc.SymbolTableIndex);
1140   W.write<uint8_t>(Reloc.SignAndSize);
1141   W.write<uint8_t>(Reloc.Type);
1142 }
1143 
1144 void XCOFFObjectWriter::writeRelocations() {
1145   for (const auto *Section : Sections) {
1146     if (Section->Index == SectionEntry::UninitializedIndex)
1147       // Nothing to write for this Section.
1148       continue;
1149 
1150     for (const auto *Group : Section->Groups) {
1151       if (Group->empty())
1152         continue;
1153 
1154       for (const auto &Csect : *Group) {
1155         for (const auto Reloc : Csect.Relocations)
1156           writeRelocation(Reloc, Csect);
1157       }
1158     }
1159   }
1160 
1161   for (const auto &DwarfSection : DwarfSections)
1162     for (const auto &Reloc : DwarfSection.DwarfSect->Relocations)
1163       writeRelocation(Reloc, *DwarfSection.DwarfSect);
1164 }
1165 
1166 void XCOFFObjectWriter::writeSymbolTable(MCAssembler &Asm) {
1167   // Write C_FILE symbols.
1168   StringRef Vers = Asm.getCompilerVersion();
1169 
1170   for (const std::pair<std::string, size_t> &F : FileNames) {
1171     // The n_name of a C_FILE symbol is the source file's name when no auxiliary
1172     // entries are present.
1173     StringRef FileName = F.first;
1174 
1175     // For C_FILE symbols, the Source Language ID overlays the high-order byte
1176     // of the SymbolType field, and the CPU Version ID is defined as the
1177     // low-order byte.
1178     // AIX's system assembler determines the source language ID based on the
1179     // source file's name suffix, and the behavior here is consistent with it.
1180     uint8_t LangID;
1181     if (FileName.ends_with(".c"))
1182       LangID = XCOFF::TB_C;
1183     else if (FileName.ends_with_insensitive(".f") ||
1184              FileName.ends_with_insensitive(".f77") ||
1185              FileName.ends_with_insensitive(".f90") ||
1186              FileName.ends_with_insensitive(".f95") ||
1187              FileName.ends_with_insensitive(".f03") ||
1188              FileName.ends_with_insensitive(".f08"))
1189       LangID = XCOFF::TB_Fortran;
1190     else
1191       LangID = XCOFF::TB_CPLUSPLUS;
1192     uint8_t CpuID;
1193     if (is64Bit())
1194       CpuID = XCOFF::TCPU_PPC64;
1195     else
1196       CpuID = XCOFF::TCPU_COM;
1197 
1198     int NumberOfFileAuxEntries = 1;
1199     if (!Vers.empty())
1200       ++NumberOfFileAuxEntries;
1201     writeSymbolEntry(".file", /*Value=*/0, XCOFF::ReservedSectionNum::N_DEBUG,
1202                      /*SymbolType=*/(LangID << 8) | CpuID, XCOFF::C_FILE,
1203                      NumberOfFileAuxEntries);
1204     writeSymbolAuxFileEntry(FileName, XCOFF::XFT_FN);
1205     if (!Vers.empty())
1206       writeSymbolAuxFileEntry(Vers, XCOFF::XFT_CV);
1207   }
1208 
1209   if (CInfoSymSection.Entry)
1210     writeSymbolEntry(CInfoSymSection.Entry->Name, CInfoSymSection.Entry->Offset,
1211                      CInfoSymSection.Index,
1212                      /*SymbolType=*/0, XCOFF::C_INFO,
1213                      /*NumberOfAuxEntries=*/0);
1214 
1215   for (const auto &Csect : UndefinedCsects) {
1216     writeSymbolEntryForControlSection(Csect, XCOFF::ReservedSectionNum::N_UNDEF,
1217                                       Csect.MCSec->getStorageClass());
1218   }
1219 
1220   for (const auto *Section : Sections) {
1221     if (Section->Index == SectionEntry::UninitializedIndex)
1222       // Nothing to write for this Section.
1223       continue;
1224 
1225     for (const auto *Group : Section->Groups) {
1226       if (Group->empty())
1227         continue;
1228 
1229       const int16_t SectionIndex = Section->Index;
1230       for (const auto &Csect : *Group) {
1231         // Write out the control section first and then each symbol in it.
1232         writeSymbolEntryForControlSection(Csect, SectionIndex,
1233                                           Csect.MCSec->getStorageClass());
1234 
1235         for (const auto &Sym : Csect.Syms)
1236           writeSymbolEntryForCsectMemberLabel(
1237               Sym, Csect, SectionIndex, Asm.getSymbolOffset(*(Sym.MCSym)));
1238       }
1239     }
1240   }
1241 
1242   for (const auto &DwarfSection : DwarfSections)
1243     writeSymbolEntryForDwarfSection(*DwarfSection.DwarfSect,
1244                                     DwarfSection.Index);
1245 }
1246 
1247 void XCOFFObjectWriter::finalizeRelocationInfo(SectionEntry *Sec,
1248                                                uint64_t RelCount) {
1249   // Handles relocation field overflows in an XCOFF32 file. An XCOFF64 file
1250   // may not contain an overflow section header.
1251   if (!is64Bit() && (RelCount >= static_cast<uint32_t>(XCOFF::RelocOverflow))) {
1252     // Generate an overflow section header.
1253     SectionEntry SecEntry(".ovrflo", XCOFF::STYP_OVRFLO);
1254 
1255     // This field specifies the file section number of the section header that
1256     // overflowed.
1257     SecEntry.RelocationCount = Sec->Index;
1258 
1259     // This field specifies the number of relocation entries actually
1260     // required.
1261     SecEntry.Address = RelCount;
1262     SecEntry.Index = ++SectionCount;
1263     OverflowSections.push_back(std::move(SecEntry));
1264 
1265     // The field in the primary section header is always 65535
1266     // (XCOFF::RelocOverflow).
1267     Sec->RelocationCount = XCOFF::RelocOverflow;
1268   } else {
1269     Sec->RelocationCount = RelCount;
1270   }
1271 }
1272 
1273 void XCOFFObjectWriter::calcOffsetToRelocations(SectionEntry *Sec,
1274                                                 uint64_t &RawPointer) {
1275   if (!Sec->RelocationCount)
1276     return;
1277 
1278   Sec->FileOffsetToRelocations = RawPointer;
1279   uint64_t RelocationSizeInSec = 0;
1280   if (!is64Bit() &&
1281       Sec->RelocationCount == static_cast<uint32_t>(XCOFF::RelocOverflow)) {
1282     // Find its corresponding overflow section.
1283     for (auto &OverflowSec : OverflowSections) {
1284       if (OverflowSec.RelocationCount == static_cast<uint32_t>(Sec->Index)) {
1285         RelocationSizeInSec =
1286             OverflowSec.Address * XCOFF::RelocationSerializationSize32;
1287 
1288         // This field must have the same values as in the corresponding
1289         // primary section header.
1290         OverflowSec.FileOffsetToRelocations = Sec->FileOffsetToRelocations;
1291       }
1292     }
1293     assert(RelocationSizeInSec && "Overflow section header doesn't exist.");
1294   } else {
1295     RelocationSizeInSec = Sec->RelocationCount *
1296                           (is64Bit() ? XCOFF::RelocationSerializationSize64
1297                                      : XCOFF::RelocationSerializationSize32);
1298   }
1299 
1300   RawPointer += RelocationSizeInSec;
1301   if (RawPointer > MaxRawDataSize)
1302     report_fatal_error("Relocation data overflowed this object file.");
1303 }
1304 
1305 void XCOFFObjectWriter::finalizeSectionInfo() {
1306   for (auto *Section : Sections) {
1307     if (Section->Index == SectionEntry::UninitializedIndex)
1308       // Nothing to record for this Section.
1309       continue;
1310 
1311     uint64_t RelCount = 0;
1312     for (const auto *Group : Section->Groups) {
1313       if (Group->empty())
1314         continue;
1315 
1316       for (auto &Csect : *Group)
1317         RelCount += Csect.Relocations.size();
1318     }
1319     finalizeRelocationInfo(Section, RelCount);
1320   }
1321 
1322   for (auto &DwarfSection : DwarfSections)
1323     finalizeRelocationInfo(&DwarfSection,
1324                            DwarfSection.DwarfSect->Relocations.size());
1325 
1326   // Calculate the RawPointer value for all headers.
1327   uint64_t RawPointer =
1328       (is64Bit() ? (XCOFF::FileHeaderSize64 +
1329                     SectionCount * XCOFF::SectionHeaderSize64)
1330                  : (XCOFF::FileHeaderSize32 +
1331                     SectionCount * XCOFF::SectionHeaderSize32)) +
1332       auxiliaryHeaderSize();
1333 
1334   // Calculate the file offset to the section data.
1335   for (auto *Sec : Sections) {
1336     if (Sec->Index == SectionEntry::UninitializedIndex || Sec->IsVirtual)
1337       continue;
1338 
1339     RawPointer = Sec->advanceFileOffset(MaxRawDataSize, RawPointer);
1340   }
1341 
1342   if (!DwarfSections.empty()) {
1343     RawPointer += PaddingsBeforeDwarf;
1344     for (auto &DwarfSection : DwarfSections) {
1345       RawPointer = DwarfSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1346     }
1347   }
1348 
1349   if (hasExceptionSection())
1350     RawPointer = ExceptionSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1351 
1352   if (CInfoSymSection.Entry)
1353     RawPointer = CInfoSymSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1354 
1355   for (auto *Sec : Sections) {
1356     if (Sec->Index != SectionEntry::UninitializedIndex)
1357       calcOffsetToRelocations(Sec, RawPointer);
1358   }
1359 
1360   for (auto &DwarfSec : DwarfSections)
1361     calcOffsetToRelocations(&DwarfSec, RawPointer);
1362 
1363   // TODO Error check that the number of symbol table entries fits in 32-bits
1364   // signed ...
1365   if (SymbolTableEntryCount)
1366     SymbolTableOffset = RawPointer;
1367 }
1368 
1369 void XCOFFObjectWriter::addExceptionEntry(
1370     const MCSymbol *Symbol, const MCSymbol *Trap, unsigned LanguageCode,
1371     unsigned ReasonCode, unsigned FunctionSize, bool hasDebug) {
1372   // If a module had debug info, debugging is enabled and XCOFF emits the
1373   // exception auxilliary entry.
1374   if (hasDebug)
1375     ExceptionSection.isDebugEnabled = true;
1376   auto Entry = ExceptionSection.ExceptionTable.find(Symbol->getName());
1377   if (Entry != ExceptionSection.ExceptionTable.end()) {
1378     Entry->second.Entries.push_back(
1379         ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1380     return;
1381   }
1382   ExceptionInfo NewEntry;
1383   NewEntry.FunctionSymbol = Symbol;
1384   NewEntry.FunctionSize = FunctionSize;
1385   NewEntry.Entries.push_back(
1386       ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1387   ExceptionSection.ExceptionTable.insert(
1388       std::pair<const StringRef, ExceptionInfo>(Symbol->getName(), NewEntry));
1389 }
1390 
1391 unsigned XCOFFObjectWriter::getExceptionSectionSize() {
1392   unsigned EntryNum = 0;
1393 
1394   for (auto it = ExceptionSection.ExceptionTable.begin();
1395        it != ExceptionSection.ExceptionTable.end(); ++it)
1396     // The size() gets +1 to account for the initial entry containing the
1397     // symbol table index.
1398     EntryNum += it->second.Entries.size() + 1;
1399 
1400   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1401                                : XCOFF::ExceptionSectionEntrySize32);
1402 }
1403 
1404 unsigned XCOFFObjectWriter::getExceptionOffset(const MCSymbol *Symbol) {
1405   unsigned EntryNum = 0;
1406   for (auto it = ExceptionSection.ExceptionTable.begin();
1407        it != ExceptionSection.ExceptionTable.end(); ++it) {
1408     if (Symbol == it->second.FunctionSymbol)
1409       break;
1410     EntryNum += it->second.Entries.size() + 1;
1411   }
1412   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1413                                : XCOFF::ExceptionSectionEntrySize32);
1414 }
1415 
1416 void XCOFFObjectWriter::addCInfoSymEntry(StringRef Name, StringRef Metadata) {
1417   assert(!CInfoSymSection.Entry && "Multiple entries are not supported");
1418   CInfoSymSection.addEntry(
1419       std::make_unique<CInfoSymInfo>(Name.str(), Metadata.str()));
1420 }
1421 
1422 void XCOFFObjectWriter::assignAddressesAndIndices(MCAssembler &Asm,
1423                                                   const MCAsmLayout &Layout) {
1424   // The symbol table starts with all the C_FILE symbols. Each C_FILE symbol
1425   // requires 1 or 2 auxiliary entries.
1426   uint32_t SymbolTableIndex =
1427       (2 + (Asm.getCompilerVersion().empty() ? 0 : 1)) * FileNames.size();
1428 
1429   if (CInfoSymSection.Entry)
1430     SymbolTableIndex++;
1431 
1432   // Calculate indices for undefined symbols.
1433   for (auto &Csect : UndefinedCsects) {
1434     Csect.Size = 0;
1435     Csect.Address = 0;
1436     Csect.SymbolTableIndex = SymbolTableIndex;
1437     SymbolIndexMap[Csect.MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1438     // 1 main and 1 auxiliary symbol table entry for each contained symbol.
1439     SymbolTableIndex += 2;
1440   }
1441 
1442   // The address corrresponds to the address of sections and symbols in the
1443   // object file. We place the shared address 0 immediately after the
1444   // section header table.
1445   uint64_t Address = 0;
1446   // Section indices are 1-based in XCOFF.
1447   int32_t SectionIndex = 1;
1448   bool HasTDataSection = false;
1449 
1450   for (auto *Section : Sections) {
1451     const bool IsEmpty =
1452         llvm::all_of(Section->Groups,
1453                      [](const CsectGroup *Group) { return Group->empty(); });
1454     if (IsEmpty)
1455       continue;
1456 
1457     if (SectionIndex > MaxSectionIndex)
1458       report_fatal_error("Section index overflow!");
1459     Section->Index = SectionIndex++;
1460     SectionCount++;
1461 
1462     bool SectionAddressSet = false;
1463     // Reset the starting address to 0 for TData section.
1464     if (Section->Flags == XCOFF::STYP_TDATA) {
1465       Address = 0;
1466       HasTDataSection = true;
1467     }
1468     // Reset the starting address to 0 for TBSS section if the object file does
1469     // not contain TData Section.
1470     if ((Section->Flags == XCOFF::STYP_TBSS) && !HasTDataSection)
1471       Address = 0;
1472 
1473     for (auto *Group : Section->Groups) {
1474       if (Group->empty())
1475         continue;
1476 
1477       for (auto &Csect : *Group) {
1478         const MCSectionXCOFF *MCSec = Csect.MCSec;
1479         Csect.Address = alignTo(Address, MCSec->getAlign());
1480         Csect.Size = Asm.getSectionAddressSize(*MCSec);
1481         Address = Csect.Address + Csect.Size;
1482         Csect.SymbolTableIndex = SymbolTableIndex;
1483         SymbolIndexMap[MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1484         // 1 main and 1 auxiliary symbol table entry for the csect.
1485         SymbolTableIndex += 2;
1486 
1487         for (auto &Sym : Csect.Syms) {
1488           bool hasExceptEntry = false;
1489           auto Entry =
1490               ExceptionSection.ExceptionTable.find(Sym.MCSym->getName());
1491           if (Entry != ExceptionSection.ExceptionTable.end()) {
1492             hasExceptEntry = true;
1493             for (auto &TrapEntry : Entry->second.Entries) {
1494               TrapEntry.TrapAddress = Layout.getSymbolOffset(*(Sym.MCSym)) +
1495                                       TrapEntry.Trap->getOffset();
1496             }
1497           }
1498           Sym.SymbolTableIndex = SymbolTableIndex;
1499           SymbolIndexMap[Sym.MCSym] = Sym.SymbolTableIndex;
1500           // 1 main and 1 auxiliary symbol table entry for each contained
1501           // symbol. For symbols with exception section entries, a function
1502           // auxilliary entry is needed, and on 64-bit XCOFF with debugging
1503           // enabled, an additional exception auxilliary entry is needed.
1504           SymbolTableIndex += 2;
1505           if (hasExceptionSection() && hasExceptEntry) {
1506             if (is64Bit() && ExceptionSection.isDebugEnabled)
1507               SymbolTableIndex += 2;
1508             else
1509               SymbolTableIndex += 1;
1510           }
1511         }
1512       }
1513 
1514       if (!SectionAddressSet) {
1515         Section->Address = Group->front().Address;
1516         SectionAddressSet = true;
1517       }
1518     }
1519 
1520     // Make sure the address of the next section aligned to
1521     // DefaultSectionAlign.
1522     Address = alignTo(Address, DefaultSectionAlign);
1523     Section->Size = Address - Section->Address;
1524   }
1525 
1526   // Start to generate DWARF sections. Sections other than DWARF section use
1527   // DefaultSectionAlign as the default alignment, while DWARF sections have
1528   // their own alignments. If these two alignments are not the same, we need
1529   // some paddings here and record the paddings bytes for FileOffsetToData
1530   // calculation.
1531   if (!DwarfSections.empty())
1532     PaddingsBeforeDwarf =
1533         alignTo(Address,
1534                 (*DwarfSections.begin()).DwarfSect->MCSec->getAlign()) -
1535         Address;
1536 
1537   DwarfSectionEntry *LastDwarfSection = nullptr;
1538   for (auto &DwarfSection : DwarfSections) {
1539     assert((SectionIndex <= MaxSectionIndex) && "Section index overflow!");
1540 
1541     XCOFFSection &DwarfSect = *DwarfSection.DwarfSect;
1542     const MCSectionXCOFF *MCSec = DwarfSect.MCSec;
1543 
1544     // Section index.
1545     DwarfSection.Index = SectionIndex++;
1546     SectionCount++;
1547 
1548     // Symbol index.
1549     DwarfSect.SymbolTableIndex = SymbolTableIndex;
1550     SymbolIndexMap[MCSec->getQualNameSymbol()] = DwarfSect.SymbolTableIndex;
1551     // 1 main and 1 auxiliary symbol table entry for the csect.
1552     SymbolTableIndex += 2;
1553 
1554     // Section address. Make it align to section alignment.
1555     // We use address 0 for DWARF sections' Physical and Virtual Addresses.
1556     // This address is used to tell where is the section in the final object.
1557     // See writeSectionForDwarfSectionEntry().
1558     DwarfSection.Address = DwarfSect.Address =
1559         alignTo(Address, MCSec->getAlign());
1560 
1561     // Section size.
1562     // For DWARF section, we must use the real size which may be not aligned.
1563     DwarfSection.Size = DwarfSect.Size = Asm.getSectionAddressSize(*MCSec);
1564 
1565     Address = DwarfSection.Address + DwarfSection.Size;
1566 
1567     if (LastDwarfSection)
1568       LastDwarfSection->MemorySize =
1569           DwarfSection.Address - LastDwarfSection->Address;
1570     LastDwarfSection = &DwarfSection;
1571   }
1572   if (LastDwarfSection) {
1573     // Make the final DWARF section address align to the default section
1574     // alignment for follow contents.
1575     Address = alignTo(LastDwarfSection->Address + LastDwarfSection->Size,
1576                       DefaultSectionAlign);
1577     LastDwarfSection->MemorySize = Address - LastDwarfSection->Address;
1578   }
1579   if (hasExceptionSection()) {
1580     ExceptionSection.Index = SectionIndex++;
1581     SectionCount++;
1582     ExceptionSection.Address = 0;
1583     ExceptionSection.Size = getExceptionSectionSize();
1584     Address += ExceptionSection.Size;
1585     Address = alignTo(Address, DefaultSectionAlign);
1586   }
1587 
1588   if (CInfoSymSection.Entry) {
1589     CInfoSymSection.Index = SectionIndex++;
1590     SectionCount++;
1591     CInfoSymSection.Address = 0;
1592     Address += CInfoSymSection.Size;
1593     Address = alignTo(Address, DefaultSectionAlign);
1594   }
1595 
1596   SymbolTableEntryCount = SymbolTableIndex;
1597 }
1598 
1599 void XCOFFObjectWriter::writeSectionForControlSectionEntry(
1600     const MCAssembler &Asm, const MCAsmLayout &Layout,
1601     const CsectSectionEntry &CsectEntry, uint64_t &CurrentAddressLocation) {
1602   // Nothing to write for this Section.
1603   if (CsectEntry.Index == SectionEntry::UninitializedIndex)
1604     return;
1605 
1606   // There could be a gap (without corresponding zero padding) between
1607   // sections.
1608   // There could be a gap (without corresponding zero padding) between
1609   // sections.
1610   assert(((CurrentAddressLocation <= CsectEntry.Address) ||
1611           (CsectEntry.Flags == XCOFF::STYP_TDATA) ||
1612           (CsectEntry.Flags == XCOFF::STYP_TBSS)) &&
1613          "CurrentAddressLocation should be less than or equal to section "
1614          "address if the section is not TData or TBSS.");
1615 
1616   CurrentAddressLocation = CsectEntry.Address;
1617 
1618   // For virtual sections, nothing to write. But need to increase
1619   // CurrentAddressLocation for later sections like DWARF section has a correct
1620   // writing location.
1621   if (CsectEntry.IsVirtual) {
1622     CurrentAddressLocation += CsectEntry.Size;
1623     return;
1624   }
1625 
1626   for (const auto &Group : CsectEntry.Groups) {
1627     for (const auto &Csect : *Group) {
1628       if (uint32_t PaddingSize = Csect.Address - CurrentAddressLocation)
1629         W.OS.write_zeros(PaddingSize);
1630       if (Csect.Size)
1631         Asm.writeSectionData(W.OS, Csect.MCSec);
1632       CurrentAddressLocation = Csect.Address + Csect.Size;
1633     }
1634   }
1635 
1636   // The size of the tail padding in a section is the end virtual address of
1637   // the current section minus the end virtual address of the last csect
1638   // in that section.
1639   if (uint64_t PaddingSize =
1640           CsectEntry.Address + CsectEntry.Size - CurrentAddressLocation) {
1641     W.OS.write_zeros(PaddingSize);
1642     CurrentAddressLocation += PaddingSize;
1643   }
1644 }
1645 
1646 void XCOFFObjectWriter::writeSectionForDwarfSectionEntry(
1647     const MCAssembler &Asm, const MCAsmLayout &Layout,
1648     const DwarfSectionEntry &DwarfEntry, uint64_t &CurrentAddressLocation) {
1649   // There could be a gap (without corresponding zero padding) between
1650   // sections. For example DWARF section alignment is bigger than
1651   // DefaultSectionAlign.
1652   assert(CurrentAddressLocation <= DwarfEntry.Address &&
1653          "CurrentAddressLocation should be less than or equal to section "
1654          "address.");
1655 
1656   if (uint64_t PaddingSize = DwarfEntry.Address - CurrentAddressLocation)
1657     W.OS.write_zeros(PaddingSize);
1658 
1659   if (DwarfEntry.Size)
1660     Asm.writeSectionData(W.OS, DwarfEntry.DwarfSect->MCSec);
1661 
1662   CurrentAddressLocation = DwarfEntry.Address + DwarfEntry.Size;
1663 
1664   // DWARF section size is not aligned to DefaultSectionAlign.
1665   // Make sure CurrentAddressLocation is aligned to DefaultSectionAlign.
1666   uint32_t Mod = CurrentAddressLocation % DefaultSectionAlign;
1667   uint32_t TailPaddingSize = Mod ? DefaultSectionAlign - Mod : 0;
1668   if (TailPaddingSize)
1669     W.OS.write_zeros(TailPaddingSize);
1670 
1671   CurrentAddressLocation += TailPaddingSize;
1672 }
1673 
1674 void XCOFFObjectWriter::writeSectionForExceptionSectionEntry(
1675     const MCAssembler &Asm, const MCAsmLayout &Layout,
1676     ExceptionSectionEntry &ExceptionEntry, uint64_t &CurrentAddressLocation) {
1677   for (auto it = ExceptionEntry.ExceptionTable.begin();
1678        it != ExceptionEntry.ExceptionTable.end(); it++) {
1679     // For every symbol that has exception entries, you must start the entries
1680     // with an initial symbol table index entry
1681     W.write<uint32_t>(SymbolIndexMap[it->second.FunctionSymbol]);
1682     if (is64Bit()) {
1683       // 4-byte padding on 64-bit.
1684       W.OS.write_zeros(4);
1685     }
1686     W.OS.write_zeros(2);
1687     for (auto &TrapEntry : it->second.Entries) {
1688       writeWord(TrapEntry.TrapAddress);
1689       W.write<uint8_t>(TrapEntry.Lang);
1690       W.write<uint8_t>(TrapEntry.Reason);
1691     }
1692   }
1693 
1694   CurrentAddressLocation += getExceptionSectionSize();
1695 }
1696 
1697 void XCOFFObjectWriter::writeSectionForCInfoSymSectionEntry(
1698     const MCAssembler &Asm, const MCAsmLayout &Layout,
1699     CInfoSymSectionEntry &CInfoSymEntry, uint64_t &CurrentAddressLocation) {
1700   if (!CInfoSymSection.Entry)
1701     return;
1702 
1703   constexpr int WordSize = sizeof(uint32_t);
1704   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymEntry.Entry;
1705   const std::string &Metadata = CISI->Metadata;
1706 
1707   // Emit the 4-byte length of the metadata.
1708   W.write<uint32_t>(Metadata.size());
1709 
1710   if (Metadata.size() == 0)
1711     return;
1712 
1713   // Write out the payload one word at a time.
1714   size_t Index = 0;
1715   while (Index + WordSize <= Metadata.size()) {
1716     uint32_t NextWord =
1717         llvm::support::endian::read32be(Metadata.data() + Index);
1718     W.write<uint32_t>(NextWord);
1719     Index += WordSize;
1720   }
1721 
1722   // If there is padding, we have at least one byte of payload left to emit.
1723   if (CISI->paddingSize()) {
1724     std::array<uint8_t, WordSize> LastWord = {0};
1725     ::memcpy(LastWord.data(), Metadata.data() + Index, Metadata.size() - Index);
1726     W.write<uint32_t>(llvm::support::endian::read32be(LastWord.data()));
1727   }
1728 
1729   CurrentAddressLocation += CISI->size();
1730 }
1731 
1732 // Takes the log base 2 of the alignment and shifts the result into the 5 most
1733 // significant bits of a byte, then or's in the csect type into the least
1734 // significant 3 bits.
1735 uint8_t getEncodedType(const MCSectionXCOFF *Sec) {
1736   unsigned Log2Align = Log2(Sec->getAlign());
1737   // Result is a number in the range [0, 31] which fits in the 5 least
1738   // significant bits. Shift this value into the 5 most significant bits, and
1739   // bitwise-or in the csect type.
1740   uint8_t EncodedAlign = Log2Align << 3;
1741   return EncodedAlign | Sec->getCSectType();
1742 }
1743 
1744 } // end anonymous namespace
1745 
1746 std::unique_ptr<MCObjectWriter>
1747 llvm::createXCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
1748                               raw_pwrite_stream &OS) {
1749   return std::make_unique<XCOFFObjectWriter>(std::move(MOTW), OS);
1750 }
1751