CodeViewDebug.cpp 113 KB

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