CodeViewDebug.cpp 99 KB

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