CodeViewDebug.cpp 114 KB

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