CodeViewDebug.cpp 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429
  1. //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing Microsoft CodeView debug info.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeViewDebug.h"
  13. #include "llvm/ADT/APSInt.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/TinyPtrVector.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/BinaryFormat/COFF.h"
  21. #include "llvm/BinaryFormat/Dwarf.h"
  22. #include "llvm/CodeGen/AsmPrinter.h"
  23. #include "llvm/CodeGen/LexicalScopes.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineInstr.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/TargetFrameLowering.h"
  29. #include "llvm/CodeGen/TargetRegisterInfo.h"
  30. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  31. #include "llvm/Config/llvm-config.h"
  32. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  33. #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
  34. #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
  35. #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
  36. #include "llvm/DebugInfo/CodeView/EnumTables.h"
  37. #include "llvm/DebugInfo/CodeView/Line.h"
  38. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  39. #include "llvm/DebugInfo/CodeView/TypeRecord.h"
  40. #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
  41. #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
  42. #include "llvm/IR/Constants.h"
  43. #include "llvm/IR/DataLayout.h"
  44. #include "llvm/IR/DebugInfoMetadata.h"
  45. #include "llvm/IR/Function.h"
  46. #include "llvm/IR/GlobalValue.h"
  47. #include "llvm/IR/GlobalVariable.h"
  48. #include "llvm/IR/Metadata.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/MC/MCAsmInfo.h"
  51. #include "llvm/MC/MCContext.h"
  52. #include "llvm/MC/MCSectionCOFF.h"
  53. #include "llvm/MC/MCStreamer.h"
  54. #include "llvm/MC/MCSymbol.h"
  55. #include "llvm/Support/BinaryStreamWriter.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/Endian.h"
  58. #include "llvm/Support/Error.h"
  59. #include "llvm/Support/ErrorHandling.h"
  60. #include "llvm/Support/FormatVariadic.h"
  61. #include "llvm/Support/Path.h"
  62. #include "llvm/Support/Program.h"
  63. #include "llvm/Support/SMLoc.h"
  64. #include "llvm/Support/ScopedPrinter.h"
  65. #include "llvm/Target/TargetLoweringObjectFile.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <cctype>
  70. #include <cstddef>
  71. #include <iterator>
  72. #include <limits>
  73. using namespace llvm;
  74. using namespace llvm::codeview;
  75. namespace {
  76. class CVMCAdapter : public CodeViewRecordStreamer {
  77. public:
  78. CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
  79. : OS(&OS), TypeTable(TypeTable) {}
  80. void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
  81. void emitIntValue(uint64_t Value, unsigned Size) override {
  82. OS->emitIntValueInHex(Value, Size);
  83. }
  84. void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
  85. void AddComment(const Twine &T) override { OS->AddComment(T); }
  86. void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
  87. bool isVerboseAsm() override { return OS->isVerboseAsm(); }
  88. std::string getTypeName(TypeIndex TI) override {
  89. std::string TypeName;
  90. if (!TI.isNoneType()) {
  91. if (TI.isSimple())
  92. TypeName = std::string(TypeIndex::simpleTypeName(TI));
  93. else
  94. TypeName = std::string(TypeTable.getTypeName(TI));
  95. }
  96. return TypeName;
  97. }
  98. private:
  99. MCStreamer *OS = nullptr;
  100. TypeCollection &TypeTable;
  101. };
  102. } // namespace
  103. static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
  104. switch (Type) {
  105. case Triple::ArchType::x86:
  106. return CPUType::Pentium3;
  107. case Triple::ArchType::x86_64:
  108. return CPUType::X64;
  109. case Triple::ArchType::thumb:
  110. // LLVM currently doesn't support Windows CE and so thumb
  111. // here is indiscriminately mapped to ARMNT specifically.
  112. return CPUType::ARMNT;
  113. case Triple::ArchType::aarch64:
  114. return CPUType::ARM64;
  115. default:
  116. report_fatal_error("target architecture doesn't map to a CodeView CPUType");
  117. }
  118. }
  119. CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
  120. : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
  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.startswith("/") || Filename.startswith("/")) {
  129. if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
  130. return Filename;
  131. Filepath = std::string(Dir);
  132. if (Dir.back() != '/')
  133. Filepath += '/';
  134. Filepath += Filename;
  135. return Filepath;
  136. }
  137. // Clang emits directory and relative filename info into the IR, but CodeView
  138. // operates on full paths. We could change Clang to emit full paths too, but
  139. // that would increase the IR size and probably not needed for other users.
  140. // For now, just concatenate and canonicalize the path here.
  141. if (Filename.find(':') == 1)
  142. Filepath = std::string(Filename);
  143. else
  144. Filepath = (Dir + "\\" + Filename).str();
  145. // Canonicalize the path. We have to do it textually because we may no longer
  146. // have access the file in the filesystem.
  147. // First, replace all slashes with backslashes.
  148. std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
  149. // Remove all "\.\" with "\".
  150. size_t Cursor = 0;
  151. while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
  152. Filepath.erase(Cursor, 2);
  153. // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
  154. // path should be well-formatted, e.g. start with a drive letter, etc.
  155. Cursor = 0;
  156. while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
  157. // Something's wrong if the path starts with "\..\", abort.
  158. if (Cursor == 0)
  159. break;
  160. size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
  161. if (PrevSlash == std::string::npos)
  162. // Something's wrong, abort.
  163. break;
  164. Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
  165. // The next ".." might be following the one we've just erased.
  166. Cursor = PrevSlash;
  167. }
  168. // Remove all duplicate backslashes.
  169. Cursor = 0;
  170. while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
  171. Filepath.erase(Cursor, 1);
  172. return Filepath;
  173. }
  174. unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
  175. StringRef FullPath = getFullFilepath(F);
  176. unsigned NextId = FileIdMap.size() + 1;
  177. auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
  178. if (Insertion.second) {
  179. // We have to compute the full filepath and emit a .cv_file directive.
  180. ArrayRef<uint8_t> ChecksumAsBytes;
  181. FileChecksumKind CSKind = FileChecksumKind::None;
  182. if (F->getChecksum()) {
  183. std::string Checksum = fromHex(F->getChecksum()->Value);
  184. void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
  185. memcpy(CKMem, Checksum.data(), Checksum.size());
  186. ChecksumAsBytes = ArrayRef<uint8_t>(
  187. reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
  188. switch (F->getChecksum()->Kind) {
  189. case DIFile::CSK_MD5:
  190. CSKind = FileChecksumKind::MD5;
  191. break;
  192. case DIFile::CSK_SHA1:
  193. CSKind = FileChecksumKind::SHA1;
  194. break;
  195. case DIFile::CSK_SHA256:
  196. CSKind = FileChecksumKind::SHA256;
  197. break;
  198. }
  199. }
  200. bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
  201. static_cast<unsigned>(CSKind));
  202. (void)Success;
  203. assert(Success && ".cv_file directive failed");
  204. }
  205. return Insertion.first->second;
  206. }
  207. CodeViewDebug::InlineSite &
  208. CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
  209. const DISubprogram *Inlinee) {
  210. auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
  211. InlineSite *Site = &SiteInsertion.first->second;
  212. if (SiteInsertion.second) {
  213. unsigned ParentFuncId = CurFn->FuncId;
  214. if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
  215. ParentFuncId =
  216. getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
  217. .SiteFuncId;
  218. Site->SiteFuncId = NextFuncId++;
  219. OS.emitCVInlineSiteIdDirective(
  220. Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
  221. InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
  222. Site->Inlinee = Inlinee;
  223. InlinedSubprograms.insert(Inlinee);
  224. getFuncIdForSubprogram(Inlinee);
  225. }
  226. return *Site;
  227. }
  228. static StringRef getPrettyScopeName(const DIScope *Scope) {
  229. StringRef ScopeName = Scope->getName();
  230. if (!ScopeName.empty())
  231. return ScopeName;
  232. switch (Scope->getTag()) {
  233. case dwarf::DW_TAG_enumeration_type:
  234. case dwarf::DW_TAG_class_type:
  235. case dwarf::DW_TAG_structure_type:
  236. case dwarf::DW_TAG_union_type:
  237. return "<unnamed-tag>";
  238. case dwarf::DW_TAG_namespace:
  239. return "`anonymous namespace'";
  240. default:
  241. return StringRef();
  242. }
  243. }
  244. const DISubprogram *CodeViewDebug::collectParentScopeNames(
  245. const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
  246. const DISubprogram *ClosestSubprogram = nullptr;
  247. while (Scope != nullptr) {
  248. if (ClosestSubprogram == nullptr)
  249. ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
  250. // If a type appears in a scope chain, make sure it gets emitted. The
  251. // frontend will be responsible for deciding if this should be a forward
  252. // declaration or a complete type.
  253. if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
  254. DeferredCompleteTypes.push_back(Ty);
  255. StringRef ScopeName = getPrettyScopeName(Scope);
  256. if (!ScopeName.empty())
  257. QualifiedNameComponents.push_back(ScopeName);
  258. Scope = Scope->getScope();
  259. }
  260. return ClosestSubprogram;
  261. }
  262. static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
  263. StringRef TypeName) {
  264. std::string FullyQualifiedName;
  265. for (StringRef QualifiedNameComponent :
  266. llvm::reverse(QualifiedNameComponents)) {
  267. FullyQualifiedName.append(std::string(QualifiedNameComponent));
  268. FullyQualifiedName.append("::");
  269. }
  270. FullyQualifiedName.append(std::string(TypeName));
  271. return FullyQualifiedName;
  272. }
  273. struct CodeViewDebug::TypeLoweringScope {
  274. TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
  275. ~TypeLoweringScope() {
  276. // Don't decrement TypeEmissionLevel until after emitting deferred types, so
  277. // inner TypeLoweringScopes don't attempt to emit deferred types.
  278. if (CVD.TypeEmissionLevel == 1)
  279. CVD.emitDeferredCompleteTypes();
  280. --CVD.TypeEmissionLevel;
  281. }
  282. CodeViewDebug &CVD;
  283. };
  284. std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
  285. StringRef Name) {
  286. // Ensure types in the scope chain are emitted as soon as possible.
  287. // This can create otherwise a situation where S_UDTs are emitted while
  288. // looping in emitDebugInfoForUDTs.
  289. TypeLoweringScope S(*this);
  290. SmallVector<StringRef, 5> QualifiedNameComponents;
  291. collectParentScopeNames(Scope, QualifiedNameComponents);
  292. return formatNestedName(QualifiedNameComponents, Name);
  293. }
  294. std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
  295. const DIScope *Scope = Ty->getScope();
  296. return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
  297. }
  298. TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
  299. // No scope means global scope and that uses the zero index.
  300. //
  301. // We also use zero index when the scope is a DISubprogram
  302. // to suppress the emission of LF_STRING_ID for the function,
  303. // which can trigger a link-time error with the linker in
  304. // VS2019 version 16.11.2 or newer.
  305. // Note, however, skipping the debug info emission for the DISubprogram
  306. // is a temporary fix. The root issue here is that we need to figure out
  307. // the proper way to encode a function nested in another function
  308. // (as introduced by the Fortran 'contains' keyword) in CodeView.
  309. if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
  310. return TypeIndex();
  311. assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
  312. // Check if we've already translated this scope.
  313. auto I = TypeIndices.find({Scope, nullptr});
  314. if (I != TypeIndices.end())
  315. return I->second;
  316. // Build the fully qualified name of the scope.
  317. std::string ScopeName = getFullyQualifiedName(Scope);
  318. StringIdRecord SID(TypeIndex(), ScopeName);
  319. auto TI = TypeTable.writeLeafType(SID);
  320. return recordTypeIndexForDINode(Scope, TI);
  321. }
  322. static StringRef removeTemplateArgs(StringRef Name) {
  323. // Remove template args from the display name. Assume that the template args
  324. // are the last thing in the name.
  325. if (Name.empty() || Name.back() != '>')
  326. return Name;
  327. int OpenBrackets = 0;
  328. for (int i = Name.size() - 1; i >= 0; --i) {
  329. if (Name[i] == '>')
  330. ++OpenBrackets;
  331. else if (Name[i] == '<') {
  332. --OpenBrackets;
  333. if (OpenBrackets == 0)
  334. return Name.substr(0, i);
  335. }
  336. }
  337. return Name;
  338. }
  339. TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
  340. assert(SP);
  341. // Check if we've already translated this subprogram.
  342. auto I = TypeIndices.find({SP, nullptr});
  343. if (I != TypeIndices.end())
  344. return I->second;
  345. // The display name includes function template arguments. Drop them to match
  346. // MSVC. We need to have the template arguments in the DISubprogram name
  347. // because they are used in other symbol records, such as S_GPROC32_IDs.
  348. StringRef DisplayName = removeTemplateArgs(SP->getName());
  349. const DIScope *Scope = SP->getScope();
  350. TypeIndex TI;
  351. if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
  352. // If the scope is a DICompositeType, then this must be a method. Member
  353. // function types take some special handling, and require access to the
  354. // subprogram.
  355. TypeIndex ClassType = getTypeIndex(Class);
  356. MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
  357. DisplayName);
  358. TI = TypeTable.writeLeafType(MFuncId);
  359. } else {
  360. // Otherwise, this must be a free function.
  361. TypeIndex ParentScope = getScopeIndex(Scope);
  362. FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
  363. TI = TypeTable.writeLeafType(FuncId);
  364. }
  365. return recordTypeIndexForDINode(SP, TI);
  366. }
  367. static bool isNonTrivial(const DICompositeType *DCTy) {
  368. return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
  369. }
  370. static FunctionOptions
  371. getFunctionOptions(const DISubroutineType *Ty,
  372. const DICompositeType *ClassTy = nullptr,
  373. StringRef SPName = StringRef("")) {
  374. FunctionOptions FO = FunctionOptions::None;
  375. const DIType *ReturnTy = nullptr;
  376. if (auto TypeArray = Ty->getTypeArray()) {
  377. if (TypeArray.size())
  378. ReturnTy = TypeArray[0];
  379. }
  380. // Add CxxReturnUdt option to functions that return nontrivial record types
  381. // or methods that return record types.
  382. if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
  383. if (isNonTrivial(ReturnDCTy) || ClassTy)
  384. FO |= FunctionOptions::CxxReturnUdt;
  385. // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
  386. if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
  387. FO |= FunctionOptions::Constructor;
  388. // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
  389. }
  390. return FO;
  391. }
  392. TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
  393. const DICompositeType *Class) {
  394. // Always use the method declaration as the key for the function type. The
  395. // method declaration contains the this adjustment.
  396. if (SP->getDeclaration())
  397. SP = SP->getDeclaration();
  398. assert(!SP->getDeclaration() && "should use declaration as key");
  399. // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
  400. // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
  401. auto I = TypeIndices.find({SP, Class});
  402. if (I != TypeIndices.end())
  403. return I->second;
  404. // Make sure complete type info for the class is emitted *after* the member
  405. // function type, as the complete class type is likely to reference this
  406. // member function type.
  407. TypeLoweringScope S(*this);
  408. const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
  409. FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
  410. TypeIndex TI = lowerTypeMemberFunction(
  411. SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
  412. return recordTypeIndexForDINode(SP, TI, Class);
  413. }
  414. TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
  415. TypeIndex TI,
  416. const DIType *ClassTy) {
  417. auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
  418. (void)InsertResult;
  419. assert(InsertResult.second && "DINode was already assigned a type index");
  420. return TI;
  421. }
  422. unsigned CodeViewDebug::getPointerSizeInBytes() {
  423. return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
  424. }
  425. void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
  426. const LexicalScope *LS) {
  427. if (const DILocation *InlinedAt = LS->getInlinedAt()) {
  428. // This variable was inlined. Associate it with the InlineSite.
  429. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
  430. InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
  431. Site.InlinedLocals.emplace_back(Var);
  432. } else {
  433. // This variable goes into the corresponding lexical scope.
  434. ScopeVariables[LS].emplace_back(Var);
  435. }
  436. }
  437. static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
  438. const DILocation *Loc) {
  439. if (!llvm::is_contained(Locs, Loc))
  440. Locs.push_back(Loc);
  441. }
  442. void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
  443. const MachineFunction *MF) {
  444. // Skip this instruction if it has the same location as the previous one.
  445. if (!DL || DL == PrevInstLoc)
  446. return;
  447. const DIScope *Scope = DL->getScope();
  448. if (!Scope)
  449. return;
  450. // Skip this line if it is longer than the maximum we can record.
  451. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
  452. if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
  453. LI.isNeverStepInto())
  454. return;
  455. ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
  456. if (CI.getStartColumn() != DL.getCol())
  457. return;
  458. if (!CurFn->HaveLineInfo)
  459. CurFn->HaveLineInfo = true;
  460. unsigned FileId = 0;
  461. if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
  462. FileId = CurFn->LastFileId;
  463. else
  464. FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
  465. PrevInstLoc = DL;
  466. unsigned FuncId = CurFn->FuncId;
  467. if (const DILocation *SiteLoc = DL->getInlinedAt()) {
  468. const DILocation *Loc = DL.get();
  469. // If this location was actually inlined from somewhere else, give it the ID
  470. // of the inline call site.
  471. FuncId =
  472. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
  473. // Ensure we have links in the tree of inline call sites.
  474. bool FirstLoc = true;
  475. while ((SiteLoc = Loc->getInlinedAt())) {
  476. InlineSite &Site =
  477. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
  478. if (!FirstLoc)
  479. addLocIfNotPresent(Site.ChildSites, Loc);
  480. FirstLoc = false;
  481. Loc = SiteLoc;
  482. }
  483. addLocIfNotPresent(CurFn->ChildSites, Loc);
  484. }
  485. OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
  486. /*PrologueEnd=*/false, /*IsStmt=*/false,
  487. DL->getFilename(), SMLoc());
  488. }
  489. void CodeViewDebug::emitCodeViewMagicVersion() {
  490. OS.emitValueToAlignment(Align(4));
  491. OS.AddComment("Debug section magic");
  492. OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
  493. }
  494. static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
  495. switch (DWLang) {
  496. case dwarf::DW_LANG_C:
  497. case dwarf::DW_LANG_C89:
  498. case dwarf::DW_LANG_C99:
  499. case dwarf::DW_LANG_C11:
  500. case dwarf::DW_LANG_ObjC:
  501. return SourceLanguage::C;
  502. case dwarf::DW_LANG_C_plus_plus:
  503. case dwarf::DW_LANG_C_plus_plus_03:
  504. case dwarf::DW_LANG_C_plus_plus_11:
  505. case dwarf::DW_LANG_C_plus_plus_14:
  506. return SourceLanguage::Cpp;
  507. case dwarf::DW_LANG_Fortran77:
  508. case dwarf::DW_LANG_Fortran90:
  509. case dwarf::DW_LANG_Fortran95:
  510. case dwarf::DW_LANG_Fortran03:
  511. case dwarf::DW_LANG_Fortran08:
  512. return SourceLanguage::Fortran;
  513. case dwarf::DW_LANG_Pascal83:
  514. return SourceLanguage::Pascal;
  515. case dwarf::DW_LANG_Cobol74:
  516. case dwarf::DW_LANG_Cobol85:
  517. return SourceLanguage::Cobol;
  518. case dwarf::DW_LANG_Java:
  519. return SourceLanguage::Java;
  520. case dwarf::DW_LANG_D:
  521. return SourceLanguage::D;
  522. case dwarf::DW_LANG_Swift:
  523. return SourceLanguage::Swift;
  524. case dwarf::DW_LANG_Rust:
  525. return SourceLanguage::Rust;
  526. default:
  527. // There's no CodeView representation for this language, and CV doesn't
  528. // have an "unknown" option for the language field, so we'll use MASM,
  529. // as it's very low level.
  530. return SourceLanguage::Masm;
  531. }
  532. }
  533. void CodeViewDebug::beginModule(Module *M) {
  534. // If module doesn't have named metadata anchors or COFF debug section
  535. // is not available, skip any debug info related stuff.
  536. if (!MMI->hasDebugInfo() ||
  537. !Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
  538. Asm = nullptr;
  539. return;
  540. }
  541. TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
  542. // Get the current source language.
  543. const MDNode *Node = *M->debug_compile_units_begin();
  544. const auto *CU = cast<DICompileUnit>(Node);
  545. CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage());
  546. collectGlobalVariableInfo();
  547. // Check if we should emit type record hashes.
  548. ConstantInt *GH =
  549. mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
  550. EmitDebugGlobalHashes = GH && !GH->isZero();
  551. }
  552. void CodeViewDebug::endModule() {
  553. if (!Asm || !MMI->hasDebugInfo())
  554. return;
  555. // The COFF .debug$S section consists of several subsections, each starting
  556. // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
  557. // of the payload followed by the payload itself. The subsections are 4-byte
  558. // aligned.
  559. // Use the generic .debug$S section, and make a subsection for all the inlined
  560. // subprograms.
  561. switchToDebugSectionForSymbol(nullptr);
  562. MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
  563. emitObjName();
  564. emitCompilerInformation();
  565. endCVSubsection(CompilerInfo);
  566. emitInlineeLinesSubsection();
  567. // Emit per-function debug information.
  568. for (auto &P : FnDebugInfo)
  569. if (!P.first->isDeclarationForLinker())
  570. emitDebugInfoForFunction(P.first, *P.second);
  571. // Get types used by globals without emitting anything.
  572. // This is meant to collect all static const data members so they can be
  573. // emitted as globals.
  574. collectDebugInfoForGlobals();
  575. // Emit retained types.
  576. emitDebugInfoForRetainedTypes();
  577. // Emit global variable debug information.
  578. setCurrentSubprogram(nullptr);
  579. emitDebugInfoForGlobals();
  580. // Switch back to the generic .debug$S section after potentially processing
  581. // comdat symbol sections.
  582. switchToDebugSectionForSymbol(nullptr);
  583. // Emit UDT records for any types used by global variables.
  584. if (!GlobalUDTs.empty()) {
  585. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  586. emitDebugInfoForUDTs(GlobalUDTs);
  587. endCVSubsection(SymbolsEnd);
  588. }
  589. // This subsection holds a file index to offset in string table table.
  590. OS.AddComment("File index to string table offset subsection");
  591. OS.emitCVFileChecksumsDirective();
  592. // This subsection holds the string table.
  593. OS.AddComment("String table");
  594. OS.emitCVStringTableDirective();
  595. // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
  596. // subsection in the generic .debug$S section at the end. There is no
  597. // particular reason for this ordering other than to match MSVC.
  598. emitBuildInfo();
  599. // Emit type information and hashes last, so that any types we translate while
  600. // emitting function info are included.
  601. emitTypeInformation();
  602. if (EmitDebugGlobalHashes)
  603. emitTypeGlobalHashes();
  604. clear();
  605. }
  606. static void
  607. emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
  608. unsigned MaxFixedRecordLength = 0xF00) {
  609. // The maximum CV record length is 0xFF00. Most of the strings we emit appear
  610. // after a fixed length portion of the record. The fixed length portion should
  611. // always be less than 0xF00 (3840) bytes, so truncate the string so that the
  612. // overall record size is less than the maximum allowed.
  613. SmallString<32> NullTerminatedString(
  614. S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
  615. NullTerminatedString.push_back('\0');
  616. OS.emitBytes(NullTerminatedString);
  617. }
  618. void CodeViewDebug::emitTypeInformation() {
  619. if (TypeTable.empty())
  620. return;
  621. // Start the .debug$T or .debug$P section with 0x4.
  622. OS.switchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
  623. emitCodeViewMagicVersion();
  624. TypeTableCollection Table(TypeTable.records());
  625. TypeVisitorCallbackPipeline Pipeline;
  626. // To emit type record using Codeview MCStreamer adapter
  627. CVMCAdapter CVMCOS(OS, Table);
  628. TypeRecordMapping typeMapping(CVMCOS);
  629. Pipeline.addCallbackToPipeline(typeMapping);
  630. std::optional<TypeIndex> B = Table.getFirst();
  631. while (B) {
  632. // This will fail if the record data is invalid.
  633. CVType Record = Table.getType(*B);
  634. Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
  635. if (E) {
  636. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  637. llvm_unreachable("produced malformed type record");
  638. }
  639. B = Table.getNext(*B);
  640. }
  641. }
  642. void CodeViewDebug::emitTypeGlobalHashes() {
  643. if (TypeTable.empty())
  644. return;
  645. // Start the .debug$H section with the version and hash algorithm, currently
  646. // hardcoded to version 0, SHA1.
  647. OS.switchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
  648. OS.emitValueToAlignment(Align(4));
  649. OS.AddComment("Magic");
  650. OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC);
  651. OS.AddComment("Section Version");
  652. OS.emitInt16(0);
  653. OS.AddComment("Hash Algorithm");
  654. OS.emitInt16(uint16_t(GlobalTypeHashAlg::BLAKE3));
  655. TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
  656. for (const auto &GHR : TypeTable.hashes()) {
  657. if (OS.isVerboseAsm()) {
  658. // Emit an EOL-comment describing which TypeIndex this hash corresponds
  659. // to, as well as the stringified SHA1 hash.
  660. SmallString<32> Comment;
  661. raw_svector_ostream CommentOS(Comment);
  662. CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
  663. OS.AddComment(Comment);
  664. ++TI;
  665. }
  666. assert(GHR.Hash.size() == 8);
  667. StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
  668. GHR.Hash.size());
  669. OS.emitBinaryData(S);
  670. }
  671. }
  672. void CodeViewDebug::emitObjName() {
  673. MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
  674. StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
  675. llvm::SmallString<256> PathStore(PathRef);
  676. if (PathRef.empty() || PathRef == "-") {
  677. // Don't emit the filename if we're writing to stdout or to /dev/null.
  678. PathRef = {};
  679. } else {
  680. llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true);
  681. PathRef = PathStore;
  682. }
  683. OS.AddComment("Signature");
  684. OS.emitIntValue(0, 4);
  685. OS.AddComment("Object name");
  686. emitNullTerminatedSymbolName(OS, PathRef);
  687. endSymbolRecord(CompilerEnd);
  688. }
  689. namespace {
  690. struct Version {
  691. int Part[4];
  692. };
  693. } // end anonymous namespace
  694. // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
  695. // the version number.
  696. static Version parseVersion(StringRef Name) {
  697. Version V = {{0}};
  698. int N = 0;
  699. for (const char C : Name) {
  700. if (isdigit(C)) {
  701. V.Part[N] *= 10;
  702. V.Part[N] += C - '0';
  703. V.Part[N] =
  704. std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max());
  705. } else if (C == '.') {
  706. ++N;
  707. if (N >= 4)
  708. return V;
  709. } else if (N > 0)
  710. return V;
  711. }
  712. return V;
  713. }
  714. void CodeViewDebug::emitCompilerInformation() {
  715. MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
  716. uint32_t Flags = 0;
  717. // The low byte of the flags indicates the source language.
  718. Flags = CurrentSourceLanguage;
  719. // TODO: Figure out which other flags need to be set.
  720. if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
  721. Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
  722. }
  723. using ArchType = llvm::Triple::ArchType;
  724. ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
  725. if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
  726. Arch == ArchType::aarch64) {
  727. Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
  728. }
  729. OS.AddComment("Flags and language");
  730. OS.emitInt32(Flags);
  731. OS.AddComment("CPUType");
  732. OS.emitInt16(static_cast<uint64_t>(TheCPU));
  733. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  734. const MDNode *Node = *CUs->operands().begin();
  735. const auto *CU = cast<DICompileUnit>(Node);
  736. StringRef CompilerVersion = CU->getProducer();
  737. Version FrontVer = parseVersion(CompilerVersion);
  738. OS.AddComment("Frontend version");
  739. for (int N : FrontVer.Part) {
  740. OS.emitInt16(N);
  741. }
  742. // Some Microsoft tools, like Binscope, expect a backend version number of at
  743. // least 8.something, so we'll coerce the LLVM version into a form that
  744. // guarantees it'll be big enough without really lying about the version.
  745. int Major = 1000 * LLVM_VERSION_MAJOR +
  746. 10 * LLVM_VERSION_MINOR +
  747. LLVM_VERSION_PATCH;
  748. // Clamp it for builds that use unusually large version numbers.
  749. Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
  750. Version BackVer = {{ Major, 0, 0, 0 }};
  751. OS.AddComment("Backend version");
  752. for (int N : BackVer.Part)
  753. OS.emitInt16(N);
  754. OS.AddComment("Null-terminated compiler version string");
  755. emitNullTerminatedSymbolName(OS, CompilerVersion);
  756. endSymbolRecord(CompilerEnd);
  757. }
  758. static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
  759. StringRef S) {
  760. StringIdRecord SIR(TypeIndex(0x0), S);
  761. return TypeTable.writeLeafType(SIR);
  762. }
  763. static std::string flattenCommandLine(ArrayRef<std::string> Args,
  764. StringRef MainFilename) {
  765. std::string FlatCmdLine;
  766. raw_string_ostream OS(FlatCmdLine);
  767. bool PrintedOneArg = false;
  768. if (!StringRef(Args[0]).contains("-cc1")) {
  769. llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
  770. PrintedOneArg = true;
  771. }
  772. for (unsigned i = 0; i < Args.size(); i++) {
  773. StringRef Arg = Args[i];
  774. if (Arg.empty())
  775. continue;
  776. if (Arg == "-main-file-name" || Arg == "-o") {
  777. i++; // Skip this argument and next one.
  778. continue;
  779. }
  780. if (Arg.startswith("-object-file-name") || Arg == MainFilename)
  781. continue;
  782. // Skip fmessage-length for reproduciability.
  783. if (Arg.startswith("-fmessage-length"))
  784. continue;
  785. if (PrintedOneArg)
  786. OS << " ";
  787. llvm::sys::printArg(OS, Arg, /*Quote=*/true);
  788. PrintedOneArg = true;
  789. }
  790. OS.flush();
  791. return FlatCmdLine;
  792. }
  793. void CodeViewDebug::emitBuildInfo() {
  794. // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
  795. // build info. The known prefix is:
  796. // - Absolute path of current directory
  797. // - Compiler path
  798. // - Main source file path, relative to CWD or absolute
  799. // - Type server PDB file
  800. // - Canonical compiler command line
  801. // If frontend and backend compilation are separated (think llc or LTO), it's
  802. // not clear if the compiler path should refer to the executable for the
  803. // frontend or the backend. Leave it blank for now.
  804. TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
  805. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  806. const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
  807. const auto *CU = cast<DICompileUnit>(Node);
  808. const DIFile *MainSourceFile = CU->getFile();
  809. BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
  810. getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
  811. BuildInfoArgs[BuildInfoRecord::SourceFile] =
  812. getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
  813. // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
  814. BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
  815. getStringIdTypeIdx(TypeTable, "");
  816. if (Asm->TM.Options.MCOptions.Argv0 != nullptr) {
  817. BuildInfoArgs[BuildInfoRecord::BuildTool] =
  818. getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
  819. BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
  820. TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs,
  821. MainSourceFile->getFilename()));
  822. }
  823. BuildInfoRecord BIR(BuildInfoArgs);
  824. TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
  825. // Make a new .debug$S subsection for the S_BUILDINFO record, which points
  826. // from the module symbols into the type stream.
  827. MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  828. MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
  829. OS.AddComment("LF_BUILDINFO index");
  830. OS.emitInt32(BuildInfoIndex.getIndex());
  831. endSymbolRecord(BIEnd);
  832. endCVSubsection(BISubsecEnd);
  833. }
  834. void CodeViewDebug::emitInlineeLinesSubsection() {
  835. if (InlinedSubprograms.empty())
  836. return;
  837. OS.AddComment("Inlinee lines subsection");
  838. MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
  839. // We emit the checksum info for files. This is used by debuggers to
  840. // determine if a pdb matches the source before loading it. Visual Studio,
  841. // for instance, will display a warning that the breakpoints are not valid if
  842. // the pdb does not match the source.
  843. OS.AddComment("Inlinee lines signature");
  844. OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
  845. for (const DISubprogram *SP : InlinedSubprograms) {
  846. assert(TypeIndices.count({SP, nullptr}));
  847. TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
  848. OS.addBlankLine();
  849. unsigned FileId = maybeRecordFile(SP->getFile());
  850. OS.AddComment("Inlined function " + SP->getName() + " starts at " +
  851. SP->getFilename() + Twine(':') + Twine(SP->getLine()));
  852. OS.addBlankLine();
  853. OS.AddComment("Type index of inlined function");
  854. OS.emitInt32(InlineeIdx.getIndex());
  855. OS.AddComment("Offset into filechecksum table");
  856. OS.emitCVFileChecksumOffsetDirective(FileId);
  857. OS.AddComment("Starting line number");
  858. OS.emitInt32(SP->getLine());
  859. }
  860. endCVSubsection(InlineEnd);
  861. }
  862. void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
  863. const DILocation *InlinedAt,
  864. const InlineSite &Site) {
  865. assert(TypeIndices.count({Site.Inlinee, nullptr}));
  866. TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
  867. // SymbolRecord
  868. MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
  869. OS.AddComment("PtrParent");
  870. OS.emitInt32(0);
  871. OS.AddComment("PtrEnd");
  872. OS.emitInt32(0);
  873. OS.AddComment("Inlinee type index");
  874. OS.emitInt32(InlineeIdx.getIndex());
  875. unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
  876. unsigned StartLineNum = Site.Inlinee->getLine();
  877. OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
  878. FI.Begin, FI.End);
  879. endSymbolRecord(InlineEnd);
  880. emitLocalVariableList(FI, Site.InlinedLocals);
  881. // Recurse on child inlined call sites before closing the scope.
  882. for (const DILocation *ChildSite : Site.ChildSites) {
  883. auto I = FI.InlineSites.find(ChildSite);
  884. assert(I != FI.InlineSites.end() &&
  885. "child site not in function inline site map");
  886. emitInlinedCallSite(FI, ChildSite, I->second);
  887. }
  888. // Close the scope.
  889. emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
  890. }
  891. void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
  892. // If we have a symbol, it may be in a section that is COMDAT. If so, find the
  893. // comdat key. A section may be comdat because of -ffunction-sections or
  894. // because it is comdat in the IR.
  895. MCSectionCOFF *GVSec =
  896. GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
  897. const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
  898. MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
  899. Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
  900. DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
  901. OS.switchSection(DebugSec);
  902. // Emit the magic version number if this is the first time we've switched to
  903. // this section.
  904. if (ComdatDebugSections.insert(DebugSec).second)
  905. emitCodeViewMagicVersion();
  906. }
  907. // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
  908. // The only supported thunk ordinal is currently the standard type.
  909. void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
  910. FunctionInfo &FI,
  911. const MCSymbol *Fn) {
  912. std::string FuncName =
  913. std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
  914. const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
  915. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  916. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  917. // Emit S_THUNK32
  918. MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
  919. OS.AddComment("PtrParent");
  920. OS.emitInt32(0);
  921. OS.AddComment("PtrEnd");
  922. OS.emitInt32(0);
  923. OS.AddComment("PtrNext");
  924. OS.emitInt32(0);
  925. OS.AddComment("Thunk section relative address");
  926. OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
  927. OS.AddComment("Thunk section index");
  928. OS.emitCOFFSectionIndex(Fn);
  929. OS.AddComment("Code size");
  930. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
  931. OS.AddComment("Ordinal");
  932. OS.emitInt8(unsigned(ordinal));
  933. OS.AddComment("Function name");
  934. emitNullTerminatedSymbolName(OS, FuncName);
  935. // Additional fields specific to the thunk ordinal would go here.
  936. endSymbolRecord(ThunkRecordEnd);
  937. // Local variables/inlined routines are purposely omitted here. The point of
  938. // marking this as a thunk is so Visual Studio will NOT stop in this routine.
  939. // Emit S_PROC_ID_END
  940. emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
  941. endCVSubsection(SymbolsEnd);
  942. }
  943. void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
  944. FunctionInfo &FI) {
  945. // For each function there is a separate subsection which holds the PC to
  946. // file:line table.
  947. const MCSymbol *Fn = Asm->getSymbol(GV);
  948. assert(Fn);
  949. // Switch to the to a comdat section, if appropriate.
  950. switchToDebugSectionForSymbol(Fn);
  951. std::string FuncName;
  952. auto *SP = GV->getSubprogram();
  953. assert(SP);
  954. setCurrentSubprogram(SP);
  955. if (SP->isThunk()) {
  956. emitDebugInfoForThunk(GV, FI, Fn);
  957. return;
  958. }
  959. // If we have a display name, build the fully qualified name by walking the
  960. // chain of scopes.
  961. if (!SP->getName().empty())
  962. FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
  963. // If our DISubprogram name is empty, use the mangled name.
  964. if (FuncName.empty())
  965. FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
  966. // Emit FPO data, but only on 32-bit x86. No other platforms use it.
  967. if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
  968. OS.emitCVFPOData(Fn);
  969. // Emit a symbol subsection, required by VS2012+ to find function boundaries.
  970. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  971. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  972. {
  973. SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
  974. : SymbolKind::S_GPROC32_ID;
  975. MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
  976. // These fields are filled in by tools like CVPACK which run after the fact.
  977. OS.AddComment("PtrParent");
  978. OS.emitInt32(0);
  979. OS.AddComment("PtrEnd");
  980. OS.emitInt32(0);
  981. OS.AddComment("PtrNext");
  982. OS.emitInt32(0);
  983. // This is the important bit that tells the debugger where the function
  984. // code is located and what's its size:
  985. OS.AddComment("Code size");
  986. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
  987. OS.AddComment("Offset after prologue");
  988. OS.emitInt32(0);
  989. OS.AddComment("Offset before epilogue");
  990. OS.emitInt32(0);
  991. OS.AddComment("Function type index");
  992. OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
  993. OS.AddComment("Function section relative address");
  994. OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
  995. OS.AddComment("Function section index");
  996. OS.emitCOFFSectionIndex(Fn);
  997. OS.AddComment("Flags");
  998. OS.emitInt8(0);
  999. // Emit the function display name as a null-terminated string.
  1000. OS.AddComment("Function name");
  1001. // Truncate the name so we won't overflow the record length field.
  1002. emitNullTerminatedSymbolName(OS, FuncName);
  1003. endSymbolRecord(ProcRecordEnd);
  1004. MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
  1005. // Subtract out the CSR size since MSVC excludes that and we include it.
  1006. OS.AddComment("FrameSize");
  1007. OS.emitInt32(FI.FrameSize - FI.CSRSize);
  1008. OS.AddComment("Padding");
  1009. OS.emitInt32(0);
  1010. OS.AddComment("Offset of padding");
  1011. OS.emitInt32(0);
  1012. OS.AddComment("Bytes of callee saved registers");
  1013. OS.emitInt32(FI.CSRSize);
  1014. OS.AddComment("Exception handler offset");
  1015. OS.emitInt32(0);
  1016. OS.AddComment("Exception handler section");
  1017. OS.emitInt16(0);
  1018. OS.AddComment("Flags (defines frame register)");
  1019. OS.emitInt32(uint32_t(FI.FrameProcOpts));
  1020. endSymbolRecord(FrameProcEnd);
  1021. emitLocalVariableList(FI, FI.Locals);
  1022. emitGlobalVariableList(FI.Globals);
  1023. emitLexicalBlockList(FI.ChildBlocks, FI);
  1024. // Emit inlined call site information. Only emit functions inlined directly
  1025. // into the parent function. We'll emit the other sites recursively as part
  1026. // of their parent inline site.
  1027. for (const DILocation *InlinedAt : FI.ChildSites) {
  1028. auto I = FI.InlineSites.find(InlinedAt);
  1029. assert(I != FI.InlineSites.end() &&
  1030. "child site not in function inline site map");
  1031. emitInlinedCallSite(FI, InlinedAt, I->second);
  1032. }
  1033. for (auto Annot : FI.Annotations) {
  1034. MCSymbol *Label = Annot.first;
  1035. MDTuple *Strs = cast<MDTuple>(Annot.second);
  1036. MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
  1037. OS.emitCOFFSecRel32(Label, /*Offset=*/0);
  1038. // FIXME: Make sure we don't overflow the max record size.
  1039. OS.emitCOFFSectionIndex(Label);
  1040. OS.emitInt16(Strs->getNumOperands());
  1041. for (Metadata *MD : Strs->operands()) {
  1042. // MDStrings are null terminated, so we can do EmitBytes and get the
  1043. // nice .asciz directive.
  1044. StringRef Str = cast<MDString>(MD)->getString();
  1045. assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
  1046. OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
  1047. }
  1048. endSymbolRecord(AnnotEnd);
  1049. }
  1050. for (auto HeapAllocSite : FI.HeapAllocSites) {
  1051. const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
  1052. const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
  1053. const DIType *DITy = std::get<2>(HeapAllocSite);
  1054. MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
  1055. OS.AddComment("Call site offset");
  1056. OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0);
  1057. OS.AddComment("Call site section index");
  1058. OS.emitCOFFSectionIndex(BeginLabel);
  1059. OS.AddComment("Call instruction length");
  1060. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
  1061. OS.AddComment("Type index");
  1062. OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
  1063. endSymbolRecord(HeapAllocEnd);
  1064. }
  1065. if (SP != nullptr)
  1066. emitDebugInfoForUDTs(LocalUDTs);
  1067. // We're done with this function.
  1068. emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
  1069. }
  1070. endCVSubsection(SymbolsEnd);
  1071. // We have an assembler directive that takes care of the whole line table.
  1072. OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
  1073. }
  1074. CodeViewDebug::LocalVarDef
  1075. CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
  1076. LocalVarDef DR;
  1077. DR.InMemory = -1;
  1078. DR.DataOffset = Offset;
  1079. assert(DR.DataOffset == Offset && "truncation");
  1080. DR.IsSubfield = 0;
  1081. DR.StructOffset = 0;
  1082. DR.CVRegister = CVRegister;
  1083. return DR;
  1084. }
  1085. void CodeViewDebug::collectVariableInfoFromMFTable(
  1086. DenseSet<InlinedEntity> &Processed) {
  1087. const MachineFunction &MF = *Asm->MF;
  1088. const TargetSubtargetInfo &TSI = MF.getSubtarget();
  1089. const TargetFrameLowering *TFI = TSI.getFrameLowering();
  1090. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  1091. for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
  1092. if (!VI.Var)
  1093. continue;
  1094. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  1095. "Expected inlined-at fields to agree");
  1096. Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
  1097. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  1098. // If variable scope is not found then skip this variable.
  1099. if (!Scope)
  1100. continue;
  1101. // If the variable has an attached offset expression, extract it.
  1102. // FIXME: Try to handle DW_OP_deref as well.
  1103. int64_t ExprOffset = 0;
  1104. bool Deref = false;
  1105. if (VI.Expr) {
  1106. // If there is one DW_OP_deref element, use offset of 0 and keep going.
  1107. if (VI.Expr->getNumElements() == 1 &&
  1108. VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
  1109. Deref = true;
  1110. else if (!VI.Expr->extractIfOffset(ExprOffset))
  1111. continue;
  1112. }
  1113. // Get the frame register used and the offset.
  1114. Register FrameReg;
  1115. StackOffset FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
  1116. uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
  1117. assert(!FrameOffset.getScalable() &&
  1118. "Frame offsets with a scalable component are not supported");
  1119. // Calculate the label ranges.
  1120. LocalVarDef DefRange =
  1121. createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
  1122. LocalVariable Var;
  1123. Var.DIVar = VI.Var;
  1124. for (const InsnRange &Range : Scope->getRanges()) {
  1125. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  1126. const MCSymbol *End = getLabelAfterInsn(Range.second);
  1127. End = End ? End : Asm->getFunctionEnd();
  1128. Var.DefRanges[DefRange].emplace_back(Begin, End);
  1129. }
  1130. if (Deref)
  1131. Var.UseReferenceType = true;
  1132. recordLocalVariable(std::move(Var), Scope);
  1133. }
  1134. }
  1135. static bool canUseReferenceType(const DbgVariableLocation &Loc) {
  1136. return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
  1137. }
  1138. static bool needsReferenceType(const DbgVariableLocation &Loc) {
  1139. return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
  1140. }
  1141. void CodeViewDebug::calculateRanges(
  1142. LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
  1143. const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  1144. // Calculate the definition ranges.
  1145. for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
  1146. const auto &Entry = *I;
  1147. if (!Entry.isDbgValue())
  1148. continue;
  1149. const MachineInstr *DVInst = Entry.getInstr();
  1150. assert(DVInst->isDebugValue() && "Invalid History entry");
  1151. // FIXME: Find a way to represent constant variables, since they are
  1152. // relatively common.
  1153. std::optional<DbgVariableLocation> Location =
  1154. DbgVariableLocation::extractFromMachineInstruction(*DVInst);
  1155. if (!Location)
  1156. {
  1157. // When we don't have a location this is usually because LLVM has
  1158. // transformed it into a constant and we only have an llvm.dbg.value. We
  1159. // can't represent these well in CodeView since S_LOCAL only works on
  1160. // registers and memory locations. Instead, we will pretend this to be a
  1161. // constant value to at least have it show up in the debugger.
  1162. auto Op = DVInst->getDebugOperand(0);
  1163. if (Op.isImm())
  1164. Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false);
  1165. continue;
  1166. }
  1167. // CodeView can only express variables in register and variables in memory
  1168. // at a constant offset from a register. However, for variables passed
  1169. // indirectly by pointer, it is common for that pointer to be spilled to a
  1170. // stack location. For the special case of one offseted load followed by a
  1171. // zero offset load (a pointer spilled to the stack), we change the type of
  1172. // the local variable from a value type to a reference type. This tricks the
  1173. // debugger into doing the load for us.
  1174. if (Var.UseReferenceType) {
  1175. // We're using a reference type. Drop the last zero offset load.
  1176. if (canUseReferenceType(*Location))
  1177. Location->LoadChain.pop_back();
  1178. else
  1179. continue;
  1180. } else if (needsReferenceType(*Location)) {
  1181. // This location can't be expressed without switching to a reference type.
  1182. // Start over using that.
  1183. Var.UseReferenceType = true;
  1184. Var.DefRanges.clear();
  1185. calculateRanges(Var, Entries);
  1186. return;
  1187. }
  1188. // We can only handle a register or an offseted load of a register.
  1189. if (Location->Register == 0 || Location->LoadChain.size() > 1)
  1190. continue;
  1191. LocalVarDef DR;
  1192. DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
  1193. DR.InMemory = !Location->LoadChain.empty();
  1194. DR.DataOffset =
  1195. !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
  1196. if (Location->FragmentInfo) {
  1197. DR.IsSubfield = true;
  1198. DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
  1199. } else {
  1200. DR.IsSubfield = false;
  1201. DR.StructOffset = 0;
  1202. }
  1203. // Compute the label range.
  1204. const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
  1205. const MCSymbol *End;
  1206. if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
  1207. auto &EndingEntry = Entries[Entry.getEndIndex()];
  1208. End = EndingEntry.isDbgValue()
  1209. ? getLabelBeforeInsn(EndingEntry.getInstr())
  1210. : getLabelAfterInsn(EndingEntry.getInstr());
  1211. } else
  1212. End = Asm->getFunctionEnd();
  1213. // If the last range end is our begin, just extend the last range.
  1214. // Otherwise make a new range.
  1215. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
  1216. Var.DefRanges[DR];
  1217. if (!R.empty() && R.back().second == Begin)
  1218. R.back().second = End;
  1219. else
  1220. R.emplace_back(Begin, End);
  1221. // FIXME: Do more range combining.
  1222. }
  1223. }
  1224. void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
  1225. DenseSet<InlinedEntity> Processed;
  1226. // Grab the variable info that was squirreled away in the MMI side-table.
  1227. collectVariableInfoFromMFTable(Processed);
  1228. for (const auto &I : DbgValues) {
  1229. InlinedEntity IV = I.first;
  1230. if (Processed.count(IV))
  1231. continue;
  1232. const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
  1233. const DILocation *InlinedAt = IV.second;
  1234. // Instruction ranges, specifying where IV is accessible.
  1235. const auto &Entries = I.second;
  1236. LexicalScope *Scope = nullptr;
  1237. if (InlinedAt)
  1238. Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
  1239. else
  1240. Scope = LScopes.findLexicalScope(DIVar->getScope());
  1241. // If variable scope is not found then skip this variable.
  1242. if (!Scope)
  1243. continue;
  1244. LocalVariable Var;
  1245. Var.DIVar = DIVar;
  1246. calculateRanges(Var, Entries);
  1247. recordLocalVariable(std::move(Var), Scope);
  1248. }
  1249. }
  1250. void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
  1251. const TargetSubtargetInfo &TSI = MF->getSubtarget();
  1252. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  1253. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1254. const Function &GV = MF->getFunction();
  1255. auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
  1256. assert(Insertion.second && "function already has info");
  1257. CurFn = Insertion.first->second.get();
  1258. CurFn->FuncId = NextFuncId++;
  1259. CurFn->Begin = Asm->getFunctionBegin();
  1260. // The S_FRAMEPROC record reports the stack size, and how many bytes of
  1261. // callee-saved registers were used. For targets that don't use a PUSH
  1262. // instruction (AArch64), this will be zero.
  1263. CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
  1264. CurFn->FrameSize = MFI.getStackSize();
  1265. CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
  1266. CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
  1267. // For this function S_FRAMEPROC record, figure out which codeview register
  1268. // will be the frame pointer.
  1269. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
  1270. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
  1271. if (CurFn->FrameSize > 0) {
  1272. if (!TSI.getFrameLowering()->hasFP(*MF)) {
  1273. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
  1274. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
  1275. } else {
  1276. // If there is an FP, parameters are always relative to it.
  1277. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
  1278. if (CurFn->HasStackRealignment) {
  1279. // If the stack needs realignment, locals are relative to SP or VFRAME.
  1280. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
  1281. } else {
  1282. // Otherwise, locals are relative to EBP, and we probably have VLAs or
  1283. // other stack adjustments.
  1284. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
  1285. }
  1286. }
  1287. }
  1288. // Compute other frame procedure options.
  1289. FrameProcedureOptions FPO = FrameProcedureOptions::None;
  1290. if (MFI.hasVarSizedObjects())
  1291. FPO |= FrameProcedureOptions::HasAlloca;
  1292. if (MF->exposesReturnsTwice())
  1293. FPO |= FrameProcedureOptions::HasSetJmp;
  1294. // FIXME: Set HasLongJmp if we ever track that info.
  1295. if (MF->hasInlineAsm())
  1296. FPO |= FrameProcedureOptions::HasInlineAssembly;
  1297. if (GV.hasPersonalityFn()) {
  1298. if (isAsynchronousEHPersonality(
  1299. classifyEHPersonality(GV.getPersonalityFn())))
  1300. FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
  1301. else
  1302. FPO |= FrameProcedureOptions::HasExceptionHandling;
  1303. }
  1304. if (GV.hasFnAttribute(Attribute::InlineHint))
  1305. FPO |= FrameProcedureOptions::MarkedInline;
  1306. if (GV.hasFnAttribute(Attribute::Naked))
  1307. FPO |= FrameProcedureOptions::Naked;
  1308. if (MFI.hasStackProtectorIndex()) {
  1309. FPO |= FrameProcedureOptions::SecurityChecks;
  1310. if (GV.hasFnAttribute(Attribute::StackProtectStrong) ||
  1311. GV.hasFnAttribute(Attribute::StackProtectReq)) {
  1312. FPO |= FrameProcedureOptions::StrictSecurityChecks;
  1313. }
  1314. } else if (!GV.hasStackProtectorFnAttr()) {
  1315. // __declspec(safebuffers) disables stack guards.
  1316. FPO |= FrameProcedureOptions::SafeBuffers;
  1317. }
  1318. FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
  1319. FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
  1320. if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
  1321. !GV.hasOptSize() && !GV.hasOptNone())
  1322. FPO |= FrameProcedureOptions::OptimizedForSpeed;
  1323. if (GV.hasProfileData()) {
  1324. FPO |= FrameProcedureOptions::ValidProfileCounts;
  1325. FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
  1326. }
  1327. // FIXME: Set GuardCfg when it is implemented.
  1328. CurFn->FrameProcOpts = FPO;
  1329. OS.emitCVFuncIdDirective(CurFn->FuncId);
  1330. // Find the end of the function prolog. First known non-DBG_VALUE and
  1331. // non-frame setup location marks the beginning of the function body.
  1332. // FIXME: is there a simpler a way to do this? Can we just search
  1333. // for the first instruction of the function, not the last of the prolog?
  1334. DebugLoc PrologEndLoc;
  1335. bool EmptyPrologue = true;
  1336. for (const auto &MBB : *MF) {
  1337. for (const auto &MI : MBB) {
  1338. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1339. MI.getDebugLoc()) {
  1340. PrologEndLoc = MI.getDebugLoc();
  1341. break;
  1342. } else if (!MI.isMetaInstruction()) {
  1343. EmptyPrologue = false;
  1344. }
  1345. }
  1346. }
  1347. // Record beginning of function if we have a non-empty prologue.
  1348. if (PrologEndLoc && !EmptyPrologue) {
  1349. DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
  1350. maybeRecordLocation(FnStartDL, MF);
  1351. }
  1352. // Find heap alloc sites and emit labels around them.
  1353. for (const auto &MBB : *MF) {
  1354. for (const auto &MI : MBB) {
  1355. if (MI.getHeapAllocMarker()) {
  1356. requestLabelBeforeInsn(&MI);
  1357. requestLabelAfterInsn(&MI);
  1358. }
  1359. }
  1360. }
  1361. }
  1362. static bool shouldEmitUdt(const DIType *T) {
  1363. if (!T)
  1364. return false;
  1365. // MSVC does not emit UDTs for typedefs that are scoped to classes.
  1366. if (T->getTag() == dwarf::DW_TAG_typedef) {
  1367. if (DIScope *Scope = T->getScope()) {
  1368. switch (Scope->getTag()) {
  1369. case dwarf::DW_TAG_structure_type:
  1370. case dwarf::DW_TAG_class_type:
  1371. case dwarf::DW_TAG_union_type:
  1372. return false;
  1373. default:
  1374. // do nothing.
  1375. ;
  1376. }
  1377. }
  1378. }
  1379. while (true) {
  1380. if (!T || T->isForwardDecl())
  1381. return false;
  1382. const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
  1383. if (!DT)
  1384. return true;
  1385. T = DT->getBaseType();
  1386. }
  1387. return true;
  1388. }
  1389. void CodeViewDebug::addToUDTs(const DIType *Ty) {
  1390. // Don't record empty UDTs.
  1391. if (Ty->getName().empty())
  1392. return;
  1393. if (!shouldEmitUdt(Ty))
  1394. return;
  1395. SmallVector<StringRef, 5> ParentScopeNames;
  1396. const DISubprogram *ClosestSubprogram =
  1397. collectParentScopeNames(Ty->getScope(), ParentScopeNames);
  1398. std::string FullyQualifiedName =
  1399. formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
  1400. if (ClosestSubprogram == nullptr) {
  1401. GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1402. } else if (ClosestSubprogram == CurrentSubprogram) {
  1403. LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1404. }
  1405. // TODO: What if the ClosestSubprogram is neither null or the current
  1406. // subprogram? Currently, the UDT just gets dropped on the floor.
  1407. //
  1408. // The current behavior is not desirable. To get maximal fidelity, we would
  1409. // need to perform all type translation before beginning emission of .debug$S
  1410. // and then make LocalUDTs a member of FunctionInfo
  1411. }
  1412. TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
  1413. // Generic dispatch for lowering an unknown type.
  1414. switch (Ty->getTag()) {
  1415. case dwarf::DW_TAG_array_type:
  1416. return lowerTypeArray(cast<DICompositeType>(Ty));
  1417. case dwarf::DW_TAG_typedef:
  1418. return lowerTypeAlias(cast<DIDerivedType>(Ty));
  1419. case dwarf::DW_TAG_base_type:
  1420. return lowerTypeBasic(cast<DIBasicType>(Ty));
  1421. case dwarf::DW_TAG_pointer_type:
  1422. if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
  1423. return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
  1424. [[fallthrough]];
  1425. case dwarf::DW_TAG_reference_type:
  1426. case dwarf::DW_TAG_rvalue_reference_type:
  1427. return lowerTypePointer(cast<DIDerivedType>(Ty));
  1428. case dwarf::DW_TAG_ptr_to_member_type:
  1429. return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
  1430. case dwarf::DW_TAG_restrict_type:
  1431. case dwarf::DW_TAG_const_type:
  1432. case dwarf::DW_TAG_volatile_type:
  1433. // TODO: add support for DW_TAG_atomic_type here
  1434. return lowerTypeModifier(cast<DIDerivedType>(Ty));
  1435. case dwarf::DW_TAG_subroutine_type:
  1436. if (ClassTy) {
  1437. // The member function type of a member function pointer has no
  1438. // ThisAdjustment.
  1439. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
  1440. /*ThisAdjustment=*/0,
  1441. /*IsStaticMethod=*/false);
  1442. }
  1443. return lowerTypeFunction(cast<DISubroutineType>(Ty));
  1444. case dwarf::DW_TAG_enumeration_type:
  1445. return lowerTypeEnum(cast<DICompositeType>(Ty));
  1446. case dwarf::DW_TAG_class_type:
  1447. case dwarf::DW_TAG_structure_type:
  1448. return lowerTypeClass(cast<DICompositeType>(Ty));
  1449. case dwarf::DW_TAG_union_type:
  1450. return lowerTypeUnion(cast<DICompositeType>(Ty));
  1451. case dwarf::DW_TAG_string_type:
  1452. return lowerTypeString(cast<DIStringType>(Ty));
  1453. case dwarf::DW_TAG_unspecified_type:
  1454. if (Ty->getName() == "decltype(nullptr)")
  1455. return TypeIndex::NullptrT();
  1456. return TypeIndex::None();
  1457. default:
  1458. // Use the null type index.
  1459. return TypeIndex();
  1460. }
  1461. }
  1462. TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
  1463. TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
  1464. StringRef TypeName = Ty->getName();
  1465. addToUDTs(Ty);
  1466. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
  1467. TypeName == "HRESULT")
  1468. return TypeIndex(SimpleTypeKind::HResult);
  1469. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
  1470. TypeName == "wchar_t")
  1471. return TypeIndex(SimpleTypeKind::WideCharacter);
  1472. return UnderlyingTypeIndex;
  1473. }
  1474. TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
  1475. const DIType *ElementType = Ty->getBaseType();
  1476. TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
  1477. // IndexType is size_t, which depends on the bitness of the target.
  1478. TypeIndex IndexType = getPointerSizeInBytes() == 8
  1479. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  1480. : TypeIndex(SimpleTypeKind::UInt32Long);
  1481. uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
  1482. // Add subranges to array type.
  1483. DINodeArray Elements = Ty->getElements();
  1484. for (int i = Elements.size() - 1; i >= 0; --i) {
  1485. const DINode *Element = Elements[i];
  1486. assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
  1487. const DISubrange *Subrange = cast<DISubrange>(Element);
  1488. int64_t Count = -1;
  1489. // If Subrange has a Count field, use it.
  1490. // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
  1491. // where lowerbound is from the LowerBound field of the Subrange,
  1492. // or the language default lowerbound if that field is unspecified.
  1493. if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt *>())
  1494. Count = CI->getSExtValue();
  1495. else if (auto *UI = Subrange->getUpperBound().dyn_cast<ConstantInt *>()) {
  1496. // Fortran uses 1 as the default lowerbound; other languages use 0.
  1497. int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
  1498. auto *LI = Subrange->getLowerBound().dyn_cast<ConstantInt *>();
  1499. Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
  1500. Count = UI->getSExtValue() - Lowerbound + 1;
  1501. }
  1502. // Forward declarations of arrays without a size and VLAs use a count of -1.
  1503. // Emit a count of zero in these cases to match what MSVC does for arrays
  1504. // without a size. MSVC doesn't support VLAs, so it's not clear what we
  1505. // should do for them even if we could distinguish them.
  1506. if (Count == -1)
  1507. Count = 0;
  1508. // Update the element size and element type index for subsequent subranges.
  1509. ElementSize *= Count;
  1510. // If this is the outermost array, use the size from the array. It will be
  1511. // more accurate if we had a VLA or an incomplete element type size.
  1512. uint64_t ArraySize =
  1513. (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
  1514. StringRef Name = (i == 0) ? Ty->getName() : "";
  1515. ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
  1516. ElementTypeIndex = TypeTable.writeLeafType(AR);
  1517. }
  1518. return ElementTypeIndex;
  1519. }
  1520. // This function lowers a Fortran character type (DIStringType).
  1521. // Note that it handles only the character*n variant (using SizeInBits
  1522. // field in DIString to describe the type size) at the moment.
  1523. // Other variants (leveraging the StringLength and StringLengthExp
  1524. // fields in DIStringType) remain TBD.
  1525. TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
  1526. TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
  1527. uint64_t ArraySize = Ty->getSizeInBits() >> 3;
  1528. StringRef Name = Ty->getName();
  1529. // IndexType is size_t, which depends on the bitness of the target.
  1530. TypeIndex IndexType = getPointerSizeInBytes() == 8
  1531. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  1532. : TypeIndex(SimpleTypeKind::UInt32Long);
  1533. // Create a type of character array of ArraySize.
  1534. ArrayRecord AR(CharType, IndexType, ArraySize, Name);
  1535. return TypeTable.writeLeafType(AR);
  1536. }
  1537. TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
  1538. TypeIndex Index;
  1539. dwarf::TypeKind Kind;
  1540. uint32_t ByteSize;
  1541. Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
  1542. ByteSize = Ty->getSizeInBits() / 8;
  1543. SimpleTypeKind STK = SimpleTypeKind::None;
  1544. switch (Kind) {
  1545. case dwarf::DW_ATE_address:
  1546. // FIXME: Translate
  1547. break;
  1548. case dwarf::DW_ATE_boolean:
  1549. switch (ByteSize) {
  1550. case 1: STK = SimpleTypeKind::Boolean8; break;
  1551. case 2: STK = SimpleTypeKind::Boolean16; break;
  1552. case 4: STK = SimpleTypeKind::Boolean32; break;
  1553. case 8: STK = SimpleTypeKind::Boolean64; break;
  1554. case 16: STK = SimpleTypeKind::Boolean128; break;
  1555. }
  1556. break;
  1557. case dwarf::DW_ATE_complex_float:
  1558. switch (ByteSize) {
  1559. case 2: STK = SimpleTypeKind::Complex16; break;
  1560. case 4: STK = SimpleTypeKind::Complex32; break;
  1561. case 8: STK = SimpleTypeKind::Complex64; break;
  1562. case 10: STK = SimpleTypeKind::Complex80; break;
  1563. case 16: STK = SimpleTypeKind::Complex128; break;
  1564. }
  1565. break;
  1566. case dwarf::DW_ATE_float:
  1567. switch (ByteSize) {
  1568. case 2: STK = SimpleTypeKind::Float16; break;
  1569. case 4: STK = SimpleTypeKind::Float32; break;
  1570. case 6: STK = SimpleTypeKind::Float48; break;
  1571. case 8: STK = SimpleTypeKind::Float64; break;
  1572. case 10: STK = SimpleTypeKind::Float80; break;
  1573. case 16: STK = SimpleTypeKind::Float128; break;
  1574. }
  1575. break;
  1576. case dwarf::DW_ATE_signed:
  1577. switch (ByteSize) {
  1578. case 1: STK = SimpleTypeKind::SignedCharacter; break;
  1579. case 2: STK = SimpleTypeKind::Int16Short; break;
  1580. case 4: STK = SimpleTypeKind::Int32; break;
  1581. case 8: STK = SimpleTypeKind::Int64Quad; break;
  1582. case 16: STK = SimpleTypeKind::Int128Oct; break;
  1583. }
  1584. break;
  1585. case dwarf::DW_ATE_unsigned:
  1586. switch (ByteSize) {
  1587. case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
  1588. case 2: STK = SimpleTypeKind::UInt16Short; break;
  1589. case 4: STK = SimpleTypeKind::UInt32; break;
  1590. case 8: STK = SimpleTypeKind::UInt64Quad; break;
  1591. case 16: STK = SimpleTypeKind::UInt128Oct; break;
  1592. }
  1593. break;
  1594. case dwarf::DW_ATE_UTF:
  1595. switch (ByteSize) {
  1596. case 1: STK = SimpleTypeKind::Character8; break;
  1597. case 2: STK = SimpleTypeKind::Character16; break;
  1598. case 4: STK = SimpleTypeKind::Character32; break;
  1599. }
  1600. break;
  1601. case dwarf::DW_ATE_signed_char:
  1602. if (ByteSize == 1)
  1603. STK = SimpleTypeKind::SignedCharacter;
  1604. break;
  1605. case dwarf::DW_ATE_unsigned_char:
  1606. if (ByteSize == 1)
  1607. STK = SimpleTypeKind::UnsignedCharacter;
  1608. break;
  1609. default:
  1610. break;
  1611. }
  1612. // Apply some fixups based on the source-level type name.
  1613. // Include some amount of canonicalization from an old naming scheme Clang
  1614. // used to use for integer types (in an outdated effort to be compatible with
  1615. // GCC's debug info/GDB's behavior, which has since been addressed).
  1616. if (STK == SimpleTypeKind::Int32 &&
  1617. (Ty->getName() == "long int" || Ty->getName() == "long"))
  1618. STK = SimpleTypeKind::Int32Long;
  1619. if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
  1620. Ty->getName() == "unsigned long"))
  1621. STK = SimpleTypeKind::UInt32Long;
  1622. if (STK == SimpleTypeKind::UInt16Short &&
  1623. (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
  1624. STK = SimpleTypeKind::WideCharacter;
  1625. if ((STK == SimpleTypeKind::SignedCharacter ||
  1626. STK == SimpleTypeKind::UnsignedCharacter) &&
  1627. Ty->getName() == "char")
  1628. STK = SimpleTypeKind::NarrowCharacter;
  1629. return TypeIndex(STK);
  1630. }
  1631. TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
  1632. PointerOptions PO) {
  1633. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
  1634. // Pointers to simple types without any options can use SimpleTypeMode, rather
  1635. // than having a dedicated pointer type record.
  1636. if (PointeeTI.isSimple() && PO == PointerOptions::None &&
  1637. PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
  1638. Ty->getTag() == dwarf::DW_TAG_pointer_type) {
  1639. SimpleTypeMode Mode = Ty->getSizeInBits() == 64
  1640. ? SimpleTypeMode::NearPointer64
  1641. : SimpleTypeMode::NearPointer32;
  1642. return TypeIndex(PointeeTI.getSimpleKind(), Mode);
  1643. }
  1644. PointerKind PK =
  1645. Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
  1646. PointerMode PM = PointerMode::Pointer;
  1647. switch (Ty->getTag()) {
  1648. default: llvm_unreachable("not a pointer tag type");
  1649. case dwarf::DW_TAG_pointer_type:
  1650. PM = PointerMode::Pointer;
  1651. break;
  1652. case dwarf::DW_TAG_reference_type:
  1653. PM = PointerMode::LValueReference;
  1654. break;
  1655. case dwarf::DW_TAG_rvalue_reference_type:
  1656. PM = PointerMode::RValueReference;
  1657. break;
  1658. }
  1659. if (Ty->isObjectPointer())
  1660. PO |= PointerOptions::Const;
  1661. PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
  1662. return TypeTable.writeLeafType(PR);
  1663. }
  1664. static PointerToMemberRepresentation
  1665. translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
  1666. // SizeInBytes being zero generally implies that the member pointer type was
  1667. // incomplete, which can happen if it is part of a function prototype. In this
  1668. // case, use the unknown model instead of the general model.
  1669. if (IsPMF) {
  1670. switch (Flags & DINode::FlagPtrToMemberRep) {
  1671. case 0:
  1672. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1673. : PointerToMemberRepresentation::GeneralFunction;
  1674. case DINode::FlagSingleInheritance:
  1675. return PointerToMemberRepresentation::SingleInheritanceFunction;
  1676. case DINode::FlagMultipleInheritance:
  1677. return PointerToMemberRepresentation::MultipleInheritanceFunction;
  1678. case DINode::FlagVirtualInheritance:
  1679. return PointerToMemberRepresentation::VirtualInheritanceFunction;
  1680. }
  1681. } else {
  1682. switch (Flags & DINode::FlagPtrToMemberRep) {
  1683. case 0:
  1684. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1685. : PointerToMemberRepresentation::GeneralData;
  1686. case DINode::FlagSingleInheritance:
  1687. return PointerToMemberRepresentation::SingleInheritanceData;
  1688. case DINode::FlagMultipleInheritance:
  1689. return PointerToMemberRepresentation::MultipleInheritanceData;
  1690. case DINode::FlagVirtualInheritance:
  1691. return PointerToMemberRepresentation::VirtualInheritanceData;
  1692. }
  1693. }
  1694. llvm_unreachable("invalid ptr to member representation");
  1695. }
  1696. TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
  1697. PointerOptions PO) {
  1698. assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
  1699. bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
  1700. TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
  1701. TypeIndex PointeeTI =
  1702. getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
  1703. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1704. : PointerKind::Near32;
  1705. PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
  1706. : PointerMode::PointerToDataMember;
  1707. assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
  1708. uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
  1709. MemberPointerInfo MPI(
  1710. ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
  1711. PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
  1712. return TypeTable.writeLeafType(PR);
  1713. }
  1714. /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
  1715. /// have a translation, use the NearC convention.
  1716. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
  1717. switch (DwarfCC) {
  1718. case dwarf::DW_CC_normal: return CallingConvention::NearC;
  1719. case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
  1720. case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
  1721. case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
  1722. case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
  1723. case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
  1724. }
  1725. return CallingConvention::NearC;
  1726. }
  1727. TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
  1728. ModifierOptions Mods = ModifierOptions::None;
  1729. PointerOptions PO = PointerOptions::None;
  1730. bool IsModifier = true;
  1731. const DIType *BaseTy = Ty;
  1732. while (IsModifier && BaseTy) {
  1733. // FIXME: Need to add DWARF tags for __unaligned and _Atomic
  1734. switch (BaseTy->getTag()) {
  1735. case dwarf::DW_TAG_const_type:
  1736. Mods |= ModifierOptions::Const;
  1737. PO |= PointerOptions::Const;
  1738. break;
  1739. case dwarf::DW_TAG_volatile_type:
  1740. Mods |= ModifierOptions::Volatile;
  1741. PO |= PointerOptions::Volatile;
  1742. break;
  1743. case dwarf::DW_TAG_restrict_type:
  1744. // Only pointer types be marked with __restrict. There is no known flag
  1745. // for __restrict in LF_MODIFIER records.
  1746. PO |= PointerOptions::Restrict;
  1747. break;
  1748. default:
  1749. IsModifier = false;
  1750. break;
  1751. }
  1752. if (IsModifier)
  1753. BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
  1754. }
  1755. // Check if the inner type will use an LF_POINTER record. If so, the
  1756. // qualifiers will go in the LF_POINTER record. This comes up for types like
  1757. // 'int *const' and 'int *__restrict', not the more common cases like 'const
  1758. // char *'.
  1759. if (BaseTy) {
  1760. switch (BaseTy->getTag()) {
  1761. case dwarf::DW_TAG_pointer_type:
  1762. case dwarf::DW_TAG_reference_type:
  1763. case dwarf::DW_TAG_rvalue_reference_type:
  1764. return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
  1765. case dwarf::DW_TAG_ptr_to_member_type:
  1766. return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
  1767. default:
  1768. break;
  1769. }
  1770. }
  1771. TypeIndex ModifiedTI = getTypeIndex(BaseTy);
  1772. // Return the base type index if there aren't any modifiers. For example, the
  1773. // metadata could contain restrict wrappers around non-pointer types.
  1774. if (Mods == ModifierOptions::None)
  1775. return ModifiedTI;
  1776. ModifierRecord MR(ModifiedTI, Mods);
  1777. return TypeTable.writeLeafType(MR);
  1778. }
  1779. TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
  1780. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1781. for (const DIType *ArgType : Ty->getTypeArray())
  1782. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
  1783. // MSVC uses type none for variadic argument.
  1784. if (ReturnAndArgTypeIndices.size() > 1 &&
  1785. ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
  1786. ReturnAndArgTypeIndices.back() = TypeIndex::None();
  1787. }
  1788. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1789. ArrayRef<TypeIndex> ArgTypeIndices = std::nullopt;
  1790. if (!ReturnAndArgTypeIndices.empty()) {
  1791. auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
  1792. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1793. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1794. }
  1795. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1796. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1797. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1798. FunctionOptions FO = getFunctionOptions(Ty);
  1799. ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
  1800. ArgListIndex);
  1801. return TypeTable.writeLeafType(Procedure);
  1802. }
  1803. TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
  1804. const DIType *ClassTy,
  1805. int ThisAdjustment,
  1806. bool IsStaticMethod,
  1807. FunctionOptions FO) {
  1808. // Lower the containing class type.
  1809. TypeIndex ClassType = getTypeIndex(ClassTy);
  1810. DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
  1811. unsigned Index = 0;
  1812. SmallVector<TypeIndex, 8> ArgTypeIndices;
  1813. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1814. if (ReturnAndArgs.size() > Index) {
  1815. ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
  1816. }
  1817. // If the first argument is a pointer type and this isn't a static method,
  1818. // treat it as the special 'this' parameter, which is encoded separately from
  1819. // the arguments.
  1820. TypeIndex ThisTypeIndex;
  1821. if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
  1822. if (const DIDerivedType *PtrTy =
  1823. dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
  1824. if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
  1825. ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
  1826. Index++;
  1827. }
  1828. }
  1829. }
  1830. while (Index < ReturnAndArgs.size())
  1831. ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
  1832. // MSVC uses type none for variadic argument.
  1833. if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
  1834. ArgTypeIndices.back() = TypeIndex::None();
  1835. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1836. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1837. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1838. MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
  1839. ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
  1840. return TypeTable.writeLeafType(MFR);
  1841. }
  1842. TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
  1843. unsigned VSlotCount =
  1844. Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
  1845. SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
  1846. VFTableShapeRecord VFTSR(Slots);
  1847. return TypeTable.writeLeafType(VFTSR);
  1848. }
  1849. static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
  1850. switch (Flags & DINode::FlagAccessibility) {
  1851. case DINode::FlagPrivate: return MemberAccess::Private;
  1852. case DINode::FlagPublic: return MemberAccess::Public;
  1853. case DINode::FlagProtected: return MemberAccess::Protected;
  1854. case 0:
  1855. // If there was no explicit access control, provide the default for the tag.
  1856. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
  1857. : MemberAccess::Public;
  1858. }
  1859. llvm_unreachable("access flags are exclusive");
  1860. }
  1861. static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
  1862. if (SP->isArtificial())
  1863. return MethodOptions::CompilerGenerated;
  1864. // FIXME: Handle other MethodOptions.
  1865. return MethodOptions::None;
  1866. }
  1867. static MethodKind translateMethodKindFlags(const DISubprogram *SP,
  1868. bool Introduced) {
  1869. if (SP->getFlags() & DINode::FlagStaticMember)
  1870. return MethodKind::Static;
  1871. switch (SP->getVirtuality()) {
  1872. case dwarf::DW_VIRTUALITY_none:
  1873. break;
  1874. case dwarf::DW_VIRTUALITY_virtual:
  1875. return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
  1876. case dwarf::DW_VIRTUALITY_pure_virtual:
  1877. return Introduced ? MethodKind::PureIntroducingVirtual
  1878. : MethodKind::PureVirtual;
  1879. default:
  1880. llvm_unreachable("unhandled virtuality case");
  1881. }
  1882. return MethodKind::Vanilla;
  1883. }
  1884. static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
  1885. switch (Ty->getTag()) {
  1886. case dwarf::DW_TAG_class_type:
  1887. return TypeRecordKind::Class;
  1888. case dwarf::DW_TAG_structure_type:
  1889. return TypeRecordKind::Struct;
  1890. default:
  1891. llvm_unreachable("unexpected tag");
  1892. }
  1893. }
  1894. /// Return ClassOptions that should be present on both the forward declaration
  1895. /// and the defintion of a tag type.
  1896. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
  1897. ClassOptions CO = ClassOptions::None;
  1898. // MSVC always sets this flag, even for local types. Clang doesn't always
  1899. // appear to give every type a linkage name, which may be problematic for us.
  1900. // FIXME: Investigate the consequences of not following them here.
  1901. if (!Ty->getIdentifier().empty())
  1902. CO |= ClassOptions::HasUniqueName;
  1903. // Put the Nested flag on a type if it appears immediately inside a tag type.
  1904. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
  1905. // here. That flag is only set on definitions, and not forward declarations.
  1906. const DIScope *ImmediateScope = Ty->getScope();
  1907. if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
  1908. CO |= ClassOptions::Nested;
  1909. // Put the Scoped flag on function-local types. MSVC puts this flag for enum
  1910. // type only when it has an immediate function scope. Clang never puts enums
  1911. // inside DILexicalBlock scopes. Enum types, as generated by clang, are
  1912. // always in function, class, or file scopes.
  1913. if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
  1914. if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
  1915. CO |= ClassOptions::Scoped;
  1916. } else {
  1917. for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
  1918. Scope = Scope->getScope()) {
  1919. if (isa<DISubprogram>(Scope)) {
  1920. CO |= ClassOptions::Scoped;
  1921. break;
  1922. }
  1923. }
  1924. }
  1925. return CO;
  1926. }
  1927. void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
  1928. switch (Ty->getTag()) {
  1929. case dwarf::DW_TAG_class_type:
  1930. case dwarf::DW_TAG_structure_type:
  1931. case dwarf::DW_TAG_union_type:
  1932. case dwarf::DW_TAG_enumeration_type:
  1933. break;
  1934. default:
  1935. return;
  1936. }
  1937. if (const auto *File = Ty->getFile()) {
  1938. StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
  1939. TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
  1940. UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
  1941. TypeTable.writeLeafType(USLR);
  1942. }
  1943. }
  1944. TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
  1945. ClassOptions CO = getCommonClassOptions(Ty);
  1946. TypeIndex FTI;
  1947. unsigned EnumeratorCount = 0;
  1948. if (Ty->isForwardDecl()) {
  1949. CO |= ClassOptions::ForwardReference;
  1950. } else {
  1951. ContinuationRecordBuilder ContinuationBuilder;
  1952. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  1953. for (const DINode *Element : Ty->getElements()) {
  1954. // We assume that the frontend provides all members in source declaration
  1955. // order, which is what MSVC does.
  1956. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
  1957. // FIXME: Is it correct to always emit these as unsigned here?
  1958. EnumeratorRecord ER(MemberAccess::Public,
  1959. APSInt(Enumerator->getValue(), true),
  1960. Enumerator->getName());
  1961. ContinuationBuilder.writeMemberType(ER);
  1962. EnumeratorCount++;
  1963. }
  1964. }
  1965. FTI = TypeTable.insertRecord(ContinuationBuilder);
  1966. }
  1967. std::string FullName = getFullyQualifiedName(Ty);
  1968. EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
  1969. getTypeIndex(Ty->getBaseType()));
  1970. TypeIndex EnumTI = TypeTable.writeLeafType(ER);
  1971. addUDTSrcLine(Ty, EnumTI);
  1972. return EnumTI;
  1973. }
  1974. //===----------------------------------------------------------------------===//
  1975. // ClassInfo
  1976. //===----------------------------------------------------------------------===//
  1977. struct llvm::ClassInfo {
  1978. struct MemberInfo {
  1979. const DIDerivedType *MemberTypeNode;
  1980. uint64_t BaseOffset;
  1981. };
  1982. // [MemberInfo]
  1983. using MemberList = std::vector<MemberInfo>;
  1984. using MethodsList = TinyPtrVector<const DISubprogram *>;
  1985. // MethodName -> MethodsList
  1986. using MethodsMap = MapVector<MDString *, MethodsList>;
  1987. /// Base classes.
  1988. std::vector<const DIDerivedType *> Inheritance;
  1989. /// Direct members.
  1990. MemberList Members;
  1991. // Direct overloaded methods gathered by name.
  1992. MethodsMap Methods;
  1993. TypeIndex VShapeTI;
  1994. std::vector<const DIType *> NestedTypes;
  1995. };
  1996. void CodeViewDebug::clear() {
  1997. assert(CurFn == nullptr);
  1998. FileIdMap.clear();
  1999. FnDebugInfo.clear();
  2000. FileToFilepathMap.clear();
  2001. LocalUDTs.clear();
  2002. GlobalUDTs.clear();
  2003. TypeIndices.clear();
  2004. CompleteTypeIndices.clear();
  2005. ScopeGlobals.clear();
  2006. CVGlobalVariableOffsets.clear();
  2007. }
  2008. void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
  2009. const DIDerivedType *DDTy) {
  2010. if (!DDTy->getName().empty()) {
  2011. Info.Members.push_back({DDTy, 0});
  2012. // Collect static const data members with values.
  2013. if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
  2014. DINode::FlagStaticMember) {
  2015. if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
  2016. isa<ConstantFP>(DDTy->getConstant())))
  2017. StaticConstMembers.push_back(DDTy);
  2018. }
  2019. return;
  2020. }
  2021. // An unnamed member may represent a nested struct or union. Attempt to
  2022. // interpret the unnamed member as a DICompositeType possibly wrapped in
  2023. // qualifier types. Add all the indirect fields to the current record if that
  2024. // succeeds, and drop the member if that fails.
  2025. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
  2026. uint64_t Offset = DDTy->getOffsetInBits();
  2027. const DIType *Ty = DDTy->getBaseType();
  2028. bool FullyResolved = false;
  2029. while (!FullyResolved) {
  2030. switch (Ty->getTag()) {
  2031. case dwarf::DW_TAG_const_type:
  2032. case dwarf::DW_TAG_volatile_type:
  2033. // FIXME: we should apply the qualifier types to the indirect fields
  2034. // rather than dropping them.
  2035. Ty = cast<DIDerivedType>(Ty)->getBaseType();
  2036. break;
  2037. default:
  2038. FullyResolved = true;
  2039. break;
  2040. }
  2041. }
  2042. const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
  2043. if (!DCTy)
  2044. return;
  2045. ClassInfo NestedInfo = collectClassInfo(DCTy);
  2046. for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
  2047. Info.Members.push_back(
  2048. {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
  2049. }
  2050. ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
  2051. ClassInfo Info;
  2052. // Add elements to structure type.
  2053. DINodeArray Elements = Ty->getElements();
  2054. for (auto *Element : Elements) {
  2055. // We assume that the frontend provides all members in source declaration
  2056. // order, which is what MSVC does.
  2057. if (!Element)
  2058. continue;
  2059. if (auto *SP = dyn_cast<DISubprogram>(Element)) {
  2060. Info.Methods[SP->getRawName()].push_back(SP);
  2061. } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  2062. if (DDTy->getTag() == dwarf::DW_TAG_member) {
  2063. collectMemberInfo(Info, DDTy);
  2064. } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
  2065. Info.Inheritance.push_back(DDTy);
  2066. } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
  2067. DDTy->getName() == "__vtbl_ptr_type") {
  2068. Info.VShapeTI = getTypeIndex(DDTy);
  2069. } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
  2070. Info.NestedTypes.push_back(DDTy);
  2071. } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  2072. // Ignore friend members. It appears that MSVC emitted info about
  2073. // friends in the past, but modern versions do not.
  2074. }
  2075. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  2076. Info.NestedTypes.push_back(Composite);
  2077. }
  2078. // Skip other unrecognized kinds of elements.
  2079. }
  2080. return Info;
  2081. }
  2082. static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
  2083. // This routine is used by lowerTypeClass and lowerTypeUnion to determine
  2084. // if a complete type should be emitted instead of a forward reference.
  2085. return Ty->getName().empty() && Ty->getIdentifier().empty() &&
  2086. !Ty->isForwardDecl();
  2087. }
  2088. TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
  2089. // Emit the complete type for unnamed structs. C++ classes with methods
  2090. // which have a circular reference back to the class type are expected to
  2091. // be named by the front-end and should not be "unnamed". C unnamed
  2092. // structs should not have circular references.
  2093. if (shouldAlwaysEmitCompleteClassType(Ty)) {
  2094. // If this unnamed complete type is already in the process of being defined
  2095. // then the description of the type is malformed and cannot be emitted
  2096. // into CodeView correctly so report a fatal error.
  2097. auto I = CompleteTypeIndices.find(Ty);
  2098. if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
  2099. report_fatal_error("cannot debug circular reference to unnamed type");
  2100. return getCompleteTypeIndex(Ty);
  2101. }
  2102. // First, construct the forward decl. Don't look into Ty to compute the
  2103. // forward decl options, since it might not be available in all TUs.
  2104. TypeRecordKind Kind = getRecordKind(Ty);
  2105. ClassOptions CO =
  2106. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  2107. std::string FullName = getFullyQualifiedName(Ty);
  2108. ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
  2109. FullName, Ty->getIdentifier());
  2110. TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
  2111. if (!Ty->isForwardDecl())
  2112. DeferredCompleteTypes.push_back(Ty);
  2113. return FwdDeclTI;
  2114. }
  2115. TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
  2116. // Construct the field list and complete type record.
  2117. TypeRecordKind Kind = getRecordKind(Ty);
  2118. ClassOptions CO = getCommonClassOptions(Ty);
  2119. TypeIndex FieldTI;
  2120. TypeIndex VShapeTI;
  2121. unsigned FieldCount;
  2122. bool ContainsNestedClass;
  2123. std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
  2124. lowerRecordFieldList(Ty);
  2125. if (ContainsNestedClass)
  2126. CO |= ClassOptions::ContainsNestedClass;
  2127. // MSVC appears to set this flag by searching any destructor or method with
  2128. // FunctionOptions::Constructor among the emitted members. Clang AST has all
  2129. // the members, however special member functions are not yet emitted into
  2130. // debug information. For now checking a class's non-triviality seems enough.
  2131. // FIXME: not true for a nested unnamed struct.
  2132. if (isNonTrivial(Ty))
  2133. CO |= ClassOptions::HasConstructorOrDestructor;
  2134. std::string FullName = getFullyQualifiedName(Ty);
  2135. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  2136. ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
  2137. SizeInBytes, FullName, Ty->getIdentifier());
  2138. TypeIndex ClassTI = TypeTable.writeLeafType(CR);
  2139. addUDTSrcLine(Ty, ClassTI);
  2140. addToUDTs(Ty);
  2141. return ClassTI;
  2142. }
  2143. TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
  2144. // Emit the complete type for unnamed unions.
  2145. if (shouldAlwaysEmitCompleteClassType(Ty))
  2146. return getCompleteTypeIndex(Ty);
  2147. ClassOptions CO =
  2148. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  2149. std::string FullName = getFullyQualifiedName(Ty);
  2150. UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
  2151. TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
  2152. if (!Ty->isForwardDecl())
  2153. DeferredCompleteTypes.push_back(Ty);
  2154. return FwdDeclTI;
  2155. }
  2156. TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
  2157. ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
  2158. TypeIndex FieldTI;
  2159. unsigned FieldCount;
  2160. bool ContainsNestedClass;
  2161. std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
  2162. lowerRecordFieldList(Ty);
  2163. if (ContainsNestedClass)
  2164. CO |= ClassOptions::ContainsNestedClass;
  2165. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  2166. std::string FullName = getFullyQualifiedName(Ty);
  2167. UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
  2168. Ty->getIdentifier());
  2169. TypeIndex UnionTI = TypeTable.writeLeafType(UR);
  2170. addUDTSrcLine(Ty, UnionTI);
  2171. addToUDTs(Ty);
  2172. return UnionTI;
  2173. }
  2174. std::tuple<TypeIndex, TypeIndex, unsigned, bool>
  2175. CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
  2176. // Manually count members. MSVC appears to count everything that generates a
  2177. // field list record. Each individual overload in a method overload group
  2178. // contributes to this count, even though the overload group is a single field
  2179. // list record.
  2180. unsigned MemberCount = 0;
  2181. ClassInfo Info = collectClassInfo(Ty);
  2182. ContinuationRecordBuilder ContinuationBuilder;
  2183. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  2184. // Create base classes.
  2185. for (const DIDerivedType *I : Info.Inheritance) {
  2186. if (I->getFlags() & DINode::FlagVirtual) {
  2187. // Virtual base.
  2188. unsigned VBPtrOffset = I->getVBPtrOffset();
  2189. // FIXME: Despite the accessor name, the offset is really in bytes.
  2190. unsigned VBTableIndex = I->getOffsetInBits() / 4;
  2191. auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
  2192. ? TypeRecordKind::IndirectVirtualBaseClass
  2193. : TypeRecordKind::VirtualBaseClass;
  2194. VirtualBaseClassRecord VBCR(
  2195. RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
  2196. getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
  2197. VBTableIndex);
  2198. ContinuationBuilder.writeMemberType(VBCR);
  2199. MemberCount++;
  2200. } else {
  2201. assert(I->getOffsetInBits() % 8 == 0 &&
  2202. "bases must be on byte boundaries");
  2203. BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
  2204. getTypeIndex(I->getBaseType()),
  2205. I->getOffsetInBits() / 8);
  2206. ContinuationBuilder.writeMemberType(BCR);
  2207. MemberCount++;
  2208. }
  2209. }
  2210. // Create members.
  2211. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
  2212. const DIDerivedType *Member = MemberInfo.MemberTypeNode;
  2213. TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
  2214. StringRef MemberName = Member->getName();
  2215. MemberAccess Access =
  2216. translateAccessFlags(Ty->getTag(), Member->getFlags());
  2217. if (Member->isStaticMember()) {
  2218. StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
  2219. ContinuationBuilder.writeMemberType(SDMR);
  2220. MemberCount++;
  2221. continue;
  2222. }
  2223. // Virtual function pointer member.
  2224. if ((Member->getFlags() & DINode::FlagArtificial) &&
  2225. Member->getName().startswith("_vptr$")) {
  2226. VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
  2227. ContinuationBuilder.writeMemberType(VFPR);
  2228. MemberCount++;
  2229. continue;
  2230. }
  2231. // Data member.
  2232. uint64_t MemberOffsetInBits =
  2233. Member->getOffsetInBits() + MemberInfo.BaseOffset;
  2234. if (Member->isBitField()) {
  2235. uint64_t StartBitOffset = MemberOffsetInBits;
  2236. if (const auto *CI =
  2237. dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
  2238. MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
  2239. }
  2240. StartBitOffset -= MemberOffsetInBits;
  2241. BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
  2242. StartBitOffset);
  2243. MemberBaseType = TypeTable.writeLeafType(BFR);
  2244. }
  2245. uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
  2246. DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
  2247. MemberName);
  2248. ContinuationBuilder.writeMemberType(DMR);
  2249. MemberCount++;
  2250. }
  2251. // Create methods
  2252. for (auto &MethodItr : Info.Methods) {
  2253. StringRef Name = MethodItr.first->getString();
  2254. std::vector<OneMethodRecord> Methods;
  2255. for (const DISubprogram *SP : MethodItr.second) {
  2256. TypeIndex MethodType = getMemberFunctionType(SP, Ty);
  2257. bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
  2258. unsigned VFTableOffset = -1;
  2259. if (Introduced)
  2260. VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
  2261. Methods.push_back(OneMethodRecord(
  2262. MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
  2263. translateMethodKindFlags(SP, Introduced),
  2264. translateMethodOptionFlags(SP), VFTableOffset, Name));
  2265. MemberCount++;
  2266. }
  2267. assert(!Methods.empty() && "Empty methods map entry");
  2268. if (Methods.size() == 1)
  2269. ContinuationBuilder.writeMemberType(Methods[0]);
  2270. else {
  2271. // FIXME: Make this use its own ContinuationBuilder so that
  2272. // MethodOverloadList can be split correctly.
  2273. MethodOverloadListRecord MOLR(Methods);
  2274. TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
  2275. OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
  2276. ContinuationBuilder.writeMemberType(OMR);
  2277. }
  2278. }
  2279. // Create nested classes.
  2280. for (const DIType *Nested : Info.NestedTypes) {
  2281. NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
  2282. ContinuationBuilder.writeMemberType(R);
  2283. MemberCount++;
  2284. }
  2285. TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
  2286. return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
  2287. !Info.NestedTypes.empty());
  2288. }
  2289. TypeIndex CodeViewDebug::getVBPTypeIndex() {
  2290. if (!VBPType.getIndex()) {
  2291. // Make a 'const int *' type.
  2292. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
  2293. TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
  2294. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  2295. : PointerKind::Near32;
  2296. PointerMode PM = PointerMode::Pointer;
  2297. PointerOptions PO = PointerOptions::None;
  2298. PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
  2299. VBPType = TypeTable.writeLeafType(PR);
  2300. }
  2301. return VBPType;
  2302. }
  2303. TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
  2304. // The null DIType is the void type. Don't try to hash it.
  2305. if (!Ty)
  2306. return TypeIndex::Void();
  2307. // Check if we've already translated this type. Don't try to do a
  2308. // get-or-create style insertion that caches the hash lookup across the
  2309. // lowerType call. It will update the TypeIndices map.
  2310. auto I = TypeIndices.find({Ty, ClassTy});
  2311. if (I != TypeIndices.end())
  2312. return I->second;
  2313. TypeLoweringScope S(*this);
  2314. TypeIndex TI = lowerType(Ty, ClassTy);
  2315. return recordTypeIndexForDINode(Ty, TI, ClassTy);
  2316. }
  2317. codeview::TypeIndex
  2318. CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
  2319. const DISubroutineType *SubroutineTy) {
  2320. assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
  2321. "this type must be a pointer type");
  2322. PointerOptions Options = PointerOptions::None;
  2323. if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
  2324. Options = PointerOptions::LValueRefThisPointer;
  2325. else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
  2326. Options = PointerOptions::RValueRefThisPointer;
  2327. // Check if we've already translated this type. If there is no ref qualifier
  2328. // on the function then we look up this pointer type with no associated class
  2329. // so that the TypeIndex for the this pointer can be shared with the type
  2330. // index for other pointers to this class type. If there is a ref qualifier
  2331. // then we lookup the pointer using the subroutine as the parent type.
  2332. auto I = TypeIndices.find({PtrTy, SubroutineTy});
  2333. if (I != TypeIndices.end())
  2334. return I->second;
  2335. TypeLoweringScope S(*this);
  2336. TypeIndex TI = lowerTypePointer(PtrTy, Options);
  2337. return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
  2338. }
  2339. TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
  2340. PointerRecord PR(getTypeIndex(Ty),
  2341. getPointerSizeInBytes() == 8 ? PointerKind::Near64
  2342. : PointerKind::Near32,
  2343. PointerMode::LValueReference, PointerOptions::None,
  2344. Ty->getSizeInBits() / 8);
  2345. return TypeTable.writeLeafType(PR);
  2346. }
  2347. TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
  2348. // The null DIType is the void type. Don't try to hash it.
  2349. if (!Ty)
  2350. return TypeIndex::Void();
  2351. // Look through typedefs when getting the complete type index. Call
  2352. // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
  2353. // emitted only once.
  2354. if (Ty->getTag() == dwarf::DW_TAG_typedef)
  2355. (void)getTypeIndex(Ty);
  2356. while (Ty->getTag() == dwarf::DW_TAG_typedef)
  2357. Ty = cast<DIDerivedType>(Ty)->getBaseType();
  2358. // If this is a non-record type, the complete type index is the same as the
  2359. // normal type index. Just call getTypeIndex.
  2360. switch (Ty->getTag()) {
  2361. case dwarf::DW_TAG_class_type:
  2362. case dwarf::DW_TAG_structure_type:
  2363. case dwarf::DW_TAG_union_type:
  2364. break;
  2365. default:
  2366. return getTypeIndex(Ty);
  2367. }
  2368. const auto *CTy = cast<DICompositeType>(Ty);
  2369. TypeLoweringScope S(*this);
  2370. // Make sure the forward declaration is emitted first. It's unclear if this
  2371. // is necessary, but MSVC does it, and we should follow suit until we can show
  2372. // otherwise.
  2373. // We only emit a forward declaration for named types.
  2374. if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
  2375. TypeIndex FwdDeclTI = getTypeIndex(CTy);
  2376. // Just use the forward decl if we don't have complete type info. This
  2377. // might happen if the frontend is using modules and expects the complete
  2378. // definition to be emitted elsewhere.
  2379. if (CTy->isForwardDecl())
  2380. return FwdDeclTI;
  2381. }
  2382. // Check if we've already translated the complete record type.
  2383. // Insert the type with a null TypeIndex to signify that the type is currently
  2384. // being lowered.
  2385. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
  2386. if (!InsertResult.second)
  2387. return InsertResult.first->second;
  2388. TypeIndex TI;
  2389. switch (CTy->getTag()) {
  2390. case dwarf::DW_TAG_class_type:
  2391. case dwarf::DW_TAG_structure_type:
  2392. TI = lowerCompleteTypeClass(CTy);
  2393. break;
  2394. case dwarf::DW_TAG_union_type:
  2395. TI = lowerCompleteTypeUnion(CTy);
  2396. break;
  2397. default:
  2398. llvm_unreachable("not a record");
  2399. }
  2400. // Update the type index associated with this CompositeType. This cannot
  2401. // use the 'InsertResult' iterator above because it is potentially
  2402. // invalidated by map insertions which can occur while lowering the class
  2403. // type above.
  2404. CompleteTypeIndices[CTy] = TI;
  2405. return TI;
  2406. }
  2407. /// Emit all the deferred complete record types. Try to do this in FIFO order,
  2408. /// and do this until fixpoint, as each complete record type typically
  2409. /// references
  2410. /// many other record types.
  2411. void CodeViewDebug::emitDeferredCompleteTypes() {
  2412. SmallVector<const DICompositeType *, 4> TypesToEmit;
  2413. while (!DeferredCompleteTypes.empty()) {
  2414. std::swap(DeferredCompleteTypes, TypesToEmit);
  2415. for (const DICompositeType *RecordTy : TypesToEmit)
  2416. getCompleteTypeIndex(RecordTy);
  2417. TypesToEmit.clear();
  2418. }
  2419. }
  2420. void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
  2421. ArrayRef<LocalVariable> Locals) {
  2422. // Get the sorted list of parameters and emit them first.
  2423. SmallVector<const LocalVariable *, 6> Params;
  2424. for (const LocalVariable &L : Locals)
  2425. if (L.DIVar->isParameter())
  2426. Params.push_back(&L);
  2427. llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
  2428. return L->DIVar->getArg() < R->DIVar->getArg();
  2429. });
  2430. for (const LocalVariable *L : Params)
  2431. emitLocalVariable(FI, *L);
  2432. // Next emit all non-parameters in the order that we found them.
  2433. for (const LocalVariable &L : Locals) {
  2434. if (!L.DIVar->isParameter()) {
  2435. if (L.ConstantValue) {
  2436. // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
  2437. // S_LOCAL in order to be able to represent it at all.
  2438. const DIType *Ty = L.DIVar->getType();
  2439. APSInt Val(*L.ConstantValue);
  2440. emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName()));
  2441. } else {
  2442. emitLocalVariable(FI, L);
  2443. }
  2444. }
  2445. }
  2446. }
  2447. void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
  2448. const LocalVariable &Var) {
  2449. // LocalSym record, see SymbolRecord.h for more info.
  2450. MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
  2451. LocalSymFlags Flags = LocalSymFlags::None;
  2452. if (Var.DIVar->isParameter())
  2453. Flags |= LocalSymFlags::IsParameter;
  2454. if (Var.DefRanges.empty())
  2455. Flags |= LocalSymFlags::IsOptimizedOut;
  2456. OS.AddComment("TypeIndex");
  2457. TypeIndex TI = Var.UseReferenceType
  2458. ? getTypeIndexForReferenceTo(Var.DIVar->getType())
  2459. : getCompleteTypeIndex(Var.DIVar->getType());
  2460. OS.emitInt32(TI.getIndex());
  2461. OS.AddComment("Flags");
  2462. OS.emitInt16(static_cast<uint16_t>(Flags));
  2463. // Truncate the name so we won't overflow the record length field.
  2464. emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
  2465. endSymbolRecord(LocalEnd);
  2466. // Calculate the on disk prefix of the appropriate def range record. The
  2467. // records and on disk formats are described in SymbolRecords.h. BytePrefix
  2468. // should be big enough to hold all forms without memory allocation.
  2469. SmallString<20> BytePrefix;
  2470. for (const auto &Pair : Var.DefRanges) {
  2471. LocalVarDef DefRange = Pair.first;
  2472. const auto &Ranges = Pair.second;
  2473. BytePrefix.clear();
  2474. if (DefRange.InMemory) {
  2475. int Offset = DefRange.DataOffset;
  2476. unsigned Reg = DefRange.CVRegister;
  2477. // 32-bit x86 call sequences often use PUSH instructions, which disrupt
  2478. // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
  2479. // instead. In frames without stack realignment, $T0 will be the CFA.
  2480. if (RegisterId(Reg) == RegisterId::ESP) {
  2481. Reg = unsigned(RegisterId::VFRAME);
  2482. Offset += FI.OffsetAdjustment;
  2483. }
  2484. // If we can use the chosen frame pointer for the frame and this isn't a
  2485. // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
  2486. // Otherwise, use S_DEFRANGE_REGISTER_REL.
  2487. EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
  2488. if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
  2489. (bool(Flags & LocalSymFlags::IsParameter)
  2490. ? (EncFP == FI.EncodedParamFramePtrReg)
  2491. : (EncFP == FI.EncodedLocalFramePtrReg))) {
  2492. DefRangeFramePointerRelHeader DRHdr;
  2493. DRHdr.Offset = Offset;
  2494. OS.emitCVDefRangeDirective(Ranges, DRHdr);
  2495. } else {
  2496. uint16_t RegRelFlags = 0;
  2497. if (DefRange.IsSubfield) {
  2498. RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
  2499. (DefRange.StructOffset
  2500. << DefRangeRegisterRelSym::OffsetInParentShift);
  2501. }
  2502. DefRangeRegisterRelHeader DRHdr;
  2503. DRHdr.Register = Reg;
  2504. DRHdr.Flags = RegRelFlags;
  2505. DRHdr.BasePointerOffset = Offset;
  2506. OS.emitCVDefRangeDirective(Ranges, DRHdr);
  2507. }
  2508. } else {
  2509. assert(DefRange.DataOffset == 0 && "unexpected offset into register");
  2510. if (DefRange.IsSubfield) {
  2511. DefRangeSubfieldRegisterHeader DRHdr;
  2512. DRHdr.Register = DefRange.CVRegister;
  2513. DRHdr.MayHaveNoName = 0;
  2514. DRHdr.OffsetInParent = DefRange.StructOffset;
  2515. OS.emitCVDefRangeDirective(Ranges, DRHdr);
  2516. } else {
  2517. DefRangeRegisterHeader DRHdr;
  2518. DRHdr.Register = DefRange.CVRegister;
  2519. DRHdr.MayHaveNoName = 0;
  2520. OS.emitCVDefRangeDirective(Ranges, DRHdr);
  2521. }
  2522. }
  2523. }
  2524. }
  2525. void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
  2526. const FunctionInfo& FI) {
  2527. for (LexicalBlock *Block : Blocks)
  2528. emitLexicalBlock(*Block, FI);
  2529. }
  2530. /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
  2531. /// lexical block scope.
  2532. void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
  2533. const FunctionInfo& FI) {
  2534. MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
  2535. OS.AddComment("PtrParent");
  2536. OS.emitInt32(0); // PtrParent
  2537. OS.AddComment("PtrEnd");
  2538. OS.emitInt32(0); // PtrEnd
  2539. OS.AddComment("Code size");
  2540. OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
  2541. OS.AddComment("Function section relative address");
  2542. OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
  2543. OS.AddComment("Function section index");
  2544. OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol
  2545. OS.AddComment("Lexical block name");
  2546. emitNullTerminatedSymbolName(OS, Block.Name); // Name
  2547. endSymbolRecord(RecordEnd);
  2548. // Emit variables local to this lexical block.
  2549. emitLocalVariableList(FI, Block.Locals);
  2550. emitGlobalVariableList(Block.Globals);
  2551. // Emit lexical blocks contained within this block.
  2552. emitLexicalBlockList(Block.Children, FI);
  2553. // Close the lexical block scope.
  2554. emitEndSymbolRecord(SymbolKind::S_END);
  2555. }
  2556. /// Convenience routine for collecting lexical block information for a list
  2557. /// of lexical scopes.
  2558. void CodeViewDebug::collectLexicalBlockInfo(
  2559. SmallVectorImpl<LexicalScope *> &Scopes,
  2560. SmallVectorImpl<LexicalBlock *> &Blocks,
  2561. SmallVectorImpl<LocalVariable> &Locals,
  2562. SmallVectorImpl<CVGlobalVariable> &Globals) {
  2563. for (LexicalScope *Scope : Scopes)
  2564. collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
  2565. }
  2566. /// Populate the lexical blocks and local variable lists of the parent with
  2567. /// information about the specified lexical scope.
  2568. void CodeViewDebug::collectLexicalBlockInfo(
  2569. LexicalScope &Scope,
  2570. SmallVectorImpl<LexicalBlock *> &ParentBlocks,
  2571. SmallVectorImpl<LocalVariable> &ParentLocals,
  2572. SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
  2573. if (Scope.isAbstractScope())
  2574. return;
  2575. // Gather information about the lexical scope including local variables,
  2576. // global variables, and address ranges.
  2577. bool IgnoreScope = false;
  2578. auto LI = ScopeVariables.find(&Scope);
  2579. SmallVectorImpl<LocalVariable> *Locals =
  2580. LI != ScopeVariables.end() ? &LI->second : nullptr;
  2581. auto GI = ScopeGlobals.find(Scope.getScopeNode());
  2582. SmallVectorImpl<CVGlobalVariable> *Globals =
  2583. GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
  2584. const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
  2585. const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
  2586. // Ignore lexical scopes which do not contain variables.
  2587. if (!Locals && !Globals)
  2588. IgnoreScope = true;
  2589. // Ignore lexical scopes which are not lexical blocks.
  2590. if (!DILB)
  2591. IgnoreScope = true;
  2592. // Ignore scopes which have too many address ranges to represent in the
  2593. // current CodeView format or do not have a valid address range.
  2594. //
  2595. // For lexical scopes with multiple address ranges you may be tempted to
  2596. // construct a single range covering every instruction where the block is
  2597. // live and everything in between. Unfortunately, Visual Studio only
  2598. // displays variables from the first matching lexical block scope. If the
  2599. // first lexical block contains exception handling code or cold code which
  2600. // is moved to the bottom of the routine creating a single range covering
  2601. // nearly the entire routine, then it will hide all other lexical blocks
  2602. // and the variables they contain.
  2603. if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
  2604. IgnoreScope = true;
  2605. if (IgnoreScope) {
  2606. // This scope can be safely ignored and eliminating it will reduce the
  2607. // size of the debug information. Be sure to collect any variable and scope
  2608. // information from the this scope or any of its children and collapse them
  2609. // into the parent scope.
  2610. if (Locals)
  2611. ParentLocals.append(Locals->begin(), Locals->end());
  2612. if (Globals)
  2613. ParentGlobals.append(Globals->begin(), Globals->end());
  2614. collectLexicalBlockInfo(Scope.getChildren(),
  2615. ParentBlocks,
  2616. ParentLocals,
  2617. ParentGlobals);
  2618. return;
  2619. }
  2620. // Create a new CodeView lexical block for this lexical scope. If we've
  2621. // seen this DILexicalBlock before then the scope tree is malformed and
  2622. // we can handle this gracefully by not processing it a second time.
  2623. auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
  2624. if (!BlockInsertion.second)
  2625. return;
  2626. // Create a lexical block containing the variables and collect the the
  2627. // lexical block information for the children.
  2628. const InsnRange &Range = Ranges.front();
  2629. assert(Range.first && Range.second);
  2630. LexicalBlock &Block = BlockInsertion.first->second;
  2631. Block.Begin = getLabelBeforeInsn(Range.first);
  2632. Block.End = getLabelAfterInsn(Range.second);
  2633. assert(Block.Begin && "missing label for scope begin");
  2634. assert(Block.End && "missing label for scope end");
  2635. Block.Name = DILB->getName();
  2636. if (Locals)
  2637. Block.Locals = std::move(*Locals);
  2638. if (Globals)
  2639. Block.Globals = std::move(*Globals);
  2640. ParentBlocks.push_back(&Block);
  2641. collectLexicalBlockInfo(Scope.getChildren(),
  2642. Block.Children,
  2643. Block.Locals,
  2644. Block.Globals);
  2645. }
  2646. void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
  2647. const Function &GV = MF->getFunction();
  2648. assert(FnDebugInfo.count(&GV));
  2649. assert(CurFn == FnDebugInfo[&GV].get());
  2650. collectVariableInfo(GV.getSubprogram());
  2651. // Build the lexical block structure to emit for this routine.
  2652. if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
  2653. collectLexicalBlockInfo(*CFS,
  2654. CurFn->ChildBlocks,
  2655. CurFn->Locals,
  2656. CurFn->Globals);
  2657. // Clear the scope and variable information from the map which will not be
  2658. // valid after we have finished processing this routine. This also prepares
  2659. // the map for the subsequent routine.
  2660. ScopeVariables.clear();
  2661. // Don't emit anything if we don't have any line tables.
  2662. // Thunks are compiler-generated and probably won't have source correlation.
  2663. if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
  2664. FnDebugInfo.erase(&GV);
  2665. CurFn = nullptr;
  2666. return;
  2667. }
  2668. // Find heap alloc sites and add to list.
  2669. for (const auto &MBB : *MF) {
  2670. for (const auto &MI : MBB) {
  2671. if (MDNode *MD = MI.getHeapAllocMarker()) {
  2672. CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
  2673. getLabelAfterInsn(&MI),
  2674. dyn_cast<DIType>(MD)));
  2675. }
  2676. }
  2677. }
  2678. CurFn->Annotations = MF->getCodeViewAnnotations();
  2679. CurFn->End = Asm->getFunctionEnd();
  2680. CurFn = nullptr;
  2681. }
  2682. // Usable locations are valid with non-zero line numbers. A line number of zero
  2683. // corresponds to optimized code that doesn't have a distinct source location.
  2684. // In this case, we try to use the previous or next source location depending on
  2685. // the context.
  2686. static bool isUsableDebugLoc(DebugLoc DL) {
  2687. return DL && DL.getLine() != 0;
  2688. }
  2689. void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
  2690. DebugHandlerBase::beginInstruction(MI);
  2691. // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
  2692. if (!Asm || !CurFn || MI->isDebugInstr() ||
  2693. MI->getFlag(MachineInstr::FrameSetup))
  2694. return;
  2695. // If the first instruction of a new MBB has no location, find the first
  2696. // instruction with a location and use that.
  2697. DebugLoc DL = MI->getDebugLoc();
  2698. if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
  2699. for (const auto &NextMI : *MI->getParent()) {
  2700. if (NextMI.isDebugInstr())
  2701. continue;
  2702. DL = NextMI.getDebugLoc();
  2703. if (isUsableDebugLoc(DL))
  2704. break;
  2705. }
  2706. // FIXME: Handle the case where the BB has no valid locations. This would
  2707. // probably require doing a real dataflow analysis.
  2708. }
  2709. PrevInstBB = MI->getParent();
  2710. // If we still don't have a debug location, don't record a location.
  2711. if (!isUsableDebugLoc(DL))
  2712. return;
  2713. maybeRecordLocation(DL, Asm->MF);
  2714. }
  2715. MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
  2716. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  2717. *EndLabel = MMI->getContext().createTempSymbol();
  2718. OS.emitInt32(unsigned(Kind));
  2719. OS.AddComment("Subsection size");
  2720. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
  2721. OS.emitLabel(BeginLabel);
  2722. return EndLabel;
  2723. }
  2724. void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
  2725. OS.emitLabel(EndLabel);
  2726. // Every subsection must be aligned to a 4-byte boundary.
  2727. OS.emitValueToAlignment(Align(4));
  2728. }
  2729. static StringRef getSymbolName(SymbolKind SymKind) {
  2730. for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
  2731. if (EE.Value == SymKind)
  2732. return EE.Name;
  2733. return "";
  2734. }
  2735. MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
  2736. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  2737. *EndLabel = MMI->getContext().createTempSymbol();
  2738. OS.AddComment("Record length");
  2739. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
  2740. OS.emitLabel(BeginLabel);
  2741. if (OS.isVerboseAsm())
  2742. OS.AddComment("Record kind: " + getSymbolName(SymKind));
  2743. OS.emitInt16(unsigned(SymKind));
  2744. return EndLabel;
  2745. }
  2746. void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
  2747. // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
  2748. // an extra copy of every symbol record in LLD. This increases object file
  2749. // size by less than 1% in the clang build, and is compatible with the Visual
  2750. // C++ linker.
  2751. OS.emitValueToAlignment(Align(4));
  2752. OS.emitLabel(SymEnd);
  2753. }
  2754. void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
  2755. OS.AddComment("Record length");
  2756. OS.emitInt16(2);
  2757. if (OS.isVerboseAsm())
  2758. OS.AddComment("Record kind: " + getSymbolName(EndKind));
  2759. OS.emitInt16(uint16_t(EndKind)); // Record Kind
  2760. }
  2761. void CodeViewDebug::emitDebugInfoForUDTs(
  2762. const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
  2763. #ifndef NDEBUG
  2764. size_t OriginalSize = UDTs.size();
  2765. #endif
  2766. for (const auto &UDT : UDTs) {
  2767. const DIType *T = UDT.second;
  2768. assert(shouldEmitUdt(T));
  2769. MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
  2770. OS.AddComment("Type");
  2771. OS.emitInt32(getCompleteTypeIndex(T).getIndex());
  2772. assert(OriginalSize == UDTs.size() &&
  2773. "getCompleteTypeIndex found new UDTs!");
  2774. emitNullTerminatedSymbolName(OS, UDT.first);
  2775. endSymbolRecord(UDTRecordEnd);
  2776. }
  2777. }
  2778. void CodeViewDebug::collectGlobalVariableInfo() {
  2779. DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
  2780. GlobalMap;
  2781. for (const GlobalVariable &GV : MMI->getModule()->globals()) {
  2782. SmallVector<DIGlobalVariableExpression *, 1> GVEs;
  2783. GV.getDebugInfo(GVEs);
  2784. for (const auto *GVE : GVEs)
  2785. GlobalMap[GVE] = &GV;
  2786. }
  2787. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2788. for (const MDNode *Node : CUs->operands()) {
  2789. const auto *CU = cast<DICompileUnit>(Node);
  2790. for (const auto *GVE : CU->getGlobalVariables()) {
  2791. const DIGlobalVariable *DIGV = GVE->getVariable();
  2792. const DIExpression *DIE = GVE->getExpression();
  2793. // Don't emit string literals in CodeView, as the only useful parts are
  2794. // generally the filename and line number, which isn't possible to output
  2795. // in CodeView. String literals should be the only unnamed GlobalVariable
  2796. // with debug info.
  2797. if (DIGV->getName().empty()) continue;
  2798. if ((DIE->getNumElements() == 2) &&
  2799. (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
  2800. // Record the constant offset for the variable.
  2801. //
  2802. // A Fortran common block uses this idiom to encode the offset
  2803. // of a variable from the common block's starting address.
  2804. CVGlobalVariableOffsets.insert(
  2805. std::make_pair(DIGV, DIE->getElement(1)));
  2806. // Emit constant global variables in a global symbol section.
  2807. if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
  2808. CVGlobalVariable CVGV = {DIGV, DIE};
  2809. GlobalVariables.emplace_back(std::move(CVGV));
  2810. }
  2811. const auto *GV = GlobalMap.lookup(GVE);
  2812. if (!GV || GV->isDeclarationForLinker())
  2813. continue;
  2814. DIScope *Scope = DIGV->getScope();
  2815. SmallVector<CVGlobalVariable, 1> *VariableList;
  2816. if (Scope && isa<DILocalScope>(Scope)) {
  2817. // Locate a global variable list for this scope, creating one if
  2818. // necessary.
  2819. auto Insertion = ScopeGlobals.insert(
  2820. {Scope, std::unique_ptr<GlobalVariableList>()});
  2821. if (Insertion.second)
  2822. Insertion.first->second = std::make_unique<GlobalVariableList>();
  2823. VariableList = Insertion.first->second.get();
  2824. } else if (GV->hasComdat())
  2825. // Emit this global variable into a COMDAT section.
  2826. VariableList = &ComdatVariables;
  2827. else
  2828. // Emit this global variable in a single global symbol section.
  2829. VariableList = &GlobalVariables;
  2830. CVGlobalVariable CVGV = {DIGV, GV};
  2831. VariableList->emplace_back(std::move(CVGV));
  2832. }
  2833. }
  2834. }
  2835. void CodeViewDebug::collectDebugInfoForGlobals() {
  2836. for (const CVGlobalVariable &CVGV : GlobalVariables) {
  2837. const DIGlobalVariable *DIGV = CVGV.DIGV;
  2838. const DIScope *Scope = DIGV->getScope();
  2839. getCompleteTypeIndex(DIGV->getType());
  2840. getFullyQualifiedName(Scope, DIGV->getName());
  2841. }
  2842. for (const CVGlobalVariable &CVGV : ComdatVariables) {
  2843. const DIGlobalVariable *DIGV = CVGV.DIGV;
  2844. const DIScope *Scope = DIGV->getScope();
  2845. getCompleteTypeIndex(DIGV->getType());
  2846. getFullyQualifiedName(Scope, DIGV->getName());
  2847. }
  2848. }
  2849. void CodeViewDebug::emitDebugInfoForGlobals() {
  2850. // First, emit all globals that are not in a comdat in a single symbol
  2851. // substream. MSVC doesn't like it if the substream is empty, so only open
  2852. // it if we have at least one global to emit.
  2853. switchToDebugSectionForSymbol(nullptr);
  2854. if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
  2855. OS.AddComment("Symbol subsection for globals");
  2856. MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2857. emitGlobalVariableList(GlobalVariables);
  2858. emitStaticConstMemberList();
  2859. endCVSubsection(EndLabel);
  2860. }
  2861. // Second, emit each global that is in a comdat into its own .debug$S
  2862. // section along with its own symbol substream.
  2863. for (const CVGlobalVariable &CVGV : ComdatVariables) {
  2864. const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
  2865. MCSymbol *GVSym = Asm->getSymbol(GV);
  2866. OS.AddComment("Symbol subsection for " +
  2867. Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
  2868. switchToDebugSectionForSymbol(GVSym);
  2869. MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2870. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2871. emitDebugInfoForGlobal(CVGV);
  2872. endCVSubsection(EndLabel);
  2873. }
  2874. }
  2875. void CodeViewDebug::emitDebugInfoForRetainedTypes() {
  2876. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2877. for (const MDNode *Node : CUs->operands()) {
  2878. for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
  2879. if (DIType *RT = dyn_cast<DIType>(Ty)) {
  2880. getTypeIndex(RT);
  2881. // FIXME: Add to global/local DTU list.
  2882. }
  2883. }
  2884. }
  2885. }
  2886. // Emit each global variable in the specified array.
  2887. void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
  2888. for (const CVGlobalVariable &CVGV : Globals) {
  2889. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2890. emitDebugInfoForGlobal(CVGV);
  2891. }
  2892. }
  2893. void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
  2894. const std::string &QualifiedName) {
  2895. MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
  2896. OS.AddComment("Type");
  2897. OS.emitInt32(getTypeIndex(DTy).getIndex());
  2898. OS.AddComment("Value");
  2899. // Encoded integers shouldn't need more than 10 bytes.
  2900. uint8_t Data[10];
  2901. BinaryStreamWriter Writer(Data, llvm::support::endianness::little);
  2902. CodeViewRecordIO IO(Writer);
  2903. cantFail(IO.mapEncodedInteger(Value));
  2904. StringRef SRef((char *)Data, Writer.getOffset());
  2905. OS.emitBinaryData(SRef);
  2906. OS.AddComment("Name");
  2907. emitNullTerminatedSymbolName(OS, QualifiedName);
  2908. endSymbolRecord(SConstantEnd);
  2909. }
  2910. void CodeViewDebug::emitStaticConstMemberList() {
  2911. for (const DIDerivedType *DTy : StaticConstMembers) {
  2912. const DIScope *Scope = DTy->getScope();
  2913. APSInt Value;
  2914. if (const ConstantInt *CI =
  2915. dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
  2916. Value = APSInt(CI->getValue(),
  2917. DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
  2918. else if (const ConstantFP *CFP =
  2919. dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
  2920. Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
  2921. else
  2922. llvm_unreachable("cannot emit a constant without a value");
  2923. emitConstantSymbolRecord(DTy->getBaseType(), Value,
  2924. getFullyQualifiedName(Scope, DTy->getName()));
  2925. }
  2926. }
  2927. static bool isFloatDIType(const DIType *Ty) {
  2928. if (isa<DICompositeType>(Ty))
  2929. return false;
  2930. if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
  2931. dwarf::Tag T = (dwarf::Tag)Ty->getTag();
  2932. if (T == dwarf::DW_TAG_pointer_type ||
  2933. T == dwarf::DW_TAG_ptr_to_member_type ||
  2934. T == dwarf::DW_TAG_reference_type ||
  2935. T == dwarf::DW_TAG_rvalue_reference_type)
  2936. return false;
  2937. assert(DTy->getBaseType() && "Expected valid base type");
  2938. return isFloatDIType(DTy->getBaseType());
  2939. }
  2940. auto *BTy = cast<DIBasicType>(Ty);
  2941. return (BTy->getEncoding() == dwarf::DW_ATE_float);
  2942. }
  2943. void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
  2944. const DIGlobalVariable *DIGV = CVGV.DIGV;
  2945. const DIScope *Scope = DIGV->getScope();
  2946. // For static data members, get the scope from the declaration.
  2947. if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
  2948. DIGV->getRawStaticDataMemberDeclaration()))
  2949. Scope = MemberDecl->getScope();
  2950. // For static local variables and Fortran, the scoping portion is elided
  2951. // in its name so that we can reference the variable in the command line
  2952. // of the VS debugger.
  2953. std::string QualifiedName =
  2954. (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope)))
  2955. ? std::string(DIGV->getName())
  2956. : getFullyQualifiedName(Scope, DIGV->getName());
  2957. if (const GlobalVariable *GV =
  2958. CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
  2959. // DataSym record, see SymbolRecord.h for more info. Thread local data
  2960. // happens to have the same format as global data.
  2961. MCSymbol *GVSym = Asm->getSymbol(GV);
  2962. SymbolKind DataSym = GV->isThreadLocal()
  2963. ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
  2964. : SymbolKind::S_GTHREAD32)
  2965. : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
  2966. : SymbolKind::S_GDATA32);
  2967. MCSymbol *DataEnd = beginSymbolRecord(DataSym);
  2968. OS.AddComment("Type");
  2969. OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
  2970. OS.AddComment("DataOffset");
  2971. uint64_t Offset = 0;
  2972. if (CVGlobalVariableOffsets.find(DIGV) != CVGlobalVariableOffsets.end())
  2973. // Use the offset seen while collecting info on globals.
  2974. Offset = CVGlobalVariableOffsets[DIGV];
  2975. OS.emitCOFFSecRel32(GVSym, Offset);
  2976. OS.AddComment("Segment");
  2977. OS.emitCOFFSectionIndex(GVSym);
  2978. OS.AddComment("Name");
  2979. const unsigned LengthOfDataRecord = 12;
  2980. emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
  2981. endSymbolRecord(DataEnd);
  2982. } else {
  2983. const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
  2984. assert(DIE->isConstant() &&
  2985. "Global constant variables must contain a constant expression.");
  2986. // Use unsigned for floats.
  2987. bool isUnsigned = isFloatDIType(DIGV->getType())
  2988. ? true
  2989. : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
  2990. APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
  2991. emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
  2992. }
  2993. }