CodeViewDebug.cpp 115 KB

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