CodeViewDebug.cpp 113 KB

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