CodeViewDebug.cpp 106 KB

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