CodeViewDebug.cpp 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  1. //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains support for writing Microsoft CodeView debug info.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeViewDebug.h"
  14. #include "DwarfExpression.h"
  15. #include "llvm/ADT/APSInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/TinyPtrVector.h"
  27. #include "llvm/ADT/Triple.h"
  28. #include "llvm/ADT/Twine.h"
  29. #include "llvm/BinaryFormat/COFF.h"
  30. #include "llvm/BinaryFormat/Dwarf.h"
  31. #include "llvm/CodeGen/AsmPrinter.h"
  32. #include "llvm/CodeGen/LexicalScopes.h"
  33. #include "llvm/CodeGen/MachineFunction.h"
  34. #include "llvm/CodeGen/MachineInstr.h"
  35. #include "llvm/CodeGen/MachineModuleInfo.h"
  36. #include "llvm/CodeGen/MachineOperand.h"
  37. #include "llvm/CodeGen/TargetFrameLowering.h"
  38. #include "llvm/CodeGen/TargetLoweringObjectFile.h"
  39. #include "llvm/CodeGen/TargetRegisterInfo.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/Config/llvm-config.h"
  42. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  43. #include "llvm/DebugInfo/CodeView/CodeView.h"
  44. #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
  45. #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
  46. #include "llvm/DebugInfo/CodeView/Line.h"
  47. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  48. #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
  49. #include "llvm/DebugInfo/CodeView/TypeIndex.h"
  50. #include "llvm/DebugInfo/CodeView/TypeRecord.h"
  51. #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
  52. #include "llvm/IR/Constants.h"
  53. #include "llvm/IR/DataLayout.h"
  54. #include "llvm/IR/DebugInfoMetadata.h"
  55. #include "llvm/IR/DebugLoc.h"
  56. #include "llvm/IR/Function.h"
  57. #include "llvm/IR/GlobalValue.h"
  58. #include "llvm/IR/GlobalVariable.h"
  59. #include "llvm/IR/Metadata.h"
  60. #include "llvm/IR/Module.h"
  61. #include "llvm/MC/MCAsmInfo.h"
  62. #include "llvm/MC/MCContext.h"
  63. #include "llvm/MC/MCSectionCOFF.h"
  64. #include "llvm/MC/MCStreamer.h"
  65. #include "llvm/MC/MCSymbol.h"
  66. #include "llvm/Support/BinaryByteStream.h"
  67. #include "llvm/Support/BinaryStreamReader.h"
  68. #include "llvm/Support/Casting.h"
  69. #include "llvm/Support/CommandLine.h"
  70. #include "llvm/Support/Compiler.h"
  71. #include "llvm/Support/Endian.h"
  72. #include "llvm/Support/Error.h"
  73. #include "llvm/Support/ErrorHandling.h"
  74. #include "llvm/Support/FormatVariadic.h"
  75. #include "llvm/Support/SMLoc.h"
  76. #include "llvm/Support/ScopedPrinter.h"
  77. #include "llvm/Target/TargetMachine.h"
  78. #include <algorithm>
  79. #include <cassert>
  80. #include <cctype>
  81. #include <cstddef>
  82. #include <cstdint>
  83. #include <iterator>
  84. #include <limits>
  85. #include <string>
  86. #include <utility>
  87. #include <vector>
  88. using namespace llvm;
  89. using namespace llvm::codeview;
  90. static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
  91. cl::ReallyHidden, cl::init(false));
  92. CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
  93. : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
  94. // If module doesn't have named metadata anchors or COFF debug section
  95. // is not available, skip any debug info related stuff.
  96. if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
  97. !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
  98. Asm = nullptr;
  99. return;
  100. }
  101. // Tell MMI that we have debug info.
  102. MMI->setDebugInfoAvailability(true);
  103. }
  104. StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
  105. std::string &Filepath = FileToFilepathMap[File];
  106. if (!Filepath.empty())
  107. return Filepath;
  108. StringRef Dir = File->getDirectory(), Filename = File->getFilename();
  109. // Clang emits directory and relative filename info into the IR, but CodeView
  110. // operates on full paths. We could change Clang to emit full paths too, but
  111. // that would increase the IR size and probably not needed for other users.
  112. // For now, just concatenate and canonicalize the path here.
  113. if (Filename.find(':') == 1)
  114. Filepath = Filename;
  115. else
  116. Filepath = (Dir + "\\" + Filename).str();
  117. // Canonicalize the path. We have to do it textually because we may no longer
  118. // have access the file in the filesystem.
  119. // First, replace all slashes with backslashes.
  120. std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
  121. // Remove all "\.\" with "\".
  122. size_t Cursor = 0;
  123. while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
  124. Filepath.erase(Cursor, 2);
  125. // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
  126. // path should be well-formatted, e.g. start with a drive letter, etc.
  127. Cursor = 0;
  128. while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
  129. // Something's wrong if the path starts with "\..\", abort.
  130. if (Cursor == 0)
  131. break;
  132. size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
  133. if (PrevSlash == std::string::npos)
  134. // Something's wrong, abort.
  135. break;
  136. Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
  137. // The next ".." might be following the one we've just erased.
  138. Cursor = PrevSlash;
  139. }
  140. // Remove all duplicate backslashes.
  141. Cursor = 0;
  142. while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
  143. Filepath.erase(Cursor, 1);
  144. return Filepath;
  145. }
  146. unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
  147. StringRef FullPath = getFullFilepath(F);
  148. unsigned NextId = FileIdMap.size() + 1;
  149. auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
  150. if (Insertion.second) {
  151. // We have to compute the full filepath and emit a .cv_file directive.
  152. std::string Checksum = fromHex(F->getChecksum());
  153. void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
  154. memcpy(CKMem, Checksum.data(), Checksum.size());
  155. ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
  156. Checksum.size());
  157. DIFile::ChecksumKind ChecksumKind = F->getChecksumKind();
  158. bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
  159. static_cast<unsigned>(ChecksumKind));
  160. (void)Success;
  161. assert(Success && ".cv_file directive failed");
  162. }
  163. return Insertion.first->second;
  164. }
  165. CodeViewDebug::InlineSite &
  166. CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
  167. const DISubprogram *Inlinee) {
  168. auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
  169. InlineSite *Site = &SiteInsertion.first->second;
  170. if (SiteInsertion.second) {
  171. unsigned ParentFuncId = CurFn->FuncId;
  172. if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
  173. ParentFuncId =
  174. getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
  175. .SiteFuncId;
  176. Site->SiteFuncId = NextFuncId++;
  177. OS.EmitCVInlineSiteIdDirective(
  178. Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
  179. InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
  180. Site->Inlinee = Inlinee;
  181. InlinedSubprograms.insert(Inlinee);
  182. getFuncIdForSubprogram(Inlinee);
  183. }
  184. return *Site;
  185. }
  186. static StringRef getPrettyScopeName(const DIScope *Scope) {
  187. StringRef ScopeName = Scope->getName();
  188. if (!ScopeName.empty())
  189. return ScopeName;
  190. switch (Scope->getTag()) {
  191. case dwarf::DW_TAG_enumeration_type:
  192. case dwarf::DW_TAG_class_type:
  193. case dwarf::DW_TAG_structure_type:
  194. case dwarf::DW_TAG_union_type:
  195. return "<unnamed-tag>";
  196. case dwarf::DW_TAG_namespace:
  197. return "`anonymous namespace'";
  198. }
  199. return StringRef();
  200. }
  201. static const DISubprogram *getQualifiedNameComponents(
  202. const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
  203. const DISubprogram *ClosestSubprogram = nullptr;
  204. while (Scope != nullptr) {
  205. if (ClosestSubprogram == nullptr)
  206. ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
  207. StringRef ScopeName = getPrettyScopeName(Scope);
  208. if (!ScopeName.empty())
  209. QualifiedNameComponents.push_back(ScopeName);
  210. Scope = Scope->getScope().resolve();
  211. }
  212. return ClosestSubprogram;
  213. }
  214. static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
  215. StringRef TypeName) {
  216. std::string FullyQualifiedName;
  217. for (StringRef QualifiedNameComponent :
  218. llvm::reverse(QualifiedNameComponents)) {
  219. FullyQualifiedName.append(QualifiedNameComponent);
  220. FullyQualifiedName.append("::");
  221. }
  222. FullyQualifiedName.append(TypeName);
  223. return FullyQualifiedName;
  224. }
  225. static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
  226. SmallVector<StringRef, 5> QualifiedNameComponents;
  227. getQualifiedNameComponents(Scope, QualifiedNameComponents);
  228. return getQualifiedName(QualifiedNameComponents, Name);
  229. }
  230. struct CodeViewDebug::TypeLoweringScope {
  231. TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
  232. ~TypeLoweringScope() {
  233. // Don't decrement TypeEmissionLevel until after emitting deferred types, so
  234. // inner TypeLoweringScopes don't attempt to emit deferred types.
  235. if (CVD.TypeEmissionLevel == 1)
  236. CVD.emitDeferredCompleteTypes();
  237. --CVD.TypeEmissionLevel;
  238. }
  239. CodeViewDebug &CVD;
  240. };
  241. static std::string getFullyQualifiedName(const DIScope *Ty) {
  242. const DIScope *Scope = Ty->getScope().resolve();
  243. return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
  244. }
  245. TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
  246. // No scope means global scope and that uses the zero index.
  247. if (!Scope || isa<DIFile>(Scope))
  248. return TypeIndex();
  249. assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
  250. // Check if we've already translated this scope.
  251. auto I = TypeIndices.find({Scope, nullptr});
  252. if (I != TypeIndices.end())
  253. return I->second;
  254. // Build the fully qualified name of the scope.
  255. std::string ScopeName = getFullyQualifiedName(Scope);
  256. StringIdRecord SID(TypeIndex(), ScopeName);
  257. auto TI = TypeTable.writeLeafType(SID);
  258. return recordTypeIndexForDINode(Scope, TI);
  259. }
  260. TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
  261. assert(SP);
  262. // Check if we've already translated this subprogram.
  263. auto I = TypeIndices.find({SP, nullptr});
  264. if (I != TypeIndices.end())
  265. return I->second;
  266. // The display name includes function template arguments. Drop them to match
  267. // MSVC.
  268. StringRef DisplayName = SP->getName().split('<').first;
  269. const DIScope *Scope = SP->getScope().resolve();
  270. TypeIndex TI;
  271. if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
  272. // If the scope is a DICompositeType, then this must be a method. Member
  273. // function types take some special handling, and require access to the
  274. // subprogram.
  275. TypeIndex ClassType = getTypeIndex(Class);
  276. MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
  277. DisplayName);
  278. TI = TypeTable.writeLeafType(MFuncId);
  279. } else {
  280. // Otherwise, this must be a free function.
  281. TypeIndex ParentScope = getScopeIndex(Scope);
  282. FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
  283. TI = TypeTable.writeLeafType(FuncId);
  284. }
  285. return recordTypeIndexForDINode(SP, TI);
  286. }
  287. TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
  288. const DICompositeType *Class) {
  289. // Always use the method declaration as the key for the function type. The
  290. // method declaration contains the this adjustment.
  291. if (SP->getDeclaration())
  292. SP = SP->getDeclaration();
  293. assert(!SP->getDeclaration() && "should use declaration as key");
  294. // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
  295. // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
  296. auto I = TypeIndices.find({SP, Class});
  297. if (I != TypeIndices.end())
  298. return I->second;
  299. // Make sure complete type info for the class is emitted *after* the member
  300. // function type, as the complete class type is likely to reference this
  301. // member function type.
  302. TypeLoweringScope S(*this);
  303. const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
  304. TypeIndex TI = lowerTypeMemberFunction(
  305. SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
  306. return recordTypeIndexForDINode(SP, TI, Class);
  307. }
  308. TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
  309. TypeIndex TI,
  310. const DIType *ClassTy) {
  311. auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
  312. (void)InsertResult;
  313. assert(InsertResult.second && "DINode was already assigned a type index");
  314. return TI;
  315. }
  316. unsigned CodeViewDebug::getPointerSizeInBytes() {
  317. return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
  318. }
  319. void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
  320. const DILocation *InlinedAt) {
  321. if (InlinedAt) {
  322. // This variable was inlined. Associate it with the InlineSite.
  323. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
  324. InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
  325. Site.InlinedLocals.emplace_back(Var);
  326. } else {
  327. // This variable goes in the main ProcSym.
  328. CurFn->Locals.emplace_back(Var);
  329. }
  330. }
  331. static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
  332. const DILocation *Loc) {
  333. auto B = Locs.begin(), E = Locs.end();
  334. if (std::find(B, E, Loc) == E)
  335. Locs.push_back(Loc);
  336. }
  337. void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
  338. const MachineFunction *MF) {
  339. // Skip this instruction if it has the same location as the previous one.
  340. if (!DL || DL == PrevInstLoc)
  341. return;
  342. const DIScope *Scope = DL.get()->getScope();
  343. if (!Scope)
  344. return;
  345. // Skip this line if it is longer than the maximum we can record.
  346. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
  347. if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
  348. LI.isNeverStepInto())
  349. return;
  350. ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
  351. if (CI.getStartColumn() != DL.getCol())
  352. return;
  353. if (!CurFn->HaveLineInfo)
  354. CurFn->HaveLineInfo = true;
  355. unsigned FileId = 0;
  356. if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
  357. FileId = CurFn->LastFileId;
  358. else
  359. FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
  360. PrevInstLoc = DL;
  361. unsigned FuncId = CurFn->FuncId;
  362. if (const DILocation *SiteLoc = DL->getInlinedAt()) {
  363. const DILocation *Loc = DL.get();
  364. // If this location was actually inlined from somewhere else, give it the ID
  365. // of the inline call site.
  366. FuncId =
  367. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
  368. // Ensure we have links in the tree of inline call sites.
  369. bool FirstLoc = true;
  370. while ((SiteLoc = Loc->getInlinedAt())) {
  371. InlineSite &Site =
  372. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
  373. if (!FirstLoc)
  374. addLocIfNotPresent(Site.ChildSites, Loc);
  375. FirstLoc = false;
  376. Loc = SiteLoc;
  377. }
  378. addLocIfNotPresent(CurFn->ChildSites, Loc);
  379. }
  380. OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
  381. /*PrologueEnd=*/false, /*IsStmt=*/false,
  382. DL->getFilename(), SMLoc());
  383. }
  384. void CodeViewDebug::emitCodeViewMagicVersion() {
  385. OS.EmitValueToAlignment(4);
  386. OS.AddComment("Debug section magic");
  387. OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
  388. }
  389. void CodeViewDebug::endModule() {
  390. if (!Asm || !MMI->hasDebugInfo())
  391. return;
  392. assert(Asm != nullptr);
  393. // The COFF .debug$S section consists of several subsections, each starting
  394. // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
  395. // of the payload followed by the payload itself. The subsections are 4-byte
  396. // aligned.
  397. // Use the generic .debug$S section, and make a subsection for all the inlined
  398. // subprograms.
  399. switchToDebugSectionForSymbol(nullptr);
  400. MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
  401. emitCompilerInformation();
  402. endCVSubsection(CompilerInfo);
  403. emitInlineeLinesSubsection();
  404. // Emit per-function debug information.
  405. for (auto &P : FnDebugInfo)
  406. if (!P.first->isDeclarationForLinker())
  407. emitDebugInfoForFunction(P.first, P.second);
  408. // Emit global variable debug information.
  409. setCurrentSubprogram(nullptr);
  410. emitDebugInfoForGlobals();
  411. // Emit retained types.
  412. emitDebugInfoForRetainedTypes();
  413. // Switch back to the generic .debug$S section after potentially processing
  414. // comdat symbol sections.
  415. switchToDebugSectionForSymbol(nullptr);
  416. // Emit UDT records for any types used by global variables.
  417. if (!GlobalUDTs.empty()) {
  418. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  419. emitDebugInfoForUDTs(GlobalUDTs);
  420. endCVSubsection(SymbolsEnd);
  421. }
  422. // This subsection holds a file index to offset in string table table.
  423. OS.AddComment("File index to string table offset subsection");
  424. OS.EmitCVFileChecksumsDirective();
  425. // This subsection holds the string table.
  426. OS.AddComment("String table");
  427. OS.EmitCVStringTableDirective();
  428. // Emit type information and hashes last, so that any types we translate while
  429. // emitting function info are included.
  430. emitTypeInformation();
  431. if (EmitDebugGlobalHashes)
  432. emitTypeGlobalHashes();
  433. clear();
  434. }
  435. static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
  436. // The maximum CV record length is 0xFF00. Most of the strings we emit appear
  437. // after a fixed length portion of the record. The fixed length portion should
  438. // always be less than 0xF00 (3840) bytes, so truncate the string so that the
  439. // overall record size is less than the maximum allowed.
  440. unsigned MaxFixedRecordLength = 0xF00;
  441. SmallString<32> NullTerminatedString(
  442. S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
  443. NullTerminatedString.push_back('\0');
  444. OS.EmitBytes(NullTerminatedString);
  445. }
  446. void CodeViewDebug::emitTypeInformation() {
  447. if (TypeTable.empty())
  448. return;
  449. // Start the .debug$T section with 0x4.
  450. OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
  451. emitCodeViewMagicVersion();
  452. SmallString<8> CommentPrefix;
  453. if (OS.isVerboseAsm()) {
  454. CommentPrefix += '\t';
  455. CommentPrefix += Asm->MAI->getCommentString();
  456. CommentPrefix += ' ';
  457. }
  458. TypeTableCollection Table(TypeTable.records());
  459. Optional<TypeIndex> B = Table.getFirst();
  460. while (B) {
  461. // This will fail if the record data is invalid.
  462. CVType Record = Table.getType(*B);
  463. if (OS.isVerboseAsm()) {
  464. // Emit a block comment describing the type record for readability.
  465. SmallString<512> CommentBlock;
  466. raw_svector_ostream CommentOS(CommentBlock);
  467. ScopedPrinter SP(CommentOS);
  468. SP.setPrefix(CommentPrefix);
  469. TypeDumpVisitor TDV(Table, &SP, false);
  470. Error E = codeview::visitTypeRecord(Record, *B, TDV);
  471. if (E) {
  472. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  473. llvm_unreachable("produced malformed type record");
  474. }
  475. // emitRawComment will insert its own tab and comment string before
  476. // the first line, so strip off our first one. It also prints its own
  477. // newline.
  478. OS.emitRawComment(
  479. CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
  480. }
  481. OS.EmitBinaryData(Record.str_data());
  482. B = Table.getNext(*B);
  483. }
  484. }
  485. void CodeViewDebug::emitTypeGlobalHashes() {
  486. if (TypeTable.empty())
  487. return;
  488. // Start the .debug$H section with the version and hash algorithm, currently
  489. // hardcoded to version 0, SHA1.
  490. OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
  491. OS.EmitValueToAlignment(4);
  492. OS.AddComment("Magic");
  493. OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
  494. OS.AddComment("Section Version");
  495. OS.EmitIntValue(0, 2);
  496. OS.AddComment("Hash Algorithm");
  497. OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1), 2);
  498. TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
  499. for (const auto &GHR : TypeTable.hashes()) {
  500. if (OS.isVerboseAsm()) {
  501. // Emit an EOL-comment describing which TypeIndex this hash corresponds
  502. // to, as well as the stringified SHA1 hash.
  503. SmallString<32> Comment;
  504. raw_svector_ostream CommentOS(Comment);
  505. CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
  506. OS.AddComment(Comment);
  507. ++TI;
  508. }
  509. assert(GHR.Hash.size() % 20 == 0);
  510. StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
  511. GHR.Hash.size());
  512. OS.EmitBinaryData(S);
  513. }
  514. }
  515. static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
  516. switch (DWLang) {
  517. case dwarf::DW_LANG_C:
  518. case dwarf::DW_LANG_C89:
  519. case dwarf::DW_LANG_C99:
  520. case dwarf::DW_LANG_C11:
  521. case dwarf::DW_LANG_ObjC:
  522. return SourceLanguage::C;
  523. case dwarf::DW_LANG_C_plus_plus:
  524. case dwarf::DW_LANG_C_plus_plus_03:
  525. case dwarf::DW_LANG_C_plus_plus_11:
  526. case dwarf::DW_LANG_C_plus_plus_14:
  527. return SourceLanguage::Cpp;
  528. case dwarf::DW_LANG_Fortran77:
  529. case dwarf::DW_LANG_Fortran90:
  530. case dwarf::DW_LANG_Fortran03:
  531. case dwarf::DW_LANG_Fortran08:
  532. return SourceLanguage::Fortran;
  533. case dwarf::DW_LANG_Pascal83:
  534. return SourceLanguage::Pascal;
  535. case dwarf::DW_LANG_Cobol74:
  536. case dwarf::DW_LANG_Cobol85:
  537. return SourceLanguage::Cobol;
  538. case dwarf::DW_LANG_Java:
  539. return SourceLanguage::Java;
  540. case dwarf::DW_LANG_D:
  541. return SourceLanguage::D;
  542. default:
  543. // There's no CodeView representation for this language, and CV doesn't
  544. // have an "unknown" option for the language field, so we'll use MASM,
  545. // as it's very low level.
  546. return SourceLanguage::Masm;
  547. }
  548. }
  549. namespace {
  550. struct Version {
  551. int Part[4];
  552. };
  553. } // end anonymous namespace
  554. // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
  555. // the version number.
  556. static Version parseVersion(StringRef Name) {
  557. Version V = {{0}};
  558. int N = 0;
  559. for (const char C : Name) {
  560. if (isdigit(C)) {
  561. V.Part[N] *= 10;
  562. V.Part[N] += C - '0';
  563. } else if (C == '.') {
  564. ++N;
  565. if (N >= 4)
  566. return V;
  567. } else if (N > 0)
  568. return V;
  569. }
  570. return V;
  571. }
  572. static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
  573. switch (Type) {
  574. case Triple::ArchType::x86:
  575. return CPUType::Pentium3;
  576. case Triple::ArchType::x86_64:
  577. return CPUType::X64;
  578. case Triple::ArchType::thumb:
  579. return CPUType::Thumb;
  580. case Triple::ArchType::aarch64:
  581. return CPUType::ARM64;
  582. default:
  583. report_fatal_error("target architecture doesn't map to a CodeView CPUType");
  584. }
  585. }
  586. void CodeViewDebug::emitCompilerInformation() {
  587. MCContext &Context = MMI->getContext();
  588. MCSymbol *CompilerBegin = Context.createTempSymbol(),
  589. *CompilerEnd = Context.createTempSymbol();
  590. OS.AddComment("Record length");
  591. OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
  592. OS.EmitLabel(CompilerBegin);
  593. OS.AddComment("Record kind: S_COMPILE3");
  594. OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
  595. uint32_t Flags = 0;
  596. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  597. const MDNode *Node = *CUs->operands().begin();
  598. const auto *CU = cast<DICompileUnit>(Node);
  599. // The low byte of the flags indicates the source language.
  600. Flags = MapDWLangToCVLang(CU->getSourceLanguage());
  601. // TODO: Figure out which other flags need to be set.
  602. OS.AddComment("Flags and language");
  603. OS.EmitIntValue(Flags, 4);
  604. OS.AddComment("CPUType");
  605. CPUType CPU =
  606. mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
  607. OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
  608. StringRef CompilerVersion = CU->getProducer();
  609. Version FrontVer = parseVersion(CompilerVersion);
  610. OS.AddComment("Frontend version");
  611. for (int N = 0; N < 4; ++N)
  612. OS.EmitIntValue(FrontVer.Part[N], 2);
  613. // Some Microsoft tools, like Binscope, expect a backend version number of at
  614. // least 8.something, so we'll coerce the LLVM version into a form that
  615. // guarantees it'll be big enough without really lying about the version.
  616. int Major = 1000 * LLVM_VERSION_MAJOR +
  617. 10 * LLVM_VERSION_MINOR +
  618. LLVM_VERSION_PATCH;
  619. // Clamp it for builds that use unusually large version numbers.
  620. Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
  621. Version BackVer = {{ Major, 0, 0, 0 }};
  622. OS.AddComment("Backend version");
  623. for (int N = 0; N < 4; ++N)
  624. OS.EmitIntValue(BackVer.Part[N], 2);
  625. OS.AddComment("Null-terminated compiler version string");
  626. emitNullTerminatedSymbolName(OS, CompilerVersion);
  627. OS.EmitLabel(CompilerEnd);
  628. }
  629. void CodeViewDebug::emitInlineeLinesSubsection() {
  630. if (InlinedSubprograms.empty())
  631. return;
  632. OS.AddComment("Inlinee lines subsection");
  633. MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
  634. // We emit the checksum info for files. This is used by debuggers to
  635. // determine if a pdb matches the source before loading it. Visual Studio,
  636. // for instance, will display a warning that the breakpoints are not valid if
  637. // the pdb does not match the source.
  638. OS.AddComment("Inlinee lines signature");
  639. OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
  640. for (const DISubprogram *SP : InlinedSubprograms) {
  641. assert(TypeIndices.count({SP, nullptr}));
  642. TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
  643. OS.AddBlankLine();
  644. unsigned FileId = maybeRecordFile(SP->getFile());
  645. OS.AddComment("Inlined function " + SP->getName() + " starts at " +
  646. SP->getFilename() + Twine(':') + Twine(SP->getLine()));
  647. OS.AddBlankLine();
  648. OS.AddComment("Type index of inlined function");
  649. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  650. OS.AddComment("Offset into filechecksum table");
  651. OS.EmitCVFileChecksumOffsetDirective(FileId);
  652. OS.AddComment("Starting line number");
  653. OS.EmitIntValue(SP->getLine(), 4);
  654. }
  655. endCVSubsection(InlineEnd);
  656. }
  657. void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
  658. const DILocation *InlinedAt,
  659. const InlineSite &Site) {
  660. MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
  661. *InlineEnd = MMI->getContext().createTempSymbol();
  662. assert(TypeIndices.count({Site.Inlinee, nullptr}));
  663. TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
  664. // SymbolRecord
  665. OS.AddComment("Record length");
  666. OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
  667. OS.EmitLabel(InlineBegin);
  668. OS.AddComment("Record kind: S_INLINESITE");
  669. OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
  670. OS.AddComment("PtrParent");
  671. OS.EmitIntValue(0, 4);
  672. OS.AddComment("PtrEnd");
  673. OS.EmitIntValue(0, 4);
  674. OS.AddComment("Inlinee type index");
  675. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  676. unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
  677. unsigned StartLineNum = Site.Inlinee->getLine();
  678. OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
  679. FI.Begin, FI.End);
  680. OS.EmitLabel(InlineEnd);
  681. emitLocalVariableList(Site.InlinedLocals);
  682. // Recurse on child inlined call sites before closing the scope.
  683. for (const DILocation *ChildSite : Site.ChildSites) {
  684. auto I = FI.InlineSites.find(ChildSite);
  685. assert(I != FI.InlineSites.end() &&
  686. "child site not in function inline site map");
  687. emitInlinedCallSite(FI, ChildSite, I->second);
  688. }
  689. // Close the scope.
  690. OS.AddComment("Record length");
  691. OS.EmitIntValue(2, 2); // RecordLength
  692. OS.AddComment("Record kind: S_INLINESITE_END");
  693. OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
  694. }
  695. void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
  696. // If we have a symbol, it may be in a section that is COMDAT. If so, find the
  697. // comdat key. A section may be comdat because of -ffunction-sections or
  698. // because it is comdat in the IR.
  699. MCSectionCOFF *GVSec =
  700. GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
  701. const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
  702. MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
  703. Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
  704. DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
  705. OS.SwitchSection(DebugSec);
  706. // Emit the magic version number if this is the first time we've switched to
  707. // this section.
  708. if (ComdatDebugSections.insert(DebugSec).second)
  709. emitCodeViewMagicVersion();
  710. }
  711. void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
  712. FunctionInfo &FI) {
  713. // For each function there is a separate subsection which holds the PC to
  714. // file:line table.
  715. const MCSymbol *Fn = Asm->getSymbol(GV);
  716. assert(Fn);
  717. // Switch to the to a comdat section, if appropriate.
  718. switchToDebugSectionForSymbol(Fn);
  719. std::string FuncName;
  720. auto *SP = GV->getSubprogram();
  721. assert(SP);
  722. setCurrentSubprogram(SP);
  723. // If we have a display name, build the fully qualified name by walking the
  724. // chain of scopes.
  725. if (!SP->getName().empty())
  726. FuncName =
  727. getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
  728. // If our DISubprogram name is empty, use the mangled name.
  729. if (FuncName.empty())
  730. FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
  731. // Emit FPO data, but only on 32-bit x86. No other platforms use it.
  732. if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
  733. OS.EmitCVFPOData(Fn);
  734. // Emit a symbol subsection, required by VS2012+ to find function boundaries.
  735. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  736. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  737. {
  738. MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
  739. *ProcRecordEnd = MMI->getContext().createTempSymbol();
  740. OS.AddComment("Record length");
  741. OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
  742. OS.EmitLabel(ProcRecordBegin);
  743. if (GV->hasLocalLinkage()) {
  744. OS.AddComment("Record kind: S_LPROC32_ID");
  745. OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
  746. } else {
  747. OS.AddComment("Record kind: S_GPROC32_ID");
  748. OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
  749. }
  750. // These fields are filled in by tools like CVPACK which run after the fact.
  751. OS.AddComment("PtrParent");
  752. OS.EmitIntValue(0, 4);
  753. OS.AddComment("PtrEnd");
  754. OS.EmitIntValue(0, 4);
  755. OS.AddComment("PtrNext");
  756. OS.EmitIntValue(0, 4);
  757. // This is the important bit that tells the debugger where the function
  758. // code is located and what's its size:
  759. OS.AddComment("Code size");
  760. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
  761. OS.AddComment("Offset after prologue");
  762. OS.EmitIntValue(0, 4);
  763. OS.AddComment("Offset before epilogue");
  764. OS.EmitIntValue(0, 4);
  765. OS.AddComment("Function type index");
  766. OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
  767. OS.AddComment("Function section relative address");
  768. OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
  769. OS.AddComment("Function section index");
  770. OS.EmitCOFFSectionIndex(Fn);
  771. OS.AddComment("Flags");
  772. OS.EmitIntValue(0, 1);
  773. // Emit the function display name as a null-terminated string.
  774. OS.AddComment("Function name");
  775. // Truncate the name so we won't overflow the record length field.
  776. emitNullTerminatedSymbolName(OS, FuncName);
  777. OS.EmitLabel(ProcRecordEnd);
  778. emitLocalVariableList(FI.Locals);
  779. // Emit inlined call site information. Only emit functions inlined directly
  780. // into the parent function. We'll emit the other sites recursively as part
  781. // of their parent inline site.
  782. for (const DILocation *InlinedAt : FI.ChildSites) {
  783. auto I = FI.InlineSites.find(InlinedAt);
  784. assert(I != FI.InlineSites.end() &&
  785. "child site not in function inline site map");
  786. emitInlinedCallSite(FI, InlinedAt, I->second);
  787. }
  788. for (auto Annot : FI.Annotations) {
  789. MCSymbol *Label = Annot.first;
  790. MDTuple *Strs = cast<MDTuple>(Annot.second);
  791. MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
  792. *AnnotEnd = MMI->getContext().createTempSymbol();
  793. OS.AddComment("Record length");
  794. OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
  795. OS.EmitLabel(AnnotBegin);
  796. OS.AddComment("Record kind: S_ANNOTATION");
  797. OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
  798. OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
  799. // FIXME: Make sure we don't overflow the max record size.
  800. OS.EmitCOFFSectionIndex(Label);
  801. OS.EmitIntValue(Strs->getNumOperands(), 2);
  802. for (Metadata *MD : Strs->operands()) {
  803. // MDStrings are null terminated, so we can do EmitBytes and get the
  804. // nice .asciz directive.
  805. StringRef Str = cast<MDString>(MD)->getString();
  806. assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
  807. OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
  808. }
  809. OS.EmitLabel(AnnotEnd);
  810. }
  811. if (SP != nullptr)
  812. emitDebugInfoForUDTs(LocalUDTs);
  813. // We're done with this function.
  814. OS.AddComment("Record length");
  815. OS.EmitIntValue(0x0002, 2);
  816. OS.AddComment("Record kind: S_PROC_ID_END");
  817. OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
  818. }
  819. endCVSubsection(SymbolsEnd);
  820. // We have an assembler directive that takes care of the whole line table.
  821. OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
  822. }
  823. CodeViewDebug::LocalVarDefRange
  824. CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
  825. LocalVarDefRange DR;
  826. DR.InMemory = -1;
  827. DR.DataOffset = Offset;
  828. assert(DR.DataOffset == Offset && "truncation");
  829. DR.IsSubfield = 0;
  830. DR.StructOffset = 0;
  831. DR.CVRegister = CVRegister;
  832. return DR;
  833. }
  834. CodeViewDebug::LocalVarDefRange
  835. CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
  836. int Offset, bool IsSubfield,
  837. uint16_t StructOffset) {
  838. LocalVarDefRange DR;
  839. DR.InMemory = InMemory;
  840. DR.DataOffset = Offset;
  841. DR.IsSubfield = IsSubfield;
  842. DR.StructOffset = StructOffset;
  843. DR.CVRegister = CVRegister;
  844. return DR;
  845. }
  846. void CodeViewDebug::collectVariableInfoFromMFTable(
  847. DenseSet<InlinedVariable> &Processed) {
  848. const MachineFunction &MF = *Asm->MF;
  849. const TargetSubtargetInfo &TSI = MF.getSubtarget();
  850. const TargetFrameLowering *TFI = TSI.getFrameLowering();
  851. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  852. for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
  853. if (!VI.Var)
  854. continue;
  855. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  856. "Expected inlined-at fields to agree");
  857. Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
  858. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  859. // If variable scope is not found then skip this variable.
  860. if (!Scope)
  861. continue;
  862. // If the variable has an attached offset expression, extract it.
  863. // FIXME: Try to handle DW_OP_deref as well.
  864. int64_t ExprOffset = 0;
  865. if (VI.Expr)
  866. if (!VI.Expr->extractIfOffset(ExprOffset))
  867. continue;
  868. // Get the frame register used and the offset.
  869. unsigned FrameReg = 0;
  870. int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
  871. uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
  872. // Calculate the label ranges.
  873. LocalVarDefRange DefRange =
  874. createDefRangeMem(CVReg, FrameOffset + ExprOffset);
  875. for (const InsnRange &Range : Scope->getRanges()) {
  876. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  877. const MCSymbol *End = getLabelAfterInsn(Range.second);
  878. End = End ? End : Asm->getFunctionEnd();
  879. DefRange.Ranges.emplace_back(Begin, End);
  880. }
  881. LocalVariable Var;
  882. Var.DIVar = VI.Var;
  883. Var.DefRanges.emplace_back(std::move(DefRange));
  884. recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
  885. }
  886. }
  887. static bool canUseReferenceType(const DbgVariableLocation &Loc) {
  888. return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
  889. }
  890. static bool needsReferenceType(const DbgVariableLocation &Loc) {
  891. return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
  892. }
  893. void CodeViewDebug::calculateRanges(
  894. LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
  895. const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  896. // Calculate the definition ranges.
  897. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  898. const InsnRange &Range = *I;
  899. const MachineInstr *DVInst = Range.first;
  900. assert(DVInst->isDebugValue() && "Invalid History entry");
  901. // FIXME: Find a way to represent constant variables, since they are
  902. // relatively common.
  903. Optional<DbgVariableLocation> Location =
  904. DbgVariableLocation::extractFromMachineInstruction(*DVInst);
  905. if (!Location)
  906. continue;
  907. // CodeView can only express variables in register and variables in memory
  908. // at a constant offset from a register. However, for variables passed
  909. // indirectly by pointer, it is common for that pointer to be spilled to a
  910. // stack location. For the special case of one offseted load followed by a
  911. // zero offset load (a pointer spilled to the stack), we change the type of
  912. // the local variable from a value type to a reference type. This tricks the
  913. // debugger into doing the load for us.
  914. if (Var.UseReferenceType) {
  915. // We're using a reference type. Drop the last zero offset load.
  916. if (canUseReferenceType(*Location))
  917. Location->LoadChain.pop_back();
  918. else
  919. continue;
  920. } else if (needsReferenceType(*Location)) {
  921. // This location can't be expressed without switching to a reference type.
  922. // Start over using that.
  923. Var.UseReferenceType = true;
  924. Var.DefRanges.clear();
  925. calculateRanges(Var, Ranges);
  926. return;
  927. }
  928. // We can only handle a register or an offseted load of a register.
  929. if (Location->Register == 0 || Location->LoadChain.size() > 1)
  930. continue;
  931. {
  932. LocalVarDefRange DR;
  933. DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
  934. DR.InMemory = !Location->LoadChain.empty();
  935. DR.DataOffset =
  936. !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
  937. if (Location->FragmentInfo) {
  938. DR.IsSubfield = true;
  939. DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
  940. } else {
  941. DR.IsSubfield = false;
  942. DR.StructOffset = 0;
  943. }
  944. if (Var.DefRanges.empty() ||
  945. Var.DefRanges.back().isDifferentLocation(DR)) {
  946. Var.DefRanges.emplace_back(std::move(DR));
  947. }
  948. }
  949. // Compute the label range.
  950. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  951. const MCSymbol *End = getLabelAfterInsn(Range.second);
  952. if (!End) {
  953. // This range is valid until the next overlapping bitpiece. In the
  954. // common case, ranges will not be bitpieces, so they will overlap.
  955. auto J = std::next(I);
  956. const DIExpression *DIExpr = DVInst->getDebugExpression();
  957. while (J != E &&
  958. !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
  959. ++J;
  960. if (J != E)
  961. End = getLabelBeforeInsn(J->first);
  962. else
  963. End = Asm->getFunctionEnd();
  964. }
  965. // If the last range end is our begin, just extend the last range.
  966. // Otherwise make a new range.
  967. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
  968. Var.DefRanges.back().Ranges;
  969. if (!R.empty() && R.back().second == Begin)
  970. R.back().second = End;
  971. else
  972. R.emplace_back(Begin, End);
  973. // FIXME: Do more range combining.
  974. }
  975. }
  976. void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
  977. DenseSet<InlinedVariable> Processed;
  978. // Grab the variable info that was squirreled away in the MMI side-table.
  979. collectVariableInfoFromMFTable(Processed);
  980. for (const auto &I : DbgValues) {
  981. InlinedVariable IV = I.first;
  982. if (Processed.count(IV))
  983. continue;
  984. const DILocalVariable *DIVar = IV.first;
  985. const DILocation *InlinedAt = IV.second;
  986. // Instruction ranges, specifying where IV is accessible.
  987. const auto &Ranges = I.second;
  988. LexicalScope *Scope = nullptr;
  989. if (InlinedAt)
  990. Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
  991. else
  992. Scope = LScopes.findLexicalScope(DIVar->getScope());
  993. // If variable scope is not found then skip this variable.
  994. if (!Scope)
  995. continue;
  996. LocalVariable Var;
  997. Var.DIVar = DIVar;
  998. calculateRanges(Var, Ranges);
  999. recordLocalVariable(std::move(Var), InlinedAt);
  1000. }
  1001. }
  1002. void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
  1003. const Function &GV = MF->getFunction();
  1004. assert(FnDebugInfo.count(&GV) == false);
  1005. CurFn = &FnDebugInfo[&GV];
  1006. CurFn->FuncId = NextFuncId++;
  1007. CurFn->Begin = Asm->getFunctionBegin();
  1008. OS.EmitCVFuncIdDirective(CurFn->FuncId);
  1009. // Find the end of the function prolog. First known non-DBG_VALUE and
  1010. // non-frame setup location marks the beginning of the function body.
  1011. // FIXME: is there a simpler a way to do this? Can we just search
  1012. // for the first instruction of the function, not the last of the prolog?
  1013. DebugLoc PrologEndLoc;
  1014. bool EmptyPrologue = true;
  1015. for (const auto &MBB : *MF) {
  1016. for (const auto &MI : MBB) {
  1017. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1018. MI.getDebugLoc()) {
  1019. PrologEndLoc = MI.getDebugLoc();
  1020. break;
  1021. } else if (!MI.isMetaInstruction()) {
  1022. EmptyPrologue = false;
  1023. }
  1024. }
  1025. }
  1026. // Record beginning of function if we have a non-empty prologue.
  1027. if (PrologEndLoc && !EmptyPrologue) {
  1028. DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
  1029. maybeRecordLocation(FnStartDL, MF);
  1030. }
  1031. }
  1032. static bool shouldEmitUdt(const DIType *T) {
  1033. if (!T)
  1034. return false;
  1035. // MSVC does not emit UDTs for typedefs that are scoped to classes.
  1036. if (T->getTag() == dwarf::DW_TAG_typedef) {
  1037. if (DIScope *Scope = T->getScope().resolve()) {
  1038. switch (Scope->getTag()) {
  1039. case dwarf::DW_TAG_structure_type:
  1040. case dwarf::DW_TAG_class_type:
  1041. case dwarf::DW_TAG_union_type:
  1042. return false;
  1043. }
  1044. }
  1045. }
  1046. while (true) {
  1047. if (!T || T->isForwardDecl())
  1048. return false;
  1049. const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
  1050. if (!DT)
  1051. return true;
  1052. T = DT->getBaseType().resolve();
  1053. }
  1054. return true;
  1055. }
  1056. void CodeViewDebug::addToUDTs(const DIType *Ty) {
  1057. // Don't record empty UDTs.
  1058. if (Ty->getName().empty())
  1059. return;
  1060. if (!shouldEmitUdt(Ty))
  1061. return;
  1062. SmallVector<StringRef, 5> QualifiedNameComponents;
  1063. const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
  1064. Ty->getScope().resolve(), QualifiedNameComponents);
  1065. std::string FullyQualifiedName =
  1066. getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
  1067. if (ClosestSubprogram == nullptr) {
  1068. GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1069. } else if (ClosestSubprogram == CurrentSubprogram) {
  1070. LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1071. }
  1072. // TODO: What if the ClosestSubprogram is neither null or the current
  1073. // subprogram? Currently, the UDT just gets dropped on the floor.
  1074. //
  1075. // The current behavior is not desirable. To get maximal fidelity, we would
  1076. // need to perform all type translation before beginning emission of .debug$S
  1077. // and then make LocalUDTs a member of FunctionInfo
  1078. }
  1079. TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
  1080. // Generic dispatch for lowering an unknown type.
  1081. switch (Ty->getTag()) {
  1082. case dwarf::DW_TAG_array_type:
  1083. return lowerTypeArray(cast<DICompositeType>(Ty));
  1084. case dwarf::DW_TAG_typedef:
  1085. return lowerTypeAlias(cast<DIDerivedType>(Ty));
  1086. case dwarf::DW_TAG_base_type:
  1087. return lowerTypeBasic(cast<DIBasicType>(Ty));
  1088. case dwarf::DW_TAG_pointer_type:
  1089. if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
  1090. return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
  1091. LLVM_FALLTHROUGH;
  1092. case dwarf::DW_TAG_reference_type:
  1093. case dwarf::DW_TAG_rvalue_reference_type:
  1094. return lowerTypePointer(cast<DIDerivedType>(Ty));
  1095. case dwarf::DW_TAG_ptr_to_member_type:
  1096. return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
  1097. case dwarf::DW_TAG_const_type:
  1098. case dwarf::DW_TAG_volatile_type:
  1099. // TODO: add support for DW_TAG_atomic_type here
  1100. return lowerTypeModifier(cast<DIDerivedType>(Ty));
  1101. case dwarf::DW_TAG_subroutine_type:
  1102. if (ClassTy) {
  1103. // The member function type of a member function pointer has no
  1104. // ThisAdjustment.
  1105. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
  1106. /*ThisAdjustment=*/0,
  1107. /*IsStaticMethod=*/false);
  1108. }
  1109. return lowerTypeFunction(cast<DISubroutineType>(Ty));
  1110. case dwarf::DW_TAG_enumeration_type:
  1111. return lowerTypeEnum(cast<DICompositeType>(Ty));
  1112. case dwarf::DW_TAG_class_type:
  1113. case dwarf::DW_TAG_structure_type:
  1114. return lowerTypeClass(cast<DICompositeType>(Ty));
  1115. case dwarf::DW_TAG_union_type:
  1116. return lowerTypeUnion(cast<DICompositeType>(Ty));
  1117. case dwarf::DW_TAG_unspecified_type:
  1118. return TypeIndex::None();
  1119. default:
  1120. // Use the null type index.
  1121. return TypeIndex();
  1122. }
  1123. }
  1124. TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
  1125. DITypeRef UnderlyingTypeRef = Ty->getBaseType();
  1126. TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
  1127. StringRef TypeName = Ty->getName();
  1128. addToUDTs(Ty);
  1129. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
  1130. TypeName == "HRESULT")
  1131. return TypeIndex(SimpleTypeKind::HResult);
  1132. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
  1133. TypeName == "wchar_t")
  1134. return TypeIndex(SimpleTypeKind::WideCharacter);
  1135. return UnderlyingTypeIndex;
  1136. }
  1137. TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
  1138. DITypeRef ElementTypeRef = Ty->getBaseType();
  1139. TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
  1140. // IndexType is size_t, which depends on the bitness of the target.
  1141. TypeIndex IndexType = Asm->TM.getPointerSize() == 8
  1142. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  1143. : TypeIndex(SimpleTypeKind::UInt32Long);
  1144. uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
  1145. // Add subranges to array type.
  1146. DINodeArray Elements = Ty->getElements();
  1147. for (int i = Elements.size() - 1; i >= 0; --i) {
  1148. const DINode *Element = Elements[i];
  1149. assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
  1150. const DISubrange *Subrange = cast<DISubrange>(Element);
  1151. assert(Subrange->getLowerBound() == 0 &&
  1152. "codeview doesn't support subranges with lower bounds");
  1153. int64_t Count = -1;
  1154. if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
  1155. Count = CI->getSExtValue();
  1156. // Forward declarations of arrays without a size and VLAs use a count of -1.
  1157. // Emit a count of zero in these cases to match what MSVC does for arrays
  1158. // without a size. MSVC doesn't support VLAs, so it's not clear what we
  1159. // should do for them even if we could distinguish them.
  1160. if (Count == -1)
  1161. Count = 0;
  1162. // Update the element size and element type index for subsequent subranges.
  1163. ElementSize *= Count;
  1164. // If this is the outermost array, use the size from the array. It will be
  1165. // more accurate if we had a VLA or an incomplete element type size.
  1166. uint64_t ArraySize =
  1167. (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
  1168. StringRef Name = (i == 0) ? Ty->getName() : "";
  1169. ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
  1170. ElementTypeIndex = TypeTable.writeLeafType(AR);
  1171. }
  1172. return ElementTypeIndex;
  1173. }
  1174. TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
  1175. TypeIndex Index;
  1176. dwarf::TypeKind Kind;
  1177. uint32_t ByteSize;
  1178. Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
  1179. ByteSize = Ty->getSizeInBits() / 8;
  1180. SimpleTypeKind STK = SimpleTypeKind::None;
  1181. switch (Kind) {
  1182. case dwarf::DW_ATE_address:
  1183. // FIXME: Translate
  1184. break;
  1185. case dwarf::DW_ATE_boolean:
  1186. switch (ByteSize) {
  1187. case 1: STK = SimpleTypeKind::Boolean8; break;
  1188. case 2: STK = SimpleTypeKind::Boolean16; break;
  1189. case 4: STK = SimpleTypeKind::Boolean32; break;
  1190. case 8: STK = SimpleTypeKind::Boolean64; break;
  1191. case 16: STK = SimpleTypeKind::Boolean128; break;
  1192. }
  1193. break;
  1194. case dwarf::DW_ATE_complex_float:
  1195. switch (ByteSize) {
  1196. case 2: STK = SimpleTypeKind::Complex16; break;
  1197. case 4: STK = SimpleTypeKind::Complex32; break;
  1198. case 8: STK = SimpleTypeKind::Complex64; break;
  1199. case 10: STK = SimpleTypeKind::Complex80; break;
  1200. case 16: STK = SimpleTypeKind::Complex128; break;
  1201. }
  1202. break;
  1203. case dwarf::DW_ATE_float:
  1204. switch (ByteSize) {
  1205. case 2: STK = SimpleTypeKind::Float16; break;
  1206. case 4: STK = SimpleTypeKind::Float32; break;
  1207. case 6: STK = SimpleTypeKind::Float48; break;
  1208. case 8: STK = SimpleTypeKind::Float64; break;
  1209. case 10: STK = SimpleTypeKind::Float80; break;
  1210. case 16: STK = SimpleTypeKind::Float128; break;
  1211. }
  1212. break;
  1213. case dwarf::DW_ATE_signed:
  1214. switch (ByteSize) {
  1215. case 1: STK = SimpleTypeKind::SignedCharacter; break;
  1216. case 2: STK = SimpleTypeKind::Int16Short; break;
  1217. case 4: STK = SimpleTypeKind::Int32; break;
  1218. case 8: STK = SimpleTypeKind::Int64Quad; break;
  1219. case 16: STK = SimpleTypeKind::Int128Oct; break;
  1220. }
  1221. break;
  1222. case dwarf::DW_ATE_unsigned:
  1223. switch (ByteSize) {
  1224. case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
  1225. case 2: STK = SimpleTypeKind::UInt16Short; break;
  1226. case 4: STK = SimpleTypeKind::UInt32; break;
  1227. case 8: STK = SimpleTypeKind::UInt64Quad; break;
  1228. case 16: STK = SimpleTypeKind::UInt128Oct; break;
  1229. }
  1230. break;
  1231. case dwarf::DW_ATE_UTF:
  1232. switch (ByteSize) {
  1233. case 2: STK = SimpleTypeKind::Character16; break;
  1234. case 4: STK = SimpleTypeKind::Character32; break;
  1235. }
  1236. break;
  1237. case dwarf::DW_ATE_signed_char:
  1238. if (ByteSize == 1)
  1239. STK = SimpleTypeKind::SignedCharacter;
  1240. break;
  1241. case dwarf::DW_ATE_unsigned_char:
  1242. if (ByteSize == 1)
  1243. STK = SimpleTypeKind::UnsignedCharacter;
  1244. break;
  1245. default:
  1246. break;
  1247. }
  1248. // Apply some fixups based on the source-level type name.
  1249. if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
  1250. STK = SimpleTypeKind::Int32Long;
  1251. if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
  1252. STK = SimpleTypeKind::UInt32Long;
  1253. if (STK == SimpleTypeKind::UInt16Short &&
  1254. (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
  1255. STK = SimpleTypeKind::WideCharacter;
  1256. if ((STK == SimpleTypeKind::SignedCharacter ||
  1257. STK == SimpleTypeKind::UnsignedCharacter) &&
  1258. Ty->getName() == "char")
  1259. STK = SimpleTypeKind::NarrowCharacter;
  1260. return TypeIndex(STK);
  1261. }
  1262. TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
  1263. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
  1264. // Pointers to simple types can use SimpleTypeMode, rather than having a
  1265. // dedicated pointer type record.
  1266. if (PointeeTI.isSimple() &&
  1267. PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
  1268. Ty->getTag() == dwarf::DW_TAG_pointer_type) {
  1269. SimpleTypeMode Mode = Ty->getSizeInBits() == 64
  1270. ? SimpleTypeMode::NearPointer64
  1271. : SimpleTypeMode::NearPointer32;
  1272. return TypeIndex(PointeeTI.getSimpleKind(), Mode);
  1273. }
  1274. PointerKind PK =
  1275. Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
  1276. PointerMode PM = PointerMode::Pointer;
  1277. switch (Ty->getTag()) {
  1278. default: llvm_unreachable("not a pointer tag type");
  1279. case dwarf::DW_TAG_pointer_type:
  1280. PM = PointerMode::Pointer;
  1281. break;
  1282. case dwarf::DW_TAG_reference_type:
  1283. PM = PointerMode::LValueReference;
  1284. break;
  1285. case dwarf::DW_TAG_rvalue_reference_type:
  1286. PM = PointerMode::RValueReference;
  1287. break;
  1288. }
  1289. // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
  1290. // 'this' pointer, but not normal contexts. Figure out what we're supposed to
  1291. // do.
  1292. PointerOptions PO = PointerOptions::None;
  1293. PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
  1294. return TypeTable.writeLeafType(PR);
  1295. }
  1296. static PointerToMemberRepresentation
  1297. translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
  1298. // SizeInBytes being zero generally implies that the member pointer type was
  1299. // incomplete, which can happen if it is part of a function prototype. In this
  1300. // case, use the unknown model instead of the general model.
  1301. if (IsPMF) {
  1302. switch (Flags & DINode::FlagPtrToMemberRep) {
  1303. case 0:
  1304. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1305. : PointerToMemberRepresentation::GeneralFunction;
  1306. case DINode::FlagSingleInheritance:
  1307. return PointerToMemberRepresentation::SingleInheritanceFunction;
  1308. case DINode::FlagMultipleInheritance:
  1309. return PointerToMemberRepresentation::MultipleInheritanceFunction;
  1310. case DINode::FlagVirtualInheritance:
  1311. return PointerToMemberRepresentation::VirtualInheritanceFunction;
  1312. }
  1313. } else {
  1314. switch (Flags & DINode::FlagPtrToMemberRep) {
  1315. case 0:
  1316. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1317. : PointerToMemberRepresentation::GeneralData;
  1318. case DINode::FlagSingleInheritance:
  1319. return PointerToMemberRepresentation::SingleInheritanceData;
  1320. case DINode::FlagMultipleInheritance:
  1321. return PointerToMemberRepresentation::MultipleInheritanceData;
  1322. case DINode::FlagVirtualInheritance:
  1323. return PointerToMemberRepresentation::VirtualInheritanceData;
  1324. }
  1325. }
  1326. llvm_unreachable("invalid ptr to member representation");
  1327. }
  1328. TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
  1329. assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
  1330. TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
  1331. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
  1332. PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
  1333. : PointerKind::Near32;
  1334. bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
  1335. PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
  1336. : PointerMode::PointerToDataMember;
  1337. PointerOptions PO = PointerOptions::None; // FIXME
  1338. assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
  1339. uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
  1340. MemberPointerInfo MPI(
  1341. ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
  1342. PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
  1343. return TypeTable.writeLeafType(PR);
  1344. }
  1345. /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
  1346. /// have a translation, use the NearC convention.
  1347. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
  1348. switch (DwarfCC) {
  1349. case dwarf::DW_CC_normal: return CallingConvention::NearC;
  1350. case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
  1351. case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
  1352. case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
  1353. case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
  1354. case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
  1355. }
  1356. return CallingConvention::NearC;
  1357. }
  1358. TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
  1359. ModifierOptions Mods = ModifierOptions::None;
  1360. bool IsModifier = true;
  1361. const DIType *BaseTy = Ty;
  1362. while (IsModifier && BaseTy) {
  1363. // FIXME: Need to add DWARF tags for __unaligned and _Atomic
  1364. switch (BaseTy->getTag()) {
  1365. case dwarf::DW_TAG_const_type:
  1366. Mods |= ModifierOptions::Const;
  1367. break;
  1368. case dwarf::DW_TAG_volatile_type:
  1369. Mods |= ModifierOptions::Volatile;
  1370. break;
  1371. default:
  1372. IsModifier = false;
  1373. break;
  1374. }
  1375. if (IsModifier)
  1376. BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
  1377. }
  1378. TypeIndex ModifiedTI = getTypeIndex(BaseTy);
  1379. ModifierRecord MR(ModifiedTI, Mods);
  1380. return TypeTable.writeLeafType(MR);
  1381. }
  1382. TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
  1383. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1384. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1385. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1386. // MSVC uses type none for variadic argument.
  1387. if (ReturnAndArgTypeIndices.size() > 1 &&
  1388. ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
  1389. ReturnAndArgTypeIndices.back() = TypeIndex::None();
  1390. }
  1391. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1392. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1393. if (!ReturnAndArgTypeIndices.empty()) {
  1394. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1395. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1396. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1397. }
  1398. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1399. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1400. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1401. ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
  1402. ArgTypeIndices.size(), ArgListIndex);
  1403. return TypeTable.writeLeafType(Procedure);
  1404. }
  1405. TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
  1406. const DIType *ClassTy,
  1407. int ThisAdjustment,
  1408. bool IsStaticMethod) {
  1409. // Lower the containing class type.
  1410. TypeIndex ClassType = getTypeIndex(ClassTy);
  1411. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1412. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1413. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1414. // MSVC uses type none for variadic argument.
  1415. if (ReturnAndArgTypeIndices.size() > 1 &&
  1416. ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
  1417. ReturnAndArgTypeIndices.back() = TypeIndex::None();
  1418. }
  1419. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1420. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1421. if (!ReturnAndArgTypeIndices.empty()) {
  1422. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1423. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1424. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1425. }
  1426. TypeIndex ThisTypeIndex;
  1427. if (!IsStaticMethod && !ArgTypeIndices.empty()) {
  1428. ThisTypeIndex = ArgTypeIndices.front();
  1429. ArgTypeIndices = ArgTypeIndices.drop_front();
  1430. }
  1431. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1432. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1433. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1434. // TODO: Need to use the correct values for FunctionOptions.
  1435. MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
  1436. FunctionOptions::None, ArgTypeIndices.size(),
  1437. ArgListIndex, ThisAdjustment);
  1438. return TypeTable.writeLeafType(MFR);
  1439. }
  1440. TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
  1441. unsigned VSlotCount =
  1442. Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
  1443. SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
  1444. VFTableShapeRecord VFTSR(Slots);
  1445. return TypeTable.writeLeafType(VFTSR);
  1446. }
  1447. static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
  1448. switch (Flags & DINode::FlagAccessibility) {
  1449. case DINode::FlagPrivate: return MemberAccess::Private;
  1450. case DINode::FlagPublic: return MemberAccess::Public;
  1451. case DINode::FlagProtected: return MemberAccess::Protected;
  1452. case 0:
  1453. // If there was no explicit access control, provide the default for the tag.
  1454. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
  1455. : MemberAccess::Public;
  1456. }
  1457. llvm_unreachable("access flags are exclusive");
  1458. }
  1459. static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
  1460. if (SP->isArtificial())
  1461. return MethodOptions::CompilerGenerated;
  1462. // FIXME: Handle other MethodOptions.
  1463. return MethodOptions::None;
  1464. }
  1465. static MethodKind translateMethodKindFlags(const DISubprogram *SP,
  1466. bool Introduced) {
  1467. if (SP->getFlags() & DINode::FlagStaticMember)
  1468. return MethodKind::Static;
  1469. switch (SP->getVirtuality()) {
  1470. case dwarf::DW_VIRTUALITY_none:
  1471. break;
  1472. case dwarf::DW_VIRTUALITY_virtual:
  1473. return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
  1474. case dwarf::DW_VIRTUALITY_pure_virtual:
  1475. return Introduced ? MethodKind::PureIntroducingVirtual
  1476. : MethodKind::PureVirtual;
  1477. default:
  1478. llvm_unreachable("unhandled virtuality case");
  1479. }
  1480. return MethodKind::Vanilla;
  1481. }
  1482. static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
  1483. switch (Ty->getTag()) {
  1484. case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
  1485. case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
  1486. }
  1487. llvm_unreachable("unexpected tag");
  1488. }
  1489. /// Return ClassOptions that should be present on both the forward declaration
  1490. /// and the defintion of a tag type.
  1491. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
  1492. ClassOptions CO = ClassOptions::None;
  1493. // MSVC always sets this flag, even for local types. Clang doesn't always
  1494. // appear to give every type a linkage name, which may be problematic for us.
  1495. // FIXME: Investigate the consequences of not following them here.
  1496. if (!Ty->getIdentifier().empty())
  1497. CO |= ClassOptions::HasUniqueName;
  1498. // Put the Nested flag on a type if it appears immediately inside a tag type.
  1499. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
  1500. // here. That flag is only set on definitions, and not forward declarations.
  1501. const DIScope *ImmediateScope = Ty->getScope().resolve();
  1502. if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
  1503. CO |= ClassOptions::Nested;
  1504. // Put the Scoped flag on function-local types.
  1505. for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
  1506. Scope = Scope->getScope().resolve()) {
  1507. if (isa<DISubprogram>(Scope)) {
  1508. CO |= ClassOptions::Scoped;
  1509. break;
  1510. }
  1511. }
  1512. return CO;
  1513. }
  1514. TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
  1515. ClassOptions CO = getCommonClassOptions(Ty);
  1516. TypeIndex FTI;
  1517. unsigned EnumeratorCount = 0;
  1518. if (Ty->isForwardDecl()) {
  1519. CO |= ClassOptions::ForwardReference;
  1520. } else {
  1521. ContinuationRecordBuilder ContinuationBuilder;
  1522. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  1523. for (const DINode *Element : Ty->getElements()) {
  1524. // We assume that the frontend provides all members in source declaration
  1525. // order, which is what MSVC does.
  1526. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
  1527. EnumeratorRecord ER(MemberAccess::Public,
  1528. APSInt::getUnsigned(Enumerator->getValue()),
  1529. Enumerator->getName());
  1530. ContinuationBuilder.writeMemberType(ER);
  1531. EnumeratorCount++;
  1532. }
  1533. }
  1534. FTI = TypeTable.insertRecord(ContinuationBuilder);
  1535. }
  1536. std::string FullName = getFullyQualifiedName(Ty);
  1537. EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
  1538. getTypeIndex(Ty->getBaseType()));
  1539. return TypeTable.writeLeafType(ER);
  1540. }
  1541. //===----------------------------------------------------------------------===//
  1542. // ClassInfo
  1543. //===----------------------------------------------------------------------===//
  1544. struct llvm::ClassInfo {
  1545. struct MemberInfo {
  1546. const DIDerivedType *MemberTypeNode;
  1547. uint64_t BaseOffset;
  1548. };
  1549. // [MemberInfo]
  1550. using MemberList = std::vector<MemberInfo>;
  1551. using MethodsList = TinyPtrVector<const DISubprogram *>;
  1552. // MethodName -> MethodsList
  1553. using MethodsMap = MapVector<MDString *, MethodsList>;
  1554. /// Base classes.
  1555. std::vector<const DIDerivedType *> Inheritance;
  1556. /// Direct members.
  1557. MemberList Members;
  1558. // Direct overloaded methods gathered by name.
  1559. MethodsMap Methods;
  1560. TypeIndex VShapeTI;
  1561. std::vector<const DIType *> NestedTypes;
  1562. };
  1563. void CodeViewDebug::clear() {
  1564. assert(CurFn == nullptr);
  1565. FileIdMap.clear();
  1566. FnDebugInfo.clear();
  1567. FileToFilepathMap.clear();
  1568. LocalUDTs.clear();
  1569. GlobalUDTs.clear();
  1570. TypeIndices.clear();
  1571. CompleteTypeIndices.clear();
  1572. }
  1573. void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
  1574. const DIDerivedType *DDTy) {
  1575. if (!DDTy->getName().empty()) {
  1576. Info.Members.push_back({DDTy, 0});
  1577. return;
  1578. }
  1579. // An unnamed member must represent a nested struct or union. Add all the
  1580. // indirect fields to the current record.
  1581. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
  1582. uint64_t Offset = DDTy->getOffsetInBits();
  1583. const DIType *Ty = DDTy->getBaseType().resolve();
  1584. const DICompositeType *DCTy = cast<DICompositeType>(Ty);
  1585. ClassInfo NestedInfo = collectClassInfo(DCTy);
  1586. for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
  1587. Info.Members.push_back(
  1588. {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
  1589. }
  1590. ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
  1591. ClassInfo Info;
  1592. // Add elements to structure type.
  1593. DINodeArray Elements = Ty->getElements();
  1594. for (auto *Element : Elements) {
  1595. // We assume that the frontend provides all members in source declaration
  1596. // order, which is what MSVC does.
  1597. if (!Element)
  1598. continue;
  1599. if (auto *SP = dyn_cast<DISubprogram>(Element)) {
  1600. Info.Methods[SP->getRawName()].push_back(SP);
  1601. } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  1602. if (DDTy->getTag() == dwarf::DW_TAG_member) {
  1603. collectMemberInfo(Info, DDTy);
  1604. } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
  1605. Info.Inheritance.push_back(DDTy);
  1606. } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
  1607. DDTy->getName() == "__vtbl_ptr_type") {
  1608. Info.VShapeTI = getTypeIndex(DDTy);
  1609. } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
  1610. Info.NestedTypes.push_back(DDTy);
  1611. } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  1612. // Ignore friend members. It appears that MSVC emitted info about
  1613. // friends in the past, but modern versions do not.
  1614. }
  1615. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  1616. Info.NestedTypes.push_back(Composite);
  1617. }
  1618. // Skip other unrecognized kinds of elements.
  1619. }
  1620. return Info;
  1621. }
  1622. TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
  1623. // First, construct the forward decl. Don't look into Ty to compute the
  1624. // forward decl options, since it might not be available in all TUs.
  1625. TypeRecordKind Kind = getRecordKind(Ty);
  1626. ClassOptions CO =
  1627. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1628. std::string FullName = getFullyQualifiedName(Ty);
  1629. ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
  1630. FullName, Ty->getIdentifier());
  1631. TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
  1632. if (!Ty->isForwardDecl())
  1633. DeferredCompleteTypes.push_back(Ty);
  1634. return FwdDeclTI;
  1635. }
  1636. TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
  1637. // Construct the field list and complete type record.
  1638. TypeRecordKind Kind = getRecordKind(Ty);
  1639. ClassOptions CO = getCommonClassOptions(Ty);
  1640. TypeIndex FieldTI;
  1641. TypeIndex VShapeTI;
  1642. unsigned FieldCount;
  1643. bool ContainsNestedClass;
  1644. std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
  1645. lowerRecordFieldList(Ty);
  1646. if (ContainsNestedClass)
  1647. CO |= ClassOptions::ContainsNestedClass;
  1648. std::string FullName = getFullyQualifiedName(Ty);
  1649. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1650. ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
  1651. SizeInBytes, FullName, Ty->getIdentifier());
  1652. TypeIndex ClassTI = TypeTable.writeLeafType(CR);
  1653. if (const auto *File = Ty->getFile()) {
  1654. StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
  1655. TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
  1656. UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
  1657. TypeTable.writeLeafType(USLR);
  1658. }
  1659. addToUDTs(Ty);
  1660. return ClassTI;
  1661. }
  1662. TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
  1663. ClassOptions CO =
  1664. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1665. std::string FullName = getFullyQualifiedName(Ty);
  1666. UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
  1667. TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
  1668. if (!Ty->isForwardDecl())
  1669. DeferredCompleteTypes.push_back(Ty);
  1670. return FwdDeclTI;
  1671. }
  1672. TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
  1673. ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
  1674. TypeIndex FieldTI;
  1675. unsigned FieldCount;
  1676. bool ContainsNestedClass;
  1677. std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
  1678. lowerRecordFieldList(Ty);
  1679. if (ContainsNestedClass)
  1680. CO |= ClassOptions::ContainsNestedClass;
  1681. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1682. std::string FullName = getFullyQualifiedName(Ty);
  1683. UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
  1684. Ty->getIdentifier());
  1685. TypeIndex UnionTI = TypeTable.writeLeafType(UR);
  1686. StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
  1687. TypeIndex SIRI = TypeTable.writeLeafType(SIR);
  1688. UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
  1689. TypeTable.writeLeafType(USLR);
  1690. addToUDTs(Ty);
  1691. return UnionTI;
  1692. }
  1693. std::tuple<TypeIndex, TypeIndex, unsigned, bool>
  1694. CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
  1695. // Manually count members. MSVC appears to count everything that generates a
  1696. // field list record. Each individual overload in a method overload group
  1697. // contributes to this count, even though the overload group is a single field
  1698. // list record.
  1699. unsigned MemberCount = 0;
  1700. ClassInfo Info = collectClassInfo(Ty);
  1701. ContinuationRecordBuilder ContinuationBuilder;
  1702. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  1703. // Create base classes.
  1704. for (const DIDerivedType *I : Info.Inheritance) {
  1705. if (I->getFlags() & DINode::FlagVirtual) {
  1706. // Virtual base.
  1707. // FIXME: Emit VBPtrOffset when the frontend provides it.
  1708. unsigned VBPtrOffset = 0;
  1709. // FIXME: Despite the accessor name, the offset is really in bytes.
  1710. unsigned VBTableIndex = I->getOffsetInBits() / 4;
  1711. auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
  1712. ? TypeRecordKind::IndirectVirtualBaseClass
  1713. : TypeRecordKind::VirtualBaseClass;
  1714. VirtualBaseClassRecord VBCR(
  1715. RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
  1716. getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
  1717. VBTableIndex);
  1718. ContinuationBuilder.writeMemberType(VBCR);
  1719. } else {
  1720. assert(I->getOffsetInBits() % 8 == 0 &&
  1721. "bases must be on byte boundaries");
  1722. BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
  1723. getTypeIndex(I->getBaseType()),
  1724. I->getOffsetInBits() / 8);
  1725. ContinuationBuilder.writeMemberType(BCR);
  1726. }
  1727. }
  1728. // Create members.
  1729. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
  1730. const DIDerivedType *Member = MemberInfo.MemberTypeNode;
  1731. TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
  1732. StringRef MemberName = Member->getName();
  1733. MemberAccess Access =
  1734. translateAccessFlags(Ty->getTag(), Member->getFlags());
  1735. if (Member->isStaticMember()) {
  1736. StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
  1737. ContinuationBuilder.writeMemberType(SDMR);
  1738. MemberCount++;
  1739. continue;
  1740. }
  1741. // Virtual function pointer member.
  1742. if ((Member->getFlags() & DINode::FlagArtificial) &&
  1743. Member->getName().startswith("_vptr$")) {
  1744. VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
  1745. ContinuationBuilder.writeMemberType(VFPR);
  1746. MemberCount++;
  1747. continue;
  1748. }
  1749. // Data member.
  1750. uint64_t MemberOffsetInBits =
  1751. Member->getOffsetInBits() + MemberInfo.BaseOffset;
  1752. if (Member->isBitField()) {
  1753. uint64_t StartBitOffset = MemberOffsetInBits;
  1754. if (const auto *CI =
  1755. dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
  1756. MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
  1757. }
  1758. StartBitOffset -= MemberOffsetInBits;
  1759. BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
  1760. StartBitOffset);
  1761. MemberBaseType = TypeTable.writeLeafType(BFR);
  1762. }
  1763. uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
  1764. DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
  1765. MemberName);
  1766. ContinuationBuilder.writeMemberType(DMR);
  1767. MemberCount++;
  1768. }
  1769. // Create methods
  1770. for (auto &MethodItr : Info.Methods) {
  1771. StringRef Name = MethodItr.first->getString();
  1772. std::vector<OneMethodRecord> Methods;
  1773. for (const DISubprogram *SP : MethodItr.second) {
  1774. TypeIndex MethodType = getMemberFunctionType(SP, Ty);
  1775. bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
  1776. unsigned VFTableOffset = -1;
  1777. if (Introduced)
  1778. VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
  1779. Methods.push_back(OneMethodRecord(
  1780. MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
  1781. translateMethodKindFlags(SP, Introduced),
  1782. translateMethodOptionFlags(SP), VFTableOffset, Name));
  1783. MemberCount++;
  1784. }
  1785. assert(!Methods.empty() && "Empty methods map entry");
  1786. if (Methods.size() == 1)
  1787. ContinuationBuilder.writeMemberType(Methods[0]);
  1788. else {
  1789. // FIXME: Make this use its own ContinuationBuilder so that
  1790. // MethodOverloadList can be split correctly.
  1791. MethodOverloadListRecord MOLR(Methods);
  1792. TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
  1793. OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
  1794. ContinuationBuilder.writeMemberType(OMR);
  1795. }
  1796. }
  1797. // Create nested classes.
  1798. for (const DIType *Nested : Info.NestedTypes) {
  1799. NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
  1800. ContinuationBuilder.writeMemberType(R);
  1801. MemberCount++;
  1802. }
  1803. TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
  1804. return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
  1805. !Info.NestedTypes.empty());
  1806. }
  1807. TypeIndex CodeViewDebug::getVBPTypeIndex() {
  1808. if (!VBPType.getIndex()) {
  1809. // Make a 'const int *' type.
  1810. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
  1811. TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
  1812. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1813. : PointerKind::Near32;
  1814. PointerMode PM = PointerMode::Pointer;
  1815. PointerOptions PO = PointerOptions::None;
  1816. PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
  1817. VBPType = TypeTable.writeLeafType(PR);
  1818. }
  1819. return VBPType;
  1820. }
  1821. TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
  1822. const DIType *Ty = TypeRef.resolve();
  1823. const DIType *ClassTy = ClassTyRef.resolve();
  1824. // The null DIType is the void type. Don't try to hash it.
  1825. if (!Ty)
  1826. return TypeIndex::Void();
  1827. // Check if we've already translated this type. Don't try to do a
  1828. // get-or-create style insertion that caches the hash lookup across the
  1829. // lowerType call. It will update the TypeIndices map.
  1830. auto I = TypeIndices.find({Ty, ClassTy});
  1831. if (I != TypeIndices.end())
  1832. return I->second;
  1833. TypeLoweringScope S(*this);
  1834. TypeIndex TI = lowerType(Ty, ClassTy);
  1835. return recordTypeIndexForDINode(Ty, TI, ClassTy);
  1836. }
  1837. TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
  1838. DIType *Ty = TypeRef.resolve();
  1839. PointerRecord PR(getTypeIndex(Ty),
  1840. getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1841. : PointerKind::Near32,
  1842. PointerMode::LValueReference, PointerOptions::None,
  1843. Ty->getSizeInBits() / 8);
  1844. return TypeTable.writeLeafType(PR);
  1845. }
  1846. TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
  1847. const DIType *Ty = TypeRef.resolve();
  1848. // The null DIType is the void type. Don't try to hash it.
  1849. if (!Ty)
  1850. return TypeIndex::Void();
  1851. // If this is a non-record type, the complete type index is the same as the
  1852. // normal type index. Just call getTypeIndex.
  1853. switch (Ty->getTag()) {
  1854. case dwarf::DW_TAG_class_type:
  1855. case dwarf::DW_TAG_structure_type:
  1856. case dwarf::DW_TAG_union_type:
  1857. break;
  1858. default:
  1859. return getTypeIndex(Ty);
  1860. }
  1861. // Check if we've already translated the complete record type. Lowering a
  1862. // complete type should never trigger lowering another complete type, so we
  1863. // can reuse the hash table lookup result.
  1864. const auto *CTy = cast<DICompositeType>(Ty);
  1865. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
  1866. if (!InsertResult.second)
  1867. return InsertResult.first->second;
  1868. TypeLoweringScope S(*this);
  1869. // Make sure the forward declaration is emitted first. It's unclear if this
  1870. // is necessary, but MSVC does it, and we should follow suit until we can show
  1871. // otherwise.
  1872. TypeIndex FwdDeclTI = getTypeIndex(CTy);
  1873. // Just use the forward decl if we don't have complete type info. This might
  1874. // happen if the frontend is using modules and expects the complete definition
  1875. // to be emitted elsewhere.
  1876. if (CTy->isForwardDecl())
  1877. return FwdDeclTI;
  1878. TypeIndex TI;
  1879. switch (CTy->getTag()) {
  1880. case dwarf::DW_TAG_class_type:
  1881. case dwarf::DW_TAG_structure_type:
  1882. TI = lowerCompleteTypeClass(CTy);
  1883. break;
  1884. case dwarf::DW_TAG_union_type:
  1885. TI = lowerCompleteTypeUnion(CTy);
  1886. break;
  1887. default:
  1888. llvm_unreachable("not a record");
  1889. }
  1890. InsertResult.first->second = TI;
  1891. return TI;
  1892. }
  1893. /// Emit all the deferred complete record types. Try to do this in FIFO order,
  1894. /// and do this until fixpoint, as each complete record type typically
  1895. /// references
  1896. /// many other record types.
  1897. void CodeViewDebug::emitDeferredCompleteTypes() {
  1898. SmallVector<const DICompositeType *, 4> TypesToEmit;
  1899. while (!DeferredCompleteTypes.empty()) {
  1900. std::swap(DeferredCompleteTypes, TypesToEmit);
  1901. for (const DICompositeType *RecordTy : TypesToEmit)
  1902. getCompleteTypeIndex(RecordTy);
  1903. TypesToEmit.clear();
  1904. }
  1905. }
  1906. void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
  1907. // Get the sorted list of parameters and emit them first.
  1908. SmallVector<const LocalVariable *, 6> Params;
  1909. for (const LocalVariable &L : Locals)
  1910. if (L.DIVar->isParameter())
  1911. Params.push_back(&L);
  1912. std::sort(Params.begin(), Params.end(),
  1913. [](const LocalVariable *L, const LocalVariable *R) {
  1914. return L->DIVar->getArg() < R->DIVar->getArg();
  1915. });
  1916. for (const LocalVariable *L : Params)
  1917. emitLocalVariable(*L);
  1918. // Next emit all non-parameters in the order that we found them.
  1919. for (const LocalVariable &L : Locals)
  1920. if (!L.DIVar->isParameter())
  1921. emitLocalVariable(L);
  1922. }
  1923. void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
  1924. // LocalSym record, see SymbolRecord.h for more info.
  1925. MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
  1926. *LocalEnd = MMI->getContext().createTempSymbol();
  1927. OS.AddComment("Record length");
  1928. OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
  1929. OS.EmitLabel(LocalBegin);
  1930. OS.AddComment("Record kind: S_LOCAL");
  1931. OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
  1932. LocalSymFlags Flags = LocalSymFlags::None;
  1933. if (Var.DIVar->isParameter())
  1934. Flags |= LocalSymFlags::IsParameter;
  1935. if (Var.DefRanges.empty())
  1936. Flags |= LocalSymFlags::IsOptimizedOut;
  1937. OS.AddComment("TypeIndex");
  1938. TypeIndex TI = Var.UseReferenceType
  1939. ? getTypeIndexForReferenceTo(Var.DIVar->getType())
  1940. : getCompleteTypeIndex(Var.DIVar->getType());
  1941. OS.EmitIntValue(TI.getIndex(), 4);
  1942. OS.AddComment("Flags");
  1943. OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
  1944. // Truncate the name so we won't overflow the record length field.
  1945. emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
  1946. OS.EmitLabel(LocalEnd);
  1947. // Calculate the on disk prefix of the appropriate def range record. The
  1948. // records and on disk formats are described in SymbolRecords.h. BytePrefix
  1949. // should be big enough to hold all forms without memory allocation.
  1950. SmallString<20> BytePrefix;
  1951. for (const LocalVarDefRange &DefRange : Var.DefRanges) {
  1952. BytePrefix.clear();
  1953. if (DefRange.InMemory) {
  1954. uint16_t RegRelFlags = 0;
  1955. if (DefRange.IsSubfield) {
  1956. RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
  1957. (DefRange.StructOffset
  1958. << DefRangeRegisterRelSym::OffsetInParentShift);
  1959. }
  1960. DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
  1961. Sym.Hdr.Register = DefRange.CVRegister;
  1962. Sym.Hdr.Flags = RegRelFlags;
  1963. Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
  1964. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
  1965. BytePrefix +=
  1966. StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
  1967. BytePrefix +=
  1968. StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
  1969. } else {
  1970. assert(DefRange.DataOffset == 0 && "unexpected offset into register");
  1971. if (DefRange.IsSubfield) {
  1972. // Unclear what matters here.
  1973. DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
  1974. Sym.Hdr.Register = DefRange.CVRegister;
  1975. Sym.Hdr.MayHaveNoName = 0;
  1976. Sym.Hdr.OffsetInParent = DefRange.StructOffset;
  1977. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
  1978. BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
  1979. sizeof(SymKind));
  1980. BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
  1981. sizeof(Sym.Hdr));
  1982. } else {
  1983. // Unclear what matters here.
  1984. DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
  1985. Sym.Hdr.Register = DefRange.CVRegister;
  1986. Sym.Hdr.MayHaveNoName = 0;
  1987. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
  1988. BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
  1989. sizeof(SymKind));
  1990. BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
  1991. sizeof(Sym.Hdr));
  1992. }
  1993. }
  1994. OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
  1995. }
  1996. }
  1997. void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
  1998. const Function &GV = MF->getFunction();
  1999. assert(FnDebugInfo.count(&GV));
  2000. assert(CurFn == &FnDebugInfo[&GV]);
  2001. collectVariableInfo(GV.getSubprogram());
  2002. // Don't emit anything if we don't have any line tables.
  2003. if (!CurFn->HaveLineInfo) {
  2004. FnDebugInfo.erase(&GV);
  2005. CurFn = nullptr;
  2006. return;
  2007. }
  2008. CurFn->Annotations = MF->getCodeViewAnnotations();
  2009. CurFn->End = Asm->getFunctionEnd();
  2010. CurFn = nullptr;
  2011. }
  2012. void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
  2013. DebugHandlerBase::beginInstruction(MI);
  2014. // Ignore DBG_VALUE locations and function prologue.
  2015. if (!Asm || !CurFn || MI->isDebugValue() ||
  2016. MI->getFlag(MachineInstr::FrameSetup))
  2017. return;
  2018. // If the first instruction of a new MBB has no location, find the first
  2019. // instruction with a location and use that.
  2020. DebugLoc DL = MI->getDebugLoc();
  2021. if (!DL && MI->getParent() != PrevInstBB) {
  2022. for (const auto &NextMI : *MI->getParent()) {
  2023. if (NextMI.isDebugValue())
  2024. continue;
  2025. DL = NextMI.getDebugLoc();
  2026. if (DL)
  2027. break;
  2028. }
  2029. }
  2030. PrevInstBB = MI->getParent();
  2031. // If we still don't have a debug location, don't record a location.
  2032. if (!DL)
  2033. return;
  2034. maybeRecordLocation(DL, Asm->MF);
  2035. }
  2036. MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
  2037. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  2038. *EndLabel = MMI->getContext().createTempSymbol();
  2039. OS.EmitIntValue(unsigned(Kind), 4);
  2040. OS.AddComment("Subsection size");
  2041. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
  2042. OS.EmitLabel(BeginLabel);
  2043. return EndLabel;
  2044. }
  2045. void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
  2046. OS.EmitLabel(EndLabel);
  2047. // Every subsection must be aligned to a 4-byte boundary.
  2048. OS.EmitValueToAlignment(4);
  2049. }
  2050. void CodeViewDebug::emitDebugInfoForUDTs(
  2051. ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
  2052. for (const auto &UDT : UDTs) {
  2053. const DIType *T = UDT.second;
  2054. assert(shouldEmitUdt(T));
  2055. MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
  2056. *UDTRecordEnd = MMI->getContext().createTempSymbol();
  2057. OS.AddComment("Record length");
  2058. OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
  2059. OS.EmitLabel(UDTRecordBegin);
  2060. OS.AddComment("Record kind: S_UDT");
  2061. OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
  2062. OS.AddComment("Type");
  2063. OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
  2064. emitNullTerminatedSymbolName(OS, UDT.first);
  2065. OS.EmitLabel(UDTRecordEnd);
  2066. }
  2067. }
  2068. void CodeViewDebug::emitDebugInfoForGlobals() {
  2069. DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
  2070. GlobalMap;
  2071. for (const GlobalVariable &GV : MMI->getModule()->globals()) {
  2072. SmallVector<DIGlobalVariableExpression *, 1> GVEs;
  2073. GV.getDebugInfo(GVEs);
  2074. for (const auto *GVE : GVEs)
  2075. GlobalMap[GVE] = &GV;
  2076. }
  2077. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2078. for (const MDNode *Node : CUs->operands()) {
  2079. const auto *CU = cast<DICompileUnit>(Node);
  2080. // First, emit all globals that are not in a comdat in a single symbol
  2081. // substream. MSVC doesn't like it if the substream is empty, so only open
  2082. // it if we have at least one global to emit.
  2083. switchToDebugSectionForSymbol(nullptr);
  2084. MCSymbol *EndLabel = nullptr;
  2085. for (const auto *GVE : CU->getGlobalVariables()) {
  2086. if (const auto *GV = GlobalMap.lookup(GVE))
  2087. if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
  2088. if (!EndLabel) {
  2089. OS.AddComment("Symbol subsection for globals");
  2090. EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2091. }
  2092. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2093. emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
  2094. }
  2095. }
  2096. if (EndLabel)
  2097. endCVSubsection(EndLabel);
  2098. // Second, emit each global that is in a comdat into its own .debug$S
  2099. // section along with its own symbol substream.
  2100. for (const auto *GVE : CU->getGlobalVariables()) {
  2101. if (const auto *GV = GlobalMap.lookup(GVE)) {
  2102. if (GV->hasComdat()) {
  2103. MCSymbol *GVSym = Asm->getSymbol(GV);
  2104. OS.AddComment("Symbol subsection for " +
  2105. Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
  2106. switchToDebugSectionForSymbol(GVSym);
  2107. EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2108. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2109. emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
  2110. endCVSubsection(EndLabel);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. }
  2116. void CodeViewDebug::emitDebugInfoForRetainedTypes() {
  2117. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2118. for (const MDNode *Node : CUs->operands()) {
  2119. for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
  2120. if (DIType *RT = dyn_cast<DIType>(Ty)) {
  2121. getTypeIndex(RT);
  2122. // FIXME: Add to global/local DTU list.
  2123. }
  2124. }
  2125. }
  2126. }
  2127. void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
  2128. const GlobalVariable *GV,
  2129. MCSymbol *GVSym) {
  2130. // DataSym record, see SymbolRecord.h for more info.
  2131. // FIXME: Thread local data, etc
  2132. MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
  2133. *DataEnd = MMI->getContext().createTempSymbol();
  2134. OS.AddComment("Record length");
  2135. OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
  2136. OS.EmitLabel(DataBegin);
  2137. if (DIGV->isLocalToUnit()) {
  2138. if (GV->isThreadLocal()) {
  2139. OS.AddComment("Record kind: S_LTHREAD32");
  2140. OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
  2141. } else {
  2142. OS.AddComment("Record kind: S_LDATA32");
  2143. OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
  2144. }
  2145. } else {
  2146. if (GV->isThreadLocal()) {
  2147. OS.AddComment("Record kind: S_GTHREAD32");
  2148. OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
  2149. } else {
  2150. OS.AddComment("Record kind: S_GDATA32");
  2151. OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
  2152. }
  2153. }
  2154. OS.AddComment("Type");
  2155. OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
  2156. OS.AddComment("DataOffset");
  2157. OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
  2158. OS.AddComment("Segment");
  2159. OS.EmitCOFFSectionIndex(GVSym);
  2160. OS.AddComment("Name");
  2161. emitNullTerminatedSymbolName(OS, DIGV->getName());
  2162. OS.EmitLabel(DataEnd);
  2163. }