1 #include "llvm/ADT/MapVector.h"
2 #include "llvm/ADT/STLExtras.h"
3 #include "llvm/ADT/StringSet.h"
4 #include "llvm/CodeGen/AsmPrinter.h"
5 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
6 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
7 #include "llvm/MC/MCAsmInfo.h"
8 #include "llvm/MC/MCContext.h"
9 #include "llvm/MC/MCInstrInfo.h"
10 #include "llvm/MC/MCObjectFileInfo.h"
11 #include "llvm/MC/MCRegisterInfo.h"
12 #include "llvm/MC/MCSectionELF.h"
13 #include "llvm/MC/MCStreamer.h"
14 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
15 #include "llvm/Object/ObjectFile.h"
16 #include "llvm/Support/Compression.h"
17 #include "llvm/Support/DataExtractor.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Options.h"
22 #include "llvm/Support/TargetRegistry.h"
23 #include "llvm/Support/TargetSelect.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include <list>
27 #include <iostream>
28 #include <memory>
29 #include <system_error>
30 #include <unordered_set>
31 
32 using namespace llvm;
33 using namespace llvm::object;
34 using namespace cl;
35 
36 OptionCategory DwpCategory("Specific Options");
37 static list<std::string> InputFiles(Positional, OneOrMore,
38                                     desc("<input files>"), cat(DwpCategory));
39 
40 static opt<std::string> OutputFilename(Required, "o",
41                                        desc("Specify the output file."),
42                                        value_desc("filename"),
43                                        cat(DwpCategory));
44 
45 static int error(const Twine &Error, const Twine &Context) {
46   errs() << Twine("while processing ") + Context + ":\n";
47   errs() << Twine("error: ") + Error + "\n";
48   return 1;
49 }
50 
51 static std::error_code
52 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
53                        uint32_t &StringOffset, MCSection *StrSection,
54                        MCSection *StrOffsetSection, StringRef CurStrSection,
55                        StringRef CurStrOffsetSection) {
56   // Could possibly produce an error or warning if one of these was non-null but
57   // the other was null.
58   if (CurStrSection.empty() || CurStrOffsetSection.empty())
59     return std::error_code();
60 
61   DenseMap<uint32_t, uint32_t> OffsetRemapping;
62 
63   DataExtractor Data(CurStrSection, true, 0);
64   uint32_t LocalOffset = 0;
65   uint32_t PrevOffset = 0;
66   while (const char *s = Data.getCStr(&LocalOffset)) {
67     StringRef Str(s, LocalOffset - PrevOffset - 1);
68     auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
69     if (Pair.second) {
70       Out.SwitchSection(StrSection);
71       Out.EmitBytes(
72           StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
73       StringOffset += Str.size() + 1;
74     }
75     OffsetRemapping[PrevOffset] = Pair.first->second;
76     PrevOffset = LocalOffset;
77   }
78 
79   Data = DataExtractor(CurStrOffsetSection, true, 0);
80 
81   Out.SwitchSection(StrOffsetSection);
82 
83   uint32_t Offset = 0;
84   uint64_t Size = CurStrOffsetSection.size();
85   while (Offset < Size) {
86     auto OldOffset = Data.getU32(&Offset);
87     auto NewOffset = OffsetRemapping[OldOffset];
88     Out.EmitIntValue(NewOffset, 4);
89   }
90 
91   return std::error_code();
92 }
93 
94 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
95   uint64_t CurCode;
96   uint32_t Offset = 0;
97   DataExtractor AbbrevData(Abbrev, true, 0);
98   while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
99     // Tag
100     AbbrevData.getULEB128(&Offset);
101     // DW_CHILDREN
102     AbbrevData.getU8(&Offset);
103     // Attributes
104     while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
105       ;
106   }
107   return Offset;
108 }
109 
110 static const char *getCUName(StringRef Abbrev, StringRef Info,
111                              StringRef StrOffsets, StringRef Str) {
112   uint32_t Offset = 0;
113   DataExtractor InfoData(Info, true, 0);
114   InfoData.getU32(&Offset); // Length
115   uint16_t Version = InfoData.getU16(&Offset);
116   InfoData.getU32(&Offset); // Abbrev offset (should be zero)
117   uint8_t AddrSize = InfoData.getU8(&Offset);
118 
119   uint32_t AbbrCode = InfoData.getULEB128(&Offset);
120 
121   DataExtractor AbbrevData(Abbrev, true, 0);
122   uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
123   uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
124   (void)Tag;
125   // FIXME: Real error handling
126   assert(Tag == dwarf::DW_TAG_compile_unit);
127   // DW_CHILDREN
128   AbbrevData.getU8(&AbbrevOffset);
129   uint32_t Name;
130   uint32_t Form;
131   while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
132              (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
133          Name != dwarf::DW_AT_name) {
134     DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
135   }
136   // FIXME: Real error handling
137   assert(Name == dwarf::DW_AT_name);
138   auto StrIndex = InfoData.getULEB128(&Offset);
139 
140   DataExtractor StrOffsetsData(StrOffsets, true, 0);
141   uint32_t StrOffsetsOffset = 4 * StrIndex;
142   uint32_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset);
143   DataExtractor StrData(Str, true, 0);
144   return StrData.getCStr(&StrOffset);
145 }
146 
147 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
148   uint32_t Offset = 0;
149   DataExtractor InfoData(Info, true, 0);
150   InfoData.getU32(&Offset); // Length
151   uint16_t Version = InfoData.getU16(&Offset);
152   InfoData.getU32(&Offset); // Abbrev offset (should be zero)
153   uint8_t AddrSize = InfoData.getU8(&Offset);
154 
155   uint32_t AbbrCode = InfoData.getULEB128(&Offset);
156 
157   DataExtractor AbbrevData(Abbrev, true, 0);
158   uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
159   uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
160   (void)Tag;
161   // FIXME: Real error handling
162   assert(Tag == dwarf::DW_TAG_compile_unit);
163   // DW_CHILDREN
164   AbbrevData.getU8(&AbbrevOffset);
165   uint32_t Name;
166   uint32_t Form;
167   while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
168              (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
169          Name != dwarf::DW_AT_GNU_dwo_id) {
170     DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
171   }
172   // FIXME: Real error handling
173   assert(Name == dwarf::DW_AT_GNU_dwo_id);
174   return InfoData.getU64(&Offset);
175 }
176 
177 struct UnitIndexEntry {
178   DWARFUnitIndex::Entry::SectionContribution Contributions[8];
179   std::string Name;
180   StringRef DWPName;
181 };
182 
183 StringRef getSubsection(StringRef Section, const DWARFUnitIndex::Entry &Entry, DWARFSectionKind Kind) {
184   const auto *Off = Entry.getOffset(Kind);
185   if (!Off)
186     return StringRef();
187   return Section.substr(Off->Offset, Off->Length);
188 }
189 
190 static void addAllTypesFromDWP(
191     MCStreamer &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
192     const DWARFUnitIndex &TUIndex, MCSection *OutputTypes, StringRef Types,
193     const UnitIndexEntry &TUEntry, uint32_t &TypesOffset) {
194   Out.SwitchSection(OutputTypes);
195   for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) {
196     auto *I = E.getOffsets();
197     if (!I)
198       continue;
199     auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry));
200     if (!P.second)
201       continue;
202     auto &Entry = P.first->second;
203     // Zero out the debug_info contribution
204     Entry.Contributions[0] = {};
205     for (auto Kind : TUIndex.getColumnKinds()) {
206       auto &C = Entry.Contributions[Kind - DW_SECT_INFO];
207       C.Offset += I->Offset;
208       C.Length = I->Length;
209       ++I;
210     }
211     auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
212     Out.EmitBytes(Types.substr(
213         C.Offset - TUEntry.Contributions[DW_SECT_TYPES - DW_SECT_INFO].Offset,
214         C.Length));
215     C.Offset = TypesOffset;
216     TypesOffset += C.Length;
217   }
218 }
219 
220 static void addAllTypes(MCStreamer &Out,
221                         MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
222                         MCSection *OutputTypes, StringRef Types,
223                         const UnitIndexEntry &CUEntry, uint32_t &TypesOffset) {
224   if (Types.empty())
225     return;
226 
227   Out.SwitchSection(OutputTypes);
228   uint32_t Offset = 0;
229   DataExtractor Data(Types, true, 0);
230   while (Data.isValidOffset(Offset)) {
231     UnitIndexEntry Entry = CUEntry;
232     // Zero out the debug_info contribution
233     Entry.Contributions[0] = {};
234     auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
235     C.Offset = TypesOffset;
236     auto PrevOffset = Offset;
237     // Length of the unit, including the 4 byte length field.
238     C.Length = Data.getU32(&Offset) + 4;
239 
240     Data.getU16(&Offset); // Version
241     Data.getU32(&Offset); // Abbrev offset
242     Data.getU8(&Offset);  // Address size
243     auto Signature = Data.getU64(&Offset);
244     Offset = PrevOffset + C.Length;
245 
246     auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry));
247     if (!P.second)
248       continue;
249 
250     Out.EmitBytes(Types.substr(PrevOffset, C.Length));
251     TypesOffset += C.Length;
252   }
253 }
254 
255 static void
256 writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
257                 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
258                 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
259   for (const auto &E : IndexEntries)
260     for (size_t i = 0; i != array_lengthof(E.second.Contributions); ++i)
261       if (ContributionOffsets[i])
262         Out.EmitIntValue(E.second.Contributions[i].*Field, 4);
263 }
264 
265 static void
266 writeIndex(MCStreamer &Out, MCSection *Section,
267            ArrayRef<unsigned> ContributionOffsets,
268            const MapVector<uint64_t, UnitIndexEntry> &IndexEntries) {
269   if (IndexEntries.empty())
270     return;
271 
272   unsigned Columns = 0;
273   for (auto &C : ContributionOffsets)
274     if (C)
275       ++Columns;
276 
277   std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
278   uint64_t Mask = Buckets.size() - 1;
279   size_t i = 0;
280   for (const auto &P : IndexEntries) {
281     auto S = P.first;
282     auto H = S & Mask;
283     while (Buckets[H]) {
284       assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&
285              "Duplicate unit");
286       H = (H + (((S >> 32) & Mask) | 1)) % Buckets.size();
287     }
288     Buckets[H] = i + 1;
289     ++i;
290   }
291 
292   Out.SwitchSection(Section);
293   Out.EmitIntValue(2, 4);                   // Version
294   Out.EmitIntValue(Columns, 4);             // Columns
295   Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
296   Out.EmitIntValue(Buckets.size(), 4);      // Num Buckets
297 
298   // Write the signatures.
299   for (const auto &I : Buckets)
300     Out.EmitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
301 
302   // Write the indexes.
303   for (const auto &I : Buckets)
304     Out.EmitIntValue(I, 4);
305 
306   // Write the column headers (which sections will appear in the table)
307   for (size_t i = 0; i != ContributionOffsets.size(); ++i)
308     if (ContributionOffsets[i])
309       Out.EmitIntValue(i + DW_SECT_INFO, 4);
310 
311   // Write the offsets.
312   writeIndexTable(Out, ContributionOffsets, IndexEntries,
313                   &DWARFUnitIndex::Entry::SectionContribution::Offset);
314 
315   // Write the lengths.
316   writeIndexTable(Out, ContributionOffsets, IndexEntries,
317                   &DWARFUnitIndex::Entry::SectionContribution::Length);
318 }
319 static bool consumeCompressedDebugSectionHeader(StringRef &data,
320                                                 uint64_t &OriginalSize) {
321   // Consume "ZLIB" prefix.
322   if (!data.startswith("ZLIB"))
323     return false;
324   data = data.substr(4);
325   // Consume uncompressed section size (big-endian 8 bytes).
326   DataExtractor extractor(data, false, 8);
327   uint32_t Offset = 0;
328   OriginalSize = extractor.getU64(&Offset);
329   if (Offset == 0)
330     return false;
331   data = data.substr(Offset);
332   return true;
333 }
334 
335 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
336   const auto &MCOFI = *Out.getContext().getObjectFileInfo();
337   MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
338   MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
339   MCSection *const TypesSection = MCOFI.getDwarfTypesDWOSection();
340   MCSection *const CUIndexSection = MCOFI.getDwarfCUIndexSection();
341   MCSection *const TUIndexSection = MCOFI.getDwarfTUIndexSection();
342   const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
343       {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
344       {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
345       {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
346       {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
347       {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
348       {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
349       {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}},
350       {"debug_cu_index", {CUIndexSection, static_cast<DWARFSectionKind>(0)}},
351       {"debug_tu_index", {TUIndexSection, static_cast<DWARFSectionKind>(0)}}};
352 
353   MapVector<uint64_t, UnitIndexEntry> IndexEntries;
354   MapVector<uint64_t, UnitIndexEntry> TypeIndexEntries;
355 
356   StringMap<uint32_t> Strings;
357   uint32_t StringOffset = 0;
358 
359   uint32_t ContributionOffsets[8] = {};
360 
361   for (const auto &Input : Inputs) {
362     auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
363     if (!ErrOrObj)
364       return ErrOrObj.getError();
365 
366     UnitIndexEntry CurEntry = {};
367 
368     StringRef CurStrSection;
369     StringRef CurStrOffsetSection;
370     StringRef CurTypesSection;
371     StringRef InfoSection;
372     StringRef AbbrevSection;
373     StringRef CurCUIndexSection;
374     StringRef CurTUIndexSection;
375 
376     SmallVector<SmallString<32>, 4> UncompressedSections;
377 
378     for (const auto &Section : ErrOrObj->getBinary()->sections()) {
379       if (Section.isBSS())
380         continue;
381       if (Section.isVirtual())
382         continue;
383 
384       StringRef Name;
385       if (std::error_code Err = Section.getName(Name))
386         return Err;
387 
388       Name = Name.substr(Name.find_first_not_of("._"));
389 
390       StringRef Contents;
391       if (auto Err = Section.getContents(Contents))
392         return Err;
393 
394       if (Name.startswith("zdebug_")) {
395         uint64_t OriginalSize;
396         if (!zlib::isAvailable() ||
397             !consumeCompressedDebugSectionHeader(Contents, OriginalSize))
398           return make_error_code(std::errc::invalid_argument);
399         UncompressedSections.resize(UncompressedSections.size() + 1);
400         if (zlib::uncompress(Contents, UncompressedSections.back(), OriginalSize) !=
401             zlib::StatusOK) {
402           UncompressedSections.pop_back();
403           continue;
404         }
405         Name = Name.substr(1);
406         Contents = UncompressedSections.back();
407       }
408 
409       auto SectionPair = KnownSections.find(Name);
410       if (SectionPair == KnownSections.end())
411         continue;
412 
413       if (DWARFSectionKind Kind = SectionPair->second.second) {
414         auto Index = Kind - DW_SECT_INFO;
415         if (Kind != DW_SECT_TYPES) {
416           CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
417           ContributionOffsets[Index] +=
418               (CurEntry.Contributions[Index].Length = Contents.size());
419         }
420 
421         switch (Kind) {
422         case DW_SECT_INFO:
423           InfoSection = Contents;
424           break;
425         case DW_SECT_ABBREV:
426           AbbrevSection = Contents;
427           break;
428         default:
429           break;
430         }
431       }
432 
433       MCSection *OutSection = SectionPair->second.first;
434       if (OutSection == StrOffsetSection)
435         CurStrOffsetSection = Contents;
436       else if (OutSection == StrSection)
437         CurStrSection = Contents;
438       else if (OutSection == TypesSection)
439         CurTypesSection = Contents;
440       else if (OutSection == CUIndexSection)
441         CurCUIndexSection = Contents;
442       else if (OutSection == TUIndexSection)
443         CurTUIndexSection = Contents;
444       else {
445         Out.SwitchSection(OutSection);
446         Out.EmitBytes(Contents);
447       }
448     }
449 
450     if (InfoSection.empty())
451       continue;
452 
453     if (!CurCUIndexSection.empty()) {
454       DWARFUnitIndex CUIndex(DW_SECT_INFO);
455       DataExtractor CUIndexData(CurCUIndexSection,
456                                 ErrOrObj->getBinary()->isLittleEndian(), 0);
457       if (!CUIndex.parse(CUIndexData))
458         return make_error_code(std::errc::invalid_argument);
459 
460       for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
461         auto *I = E.getOffsets();
462         if (!I)
463           continue;
464         auto P =
465             IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
466         const char* Name = getCUName(
467             getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
468             getSubsection(InfoSection, E, DW_SECT_INFO),
469             getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
470             CurStrSection);
471         if (!P.second) {
472           auto &PrevE = *P.first;
473           std::cerr << "Duplicate DWO ID (" << PrevE.first << ") in '" << PrevE.second.Name << "' ";
474           if (!PrevE.second.DWPName.empty())
475             std::cerr << "(from '" << PrevE.second.DWPName.str() << "') ";
476           std::cerr << "and '" << Name << "' (from '" << Input << "')\n";
477           return make_error_code(std::errc::invalid_argument);
478         }
479         auto &NewEntry = P.first->second;
480         NewEntry.Name = Name;
481         NewEntry.DWPName = Input;
482         for (auto Kind : CUIndex.getColumnKinds()) {
483           auto &C = NewEntry.Contributions[Kind - DW_SECT_INFO];
484           C.Offset += I->Offset;
485           C.Length = I->Length;
486           ++I;
487         }
488       }
489 
490       if (!CurTypesSection.empty()) {
491         if (CurTUIndexSection.empty())
492           return make_error_code(std::errc::invalid_argument);
493         DWARFUnitIndex TUIndex(DW_SECT_TYPES);
494         DataExtractor TUIndexData(CurTUIndexSection,
495                                   ErrOrObj->getBinary()->isLittleEndian(), 0);
496         if (!TUIndex.parse(TUIndexData))
497           return make_error_code(std::errc::invalid_argument);
498         addAllTypesFromDWP(Out, TypeIndexEntries, TUIndex, TypesSection,
499                            CurTypesSection, CurEntry,
500                            ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
501       }
502     } else {
503       auto P = IndexEntries.insert(
504           std::make_pair(getCUSignature(AbbrevSection, InfoSection), CurEntry));
505       const char *Name = getCUName(AbbrevSection, InfoSection,
506                                    CurStrOffsetSection, CurStrSection);
507       if (!P.second) {
508         auto &E = *P.first;
509         std::cerr << "Duplicate DWO ID (" << E.first << ") in '" << Name
510                   << "' ";
511         if (!E.second.DWPName.empty())
512           std::cerr << "(from '" << E.second.DWPName.str() << "') ";
513         std::cerr << "and '" << E.second.Name << "'\n";
514         return make_error_code(std::errc::invalid_argument);
515       }
516       P.first->second.Name = Name;
517       addAllTypes(Out, TypeIndexEntries, TypesSection, CurTypesSection,
518                   CurEntry, ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
519     }
520 
521     if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
522                                           StrSection, StrOffsetSection,
523                                           CurStrSection, CurStrOffsetSection))
524       return Err;
525   }
526 
527   // Lie about there being no info contributions so the TU index only includes
528   // the type unit contribution
529   ContributionOffsets[0] = 0;
530   writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
531              TypeIndexEntries);
532 
533   // Lie about the type contribution
534   ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
535   // Unlie about the info contribution
536   ContributionOffsets[0] = 1;
537 
538   writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
539              IndexEntries);
540 
541   return std::error_code();
542 }
543 
544 int main(int argc, char **argv) {
545 
546   ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
547 
548   llvm::InitializeAllTargetInfos();
549   llvm::InitializeAllTargetMCs();
550   llvm::InitializeAllTargets();
551   llvm::InitializeAllAsmPrinters();
552 
553   std::string ErrorStr;
554   StringRef Context = "dwarf streamer init";
555 
556   Triple TheTriple("x86_64-linux-gnu");
557 
558   // Get the target.
559   const Target *TheTarget =
560       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
561   if (!TheTarget)
562     return error(ErrorStr, Context);
563   std::string TripleName = TheTriple.getTriple();
564 
565   // Create all the MC Objects.
566   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
567   if (!MRI)
568     return error(Twine("no register info for target ") + TripleName, Context);
569 
570   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
571   if (!MAI)
572     return error("no asm info for target " + TripleName, Context);
573 
574   MCObjectFileInfo MOFI;
575   MCContext MC(MAI.get(), MRI.get(), &MOFI);
576   MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default, MC);
577 
578   auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
579   if (!MAB)
580     return error("no asm backend for target " + TripleName, Context);
581 
582   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
583   if (!MII)
584     return error("no instr info info for target " + TripleName, Context);
585 
586   std::unique_ptr<MCSubtargetInfo> MSTI(
587       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
588   if (!MSTI)
589     return error("no subtarget info for target " + TripleName, Context);
590 
591   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
592   if (!MCE)
593     return error("no code emitter for target " + TripleName, Context);
594 
595   // Create the output file.
596   std::error_code EC;
597   raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
598   if (EC)
599     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
600 
601   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
602   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
603       TheTriple, MC, *MAB, OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
604       MCOptions.MCIncrementalLinkerCompatible,
605       /*DWARFMustBeAtTheEnd*/ false));
606   if (!MS)
607     return error("no object streamer for target " + TripleName, Context);
608 
609   if (auto Err = write(*MS, InputFiles))
610     return error(Err.message(), "Writing DWP file");
611 
612   MS->Finish();
613 }
614