CodeViewDebug.cpp 111 KB

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