CodeViewDebug.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  1. //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
  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 "llvm/ADT/TinyPtrVector.h"
  15. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  16. #include "llvm/DebugInfo/CodeView/CodeView.h"
  17. #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
  18. #include "llvm/DebugInfo/CodeView/Line.h"
  19. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  20. #include "llvm/DebugInfo/CodeView/TypeDumper.h"
  21. #include "llvm/DebugInfo/CodeView/TypeIndex.h"
  22. #include "llvm/DebugInfo/CodeView/TypeRecord.h"
  23. #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
  24. #include "llvm/DebugInfo/MSF/ByteStream.h"
  25. #include "llvm/DebugInfo/MSF/StreamReader.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/MC/MCAsmInfo.h"
  28. #include "llvm/MC/MCExpr.h"
  29. #include "llvm/MC/MCSectionCOFF.h"
  30. #include "llvm/MC/MCSymbol.h"
  31. #include "llvm/Support/COFF.h"
  32. #include "llvm/Support/ScopedPrinter.h"
  33. #include "llvm/Target/TargetFrameLowering.h"
  34. #include "llvm/Target/TargetRegisterInfo.h"
  35. #include "llvm/Target/TargetSubtargetInfo.h"
  36. using namespace llvm;
  37. using namespace llvm::codeview;
  38. using namespace llvm::msf;
  39. CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
  40. : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
  41. // If module doesn't have named metadata anchors or COFF debug section
  42. // is not available, skip any debug info related stuff.
  43. if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
  44. !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
  45. Asm = nullptr;
  46. return;
  47. }
  48. // Tell MMI that we have debug info.
  49. MMI->setDebugInfoAvailability(true);
  50. }
  51. StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
  52. std::string &Filepath = FileToFilepathMap[File];
  53. if (!Filepath.empty())
  54. return Filepath;
  55. StringRef Dir = File->getDirectory(), Filename = File->getFilename();
  56. // Clang emits directory and relative filename info into the IR, but CodeView
  57. // operates on full paths. We could change Clang to emit full paths too, but
  58. // that would increase the IR size and probably not needed for other users.
  59. // For now, just concatenate and canonicalize the path here.
  60. if (Filename.find(':') == 1)
  61. Filepath = Filename;
  62. else
  63. Filepath = (Dir + "\\" + Filename).str();
  64. // Canonicalize the path. We have to do it textually because we may no longer
  65. // have access the file in the filesystem.
  66. // First, replace all slashes with backslashes.
  67. std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
  68. // Remove all "\.\" with "\".
  69. size_t Cursor = 0;
  70. while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
  71. Filepath.erase(Cursor, 2);
  72. // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
  73. // path should be well-formatted, e.g. start with a drive letter, etc.
  74. Cursor = 0;
  75. while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
  76. // Something's wrong if the path starts with "\..\", abort.
  77. if (Cursor == 0)
  78. break;
  79. size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
  80. if (PrevSlash == std::string::npos)
  81. // Something's wrong, abort.
  82. break;
  83. Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
  84. // The next ".." might be following the one we've just erased.
  85. Cursor = PrevSlash;
  86. }
  87. // Remove all duplicate backslashes.
  88. Cursor = 0;
  89. while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
  90. Filepath.erase(Cursor, 1);
  91. return Filepath;
  92. }
  93. unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
  94. unsigned NextId = FileIdMap.size() + 1;
  95. auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
  96. if (Insertion.second) {
  97. // We have to compute the full filepath and emit a .cv_file directive.
  98. StringRef FullPath = getFullFilepath(F);
  99. bool Success = OS.EmitCVFileDirective(NextId, FullPath);
  100. (void)Success;
  101. assert(Success && ".cv_file directive failed");
  102. }
  103. return Insertion.first->second;
  104. }
  105. CodeViewDebug::InlineSite &
  106. CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
  107. const DISubprogram *Inlinee) {
  108. auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
  109. InlineSite *Site = &SiteInsertion.first->second;
  110. if (SiteInsertion.second) {
  111. Site->SiteFuncId = NextFuncId++;
  112. Site->Inlinee = Inlinee;
  113. InlinedSubprograms.insert(Inlinee);
  114. getFuncIdForSubprogram(Inlinee);
  115. }
  116. return *Site;
  117. }
  118. static StringRef getPrettyScopeName(const DIScope *Scope) {
  119. StringRef ScopeName = Scope->getName();
  120. if (!ScopeName.empty())
  121. return ScopeName;
  122. switch (Scope->getTag()) {
  123. case dwarf::DW_TAG_enumeration_type:
  124. case dwarf::DW_TAG_class_type:
  125. case dwarf::DW_TAG_structure_type:
  126. case dwarf::DW_TAG_union_type:
  127. return "<unnamed-tag>";
  128. case dwarf::DW_TAG_namespace:
  129. return "`anonymous namespace'";
  130. }
  131. return StringRef();
  132. }
  133. static const DISubprogram *getQualifiedNameComponents(
  134. const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
  135. const DISubprogram *ClosestSubprogram = nullptr;
  136. while (Scope != nullptr) {
  137. if (ClosestSubprogram == nullptr)
  138. ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
  139. StringRef ScopeName = getPrettyScopeName(Scope);
  140. if (!ScopeName.empty())
  141. QualifiedNameComponents.push_back(ScopeName);
  142. Scope = Scope->getScope().resolve();
  143. }
  144. return ClosestSubprogram;
  145. }
  146. static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
  147. StringRef TypeName) {
  148. std::string FullyQualifiedName;
  149. for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
  150. FullyQualifiedName.append(QualifiedNameComponent);
  151. FullyQualifiedName.append("::");
  152. }
  153. FullyQualifiedName.append(TypeName);
  154. return FullyQualifiedName;
  155. }
  156. static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
  157. SmallVector<StringRef, 5> QualifiedNameComponents;
  158. getQualifiedNameComponents(Scope, QualifiedNameComponents);
  159. return getQualifiedName(QualifiedNameComponents, Name);
  160. }
  161. struct CodeViewDebug::TypeLoweringScope {
  162. TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
  163. ~TypeLoweringScope() {
  164. // Don't decrement TypeEmissionLevel until after emitting deferred types, so
  165. // inner TypeLoweringScopes don't attempt to emit deferred types.
  166. if (CVD.TypeEmissionLevel == 1)
  167. CVD.emitDeferredCompleteTypes();
  168. --CVD.TypeEmissionLevel;
  169. }
  170. CodeViewDebug &CVD;
  171. };
  172. static std::string getFullyQualifiedName(const DIScope *Ty) {
  173. const DIScope *Scope = Ty->getScope().resolve();
  174. return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
  175. }
  176. TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
  177. // No scope means global scope and that uses the zero index.
  178. if (!Scope || isa<DIFile>(Scope))
  179. return TypeIndex();
  180. assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
  181. // Check if we've already translated this scope.
  182. auto I = TypeIndices.find({Scope, nullptr});
  183. if (I != TypeIndices.end())
  184. return I->second;
  185. // Build the fully qualified name of the scope.
  186. std::string ScopeName = getFullyQualifiedName(Scope);
  187. TypeIndex TI =
  188. TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
  189. return recordTypeIndexForDINode(Scope, TI);
  190. }
  191. TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
  192. assert(SP);
  193. // Check if we've already translated this subprogram.
  194. auto I = TypeIndices.find({SP, nullptr});
  195. if (I != TypeIndices.end())
  196. return I->second;
  197. // The display name includes function template arguments. Drop them to match
  198. // MSVC.
  199. StringRef DisplayName = SP->getDisplayName().split('<').first;
  200. const DIScope *Scope = SP->getScope().resolve();
  201. TypeIndex TI;
  202. if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
  203. // If the scope is a DICompositeType, then this must be a method. Member
  204. // function types take some special handling, and require access to the
  205. // subprogram.
  206. TypeIndex ClassType = getTypeIndex(Class);
  207. MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
  208. DisplayName);
  209. TI = TypeTable.writeKnownType(MFuncId);
  210. } else {
  211. // Otherwise, this must be a free function.
  212. TypeIndex ParentScope = getScopeIndex(Scope);
  213. FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
  214. TI = TypeTable.writeKnownType(FuncId);
  215. }
  216. return recordTypeIndexForDINode(SP, TI);
  217. }
  218. TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
  219. const DICompositeType *Class) {
  220. // Always use the method declaration as the key for the function type. The
  221. // method declaration contains the this adjustment.
  222. if (SP->getDeclaration())
  223. SP = SP->getDeclaration();
  224. assert(!SP->getDeclaration() && "should use declaration as key");
  225. // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
  226. // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
  227. auto I = TypeIndices.find({SP, Class});
  228. if (I != TypeIndices.end())
  229. return I->second;
  230. // Make sure complete type info for the class is emitted *after* the member
  231. // function type, as the complete class type is likely to reference this
  232. // member function type.
  233. TypeLoweringScope S(*this);
  234. TypeIndex TI =
  235. lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
  236. return recordTypeIndexForDINode(SP, TI, Class);
  237. }
  238. TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
  239. TypeIndex TI,
  240. const DIType *ClassTy) {
  241. auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
  242. (void)InsertResult;
  243. assert(InsertResult.second && "DINode was already assigned a type index");
  244. return TI;
  245. }
  246. unsigned CodeViewDebug::getPointerSizeInBytes() {
  247. return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
  248. }
  249. void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
  250. const DILocation *InlinedAt) {
  251. if (InlinedAt) {
  252. // This variable was inlined. Associate it with the InlineSite.
  253. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
  254. InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
  255. Site.InlinedLocals.emplace_back(Var);
  256. } else {
  257. // This variable goes in the main ProcSym.
  258. CurFn->Locals.emplace_back(Var);
  259. }
  260. }
  261. static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
  262. const DILocation *Loc) {
  263. auto B = Locs.begin(), E = Locs.end();
  264. if (std::find(B, E, Loc) == E)
  265. Locs.push_back(Loc);
  266. }
  267. void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
  268. const MachineFunction *MF) {
  269. // Skip this instruction if it has the same location as the previous one.
  270. if (DL == CurFn->LastLoc)
  271. return;
  272. const DIScope *Scope = DL.get()->getScope();
  273. if (!Scope)
  274. return;
  275. // Skip this line if it is longer than the maximum we can record.
  276. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
  277. if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
  278. LI.isNeverStepInto())
  279. return;
  280. ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
  281. if (CI.getStartColumn() != DL.getCol())
  282. return;
  283. if (!CurFn->HaveLineInfo)
  284. CurFn->HaveLineInfo = true;
  285. unsigned FileId = 0;
  286. if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
  287. FileId = CurFn->LastFileId;
  288. else
  289. FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
  290. CurFn->LastLoc = DL;
  291. unsigned FuncId = CurFn->FuncId;
  292. if (const DILocation *SiteLoc = DL->getInlinedAt()) {
  293. const DILocation *Loc = DL.get();
  294. // If this location was actually inlined from somewhere else, give it the ID
  295. // of the inline call site.
  296. FuncId =
  297. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
  298. // Ensure we have links in the tree of inline call sites.
  299. bool FirstLoc = true;
  300. while ((SiteLoc = Loc->getInlinedAt())) {
  301. InlineSite &Site =
  302. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
  303. if (!FirstLoc)
  304. addLocIfNotPresent(Site.ChildSites, Loc);
  305. FirstLoc = false;
  306. Loc = SiteLoc;
  307. }
  308. addLocIfNotPresent(CurFn->ChildSites, Loc);
  309. }
  310. OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
  311. /*PrologueEnd=*/false,
  312. /*IsStmt=*/false, DL->getFilename());
  313. }
  314. void CodeViewDebug::emitCodeViewMagicVersion() {
  315. OS.EmitValueToAlignment(4);
  316. OS.AddComment("Debug section magic");
  317. OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
  318. }
  319. void CodeViewDebug::endModule() {
  320. if (!Asm || !MMI->hasDebugInfo())
  321. return;
  322. assert(Asm != nullptr);
  323. // The COFF .debug$S section consists of several subsections, each starting
  324. // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
  325. // of the payload followed by the payload itself. The subsections are 4-byte
  326. // aligned.
  327. // Use the generic .debug$S section, and make a subsection for all the inlined
  328. // subprograms.
  329. switchToDebugSectionForSymbol(nullptr);
  330. emitInlineeLinesSubsection();
  331. // Emit per-function debug information.
  332. for (auto &P : FnDebugInfo)
  333. if (!P.first->isDeclarationForLinker())
  334. emitDebugInfoForFunction(P.first, P.second);
  335. // Emit global variable debug information.
  336. setCurrentSubprogram(nullptr);
  337. emitDebugInfoForGlobals();
  338. // Emit retained types.
  339. emitDebugInfoForRetainedTypes();
  340. // Switch back to the generic .debug$S section after potentially processing
  341. // comdat symbol sections.
  342. switchToDebugSectionForSymbol(nullptr);
  343. // Emit UDT records for any types used by global variables.
  344. if (!GlobalUDTs.empty()) {
  345. MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
  346. emitDebugInfoForUDTs(GlobalUDTs);
  347. endCVSubsection(SymbolsEnd);
  348. }
  349. // This subsection holds a file index to offset in string table table.
  350. OS.AddComment("File index to string table offset subsection");
  351. OS.EmitCVFileChecksumsDirective();
  352. // This subsection holds the string table.
  353. OS.AddComment("String table");
  354. OS.EmitCVStringTableDirective();
  355. // Emit type information last, so that any types we translate while emitting
  356. // function info are included.
  357. emitTypeInformation();
  358. clear();
  359. }
  360. static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
  361. // Microsoft's linker seems to have trouble with symbol names longer than
  362. // 0xffd8 bytes.
  363. S = S.substr(0, 0xffd8);
  364. SmallString<32> NullTerminatedString(S);
  365. NullTerminatedString.push_back('\0');
  366. OS.EmitBytes(NullTerminatedString);
  367. }
  368. void CodeViewDebug::emitTypeInformation() {
  369. // Do nothing if we have no debug info or if no non-trivial types were emitted
  370. // to TypeTable during codegen.
  371. NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  372. if (!CU_Nodes)
  373. return;
  374. if (TypeTable.empty())
  375. return;
  376. // Start the .debug$T section with 0x4.
  377. OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
  378. emitCodeViewMagicVersion();
  379. SmallString<8> CommentPrefix;
  380. if (OS.isVerboseAsm()) {
  381. CommentPrefix += '\t';
  382. CommentPrefix += Asm->MAI->getCommentString();
  383. CommentPrefix += ' ';
  384. }
  385. CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
  386. TypeTable.ForEachRecord(
  387. [&](TypeIndex Index, StringRef Record) {
  388. if (OS.isVerboseAsm()) {
  389. // Emit a block comment describing the type record for readability.
  390. SmallString<512> CommentBlock;
  391. raw_svector_ostream CommentOS(CommentBlock);
  392. ScopedPrinter SP(CommentOS);
  393. SP.setPrefix(CommentPrefix);
  394. CVTD.setPrinter(&SP);
  395. Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
  396. if (E) {
  397. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  398. llvm_unreachable("produced malformed type record");
  399. }
  400. // emitRawComment will insert its own tab and comment string before
  401. // the first line, so strip off our first one. It also prints its own
  402. // newline.
  403. OS.emitRawComment(
  404. CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
  405. } else {
  406. #ifndef NDEBUG
  407. // Assert that the type data is valid even if we aren't dumping
  408. // comments. The MSVC linker doesn't do much type record validation,
  409. // so the first link of an invalid type record can succeed while
  410. // subsequent links will fail with LNK1285.
  411. ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
  412. CVTypeArray Types;
  413. StreamReader Reader(Stream);
  414. Error E = Reader.readArray(Types, Reader.getLength());
  415. if (!E) {
  416. TypeVisitorCallbacks C;
  417. E = CVTypeVisitor(C).visitTypeStream(Types);
  418. }
  419. if (E) {
  420. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  421. llvm_unreachable("produced malformed type record");
  422. }
  423. #endif
  424. }
  425. OS.EmitBinaryData(Record);
  426. });
  427. }
  428. void CodeViewDebug::emitInlineeLinesSubsection() {
  429. if (InlinedSubprograms.empty())
  430. return;
  431. OS.AddComment("Inlinee lines subsection");
  432. MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
  433. // We don't provide any extra file info.
  434. // FIXME: Find out if debuggers use this info.
  435. OS.AddComment("Inlinee lines signature");
  436. OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
  437. for (const DISubprogram *SP : InlinedSubprograms) {
  438. assert(TypeIndices.count({SP, nullptr}));
  439. TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
  440. OS.AddBlankLine();
  441. unsigned FileId = maybeRecordFile(SP->getFile());
  442. OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
  443. SP->getFilename() + Twine(':') + Twine(SP->getLine()));
  444. OS.AddBlankLine();
  445. // The filechecksum table uses 8 byte entries for now, and file ids start at
  446. // 1.
  447. unsigned FileOffset = (FileId - 1) * 8;
  448. OS.AddComment("Type index of inlined function");
  449. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  450. OS.AddComment("Offset into filechecksum table");
  451. OS.EmitIntValue(FileOffset, 4);
  452. OS.AddComment("Starting line number");
  453. OS.EmitIntValue(SP->getLine(), 4);
  454. }
  455. endCVSubsection(InlineEnd);
  456. }
  457. void CodeViewDebug::collectInlineSiteChildren(
  458. SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
  459. const InlineSite &Site) {
  460. for (const DILocation *ChildSiteLoc : Site.ChildSites) {
  461. auto I = FI.InlineSites.find(ChildSiteLoc);
  462. const InlineSite &ChildSite = I->second;
  463. Children.push_back(ChildSite.SiteFuncId);
  464. collectInlineSiteChildren(Children, FI, ChildSite);
  465. }
  466. }
  467. void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
  468. const DILocation *InlinedAt,
  469. const InlineSite &Site) {
  470. MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
  471. *InlineEnd = MMI->getContext().createTempSymbol();
  472. assert(TypeIndices.count({Site.Inlinee, nullptr}));
  473. TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
  474. // SymbolRecord
  475. OS.AddComment("Record length");
  476. OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
  477. OS.EmitLabel(InlineBegin);
  478. OS.AddComment("Record kind: S_INLINESITE");
  479. OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
  480. OS.AddComment("PtrParent");
  481. OS.EmitIntValue(0, 4);
  482. OS.AddComment("PtrEnd");
  483. OS.EmitIntValue(0, 4);
  484. OS.AddComment("Inlinee type index");
  485. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  486. unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
  487. unsigned StartLineNum = Site.Inlinee->getLine();
  488. SmallVector<unsigned, 3> SecondaryFuncIds;
  489. collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
  490. OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
  491. FI.Begin, FI.End, SecondaryFuncIds);
  492. OS.EmitLabel(InlineEnd);
  493. emitLocalVariableList(Site.InlinedLocals);
  494. // Recurse on child inlined call sites before closing the scope.
  495. for (const DILocation *ChildSite : Site.ChildSites) {
  496. auto I = FI.InlineSites.find(ChildSite);
  497. assert(I != FI.InlineSites.end() &&
  498. "child site not in function inline site map");
  499. emitInlinedCallSite(FI, ChildSite, I->second);
  500. }
  501. // Close the scope.
  502. OS.AddComment("Record length");
  503. OS.EmitIntValue(2, 2); // RecordLength
  504. OS.AddComment("Record kind: S_INLINESITE_END");
  505. OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
  506. }
  507. void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
  508. // If we have a symbol, it may be in a section that is COMDAT. If so, find the
  509. // comdat key. A section may be comdat because of -ffunction-sections or
  510. // because it is comdat in the IR.
  511. MCSectionCOFF *GVSec =
  512. GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
  513. const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
  514. MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
  515. Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
  516. DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
  517. OS.SwitchSection(DebugSec);
  518. // Emit the magic version number if this is the first time we've switched to
  519. // this section.
  520. if (ComdatDebugSections.insert(DebugSec).second)
  521. emitCodeViewMagicVersion();
  522. }
  523. void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
  524. FunctionInfo &FI) {
  525. // For each function there is a separate subsection
  526. // which holds the PC to file:line table.
  527. const MCSymbol *Fn = Asm->getSymbol(GV);
  528. assert(Fn);
  529. // Switch to the to a comdat section, if appropriate.
  530. switchToDebugSectionForSymbol(Fn);
  531. std::string FuncName;
  532. auto *SP = GV->getSubprogram();
  533. assert(SP);
  534. setCurrentSubprogram(SP);
  535. // If we have a display name, build the fully qualified name by walking the
  536. // chain of scopes.
  537. if (!SP->getDisplayName().empty())
  538. FuncName =
  539. getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
  540. // If our DISubprogram name is empty, use the mangled name.
  541. if (FuncName.empty())
  542. FuncName = GlobalValue::getRealLinkageName(GV->getName());
  543. // Emit a symbol subsection, required by VS2012+ to find function boundaries.
  544. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  545. MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
  546. {
  547. MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
  548. *ProcRecordEnd = MMI->getContext().createTempSymbol();
  549. OS.AddComment("Record length");
  550. OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
  551. OS.EmitLabel(ProcRecordBegin);
  552. if (GV->hasLocalLinkage()) {
  553. OS.AddComment("Record kind: S_LPROC32_ID");
  554. OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
  555. } else {
  556. OS.AddComment("Record kind: S_GPROC32_ID");
  557. OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
  558. }
  559. // These fields are filled in by tools like CVPACK which run after the fact.
  560. OS.AddComment("PtrParent");
  561. OS.EmitIntValue(0, 4);
  562. OS.AddComment("PtrEnd");
  563. OS.EmitIntValue(0, 4);
  564. OS.AddComment("PtrNext");
  565. OS.EmitIntValue(0, 4);
  566. // This is the important bit that tells the debugger where the function
  567. // code is located and what's its size:
  568. OS.AddComment("Code size");
  569. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
  570. OS.AddComment("Offset after prologue");
  571. OS.EmitIntValue(0, 4);
  572. OS.AddComment("Offset before epilogue");
  573. OS.EmitIntValue(0, 4);
  574. OS.AddComment("Function type index");
  575. OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
  576. OS.AddComment("Function section relative address");
  577. OS.EmitCOFFSecRel32(Fn);
  578. OS.AddComment("Function section index");
  579. OS.EmitCOFFSectionIndex(Fn);
  580. OS.AddComment("Flags");
  581. OS.EmitIntValue(0, 1);
  582. // Emit the function display name as a null-terminated string.
  583. OS.AddComment("Function name");
  584. // Truncate the name so we won't overflow the record length field.
  585. emitNullTerminatedSymbolName(OS, FuncName);
  586. OS.EmitLabel(ProcRecordEnd);
  587. emitLocalVariableList(FI.Locals);
  588. // Emit inlined call site information. Only emit functions inlined directly
  589. // into the parent function. We'll emit the other sites recursively as part
  590. // of their parent inline site.
  591. for (const DILocation *InlinedAt : FI.ChildSites) {
  592. auto I = FI.InlineSites.find(InlinedAt);
  593. assert(I != FI.InlineSites.end() &&
  594. "child site not in function inline site map");
  595. emitInlinedCallSite(FI, InlinedAt, I->second);
  596. }
  597. if (SP != nullptr)
  598. emitDebugInfoForUDTs(LocalUDTs);
  599. // We're done with this function.
  600. OS.AddComment("Record length");
  601. OS.EmitIntValue(0x0002, 2);
  602. OS.AddComment("Record kind: S_PROC_ID_END");
  603. OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
  604. }
  605. endCVSubsection(SymbolsEnd);
  606. // We have an assembler directive that takes care of the whole line table.
  607. OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
  608. }
  609. CodeViewDebug::LocalVarDefRange
  610. CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
  611. LocalVarDefRange DR;
  612. DR.InMemory = -1;
  613. DR.DataOffset = Offset;
  614. assert(DR.DataOffset == Offset && "truncation");
  615. DR.StructOffset = 0;
  616. DR.CVRegister = CVRegister;
  617. return DR;
  618. }
  619. CodeViewDebug::LocalVarDefRange
  620. CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
  621. LocalVarDefRange DR;
  622. DR.InMemory = 0;
  623. DR.DataOffset = 0;
  624. DR.StructOffset = 0;
  625. DR.CVRegister = CVRegister;
  626. return DR;
  627. }
  628. void CodeViewDebug::collectVariableInfoFromMMITable(
  629. DenseSet<InlinedVariable> &Processed) {
  630. const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
  631. const TargetFrameLowering *TFI = TSI.getFrameLowering();
  632. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  633. for (const MachineModuleInfo::VariableDbgInfo &VI :
  634. MMI->getVariableDbgInfo()) {
  635. if (!VI.Var)
  636. continue;
  637. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  638. "Expected inlined-at fields to agree");
  639. Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
  640. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  641. // If variable scope is not found then skip this variable.
  642. if (!Scope)
  643. continue;
  644. // Get the frame register used and the offset.
  645. unsigned FrameReg = 0;
  646. int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
  647. uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
  648. // Calculate the label ranges.
  649. LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
  650. for (const InsnRange &Range : Scope->getRanges()) {
  651. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  652. const MCSymbol *End = getLabelAfterInsn(Range.second);
  653. End = End ? End : Asm->getFunctionEnd();
  654. DefRange.Ranges.emplace_back(Begin, End);
  655. }
  656. LocalVariable Var;
  657. Var.DIVar = VI.Var;
  658. Var.DefRanges.emplace_back(std::move(DefRange));
  659. recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
  660. }
  661. }
  662. void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
  663. DenseSet<InlinedVariable> Processed;
  664. // Grab the variable info that was squirreled away in the MMI side-table.
  665. collectVariableInfoFromMMITable(Processed);
  666. const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  667. for (const auto &I : DbgValues) {
  668. InlinedVariable IV = I.first;
  669. if (Processed.count(IV))
  670. continue;
  671. const DILocalVariable *DIVar = IV.first;
  672. const DILocation *InlinedAt = IV.second;
  673. // Instruction ranges, specifying where IV is accessible.
  674. const auto &Ranges = I.second;
  675. LexicalScope *Scope = nullptr;
  676. if (InlinedAt)
  677. Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
  678. else
  679. Scope = LScopes.findLexicalScope(DIVar->getScope());
  680. // If variable scope is not found then skip this variable.
  681. if (!Scope)
  682. continue;
  683. LocalVariable Var;
  684. Var.DIVar = DIVar;
  685. // Calculate the definition ranges.
  686. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  687. const InsnRange &Range = *I;
  688. const MachineInstr *DVInst = Range.first;
  689. assert(DVInst->isDebugValue() && "Invalid History entry");
  690. const DIExpression *DIExpr = DVInst->getDebugExpression();
  691. // Bail if there is a complex DWARF expression for now.
  692. if (DIExpr && DIExpr->getNumElements() > 0)
  693. continue;
  694. // Bail if operand 0 is not a valid register. This means the variable is a
  695. // simple constant, or is described by a complex expression.
  696. // FIXME: Find a way to represent constant variables, since they are
  697. // relatively common.
  698. unsigned Reg =
  699. DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
  700. if (Reg == 0)
  701. continue;
  702. // Handle the two cases we can handle: indirect in memory and in register.
  703. bool IsIndirect = DVInst->getOperand(1).isImm();
  704. unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
  705. {
  706. LocalVarDefRange DefRange;
  707. if (IsIndirect) {
  708. int64_t Offset = DVInst->getOperand(1).getImm();
  709. DefRange = createDefRangeMem(CVReg, Offset);
  710. } else {
  711. DefRange = createDefRangeReg(CVReg);
  712. }
  713. if (Var.DefRanges.empty() ||
  714. Var.DefRanges.back().isDifferentLocation(DefRange)) {
  715. Var.DefRanges.emplace_back(std::move(DefRange));
  716. }
  717. }
  718. // Compute the label range.
  719. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  720. const MCSymbol *End = getLabelAfterInsn(Range.second);
  721. if (!End) {
  722. if (std::next(I) != E)
  723. End = getLabelBeforeInsn(std::next(I)->first);
  724. else
  725. End = Asm->getFunctionEnd();
  726. }
  727. // If the last range end is our begin, just extend the last range.
  728. // Otherwise make a new range.
  729. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
  730. Var.DefRanges.back().Ranges;
  731. if (!Ranges.empty() && Ranges.back().second == Begin)
  732. Ranges.back().second = End;
  733. else
  734. Ranges.emplace_back(Begin, End);
  735. // FIXME: Do more range combining.
  736. }
  737. recordLocalVariable(std::move(Var), InlinedAt);
  738. }
  739. }
  740. void CodeViewDebug::beginFunction(const MachineFunction *MF) {
  741. assert(!CurFn && "Can't process two functions at once!");
  742. if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
  743. return;
  744. DebugHandlerBase::beginFunction(MF);
  745. const Function *GV = MF->getFunction();
  746. assert(FnDebugInfo.count(GV) == false);
  747. CurFn = &FnDebugInfo[GV];
  748. CurFn->FuncId = NextFuncId++;
  749. CurFn->Begin = Asm->getFunctionBegin();
  750. // Find the end of the function prolog. First known non-DBG_VALUE and
  751. // non-frame setup location marks the beginning of the function body.
  752. // FIXME: is there a simpler a way to do this? Can we just search
  753. // for the first instruction of the function, not the last of the prolog?
  754. DebugLoc PrologEndLoc;
  755. bool EmptyPrologue = true;
  756. for (const auto &MBB : *MF) {
  757. for (const auto &MI : MBB) {
  758. if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
  759. MI.getDebugLoc()) {
  760. PrologEndLoc = MI.getDebugLoc();
  761. break;
  762. } else if (!MI.isDebugValue()) {
  763. EmptyPrologue = false;
  764. }
  765. }
  766. }
  767. // Record beginning of function if we have a non-empty prologue.
  768. if (PrologEndLoc && !EmptyPrologue) {
  769. DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
  770. maybeRecordLocation(FnStartDL, MF);
  771. }
  772. }
  773. void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
  774. // Don't record empty UDTs.
  775. if (Ty->getName().empty())
  776. return;
  777. SmallVector<StringRef, 5> QualifiedNameComponents;
  778. const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
  779. Ty->getScope().resolve(), QualifiedNameComponents);
  780. std::string FullyQualifiedName =
  781. getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
  782. if (ClosestSubprogram == nullptr)
  783. GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
  784. else if (ClosestSubprogram == CurrentSubprogram)
  785. LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
  786. // TODO: What if the ClosestSubprogram is neither null or the current
  787. // subprogram? Currently, the UDT just gets dropped on the floor.
  788. //
  789. // The current behavior is not desirable. To get maximal fidelity, we would
  790. // need to perform all type translation before beginning emission of .debug$S
  791. // and then make LocalUDTs a member of FunctionInfo
  792. }
  793. TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
  794. // Generic dispatch for lowering an unknown type.
  795. switch (Ty->getTag()) {
  796. case dwarf::DW_TAG_array_type:
  797. return lowerTypeArray(cast<DICompositeType>(Ty));
  798. case dwarf::DW_TAG_typedef:
  799. return lowerTypeAlias(cast<DIDerivedType>(Ty));
  800. case dwarf::DW_TAG_base_type:
  801. return lowerTypeBasic(cast<DIBasicType>(Ty));
  802. case dwarf::DW_TAG_pointer_type:
  803. if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
  804. return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
  805. LLVM_FALLTHROUGH;
  806. case dwarf::DW_TAG_reference_type:
  807. case dwarf::DW_TAG_rvalue_reference_type:
  808. return lowerTypePointer(cast<DIDerivedType>(Ty));
  809. case dwarf::DW_TAG_ptr_to_member_type:
  810. return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
  811. case dwarf::DW_TAG_const_type:
  812. case dwarf::DW_TAG_volatile_type:
  813. return lowerTypeModifier(cast<DIDerivedType>(Ty));
  814. case dwarf::DW_TAG_subroutine_type:
  815. if (ClassTy) {
  816. // The member function type of a member function pointer has no
  817. // ThisAdjustment.
  818. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
  819. /*ThisAdjustment=*/0);
  820. }
  821. return lowerTypeFunction(cast<DISubroutineType>(Ty));
  822. case dwarf::DW_TAG_enumeration_type:
  823. return lowerTypeEnum(cast<DICompositeType>(Ty));
  824. case dwarf::DW_TAG_class_type:
  825. case dwarf::DW_TAG_structure_type:
  826. return lowerTypeClass(cast<DICompositeType>(Ty));
  827. case dwarf::DW_TAG_union_type:
  828. return lowerTypeUnion(cast<DICompositeType>(Ty));
  829. default:
  830. // Use the null type index.
  831. return TypeIndex();
  832. }
  833. }
  834. TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
  835. DITypeRef UnderlyingTypeRef = Ty->getBaseType();
  836. TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
  837. StringRef TypeName = Ty->getName();
  838. addToUDTs(Ty, UnderlyingTypeIndex);
  839. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
  840. TypeName == "HRESULT")
  841. return TypeIndex(SimpleTypeKind::HResult);
  842. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
  843. TypeName == "wchar_t")
  844. return TypeIndex(SimpleTypeKind::WideCharacter);
  845. return UnderlyingTypeIndex;
  846. }
  847. TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
  848. DITypeRef ElementTypeRef = Ty->getBaseType();
  849. TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
  850. // IndexType is size_t, which depends on the bitness of the target.
  851. TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
  852. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  853. : TypeIndex(SimpleTypeKind::UInt32Long);
  854. uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
  855. bool UndefinedSubrange = false;
  856. // FIXME:
  857. // There is a bug in the front-end where an array of a structure, which was
  858. // declared as incomplete structure first, ends up not getting a size assigned
  859. // to it. (PR28303)
  860. // Example:
  861. // struct A(*p)[3];
  862. // struct A { int f; } a[3];
  863. //
  864. // This needs to be fixed in the front-end, but in the meantime we don't want
  865. // to trigger an assertion because of this.
  866. if (Ty->getSizeInBits() == 0) {
  867. UndefinedSubrange = true;
  868. }
  869. // Add subranges to array type.
  870. DINodeArray Elements = Ty->getElements();
  871. for (int i = Elements.size() - 1; i >= 0; --i) {
  872. const DINode *Element = Elements[i];
  873. assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
  874. const DISubrange *Subrange = cast<DISubrange>(Element);
  875. assert(Subrange->getLowerBound() == 0 &&
  876. "codeview doesn't support subranges with lower bounds");
  877. int64_t Count = Subrange->getCount();
  878. // Variable Length Array (VLA) has Count equal to '-1'.
  879. // Replace with Count '1', assume it is the minimum VLA length.
  880. // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
  881. if (Count == -1) {
  882. Count = 1;
  883. UndefinedSubrange = true;
  884. }
  885. StringRef Name = (i == 0) ? Ty->getName() : "";
  886. // Update the element size and element type index for subsequent subranges.
  887. ElementSize *= Count;
  888. ElementTypeIndex = TypeTable.writeKnownType(
  889. ArrayRecord(ElementTypeIndex, IndexType, ElementSize, Name));
  890. }
  891. (void)UndefinedSubrange;
  892. assert(UndefinedSubrange || ElementSize == (Ty->getSizeInBits() / 8));
  893. return ElementTypeIndex;
  894. }
  895. TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
  896. TypeIndex Index;
  897. dwarf::TypeKind Kind;
  898. uint32_t ByteSize;
  899. Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
  900. ByteSize = Ty->getSizeInBits() / 8;
  901. SimpleTypeKind STK = SimpleTypeKind::None;
  902. switch (Kind) {
  903. case dwarf::DW_ATE_address:
  904. // FIXME: Translate
  905. break;
  906. case dwarf::DW_ATE_boolean:
  907. switch (ByteSize) {
  908. case 1: STK = SimpleTypeKind::Boolean8; break;
  909. case 2: STK = SimpleTypeKind::Boolean16; break;
  910. case 4: STK = SimpleTypeKind::Boolean32; break;
  911. case 8: STK = SimpleTypeKind::Boolean64; break;
  912. case 16: STK = SimpleTypeKind::Boolean128; break;
  913. }
  914. break;
  915. case dwarf::DW_ATE_complex_float:
  916. switch (ByteSize) {
  917. case 2: STK = SimpleTypeKind::Complex16; break;
  918. case 4: STK = SimpleTypeKind::Complex32; break;
  919. case 8: STK = SimpleTypeKind::Complex64; break;
  920. case 10: STK = SimpleTypeKind::Complex80; break;
  921. case 16: STK = SimpleTypeKind::Complex128; break;
  922. }
  923. break;
  924. case dwarf::DW_ATE_float:
  925. switch (ByteSize) {
  926. case 2: STK = SimpleTypeKind::Float16; break;
  927. case 4: STK = SimpleTypeKind::Float32; break;
  928. case 6: STK = SimpleTypeKind::Float48; break;
  929. case 8: STK = SimpleTypeKind::Float64; break;
  930. case 10: STK = SimpleTypeKind::Float80; break;
  931. case 16: STK = SimpleTypeKind::Float128; break;
  932. }
  933. break;
  934. case dwarf::DW_ATE_signed:
  935. switch (ByteSize) {
  936. case 1: STK = SimpleTypeKind::SByte; break;
  937. case 2: STK = SimpleTypeKind::Int16Short; break;
  938. case 4: STK = SimpleTypeKind::Int32; break;
  939. case 8: STK = SimpleTypeKind::Int64Quad; break;
  940. case 16: STK = SimpleTypeKind::Int128Oct; break;
  941. }
  942. break;
  943. case dwarf::DW_ATE_unsigned:
  944. switch (ByteSize) {
  945. case 1: STK = SimpleTypeKind::Byte; break;
  946. case 2: STK = SimpleTypeKind::UInt16Short; break;
  947. case 4: STK = SimpleTypeKind::UInt32; break;
  948. case 8: STK = SimpleTypeKind::UInt64Quad; break;
  949. case 16: STK = SimpleTypeKind::UInt128Oct; break;
  950. }
  951. break;
  952. case dwarf::DW_ATE_UTF:
  953. switch (ByteSize) {
  954. case 2: STK = SimpleTypeKind::Character16; break;
  955. case 4: STK = SimpleTypeKind::Character32; break;
  956. }
  957. break;
  958. case dwarf::DW_ATE_signed_char:
  959. if (ByteSize == 1)
  960. STK = SimpleTypeKind::SignedCharacter;
  961. break;
  962. case dwarf::DW_ATE_unsigned_char:
  963. if (ByteSize == 1)
  964. STK = SimpleTypeKind::UnsignedCharacter;
  965. break;
  966. default:
  967. break;
  968. }
  969. // Apply some fixups based on the source-level type name.
  970. if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
  971. STK = SimpleTypeKind::Int32Long;
  972. if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
  973. STK = SimpleTypeKind::UInt32Long;
  974. if (STK == SimpleTypeKind::UInt16Short &&
  975. (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
  976. STK = SimpleTypeKind::WideCharacter;
  977. if ((STK == SimpleTypeKind::SignedCharacter ||
  978. STK == SimpleTypeKind::UnsignedCharacter) &&
  979. Ty->getName() == "char")
  980. STK = SimpleTypeKind::NarrowCharacter;
  981. return TypeIndex(STK);
  982. }
  983. TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
  984. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
  985. // Pointers to simple types can use SimpleTypeMode, rather than having a
  986. // dedicated pointer type record.
  987. if (PointeeTI.isSimple() &&
  988. PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
  989. Ty->getTag() == dwarf::DW_TAG_pointer_type) {
  990. SimpleTypeMode Mode = Ty->getSizeInBits() == 64
  991. ? SimpleTypeMode::NearPointer64
  992. : SimpleTypeMode::NearPointer32;
  993. return TypeIndex(PointeeTI.getSimpleKind(), Mode);
  994. }
  995. PointerKind PK =
  996. Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
  997. PointerMode PM = PointerMode::Pointer;
  998. switch (Ty->getTag()) {
  999. default: llvm_unreachable("not a pointer tag type");
  1000. case dwarf::DW_TAG_pointer_type:
  1001. PM = PointerMode::Pointer;
  1002. break;
  1003. case dwarf::DW_TAG_reference_type:
  1004. PM = PointerMode::LValueReference;
  1005. break;
  1006. case dwarf::DW_TAG_rvalue_reference_type:
  1007. PM = PointerMode::RValueReference;
  1008. break;
  1009. }
  1010. // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
  1011. // 'this' pointer, but not normal contexts. Figure out what we're supposed to
  1012. // do.
  1013. PointerOptions PO = PointerOptions::None;
  1014. PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
  1015. return TypeTable.writeKnownType(PR);
  1016. }
  1017. static PointerToMemberRepresentation
  1018. translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
  1019. // SizeInBytes being zero generally implies that the member pointer type was
  1020. // incomplete, which can happen if it is part of a function prototype. In this
  1021. // case, use the unknown model instead of the general model.
  1022. if (IsPMF) {
  1023. switch (Flags & DINode::FlagPtrToMemberRep) {
  1024. case 0:
  1025. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1026. : PointerToMemberRepresentation::GeneralFunction;
  1027. case DINode::FlagSingleInheritance:
  1028. return PointerToMemberRepresentation::SingleInheritanceFunction;
  1029. case DINode::FlagMultipleInheritance:
  1030. return PointerToMemberRepresentation::MultipleInheritanceFunction;
  1031. case DINode::FlagVirtualInheritance:
  1032. return PointerToMemberRepresentation::VirtualInheritanceFunction;
  1033. }
  1034. } else {
  1035. switch (Flags & DINode::FlagPtrToMemberRep) {
  1036. case 0:
  1037. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1038. : PointerToMemberRepresentation::GeneralData;
  1039. case DINode::FlagSingleInheritance:
  1040. return PointerToMemberRepresentation::SingleInheritanceData;
  1041. case DINode::FlagMultipleInheritance:
  1042. return PointerToMemberRepresentation::MultipleInheritanceData;
  1043. case DINode::FlagVirtualInheritance:
  1044. return PointerToMemberRepresentation::VirtualInheritanceData;
  1045. }
  1046. }
  1047. llvm_unreachable("invalid ptr to member representation");
  1048. }
  1049. TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
  1050. assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
  1051. TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
  1052. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
  1053. PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
  1054. : PointerKind::Near32;
  1055. bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
  1056. PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
  1057. : PointerMode::PointerToDataMember;
  1058. PointerOptions PO = PointerOptions::None; // FIXME
  1059. assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
  1060. uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
  1061. MemberPointerInfo MPI(
  1062. ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
  1063. PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
  1064. return TypeTable.writeKnownType(PR);
  1065. }
  1066. /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
  1067. /// have a translation, use the NearC convention.
  1068. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
  1069. switch (DwarfCC) {
  1070. case dwarf::DW_CC_normal: return CallingConvention::NearC;
  1071. case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
  1072. case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
  1073. case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
  1074. case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
  1075. case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
  1076. }
  1077. return CallingConvention::NearC;
  1078. }
  1079. TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
  1080. ModifierOptions Mods = ModifierOptions::None;
  1081. bool IsModifier = true;
  1082. const DIType *BaseTy = Ty;
  1083. while (IsModifier && BaseTy) {
  1084. // FIXME: Need to add DWARF tag for __unaligned.
  1085. switch (BaseTy->getTag()) {
  1086. case dwarf::DW_TAG_const_type:
  1087. Mods |= ModifierOptions::Const;
  1088. break;
  1089. case dwarf::DW_TAG_volatile_type:
  1090. Mods |= ModifierOptions::Volatile;
  1091. break;
  1092. default:
  1093. IsModifier = false;
  1094. break;
  1095. }
  1096. if (IsModifier)
  1097. BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
  1098. }
  1099. TypeIndex ModifiedTI = getTypeIndex(BaseTy);
  1100. return TypeTable.writeKnownType(ModifierRecord(ModifiedTI, Mods));
  1101. }
  1102. TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
  1103. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1104. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1105. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1106. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1107. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1108. if (!ReturnAndArgTypeIndices.empty()) {
  1109. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1110. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1111. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1112. }
  1113. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1114. TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
  1115. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1116. ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
  1117. ArgTypeIndices.size(), ArgListIndex);
  1118. return TypeTable.writeKnownType(Procedure);
  1119. }
  1120. TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
  1121. const DIType *ClassTy,
  1122. int ThisAdjustment) {
  1123. // Lower the containing class type.
  1124. TypeIndex ClassType = getTypeIndex(ClassTy);
  1125. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1126. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1127. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1128. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1129. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1130. if (!ReturnAndArgTypeIndices.empty()) {
  1131. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1132. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1133. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1134. }
  1135. TypeIndex ThisTypeIndex = TypeIndex::Void();
  1136. if (!ArgTypeIndices.empty()) {
  1137. ThisTypeIndex = ArgTypeIndices.front();
  1138. ArgTypeIndices = ArgTypeIndices.drop_front();
  1139. }
  1140. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1141. TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
  1142. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1143. // TODO: Need to use the correct values for:
  1144. // FunctionOptions
  1145. // ThisPointerAdjustment.
  1146. TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
  1147. ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
  1148. ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
  1149. return TI;
  1150. }
  1151. TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
  1152. unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
  1153. SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
  1154. return TypeTable.writeKnownType(VFTableShapeRecord(Slots));
  1155. }
  1156. static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
  1157. switch (Flags & DINode::FlagAccessibility) {
  1158. case DINode::FlagPrivate: return MemberAccess::Private;
  1159. case DINode::FlagPublic: return MemberAccess::Public;
  1160. case DINode::FlagProtected: return MemberAccess::Protected;
  1161. case 0:
  1162. // If there was no explicit access control, provide the default for the tag.
  1163. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
  1164. : MemberAccess::Public;
  1165. }
  1166. llvm_unreachable("access flags are exclusive");
  1167. }
  1168. static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
  1169. if (SP->isArtificial())
  1170. return MethodOptions::CompilerGenerated;
  1171. // FIXME: Handle other MethodOptions.
  1172. return MethodOptions::None;
  1173. }
  1174. static MethodKind translateMethodKindFlags(const DISubprogram *SP,
  1175. bool Introduced) {
  1176. switch (SP->getVirtuality()) {
  1177. case dwarf::DW_VIRTUALITY_none:
  1178. break;
  1179. case dwarf::DW_VIRTUALITY_virtual:
  1180. return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
  1181. case dwarf::DW_VIRTUALITY_pure_virtual:
  1182. return Introduced ? MethodKind::PureIntroducingVirtual
  1183. : MethodKind::PureVirtual;
  1184. default:
  1185. llvm_unreachable("unhandled virtuality case");
  1186. }
  1187. // FIXME: Get Clang to mark DISubprogram as static and do something with it.
  1188. return MethodKind::Vanilla;
  1189. }
  1190. static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
  1191. switch (Ty->getTag()) {
  1192. case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
  1193. case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
  1194. }
  1195. llvm_unreachable("unexpected tag");
  1196. }
  1197. /// Return ClassOptions that should be present on both the forward declaration
  1198. /// and the defintion of a tag type.
  1199. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
  1200. ClassOptions CO = ClassOptions::None;
  1201. // MSVC always sets this flag, even for local types. Clang doesn't always
  1202. // appear to give every type a linkage name, which may be problematic for us.
  1203. // FIXME: Investigate the consequences of not following them here.
  1204. if (!Ty->getIdentifier().empty())
  1205. CO |= ClassOptions::HasUniqueName;
  1206. // Put the Nested flag on a type if it appears immediately inside a tag type.
  1207. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
  1208. // here. That flag is only set on definitions, and not forward declarations.
  1209. const DIScope *ImmediateScope = Ty->getScope().resolve();
  1210. if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
  1211. CO |= ClassOptions::Nested;
  1212. // Put the Scoped flag on function-local types.
  1213. for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
  1214. Scope = Scope->getScope().resolve()) {
  1215. if (isa<DISubprogram>(Scope)) {
  1216. CO |= ClassOptions::Scoped;
  1217. break;
  1218. }
  1219. }
  1220. return CO;
  1221. }
  1222. TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
  1223. ClassOptions CO = getCommonClassOptions(Ty);
  1224. TypeIndex FTI;
  1225. unsigned EnumeratorCount = 0;
  1226. if (Ty->isForwardDecl()) {
  1227. CO |= ClassOptions::ForwardReference;
  1228. } else {
  1229. FieldListRecordBuilder Fields;
  1230. for (const DINode *Element : Ty->getElements()) {
  1231. // We assume that the frontend provides all members in source declaration
  1232. // order, which is what MSVC does.
  1233. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
  1234. Fields.writeMemberType(EnumeratorRecord(
  1235. MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
  1236. Enumerator->getName()));
  1237. EnumeratorCount++;
  1238. }
  1239. }
  1240. FTI = TypeTable.writeFieldList(Fields);
  1241. }
  1242. std::string FullName = getFullyQualifiedName(Ty);
  1243. return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
  1244. Ty->getIdentifier(),
  1245. getTypeIndex(Ty->getBaseType())));
  1246. }
  1247. //===----------------------------------------------------------------------===//
  1248. // ClassInfo
  1249. //===----------------------------------------------------------------------===//
  1250. struct llvm::ClassInfo {
  1251. struct MemberInfo {
  1252. const DIDerivedType *MemberTypeNode;
  1253. uint64_t BaseOffset;
  1254. };
  1255. // [MemberInfo]
  1256. typedef std::vector<MemberInfo> MemberList;
  1257. typedef TinyPtrVector<const DISubprogram *> MethodsList;
  1258. // MethodName -> MethodsList
  1259. typedef MapVector<MDString *, MethodsList> MethodsMap;
  1260. /// Base classes.
  1261. std::vector<const DIDerivedType *> Inheritance;
  1262. /// Direct members.
  1263. MemberList Members;
  1264. // Direct overloaded methods gathered by name.
  1265. MethodsMap Methods;
  1266. TypeIndex VShapeTI;
  1267. std::vector<const DICompositeType *> NestedClasses;
  1268. };
  1269. void CodeViewDebug::clear() {
  1270. assert(CurFn == nullptr);
  1271. FileIdMap.clear();
  1272. FnDebugInfo.clear();
  1273. FileToFilepathMap.clear();
  1274. LocalUDTs.clear();
  1275. GlobalUDTs.clear();
  1276. TypeIndices.clear();
  1277. CompleteTypeIndices.clear();
  1278. }
  1279. void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
  1280. const DIDerivedType *DDTy) {
  1281. if (!DDTy->getName().empty()) {
  1282. Info.Members.push_back({DDTy, 0});
  1283. return;
  1284. }
  1285. // An unnamed member must represent a nested struct or union. Add all the
  1286. // indirect fields to the current record.
  1287. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
  1288. uint64_t Offset = DDTy->getOffsetInBits();
  1289. const DIType *Ty = DDTy->getBaseType().resolve();
  1290. const DICompositeType *DCTy = cast<DICompositeType>(Ty);
  1291. ClassInfo NestedInfo = collectClassInfo(DCTy);
  1292. for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
  1293. Info.Members.push_back(
  1294. {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
  1295. }
  1296. ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
  1297. ClassInfo Info;
  1298. // Add elements to structure type.
  1299. DINodeArray Elements = Ty->getElements();
  1300. for (auto *Element : Elements) {
  1301. // We assume that the frontend provides all members in source declaration
  1302. // order, which is what MSVC does.
  1303. if (!Element)
  1304. continue;
  1305. if (auto *SP = dyn_cast<DISubprogram>(Element)) {
  1306. Info.Methods[SP->getRawName()].push_back(SP);
  1307. } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  1308. if (DDTy->getTag() == dwarf::DW_TAG_member) {
  1309. collectMemberInfo(Info, DDTy);
  1310. } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
  1311. Info.Inheritance.push_back(DDTy);
  1312. } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
  1313. DDTy->getName() == "__vtbl_ptr_type") {
  1314. Info.VShapeTI = getTypeIndex(DDTy);
  1315. } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  1316. // Ignore friend members. It appears that MSVC emitted info about
  1317. // friends in the past, but modern versions do not.
  1318. }
  1319. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  1320. Info.NestedClasses.push_back(Composite);
  1321. }
  1322. // Skip other unrecognized kinds of elements.
  1323. }
  1324. return Info;
  1325. }
  1326. TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
  1327. // First, construct the forward decl. Don't look into Ty to compute the
  1328. // forward decl options, since it might not be available in all TUs.
  1329. TypeRecordKind Kind = getRecordKind(Ty);
  1330. ClassOptions CO =
  1331. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1332. std::string FullName = getFullyQualifiedName(Ty);
  1333. TypeIndex FwdDeclTI = TypeTable.writeKnownType(ClassRecord(
  1334. Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
  1335. TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
  1336. if (!Ty->isForwardDecl())
  1337. DeferredCompleteTypes.push_back(Ty);
  1338. return FwdDeclTI;
  1339. }
  1340. TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
  1341. // Construct the field list and complete type record.
  1342. TypeRecordKind Kind = getRecordKind(Ty);
  1343. ClassOptions CO = getCommonClassOptions(Ty);
  1344. TypeIndex FieldTI;
  1345. TypeIndex VShapeTI;
  1346. unsigned FieldCount;
  1347. bool ContainsNestedClass;
  1348. std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
  1349. lowerRecordFieldList(Ty);
  1350. if (ContainsNestedClass)
  1351. CO |= ClassOptions::ContainsNestedClass;
  1352. std::string FullName = getFullyQualifiedName(Ty);
  1353. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1354. TypeIndex ClassTI = TypeTable.writeKnownType(ClassRecord(
  1355. Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
  1356. TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
  1357. TypeTable.writeKnownType(UdtSourceLineRecord(
  1358. ClassTI, TypeTable.writeKnownType(StringIdRecord(
  1359. TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
  1360. Ty->getLine()));
  1361. addToUDTs(Ty, ClassTI);
  1362. return ClassTI;
  1363. }
  1364. TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
  1365. ClassOptions CO =
  1366. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1367. std::string FullName = getFullyQualifiedName(Ty);
  1368. TypeIndex FwdDeclTI = TypeTable.writeKnownType(UnionRecord(
  1369. 0, CO, HfaKind::None, TypeIndex(), 0, FullName, Ty->getIdentifier()));
  1370. if (!Ty->isForwardDecl())
  1371. DeferredCompleteTypes.push_back(Ty);
  1372. return FwdDeclTI;
  1373. }
  1374. TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
  1375. ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
  1376. TypeIndex FieldTI;
  1377. unsigned FieldCount;
  1378. bool ContainsNestedClass;
  1379. std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
  1380. lowerRecordFieldList(Ty);
  1381. if (ContainsNestedClass)
  1382. CO |= ClassOptions::ContainsNestedClass;
  1383. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1384. std::string FullName = getFullyQualifiedName(Ty);
  1385. TypeIndex UnionTI = TypeTable.writeKnownType(
  1386. UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
  1387. Ty->getIdentifier()));
  1388. TypeTable.writeKnownType(UdtSourceLineRecord(
  1389. UnionTI, TypeTable.writeKnownType(StringIdRecord(
  1390. TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
  1391. Ty->getLine()));
  1392. addToUDTs(Ty, UnionTI);
  1393. return UnionTI;
  1394. }
  1395. std::tuple<TypeIndex, TypeIndex, unsigned, bool>
  1396. CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
  1397. // Manually count members. MSVC appears to count everything that generates a
  1398. // field list record. Each individual overload in a method overload group
  1399. // contributes to this count, even though the overload group is a single field
  1400. // list record.
  1401. unsigned MemberCount = 0;
  1402. ClassInfo Info = collectClassInfo(Ty);
  1403. FieldListRecordBuilder Fields;
  1404. // Create base classes.
  1405. for (const DIDerivedType *I : Info.Inheritance) {
  1406. if (I->getFlags() & DINode::FlagVirtual) {
  1407. // Virtual base.
  1408. // FIXME: Emit VBPtrOffset when the frontend provides it.
  1409. unsigned VBPtrOffset = 0;
  1410. // FIXME: Despite the accessor name, the offset is really in bytes.
  1411. unsigned VBTableIndex = I->getOffsetInBits() / 4;
  1412. Fields.writeMemberType(VirtualBaseClassRecord(
  1413. translateAccessFlags(Ty->getTag(), I->getFlags()),
  1414. getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
  1415. VBTableIndex));
  1416. } else {
  1417. assert(I->getOffsetInBits() % 8 == 0 &&
  1418. "bases must be on byte boundaries");
  1419. Fields.writeMemberType(BaseClassRecord(
  1420. translateAccessFlags(Ty->getTag(), I->getFlags()),
  1421. getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
  1422. }
  1423. }
  1424. // Create members.
  1425. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
  1426. const DIDerivedType *Member = MemberInfo.MemberTypeNode;
  1427. TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
  1428. StringRef MemberName = Member->getName();
  1429. MemberAccess Access =
  1430. translateAccessFlags(Ty->getTag(), Member->getFlags());
  1431. if (Member->isStaticMember()) {
  1432. Fields.writeMemberType(
  1433. StaticDataMemberRecord(Access, MemberBaseType, MemberName));
  1434. MemberCount++;
  1435. continue;
  1436. }
  1437. // Virtual function pointer member.
  1438. if ((Member->getFlags() & DINode::FlagArtificial) &&
  1439. Member->getName().startswith("_vptr$")) {
  1440. Fields.writeMemberType(VFPtrRecord(getTypeIndex(Member->getBaseType())));
  1441. MemberCount++;
  1442. continue;
  1443. }
  1444. // Data member.
  1445. uint64_t MemberOffsetInBits =
  1446. Member->getOffsetInBits() + MemberInfo.BaseOffset;
  1447. if (Member->isBitField()) {
  1448. uint64_t StartBitOffset = MemberOffsetInBits;
  1449. if (const auto *CI =
  1450. dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
  1451. MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
  1452. }
  1453. StartBitOffset -= MemberOffsetInBits;
  1454. MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
  1455. MemberBaseType, Member->getSizeInBits(), StartBitOffset));
  1456. }
  1457. uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
  1458. Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
  1459. MemberOffsetInBytes, MemberName));
  1460. MemberCount++;
  1461. }
  1462. // Create methods
  1463. for (auto &MethodItr : Info.Methods) {
  1464. StringRef Name = MethodItr.first->getString();
  1465. std::vector<OneMethodRecord> Methods;
  1466. for (const DISubprogram *SP : MethodItr.second) {
  1467. TypeIndex MethodType = getMemberFunctionType(SP, Ty);
  1468. bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
  1469. unsigned VFTableOffset = -1;
  1470. if (Introduced)
  1471. VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
  1472. Methods.push_back(
  1473. OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
  1474. translateMethodOptionFlags(SP),
  1475. translateAccessFlags(Ty->getTag(), SP->getFlags()),
  1476. VFTableOffset, Name));
  1477. MemberCount++;
  1478. }
  1479. assert(Methods.size() > 0 && "Empty methods map entry");
  1480. if (Methods.size() == 1)
  1481. Fields.writeMemberType(Methods[0]);
  1482. else {
  1483. TypeIndex MethodList =
  1484. TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
  1485. Fields.writeMemberType(
  1486. OverloadedMethodRecord(Methods.size(), MethodList, Name));
  1487. }
  1488. }
  1489. // Create nested classes.
  1490. for (const DICompositeType *Nested : Info.NestedClasses) {
  1491. NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
  1492. Fields.writeMemberType(R);
  1493. MemberCount++;
  1494. }
  1495. TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
  1496. return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
  1497. !Info.NestedClasses.empty());
  1498. }
  1499. TypeIndex CodeViewDebug::getVBPTypeIndex() {
  1500. if (!VBPType.getIndex()) {
  1501. // Make a 'const int *' type.
  1502. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
  1503. TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
  1504. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1505. : PointerKind::Near32;
  1506. PointerMode PM = PointerMode::Pointer;
  1507. PointerOptions PO = PointerOptions::None;
  1508. PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
  1509. VBPType = TypeTable.writeKnownType(PR);
  1510. }
  1511. return VBPType;
  1512. }
  1513. TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
  1514. const DIType *Ty = TypeRef.resolve();
  1515. const DIType *ClassTy = ClassTyRef.resolve();
  1516. // The null DIType is the void type. Don't try to hash it.
  1517. if (!Ty)
  1518. return TypeIndex::Void();
  1519. // Check if we've already translated this type. Don't try to do a
  1520. // get-or-create style insertion that caches the hash lookup across the
  1521. // lowerType call. It will update the TypeIndices map.
  1522. auto I = TypeIndices.find({Ty, ClassTy});
  1523. if (I != TypeIndices.end())
  1524. return I->second;
  1525. TypeLoweringScope S(*this);
  1526. TypeIndex TI = lowerType(Ty, ClassTy);
  1527. return recordTypeIndexForDINode(Ty, TI, ClassTy);
  1528. }
  1529. TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
  1530. const DIType *Ty = TypeRef.resolve();
  1531. // The null DIType is the void type. Don't try to hash it.
  1532. if (!Ty)
  1533. return TypeIndex::Void();
  1534. // If this is a non-record type, the complete type index is the same as the
  1535. // normal type index. Just call getTypeIndex.
  1536. switch (Ty->getTag()) {
  1537. case dwarf::DW_TAG_class_type:
  1538. case dwarf::DW_TAG_structure_type:
  1539. case dwarf::DW_TAG_union_type:
  1540. break;
  1541. default:
  1542. return getTypeIndex(Ty);
  1543. }
  1544. // Check if we've already translated the complete record type. Lowering a
  1545. // complete type should never trigger lowering another complete type, so we
  1546. // can reuse the hash table lookup result.
  1547. const auto *CTy = cast<DICompositeType>(Ty);
  1548. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
  1549. if (!InsertResult.second)
  1550. return InsertResult.first->second;
  1551. TypeLoweringScope S(*this);
  1552. // Make sure the forward declaration is emitted first. It's unclear if this
  1553. // is necessary, but MSVC does it, and we should follow suit until we can show
  1554. // otherwise.
  1555. TypeIndex FwdDeclTI = getTypeIndex(CTy);
  1556. // Just use the forward decl if we don't have complete type info. This might
  1557. // happen if the frontend is using modules and expects the complete definition
  1558. // to be emitted elsewhere.
  1559. if (CTy->isForwardDecl())
  1560. return FwdDeclTI;
  1561. TypeIndex TI;
  1562. switch (CTy->getTag()) {
  1563. case dwarf::DW_TAG_class_type:
  1564. case dwarf::DW_TAG_structure_type:
  1565. TI = lowerCompleteTypeClass(CTy);
  1566. break;
  1567. case dwarf::DW_TAG_union_type:
  1568. TI = lowerCompleteTypeUnion(CTy);
  1569. break;
  1570. default:
  1571. llvm_unreachable("not a record");
  1572. }
  1573. InsertResult.first->second = TI;
  1574. return TI;
  1575. }
  1576. /// Emit all the deferred complete record types. Try to do this in FIFO order,
  1577. /// and do this until fixpoint, as each complete record type typically
  1578. /// references
  1579. /// many other record types.
  1580. void CodeViewDebug::emitDeferredCompleteTypes() {
  1581. SmallVector<const DICompositeType *, 4> TypesToEmit;
  1582. while (!DeferredCompleteTypes.empty()) {
  1583. std::swap(DeferredCompleteTypes, TypesToEmit);
  1584. for (const DICompositeType *RecordTy : TypesToEmit)
  1585. getCompleteTypeIndex(RecordTy);
  1586. TypesToEmit.clear();
  1587. }
  1588. }
  1589. void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
  1590. // Get the sorted list of parameters and emit them first.
  1591. SmallVector<const LocalVariable *, 6> Params;
  1592. for (const LocalVariable &L : Locals)
  1593. if (L.DIVar->isParameter())
  1594. Params.push_back(&L);
  1595. std::sort(Params.begin(), Params.end(),
  1596. [](const LocalVariable *L, const LocalVariable *R) {
  1597. return L->DIVar->getArg() < R->DIVar->getArg();
  1598. });
  1599. for (const LocalVariable *L : Params)
  1600. emitLocalVariable(*L);
  1601. // Next emit all non-parameters in the order that we found them.
  1602. for (const LocalVariable &L : Locals)
  1603. if (!L.DIVar->isParameter())
  1604. emitLocalVariable(L);
  1605. }
  1606. void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
  1607. // LocalSym record, see SymbolRecord.h for more info.
  1608. MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
  1609. *LocalEnd = MMI->getContext().createTempSymbol();
  1610. OS.AddComment("Record length");
  1611. OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
  1612. OS.EmitLabel(LocalBegin);
  1613. OS.AddComment("Record kind: S_LOCAL");
  1614. OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
  1615. LocalSymFlags Flags = LocalSymFlags::None;
  1616. if (Var.DIVar->isParameter())
  1617. Flags |= LocalSymFlags::IsParameter;
  1618. if (Var.DefRanges.empty())
  1619. Flags |= LocalSymFlags::IsOptimizedOut;
  1620. OS.AddComment("TypeIndex");
  1621. TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
  1622. OS.EmitIntValue(TI.getIndex(), 4);
  1623. OS.AddComment("Flags");
  1624. OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
  1625. // Truncate the name so we won't overflow the record length field.
  1626. emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
  1627. OS.EmitLabel(LocalEnd);
  1628. // Calculate the on disk prefix of the appropriate def range record. The
  1629. // records and on disk formats are described in SymbolRecords.h. BytePrefix
  1630. // should be big enough to hold all forms without memory allocation.
  1631. SmallString<20> BytePrefix;
  1632. for (const LocalVarDefRange &DefRange : Var.DefRanges) {
  1633. BytePrefix.clear();
  1634. // FIXME: Handle bitpieces.
  1635. if (DefRange.StructOffset != 0)
  1636. continue;
  1637. if (DefRange.InMemory) {
  1638. DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
  1639. 0, 0, ArrayRef<LocalVariableAddrGap>());
  1640. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
  1641. BytePrefix +=
  1642. StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
  1643. BytePrefix +=
  1644. StringRef(reinterpret_cast<const char *>(&Sym.Header),
  1645. sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
  1646. } else {
  1647. assert(DefRange.DataOffset == 0 && "unexpected offset into register");
  1648. // Unclear what matters here.
  1649. DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
  1650. ArrayRef<LocalVariableAddrGap>());
  1651. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
  1652. BytePrefix +=
  1653. StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
  1654. BytePrefix +=
  1655. StringRef(reinterpret_cast<const char *>(&Sym.Header),
  1656. sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
  1657. }
  1658. OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
  1659. }
  1660. }
  1661. void CodeViewDebug::endFunction(const MachineFunction *MF) {
  1662. if (!Asm || !CurFn) // We haven't created any debug info for this function.
  1663. return;
  1664. const Function *GV = MF->getFunction();
  1665. assert(FnDebugInfo.count(GV));
  1666. assert(CurFn == &FnDebugInfo[GV]);
  1667. collectVariableInfo(GV->getSubprogram());
  1668. DebugHandlerBase::endFunction(MF);
  1669. // Don't emit anything if we don't have any line tables.
  1670. if (!CurFn->HaveLineInfo) {
  1671. FnDebugInfo.erase(GV);
  1672. CurFn = nullptr;
  1673. return;
  1674. }
  1675. CurFn->End = Asm->getFunctionEnd();
  1676. CurFn = nullptr;
  1677. }
  1678. void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
  1679. DebugHandlerBase::beginInstruction(MI);
  1680. // Ignore DBG_VALUE locations and function prologue.
  1681. if (!Asm || !CurFn || MI->isDebugValue() ||
  1682. MI->getFlag(MachineInstr::FrameSetup))
  1683. return;
  1684. DebugLoc DL = MI->getDebugLoc();
  1685. if (DL == PrevInstLoc || !DL)
  1686. return;
  1687. maybeRecordLocation(DL, Asm->MF);
  1688. }
  1689. MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
  1690. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  1691. *EndLabel = MMI->getContext().createTempSymbol();
  1692. OS.EmitIntValue(unsigned(Kind), 4);
  1693. OS.AddComment("Subsection size");
  1694. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
  1695. OS.EmitLabel(BeginLabel);
  1696. return EndLabel;
  1697. }
  1698. void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
  1699. OS.EmitLabel(EndLabel);
  1700. // Every subsection must be aligned to a 4-byte boundary.
  1701. OS.EmitValueToAlignment(4);
  1702. }
  1703. void CodeViewDebug::emitDebugInfoForUDTs(
  1704. ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
  1705. for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
  1706. MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
  1707. *UDTRecordEnd = MMI->getContext().createTempSymbol();
  1708. OS.AddComment("Record length");
  1709. OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
  1710. OS.EmitLabel(UDTRecordBegin);
  1711. OS.AddComment("Record kind: S_UDT");
  1712. OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
  1713. OS.AddComment("Type");
  1714. OS.EmitIntValue(UDT.second.getIndex(), 4);
  1715. emitNullTerminatedSymbolName(OS, UDT.first);
  1716. OS.EmitLabel(UDTRecordEnd);
  1717. }
  1718. }
  1719. void CodeViewDebug::emitDebugInfoForGlobals() {
  1720. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  1721. for (const MDNode *Node : CUs->operands()) {
  1722. const auto *CU = cast<DICompileUnit>(Node);
  1723. // First, emit all globals that are not in a comdat in a single symbol
  1724. // substream. MSVC doesn't like it if the substream is empty, so only open
  1725. // it if we have at least one global to emit.
  1726. switchToDebugSectionForSymbol(nullptr);
  1727. MCSymbol *EndLabel = nullptr;
  1728. for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
  1729. if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
  1730. if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
  1731. if (!EndLabel) {
  1732. OS.AddComment("Symbol subsection for globals");
  1733. EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
  1734. }
  1735. emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
  1736. }
  1737. }
  1738. }
  1739. if (EndLabel)
  1740. endCVSubsection(EndLabel);
  1741. // Second, emit each global that is in a comdat into its own .debug$S
  1742. // section along with its own symbol substream.
  1743. for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
  1744. if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
  1745. if (GV->hasComdat()) {
  1746. MCSymbol *GVSym = Asm->getSymbol(GV);
  1747. OS.AddComment("Symbol subsection for " +
  1748. Twine(GlobalValue::getRealLinkageName(GV->getName())));
  1749. switchToDebugSectionForSymbol(GVSym);
  1750. EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
  1751. emitDebugInfoForGlobal(G, GVSym);
  1752. endCVSubsection(EndLabel);
  1753. }
  1754. }
  1755. }
  1756. }
  1757. }
  1758. void CodeViewDebug::emitDebugInfoForRetainedTypes() {
  1759. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  1760. for (const MDNode *Node : CUs->operands()) {
  1761. for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
  1762. if (DIType *RT = dyn_cast<DIType>(Ty)) {
  1763. getTypeIndex(RT);
  1764. // FIXME: Add to global/local DTU list.
  1765. }
  1766. }
  1767. }
  1768. }
  1769. void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
  1770. MCSymbol *GVSym) {
  1771. // DataSym record, see SymbolRecord.h for more info.
  1772. // FIXME: Thread local data, etc
  1773. MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
  1774. *DataEnd = MMI->getContext().createTempSymbol();
  1775. OS.AddComment("Record length");
  1776. OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
  1777. OS.EmitLabel(DataBegin);
  1778. const auto *GV = cast<GlobalVariable>(DIGV->getVariable());
  1779. if (DIGV->isLocalToUnit()) {
  1780. if (GV->isThreadLocal()) {
  1781. OS.AddComment("Record kind: S_LTHREAD32");
  1782. OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
  1783. } else {
  1784. OS.AddComment("Record kind: S_LDATA32");
  1785. OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
  1786. }
  1787. } else {
  1788. if (GV->isThreadLocal()) {
  1789. OS.AddComment("Record kind: S_GTHREAD32");
  1790. OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
  1791. } else {
  1792. OS.AddComment("Record kind: S_GDATA32");
  1793. OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
  1794. }
  1795. }
  1796. OS.AddComment("Type");
  1797. OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
  1798. OS.AddComment("DataOffset");
  1799. OS.EmitCOFFSecRel32(GVSym);
  1800. OS.AddComment("Segment");
  1801. OS.EmitCOFFSectionIndex(GVSym);
  1802. OS.AddComment("Name");
  1803. emitNullTerminatedSymbolName(OS, DIGV->getName());
  1804. OS.EmitLabel(DataEnd);
  1805. }