CodeViewDebug.cpp 81 KB

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