CGDebugInfo.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015
  1. //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
  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 coordinates the debug information generation while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CGBlocks.h"
  15. #include "CGCXXABI.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CGRecordLayout.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/DeclFriend.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/RecordLayout.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/Version.h"
  29. #include "clang/Frontend/CodeGenOptions.h"
  30. #include "clang/Lex/HeaderSearchOptions.h"
  31. #include "clang/Lex/ModuleMap.h"
  32. #include "clang/Lex/PreprocessorOptions.h"
  33. #include "llvm/ADT/DenseSet.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/ADT/StringExtras.h"
  36. #include "llvm/IR/Constants.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/Intrinsics.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/MD5.h"
  44. #include "llvm/Support/Path.h"
  45. using namespace clang;
  46. using namespace clang::CodeGen;
  47. static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
  48. auto TI = Ctx.getTypeInfo(Ty);
  49. return TI.AlignIsRequired ? TI.Align : 0;
  50. }
  51. static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
  52. return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
  53. }
  54. static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
  55. return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
  56. }
  57. CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
  58. : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
  59. DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
  60. DBuilder(CGM.getModule()) {
  61. for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
  62. DebugPrefixMap[KV.first] = KV.second;
  63. CreateCompileUnit();
  64. }
  65. CGDebugInfo::~CGDebugInfo() {
  66. assert(LexicalBlockStack.empty() &&
  67. "Region stack mismatch, stack not empty!");
  68. }
  69. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  70. SourceLocation TemporaryLocation)
  71. : CGF(&CGF) {
  72. init(TemporaryLocation);
  73. }
  74. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  75. bool DefaultToEmpty,
  76. SourceLocation TemporaryLocation)
  77. : CGF(&CGF) {
  78. init(TemporaryLocation, DefaultToEmpty);
  79. }
  80. void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
  81. bool DefaultToEmpty) {
  82. auto *DI = CGF->getDebugInfo();
  83. if (!DI) {
  84. CGF = nullptr;
  85. return;
  86. }
  87. OriginalLocation = CGF->Builder.getCurrentDebugLocation();
  88. if (TemporaryLocation.isValid()) {
  89. DI->EmitLocation(CGF->Builder, TemporaryLocation);
  90. return;
  91. }
  92. if (DefaultToEmpty) {
  93. CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  94. return;
  95. }
  96. // Construct a location that has a valid scope, but no line info.
  97. assert(!DI->LexicalBlockStack.empty());
  98. CGF->Builder.SetCurrentDebugLocation(
  99. llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
  100. }
  101. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
  102. : CGF(&CGF) {
  103. init(E->getExprLoc());
  104. }
  105. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
  106. : CGF(&CGF) {
  107. if (!CGF.getDebugInfo()) {
  108. this->CGF = nullptr;
  109. return;
  110. }
  111. OriginalLocation = CGF.Builder.getCurrentDebugLocation();
  112. if (Loc)
  113. CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
  114. }
  115. ApplyDebugLocation::~ApplyDebugLocation() {
  116. // Query CGF so the location isn't overwritten when location updates are
  117. // temporarily disabled (for C++ default function arguments)
  118. if (CGF)
  119. CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
  120. }
  121. void CGDebugInfo::setLocation(SourceLocation Loc) {
  122. // If the new location isn't valid return.
  123. if (Loc.isInvalid())
  124. return;
  125. CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
  126. // If we've changed files in the middle of a lexical scope go ahead
  127. // and create a new lexical scope with file node if it's different
  128. // from the one in the scope.
  129. if (LexicalBlockStack.empty())
  130. return;
  131. SourceManager &SM = CGM.getContext().getSourceManager();
  132. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  133. PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
  134. if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
  135. return;
  136. if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
  137. LexicalBlockStack.pop_back();
  138. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
  139. LBF->getScope(), getOrCreateFile(CurLoc)));
  140. } else if (isa<llvm::DILexicalBlock>(Scope) ||
  141. isa<llvm::DISubprogram>(Scope)) {
  142. LexicalBlockStack.pop_back();
  143. LexicalBlockStack.emplace_back(
  144. DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
  145. }
  146. }
  147. llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
  148. llvm::DIScope *Mod = getParentModuleOrNull(D);
  149. return getContextDescriptor(cast<Decl>(D->getDeclContext()),
  150. Mod ? Mod : TheCU);
  151. }
  152. llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
  153. llvm::DIScope *Default) {
  154. if (!Context)
  155. return Default;
  156. auto I = RegionMap.find(Context);
  157. if (I != RegionMap.end()) {
  158. llvm::Metadata *V = I->second;
  159. return dyn_cast_or_null<llvm::DIScope>(V);
  160. }
  161. // Check namespace.
  162. if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
  163. return getOrCreateNameSpace(NSDecl);
  164. if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
  165. if (!RDecl->isDependentType())
  166. return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
  167. getOrCreateMainFile());
  168. return Default;
  169. }
  170. StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
  171. assert(FD && "Invalid FunctionDecl!");
  172. IdentifierInfo *FII = FD->getIdentifier();
  173. FunctionTemplateSpecializationInfo *Info =
  174. FD->getTemplateSpecializationInfo();
  175. // Emit the unqualified name in normal operation. LLVM and the debugger can
  176. // compute the fully qualified name from the scope chain. If we're only
  177. // emitting line table info, there won't be any scope chains, so emit the
  178. // fully qualified name here so that stack traces are more accurate.
  179. // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
  180. // evaluating the size impact.
  181. bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
  182. CGM.getCodeGenOpts().EmitCodeView;
  183. if (!Info && FII && !UseQualifiedName)
  184. return FII->getName();
  185. SmallString<128> NS;
  186. llvm::raw_svector_ostream OS(NS);
  187. PrintingPolicy Policy(CGM.getLangOpts());
  188. Policy.MSVCFormatting = CGM.getCodeGenOpts().EmitCodeView;
  189. if (!UseQualifiedName)
  190. FD->printName(OS);
  191. else
  192. FD->printQualifiedName(OS, Policy);
  193. // Add any template specialization args.
  194. if (Info) {
  195. const TemplateArgumentList *TArgs = Info->TemplateArguments;
  196. TemplateSpecializationType::PrintTemplateArgumentList(OS, TArgs->asArray(),
  197. Policy);
  198. }
  199. // Copy this name on the side and use its reference.
  200. return internString(OS.str());
  201. }
  202. StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
  203. SmallString<256> MethodName;
  204. llvm::raw_svector_ostream OS(MethodName);
  205. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  206. const DeclContext *DC = OMD->getDeclContext();
  207. if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
  208. OS << OID->getName();
  209. } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
  210. OS << OID->getName();
  211. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
  212. if (OC->IsClassExtension()) {
  213. OS << OC->getClassInterface()->getName();
  214. } else {
  215. OS << OC->getIdentifier()->getNameStart() << '('
  216. << OC->getIdentifier()->getNameStart() << ')';
  217. }
  218. } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
  219. OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
  220. << OCD->getIdentifier()->getNameStart() << ')';
  221. } else if (isa<ObjCProtocolDecl>(DC)) {
  222. // We can extract the type of the class from the self pointer.
  223. if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
  224. QualType ClassTy =
  225. cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
  226. ClassTy.print(OS, PrintingPolicy(LangOptions()));
  227. }
  228. }
  229. OS << ' ' << OMD->getSelector().getAsString() << ']';
  230. return internString(OS.str());
  231. }
  232. StringRef CGDebugInfo::getSelectorName(Selector S) {
  233. return internString(S.getAsString());
  234. }
  235. StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
  236. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  237. SmallString<128> Name;
  238. llvm::raw_svector_ostream OS(Name);
  239. RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
  240. /*Qualified*/ false);
  241. // Copy this name on the side and use its reference.
  242. return internString(Name);
  243. }
  244. // quick optimization to avoid having to intern strings that are already
  245. // stored reliably elsewhere
  246. if (const IdentifierInfo *II = RD->getIdentifier())
  247. return II->getName();
  248. // The CodeView printer in LLVM wants to see the names of unnamed types: it is
  249. // used to reconstruct the fully qualified type names.
  250. if (CGM.getCodeGenOpts().EmitCodeView) {
  251. if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
  252. assert(RD->getDeclContext() == D->getDeclContext() &&
  253. "Typedef should not be in another decl context!");
  254. assert(D->getDeclName().getAsIdentifierInfo() &&
  255. "Typedef was not named!");
  256. return D->getDeclName().getAsIdentifierInfo()->getName();
  257. }
  258. if (CGM.getLangOpts().CPlusPlus) {
  259. StringRef Name;
  260. ASTContext &Context = CGM.getContext();
  261. if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
  262. // Anonymous types without a name for linkage purposes have their
  263. // declarator mangled in if they have one.
  264. Name = DD->getName();
  265. else if (const TypedefNameDecl *TND =
  266. Context.getTypedefNameForUnnamedTagDecl(RD))
  267. // Anonymous types without a name for linkage purposes have their
  268. // associate typedef mangled in if they have one.
  269. Name = TND->getName();
  270. if (!Name.empty()) {
  271. SmallString<256> UnnamedType("<unnamed-type-");
  272. UnnamedType += Name;
  273. UnnamedType += '>';
  274. return internString(UnnamedType);
  275. }
  276. }
  277. }
  278. return StringRef();
  279. }
  280. llvm::DIFile::ChecksumKind
  281. CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
  282. Checksum.clear();
  283. if (!CGM.getCodeGenOpts().EmitCodeView)
  284. return llvm::DIFile::CSK_None;
  285. SourceManager &SM = CGM.getContext().getSourceManager();
  286. bool Invalid;
  287. llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
  288. if (Invalid)
  289. return llvm::DIFile::CSK_None;
  290. llvm::MD5 Hash;
  291. llvm::MD5::MD5Result Result;
  292. Hash.update(MemBuffer->getBuffer());
  293. Hash.final(Result);
  294. Hash.stringifyResult(Result, Checksum);
  295. return llvm::DIFile::CSK_MD5;
  296. }
  297. llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
  298. if (!Loc.isValid())
  299. // If Location is not valid then use main input file.
  300. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  301. remapDIPath(TheCU->getDirectory()),
  302. TheCU->getFile()->getChecksumKind(),
  303. TheCU->getFile()->getChecksum());
  304. SourceManager &SM = CGM.getContext().getSourceManager();
  305. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  306. if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
  307. // If the location is not valid then use main input file.
  308. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  309. remapDIPath(TheCU->getDirectory()),
  310. TheCU->getFile()->getChecksumKind(),
  311. TheCU->getFile()->getChecksum());
  312. // Cache the results.
  313. const char *fname = PLoc.getFilename();
  314. auto it = DIFileCache.find(fname);
  315. if (it != DIFileCache.end()) {
  316. // Verify that the information still exists.
  317. if (llvm::Metadata *V = it->second)
  318. return cast<llvm::DIFile>(V);
  319. }
  320. SmallString<32> Checksum;
  321. llvm::DIFile::ChecksumKind CSKind =
  322. computeChecksum(SM.getFileID(Loc), Checksum);
  323. llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
  324. remapDIPath(getCurrentDirname()),
  325. CSKind, Checksum);
  326. DIFileCache[fname].reset(F);
  327. return F;
  328. }
  329. llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
  330. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  331. remapDIPath(TheCU->getDirectory()),
  332. TheCU->getFile()->getChecksumKind(),
  333. TheCU->getFile()->getChecksum());
  334. }
  335. std::string CGDebugInfo::remapDIPath(StringRef Path) const {
  336. for (const auto &Entry : DebugPrefixMap)
  337. if (Path.startswith(Entry.first))
  338. return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
  339. return Path.str();
  340. }
  341. unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
  342. if (Loc.isInvalid() && CurLoc.isInvalid())
  343. return 0;
  344. SourceManager &SM = CGM.getContext().getSourceManager();
  345. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  346. return PLoc.isValid() ? PLoc.getLine() : 0;
  347. }
  348. unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
  349. // We may not want column information at all.
  350. if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
  351. return 0;
  352. // If the location is invalid then use the current column.
  353. if (Loc.isInvalid() && CurLoc.isInvalid())
  354. return 0;
  355. SourceManager &SM = CGM.getContext().getSourceManager();
  356. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  357. return PLoc.isValid() ? PLoc.getColumn() : 0;
  358. }
  359. StringRef CGDebugInfo::getCurrentDirname() {
  360. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  361. return CGM.getCodeGenOpts().DebugCompilationDir;
  362. if (!CWDName.empty())
  363. return CWDName;
  364. SmallString<256> CWD;
  365. llvm::sys::fs::current_path(CWD);
  366. return CWDName = internString(CWD);
  367. }
  368. void CGDebugInfo::CreateCompileUnit() {
  369. SmallString<32> Checksum;
  370. llvm::DIFile::ChecksumKind CSKind = llvm::DIFile::CSK_None;
  371. // Should we be asking the SourceManager for the main file name, instead of
  372. // accepting it as an argument? This just causes the main file name to
  373. // mismatch with source locations and create extra lexical scopes or
  374. // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
  375. // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
  376. // because that's what the SourceManager says)
  377. // Get absolute path name.
  378. SourceManager &SM = CGM.getContext().getSourceManager();
  379. std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
  380. if (MainFileName.empty())
  381. MainFileName = "<stdin>";
  382. // The main file name provided via the "-main-file-name" option contains just
  383. // the file name itself with no path information. This file name may have had
  384. // a relative path, so we look into the actual file entry for the main
  385. // file to determine the real absolute path for the file.
  386. std::string MainFileDir;
  387. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  388. MainFileDir = remapDIPath(MainFile->getDir()->getName());
  389. if (MainFileDir != ".") {
  390. llvm::SmallString<1024> MainFileDirSS(MainFileDir);
  391. llvm::sys::path::append(MainFileDirSS, MainFileName);
  392. MainFileName = MainFileDirSS.str();
  393. }
  394. CSKind = computeChecksum(SM.getMainFileID(), Checksum);
  395. }
  396. llvm::dwarf::SourceLanguage LangTag;
  397. const LangOptions &LO = CGM.getLangOpts();
  398. if (LO.CPlusPlus) {
  399. if (LO.ObjC1)
  400. LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
  401. else
  402. LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
  403. } else if (LO.ObjC1) {
  404. LangTag = llvm::dwarf::DW_LANG_ObjC;
  405. } else if (LO.RenderScript) {
  406. LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
  407. } else if (LO.C99) {
  408. LangTag = llvm::dwarf::DW_LANG_C99;
  409. } else {
  410. LangTag = llvm::dwarf::DW_LANG_C89;
  411. }
  412. std::string Producer = getClangFullVersion();
  413. // Figure out which version of the ObjC runtime we have.
  414. unsigned RuntimeVers = 0;
  415. if (LO.ObjC1)
  416. RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
  417. llvm::DICompileUnit::DebugEmissionKind EmissionKind;
  418. switch (DebugKind) {
  419. case codegenoptions::NoDebugInfo:
  420. case codegenoptions::LocTrackingOnly:
  421. EmissionKind = llvm::DICompileUnit::NoDebug;
  422. break;
  423. case codegenoptions::DebugLineTablesOnly:
  424. EmissionKind = llvm::DICompileUnit::LineTablesOnly;
  425. break;
  426. case codegenoptions::LimitedDebugInfo:
  427. case codegenoptions::FullDebugInfo:
  428. EmissionKind = llvm::DICompileUnit::FullDebug;
  429. break;
  430. }
  431. // Create new compile unit.
  432. // FIXME - Eliminate TheCU.
  433. TheCU = DBuilder.createCompileUnit(
  434. LangTag, DBuilder.createFile(remapDIPath(MainFileName),
  435. remapDIPath(getCurrentDirname()), CSKind,
  436. Checksum),
  437. Producer, LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers,
  438. CGM.getCodeGenOpts().SplitDwarfFile, EmissionKind, 0 /* DWOid */,
  439. CGM.getCodeGenOpts().SplitDwarfInlining,
  440. CGM.getCodeGenOpts().DebugInfoForProfiling);
  441. }
  442. llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
  443. llvm::dwarf::TypeKind Encoding;
  444. StringRef BTName;
  445. switch (BT->getKind()) {
  446. #define BUILTIN_TYPE(Id, SingletonId)
  447. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  448. #include "clang/AST/BuiltinTypes.def"
  449. case BuiltinType::Dependent:
  450. llvm_unreachable("Unexpected builtin type");
  451. case BuiltinType::NullPtr:
  452. return DBuilder.createNullPtrType();
  453. case BuiltinType::Void:
  454. return nullptr;
  455. case BuiltinType::ObjCClass:
  456. if (!ClassTy)
  457. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  458. "objc_class", TheCU,
  459. getOrCreateMainFile(), 0);
  460. return ClassTy;
  461. case BuiltinType::ObjCId: {
  462. // typedef struct objc_class *Class;
  463. // typedef struct objc_object {
  464. // Class isa;
  465. // } *id;
  466. if (ObjTy)
  467. return ObjTy;
  468. if (!ClassTy)
  469. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  470. "objc_class", TheCU,
  471. getOrCreateMainFile(), 0);
  472. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  473. auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
  474. ObjTy = DBuilder.createStructType(
  475. TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
  476. llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
  477. DBuilder.replaceArrays(
  478. ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
  479. ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
  480. llvm::DINode::FlagZero, ISATy)));
  481. return ObjTy;
  482. }
  483. case BuiltinType::ObjCSel: {
  484. if (!SelTy)
  485. SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  486. "objc_selector", TheCU,
  487. getOrCreateMainFile(), 0);
  488. return SelTy;
  489. }
  490. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  491. case BuiltinType::Id: \
  492. return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
  493. SingletonId);
  494. #include "clang/Basic/OpenCLImageTypes.def"
  495. case BuiltinType::OCLSampler:
  496. return getOrCreateStructPtrType("opencl_sampler_t",
  497. OCLSamplerDITy);
  498. case BuiltinType::OCLEvent:
  499. return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
  500. case BuiltinType::OCLClkEvent:
  501. return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
  502. case BuiltinType::OCLQueue:
  503. return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
  504. case BuiltinType::OCLNDRange:
  505. return getOrCreateStructPtrType("opencl_ndrange_t", OCLNDRangeDITy);
  506. case BuiltinType::OCLReserveID:
  507. return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
  508. case BuiltinType::UChar:
  509. case BuiltinType::Char_U:
  510. Encoding = llvm::dwarf::DW_ATE_unsigned_char;
  511. break;
  512. case BuiltinType::Char_S:
  513. case BuiltinType::SChar:
  514. Encoding = llvm::dwarf::DW_ATE_signed_char;
  515. break;
  516. case BuiltinType::Char16:
  517. case BuiltinType::Char32:
  518. Encoding = llvm::dwarf::DW_ATE_UTF;
  519. break;
  520. case BuiltinType::UShort:
  521. case BuiltinType::UInt:
  522. case BuiltinType::UInt128:
  523. case BuiltinType::ULong:
  524. case BuiltinType::WChar_U:
  525. case BuiltinType::ULongLong:
  526. Encoding = llvm::dwarf::DW_ATE_unsigned;
  527. break;
  528. case BuiltinType::Short:
  529. case BuiltinType::Int:
  530. case BuiltinType::Int128:
  531. case BuiltinType::Long:
  532. case BuiltinType::WChar_S:
  533. case BuiltinType::LongLong:
  534. Encoding = llvm::dwarf::DW_ATE_signed;
  535. break;
  536. case BuiltinType::Bool:
  537. Encoding = llvm::dwarf::DW_ATE_boolean;
  538. break;
  539. case BuiltinType::Half:
  540. case BuiltinType::Float:
  541. case BuiltinType::LongDouble:
  542. case BuiltinType::Float128:
  543. case BuiltinType::Double:
  544. // FIXME: For targets where long double and __float128 have the same size,
  545. // they are currently indistinguishable in the debugger without some
  546. // special treatment. However, there is currently no consensus on encoding
  547. // and this should be updated once a DWARF encoding exists for distinct
  548. // floating point types of the same size.
  549. Encoding = llvm::dwarf::DW_ATE_float;
  550. break;
  551. }
  552. switch (BT->getKind()) {
  553. case BuiltinType::Long:
  554. BTName = "long int";
  555. break;
  556. case BuiltinType::LongLong:
  557. BTName = "long long int";
  558. break;
  559. case BuiltinType::ULong:
  560. BTName = "long unsigned int";
  561. break;
  562. case BuiltinType::ULongLong:
  563. BTName = "long long unsigned int";
  564. break;
  565. default:
  566. BTName = BT->getName(CGM.getLangOpts());
  567. break;
  568. }
  569. // Bit size and offset of the type.
  570. uint64_t Size = CGM.getContext().getTypeSize(BT);
  571. return DBuilder.createBasicType(BTName, Size, Encoding);
  572. }
  573. llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
  574. // Bit size and offset of the type.
  575. llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
  576. if (Ty->isComplexIntegerType())
  577. Encoding = llvm::dwarf::DW_ATE_lo_user;
  578. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  579. return DBuilder.createBasicType("complex", Size, Encoding);
  580. }
  581. llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
  582. llvm::DIFile *Unit) {
  583. QualifierCollector Qc;
  584. const Type *T = Qc.strip(Ty);
  585. // Ignore these qualifiers for now.
  586. Qc.removeObjCGCAttr();
  587. Qc.removeAddressSpace();
  588. Qc.removeObjCLifetime();
  589. // We will create one Derived type for one qualifier and recurse to handle any
  590. // additional ones.
  591. llvm::dwarf::Tag Tag;
  592. if (Qc.hasConst()) {
  593. Tag = llvm::dwarf::DW_TAG_const_type;
  594. Qc.removeConst();
  595. } else if (Qc.hasVolatile()) {
  596. Tag = llvm::dwarf::DW_TAG_volatile_type;
  597. Qc.removeVolatile();
  598. } else if (Qc.hasRestrict()) {
  599. Tag = llvm::dwarf::DW_TAG_restrict_type;
  600. Qc.removeRestrict();
  601. } else {
  602. assert(Qc.empty() && "Unknown type qualifier for debug info");
  603. return getOrCreateType(QualType(T, 0), Unit);
  604. }
  605. auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
  606. // No need to fill in the Name, Line, Size, Alignment, Offset in case of
  607. // CVR derived types.
  608. return DBuilder.createQualifiedType(Tag, FromTy);
  609. }
  610. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
  611. llvm::DIFile *Unit) {
  612. // The frontend treats 'id' as a typedef to an ObjCObjectType,
  613. // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
  614. // debug info, we want to emit 'id' in both cases.
  615. if (Ty->isObjCQualifiedIdType())
  616. return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
  617. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  618. Ty->getPointeeType(), Unit);
  619. }
  620. llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
  621. llvm::DIFile *Unit) {
  622. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  623. Ty->getPointeeType(), Unit);
  624. }
  625. /// \return whether a C++ mangling exists for the type defined by TD.
  626. static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
  627. switch (TheCU->getSourceLanguage()) {
  628. case llvm::dwarf::DW_LANG_C_plus_plus:
  629. return true;
  630. case llvm::dwarf::DW_LANG_ObjC_plus_plus:
  631. return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
  632. default:
  633. return false;
  634. }
  635. }
  636. /// In C++ mode, types have linkage, so we can rely on the ODR and
  637. /// on their mangled names, if they're external.
  638. static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
  639. CodeGenModule &CGM,
  640. llvm::DICompileUnit *TheCU) {
  641. SmallString<256> FullName;
  642. const TagDecl *TD = Ty->getDecl();
  643. if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
  644. return FullName;
  645. // TODO: This is using the RTTI name. Is there a better way to get
  646. // a unique string for a type?
  647. llvm::raw_svector_ostream Out(FullName);
  648. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
  649. return FullName;
  650. }
  651. /// \return the approproate DWARF tag for a composite type.
  652. static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
  653. llvm::dwarf::Tag Tag;
  654. if (RD->isStruct() || RD->isInterface())
  655. Tag = llvm::dwarf::DW_TAG_structure_type;
  656. else if (RD->isUnion())
  657. Tag = llvm::dwarf::DW_TAG_union_type;
  658. else {
  659. // FIXME: This could be a struct type giving a default visibility different
  660. // than C++ class type, but needs llvm metadata changes first.
  661. assert(RD->isClass());
  662. Tag = llvm::dwarf::DW_TAG_class_type;
  663. }
  664. return Tag;
  665. }
  666. llvm::DICompositeType *
  667. CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
  668. llvm::DIScope *Ctx) {
  669. const RecordDecl *RD = Ty->getDecl();
  670. if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
  671. return cast<llvm::DICompositeType>(T);
  672. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  673. unsigned Line = getLineNumber(RD->getLocation());
  674. StringRef RDName = getClassName(RD);
  675. uint64_t Size = 0;
  676. uint32_t Align = 0;
  677. // Create the type.
  678. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  679. llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
  680. getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
  681. llvm::DINode::FlagFwdDecl, FullName);
  682. ReplaceMap.emplace_back(
  683. std::piecewise_construct, std::make_tuple(Ty),
  684. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  685. return RetTy;
  686. }
  687. llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
  688. const Type *Ty,
  689. QualType PointeeTy,
  690. llvm::DIFile *Unit) {
  691. // Bit size, align and offset of the type.
  692. // Size is always the size of a pointer. We can't use getTypeSize here
  693. // because that does not return the correct value for references.
  694. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  695. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  696. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  697. if (Tag == llvm::dwarf::DW_TAG_reference_type ||
  698. Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
  699. return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
  700. Size, Align);
  701. else
  702. return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
  703. Align);
  704. }
  705. llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
  706. llvm::DIType *&Cache) {
  707. if (Cache)
  708. return Cache;
  709. Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
  710. TheCU, getOrCreateMainFile(), 0);
  711. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  712. Cache = DBuilder.createPointerType(Cache, Size);
  713. return Cache;
  714. }
  715. llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
  716. llvm::DIFile *Unit) {
  717. SmallVector<llvm::Metadata *, 8> EltTys;
  718. QualType FType;
  719. uint64_t FieldSize, FieldOffset;
  720. uint32_t FieldAlign;
  721. llvm::DINodeArray Elements;
  722. FieldOffset = 0;
  723. FType = CGM.getContext().UnsignedLongTy;
  724. EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
  725. EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
  726. Elements = DBuilder.getOrCreateArray(EltTys);
  727. EltTys.clear();
  728. llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
  729. unsigned LineNo = 0;
  730. auto *EltTy =
  731. DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
  732. FieldOffset, 0, Flags, nullptr, Elements);
  733. // Bit size, align and offset of the type.
  734. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  735. auto *DescTy = DBuilder.createPointerType(EltTy, Size);
  736. FieldOffset = 0;
  737. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  738. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  739. FType = CGM.getContext().IntTy;
  740. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  741. EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
  742. FType = CGM.getContext().getPointerType(Ty->getPointeeType());
  743. EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
  744. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  745. FieldSize = CGM.getContext().getTypeSize(Ty);
  746. FieldAlign = CGM.getContext().getTypeAlign(Ty);
  747. EltTys.push_back(DBuilder.createMemberType(
  748. Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset,
  749. llvm::DINode::FlagZero, DescTy));
  750. FieldOffset += FieldSize;
  751. Elements = DBuilder.getOrCreateArray(EltTys);
  752. // The __block_literal_generic structs are marked with a special
  753. // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
  754. // the debugger needs to know about. To allow type uniquing, emit
  755. // them without a name or a location.
  756. EltTy =
  757. DBuilder.createStructType(Unit, "", nullptr, LineNo,
  758. FieldOffset, 0, Flags, nullptr, Elements);
  759. return DBuilder.createPointerType(EltTy, Size);
  760. }
  761. llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
  762. llvm::DIFile *Unit) {
  763. assert(Ty->isTypeAlias());
  764. llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
  765. SmallString<128> NS;
  766. llvm::raw_svector_ostream OS(NS);
  767. Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
  768. /*qualified*/ false);
  769. TemplateSpecializationType::PrintTemplateArgumentList(
  770. OS, Ty->template_arguments(),
  771. CGM.getContext().getPrintingPolicy());
  772. auto *AliasDecl = cast<TypeAliasTemplateDecl>(
  773. Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
  774. SourceLocation Loc = AliasDecl->getLocation();
  775. return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
  776. getLineNumber(Loc),
  777. getDeclContextDescriptor(AliasDecl));
  778. }
  779. llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
  780. llvm::DIFile *Unit) {
  781. // We don't set size information, but do specify where the typedef was
  782. // declared.
  783. SourceLocation Loc = Ty->getDecl()->getLocation();
  784. // Typedefs are derived from some other type.
  785. return DBuilder.createTypedef(
  786. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
  787. Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
  788. getDeclContextDescriptor(Ty->getDecl()));
  789. }
  790. static unsigned getDwarfCC(CallingConv CC) {
  791. switch (CC) {
  792. case CC_C:
  793. // Avoid emitting DW_AT_calling_convention if the C convention was used.
  794. return 0;
  795. case CC_X86StdCall:
  796. return llvm::dwarf::DW_CC_BORLAND_stdcall;
  797. case CC_X86FastCall:
  798. return llvm::dwarf::DW_CC_BORLAND_msfastcall;
  799. case CC_X86ThisCall:
  800. return llvm::dwarf::DW_CC_BORLAND_thiscall;
  801. case CC_X86VectorCall:
  802. return llvm::dwarf::DW_CC_LLVM_vectorcall;
  803. case CC_X86Pascal:
  804. return llvm::dwarf::DW_CC_BORLAND_pascal;
  805. // FIXME: Create new DW_CC_ codes for these calling conventions.
  806. case CC_X86_64Win64:
  807. case CC_X86_64SysV:
  808. case CC_AAPCS:
  809. case CC_AAPCS_VFP:
  810. case CC_IntelOclBicc:
  811. case CC_SpirFunction:
  812. case CC_OpenCLKernel:
  813. case CC_Swift:
  814. case CC_PreserveMost:
  815. case CC_PreserveAll:
  816. case CC_X86RegCall:
  817. return 0;
  818. }
  819. return 0;
  820. }
  821. llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
  822. llvm::DIFile *Unit) {
  823. SmallVector<llvm::Metadata *, 16> EltTys;
  824. // Add the result type at least.
  825. EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
  826. // Set up remainder of arguments if there is a prototype.
  827. // otherwise emit it as a variadic function.
  828. if (isa<FunctionNoProtoType>(Ty))
  829. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  830. else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
  831. for (const QualType &ParamType : FPT->param_types())
  832. EltTys.push_back(getOrCreateType(ParamType, Unit));
  833. if (FPT->isVariadic())
  834. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  835. }
  836. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  837. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  838. getDwarfCC(Ty->getCallConv()));
  839. }
  840. /// Convert an AccessSpecifier into the corresponding DINode flag.
  841. /// As an optimization, return 0 if the access specifier equals the
  842. /// default for the containing type.
  843. static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
  844. const RecordDecl *RD) {
  845. AccessSpecifier Default = clang::AS_none;
  846. if (RD && RD->isClass())
  847. Default = clang::AS_private;
  848. else if (RD && (RD->isStruct() || RD->isUnion()))
  849. Default = clang::AS_public;
  850. if (Access == Default)
  851. return llvm::DINode::FlagZero;
  852. switch (Access) {
  853. case clang::AS_private:
  854. return llvm::DINode::FlagPrivate;
  855. case clang::AS_protected:
  856. return llvm::DINode::FlagProtected;
  857. case clang::AS_public:
  858. return llvm::DINode::FlagPublic;
  859. case clang::AS_none:
  860. return llvm::DINode::FlagZero;
  861. }
  862. llvm_unreachable("unexpected access enumerator");
  863. }
  864. llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
  865. llvm::DIScope *RecordTy,
  866. const RecordDecl *RD) {
  867. StringRef Name = BitFieldDecl->getName();
  868. QualType Ty = BitFieldDecl->getType();
  869. SourceLocation Loc = BitFieldDecl->getLocation();
  870. llvm::DIFile *VUnit = getOrCreateFile(Loc);
  871. llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
  872. // Get the location for the field.
  873. llvm::DIFile *File = getOrCreateFile(Loc);
  874. unsigned Line = getLineNumber(Loc);
  875. const CGBitFieldInfo &BitFieldInfo =
  876. CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
  877. uint64_t SizeInBits = BitFieldInfo.Size;
  878. assert(SizeInBits > 0 && "found named 0-width bitfield");
  879. uint64_t StorageOffsetInBits =
  880. CGM.getContext().toBits(BitFieldInfo.StorageOffset);
  881. uint64_t OffsetInBits = StorageOffsetInBits + BitFieldInfo.Offset;
  882. llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
  883. return DBuilder.createBitFieldMemberType(
  884. RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
  885. Flags, DebugType);
  886. }
  887. llvm::DIType *
  888. CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
  889. AccessSpecifier AS, uint64_t offsetInBits,
  890. uint32_t AlignInBits, llvm::DIFile *tunit,
  891. llvm::DIScope *scope, const RecordDecl *RD) {
  892. llvm::DIType *debugType = getOrCreateType(type, tunit);
  893. // Get the location for the field.
  894. llvm::DIFile *file = getOrCreateFile(loc);
  895. unsigned line = getLineNumber(loc);
  896. uint64_t SizeInBits = 0;
  897. auto Align = AlignInBits;
  898. if (!type->isIncompleteArrayType()) {
  899. TypeInfo TI = CGM.getContext().getTypeInfo(type);
  900. SizeInBits = TI.Width;
  901. if (!Align)
  902. Align = getTypeAlignIfRequired(type, CGM.getContext());
  903. }
  904. llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
  905. return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
  906. Align, offsetInBits, flags, debugType);
  907. }
  908. void CGDebugInfo::CollectRecordLambdaFields(
  909. const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
  910. llvm::DIType *RecordTy) {
  911. // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
  912. // has the name and the location of the variable so we should iterate over
  913. // both concurrently.
  914. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
  915. RecordDecl::field_iterator Field = CXXDecl->field_begin();
  916. unsigned fieldno = 0;
  917. for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
  918. E = CXXDecl->captures_end();
  919. I != E; ++I, ++Field, ++fieldno) {
  920. const LambdaCapture &C = *I;
  921. if (C.capturesVariable()) {
  922. SourceLocation Loc = C.getLocation();
  923. assert(!Field->isBitField() && "lambdas don't have bitfield members!");
  924. VarDecl *V = C.getCapturedVar();
  925. StringRef VName = V->getName();
  926. llvm::DIFile *VUnit = getOrCreateFile(Loc);
  927. auto Align = getDeclAlignIfRequired(V, CGM.getContext());
  928. llvm::DIType *FieldType = createFieldType(
  929. VName, Field->getType(), Loc, Field->getAccess(),
  930. layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
  931. elements.push_back(FieldType);
  932. } else if (C.capturesThis()) {
  933. // TODO: Need to handle 'this' in some way by probably renaming the
  934. // this of the lambda class and having a field member of 'this' or
  935. // by using AT_object_pointer for the function and having that be
  936. // used as 'this' for semantic references.
  937. FieldDecl *f = *Field;
  938. llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
  939. QualType type = f->getType();
  940. llvm::DIType *fieldType = createFieldType(
  941. "this", type, f->getLocation(), f->getAccess(),
  942. layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
  943. elements.push_back(fieldType);
  944. }
  945. }
  946. }
  947. llvm::DIDerivedType *
  948. CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
  949. const RecordDecl *RD) {
  950. // Create the descriptor for the static variable, with or without
  951. // constant initializers.
  952. Var = Var->getCanonicalDecl();
  953. llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
  954. llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
  955. unsigned LineNumber = getLineNumber(Var->getLocation());
  956. StringRef VName = Var->getName();
  957. llvm::Constant *C = nullptr;
  958. if (Var->getInit()) {
  959. const APValue *Value = Var->evaluateValue();
  960. if (Value) {
  961. if (Value->isInt())
  962. C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
  963. if (Value->isFloat())
  964. C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
  965. }
  966. }
  967. llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
  968. auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
  969. llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
  970. RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
  971. StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
  972. return GV;
  973. }
  974. void CGDebugInfo::CollectRecordNormalField(
  975. const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
  976. SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
  977. const RecordDecl *RD) {
  978. StringRef name = field->getName();
  979. QualType type = field->getType();
  980. // Ignore unnamed fields unless they're anonymous structs/unions.
  981. if (name.empty() && !type->isRecordType())
  982. return;
  983. llvm::DIType *FieldType;
  984. if (field->isBitField()) {
  985. FieldType = createBitFieldType(field, RecordTy, RD);
  986. } else {
  987. auto Align = getDeclAlignIfRequired(field, CGM.getContext());
  988. FieldType =
  989. createFieldType(name, type, field->getLocation(), field->getAccess(),
  990. OffsetInBits, Align, tunit, RecordTy, RD);
  991. }
  992. elements.push_back(FieldType);
  993. }
  994. void CGDebugInfo::CollectRecordNestedRecord(
  995. const RecordDecl *RD, SmallVectorImpl<llvm::Metadata *> &elements) {
  996. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  997. // Injected class names are not considered nested records.
  998. if (isa<InjectedClassNameType>(Ty))
  999. return;
  1000. SourceLocation Loc = RD->getLocation();
  1001. llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
  1002. elements.push_back(nestedType);
  1003. }
  1004. void CGDebugInfo::CollectRecordFields(
  1005. const RecordDecl *record, llvm::DIFile *tunit,
  1006. SmallVectorImpl<llvm::Metadata *> &elements,
  1007. llvm::DICompositeType *RecordTy) {
  1008. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
  1009. if (CXXDecl && CXXDecl->isLambda())
  1010. CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
  1011. else {
  1012. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
  1013. // Debug info for nested records is included in the member list only for
  1014. // CodeView.
  1015. bool IncludeNestedRecords = CGM.getCodeGenOpts().EmitCodeView;
  1016. // Field number for non-static fields.
  1017. unsigned fieldNo = 0;
  1018. // Static and non-static members should appear in the same order as
  1019. // the corresponding declarations in the source program.
  1020. for (const auto *I : record->decls())
  1021. if (const auto *V = dyn_cast<VarDecl>(I)) {
  1022. if (V->hasAttr<NoDebugAttr>())
  1023. continue;
  1024. // Reuse the existing static member declaration if one exists
  1025. auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
  1026. if (MI != StaticDataMemberCache.end()) {
  1027. assert(MI->second &&
  1028. "Static data member declaration should still exist");
  1029. elements.push_back(MI->second);
  1030. } else {
  1031. auto Field = CreateRecordStaticField(V, RecordTy, record);
  1032. elements.push_back(Field);
  1033. }
  1034. } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
  1035. CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
  1036. elements, RecordTy, record);
  1037. // Bump field number for next field.
  1038. ++fieldNo;
  1039. } else if (const auto *nestedRec = dyn_cast<CXXRecordDecl>(I))
  1040. if (IncludeNestedRecords && !nestedRec->isImplicit() &&
  1041. nestedRec->getDeclContext() == record)
  1042. CollectRecordNestedRecord(nestedRec, elements);
  1043. }
  1044. }
  1045. llvm::DISubroutineType *
  1046. CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
  1047. llvm::DIFile *Unit) {
  1048. const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
  1049. if (Method->isStatic())
  1050. return cast_or_null<llvm::DISubroutineType>(
  1051. getOrCreateType(QualType(Func, 0), Unit));
  1052. return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
  1053. Func, Unit);
  1054. }
  1055. llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
  1056. QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
  1057. // Add "this" pointer.
  1058. llvm::DITypeRefArray Args(
  1059. cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
  1060. ->getTypeArray());
  1061. assert(Args.size() && "Invalid number of arguments!");
  1062. SmallVector<llvm::Metadata *, 16> Elts;
  1063. // First element is always return type. For 'void' functions it is NULL.
  1064. Elts.push_back(Args[0]);
  1065. // "this" pointer is always first argument.
  1066. const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
  1067. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  1068. // Create pointer type directly in this case.
  1069. const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
  1070. QualType PointeeTy = ThisPtrTy->getPointeeType();
  1071. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  1072. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  1073. auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
  1074. llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
  1075. llvm::DIType *ThisPtrType =
  1076. DBuilder.createPointerType(PointeeType, Size, Align);
  1077. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  1078. // TODO: This and the artificial type below are misleading, the
  1079. // types aren't artificial the argument is, but the current
  1080. // metadata doesn't represent that.
  1081. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  1082. Elts.push_back(ThisPtrType);
  1083. } else {
  1084. llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
  1085. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  1086. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  1087. Elts.push_back(ThisPtrType);
  1088. }
  1089. // Copy rest of the arguments.
  1090. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  1091. Elts.push_back(Args[i]);
  1092. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  1093. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1094. if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
  1095. Flags |= llvm::DINode::FlagLValueReference;
  1096. if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
  1097. Flags |= llvm::DINode::FlagRValueReference;
  1098. return DBuilder.createSubroutineType(EltTypeArray, Flags,
  1099. getDwarfCC(Func->getCallConv()));
  1100. }
  1101. /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
  1102. /// inside a function.
  1103. static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
  1104. if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
  1105. return isFunctionLocalClass(NRD);
  1106. if (isa<FunctionDecl>(RD->getDeclContext()))
  1107. return true;
  1108. return false;
  1109. }
  1110. llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
  1111. const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
  1112. bool IsCtorOrDtor =
  1113. isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
  1114. StringRef MethodName = getFunctionName(Method);
  1115. llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
  1116. // Since a single ctor/dtor corresponds to multiple functions, it doesn't
  1117. // make sense to give a single ctor/dtor a linkage name.
  1118. StringRef MethodLinkageName;
  1119. // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
  1120. // property to use here. It may've been intended to model "is non-external
  1121. // type" but misses cases of non-function-local but non-external classes such
  1122. // as those in anonymous namespaces as well as the reverse - external types
  1123. // that are function local, such as those in (non-local) inline functions.
  1124. if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
  1125. MethodLinkageName = CGM.getMangledName(Method);
  1126. // Get the location for the method.
  1127. llvm::DIFile *MethodDefUnit = nullptr;
  1128. unsigned MethodLine = 0;
  1129. if (!Method->isImplicit()) {
  1130. MethodDefUnit = getOrCreateFile(Method->getLocation());
  1131. MethodLine = getLineNumber(Method->getLocation());
  1132. }
  1133. // Collect virtual method info.
  1134. llvm::DIType *ContainingType = nullptr;
  1135. unsigned Virtuality = 0;
  1136. unsigned VIndex = 0;
  1137. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1138. int ThisAdjustment = 0;
  1139. if (Method->isVirtual()) {
  1140. if (Method->isPure())
  1141. Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
  1142. else
  1143. Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
  1144. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1145. // It doesn't make sense to give a virtual destructor a vtable index,
  1146. // since a single destructor has two entries in the vtable.
  1147. if (!isa<CXXDestructorDecl>(Method))
  1148. VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
  1149. } else {
  1150. // Emit MS ABI vftable information. There is only one entry for the
  1151. // deleting dtor.
  1152. const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
  1153. GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
  1154. MicrosoftVTableContext::MethodVFTableLocation ML =
  1155. CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
  1156. VIndex = ML.Index;
  1157. // CodeView only records the vftable offset in the class that introduces
  1158. // the virtual method. This is possible because, unlike Itanium, the MS
  1159. // C++ ABI does not include all virtual methods from non-primary bases in
  1160. // the vtable for the most derived class. For example, if C inherits from
  1161. // A and B, C's primary vftable will not include B's virtual methods.
  1162. if (Method->begin_overridden_methods() == Method->end_overridden_methods())
  1163. Flags |= llvm::DINode::FlagIntroducedVirtual;
  1164. // The 'this' adjustment accounts for both the virtual and non-virtual
  1165. // portions of the adjustment. Presumably the debugger only uses it when
  1166. // it knows the dynamic type of an object.
  1167. ThisAdjustment = CGM.getCXXABI()
  1168. .getVirtualFunctionPrologueThisAdjustment(GD)
  1169. .getQuantity();
  1170. }
  1171. ContainingType = RecordTy;
  1172. }
  1173. if (Method->isImplicit())
  1174. Flags |= llvm::DINode::FlagArtificial;
  1175. Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
  1176. if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
  1177. if (CXXC->isExplicit())
  1178. Flags |= llvm::DINode::FlagExplicit;
  1179. } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
  1180. if (CXXC->isExplicit())
  1181. Flags |= llvm::DINode::FlagExplicit;
  1182. }
  1183. if (Method->hasPrototype())
  1184. Flags |= llvm::DINode::FlagPrototyped;
  1185. if (Method->getRefQualifier() == RQ_LValue)
  1186. Flags |= llvm::DINode::FlagLValueReference;
  1187. if (Method->getRefQualifier() == RQ_RValue)
  1188. Flags |= llvm::DINode::FlagRValueReference;
  1189. llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
  1190. llvm::DISubprogram *SP = DBuilder.createMethod(
  1191. RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
  1192. MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
  1193. VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
  1194. TParamsArray.get());
  1195. SPCache[Method->getCanonicalDecl()].reset(SP);
  1196. return SP;
  1197. }
  1198. void CGDebugInfo::CollectCXXMemberFunctions(
  1199. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1200. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
  1201. // Since we want more than just the individual member decls if we
  1202. // have templated functions iterate over every declaration to gather
  1203. // the functions.
  1204. for (const auto *I : RD->decls()) {
  1205. const auto *Method = dyn_cast<CXXMethodDecl>(I);
  1206. // If the member is implicit, don't add it to the member list. This avoids
  1207. // the member being added to type units by LLVM, while still allowing it
  1208. // to be emitted into the type declaration/reference inside the compile
  1209. // unit.
  1210. // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
  1211. // FIXME: Handle Using(Shadow?)Decls here to create
  1212. // DW_TAG_imported_declarations inside the class for base decls brought into
  1213. // derived classes. GDB doesn't seem to notice/leverage these when I tried
  1214. // it, so I'm not rushing to fix this. (GCC seems to produce them, if
  1215. // referenced)
  1216. if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
  1217. continue;
  1218. if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
  1219. continue;
  1220. // Reuse the existing member function declaration if it exists.
  1221. // It may be associated with the declaration of the type & should be
  1222. // reused as we're building the definition.
  1223. //
  1224. // This situation can arise in the vtable-based debug info reduction where
  1225. // implicit members are emitted in a non-vtable TU.
  1226. auto MI = SPCache.find(Method->getCanonicalDecl());
  1227. EltTys.push_back(MI == SPCache.end()
  1228. ? CreateCXXMemberFunction(Method, Unit, RecordTy)
  1229. : static_cast<llvm::Metadata *>(MI->second));
  1230. }
  1231. }
  1232. void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1233. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1234. llvm::DIType *RecordTy) {
  1235. llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
  1236. CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
  1237. llvm::DINode::FlagZero);
  1238. // If we are generating CodeView debug info, we also need to emit records for
  1239. // indirect virtual base classes.
  1240. if (CGM.getCodeGenOpts().EmitCodeView) {
  1241. CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
  1242. llvm::DINode::FlagIndirectVirtualBase);
  1243. }
  1244. }
  1245. void CGDebugInfo::CollectCXXBasesAux(
  1246. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1247. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
  1248. const CXXRecordDecl::base_class_const_range &Bases,
  1249. llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
  1250. llvm::DINode::DIFlags StartingFlags) {
  1251. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1252. for (const auto &BI : Bases) {
  1253. const auto *Base =
  1254. cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
  1255. if (!SeenTypes.insert(Base).second)
  1256. continue;
  1257. auto *BaseTy = getOrCreateType(BI.getType(), Unit);
  1258. llvm::DINode::DIFlags BFlags = StartingFlags;
  1259. uint64_t BaseOffset;
  1260. if (BI.isVirtual()) {
  1261. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1262. // virtual base offset offset is -ve. The code generator emits dwarf
  1263. // expression where it expects +ve number.
  1264. BaseOffset = 0 - CGM.getItaniumVTableContext()
  1265. .getVirtualBaseOffsetOffset(RD, Base)
  1266. .getQuantity();
  1267. } else {
  1268. // In the MS ABI, store the vbtable offset, which is analogous to the
  1269. // vbase offset offset in Itanium.
  1270. BaseOffset =
  1271. 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
  1272. }
  1273. BFlags |= llvm::DINode::FlagVirtual;
  1274. } else
  1275. BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
  1276. // FIXME: Inconsistent units for BaseOffset. It is in bytes when
  1277. // BI->isVirtual() and bits when not.
  1278. BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
  1279. llvm::DIType *DTy =
  1280. DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, BFlags);
  1281. EltTys.push_back(DTy);
  1282. }
  1283. }
  1284. llvm::DINodeArray
  1285. CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
  1286. ArrayRef<TemplateArgument> TAList,
  1287. llvm::DIFile *Unit) {
  1288. SmallVector<llvm::Metadata *, 16> TemplateParams;
  1289. for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
  1290. const TemplateArgument &TA = TAList[i];
  1291. StringRef Name;
  1292. if (TPList)
  1293. Name = TPList->getParam(i)->getName();
  1294. switch (TA.getKind()) {
  1295. case TemplateArgument::Type: {
  1296. llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
  1297. TemplateParams.push_back(
  1298. DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
  1299. } break;
  1300. case TemplateArgument::Integral: {
  1301. llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
  1302. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1303. TheCU, Name, TTy,
  1304. llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
  1305. } break;
  1306. case TemplateArgument::Declaration: {
  1307. const ValueDecl *D = TA.getAsDecl();
  1308. QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
  1309. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1310. llvm::Constant *V = nullptr;
  1311. const CXXMethodDecl *MD;
  1312. // Variable pointer template parameters have a value that is the address
  1313. // of the variable.
  1314. if (const auto *VD = dyn_cast<VarDecl>(D))
  1315. V = CGM.GetAddrOfGlobalVar(VD);
  1316. // Member function pointers have special support for building them, though
  1317. // this is currently unsupported in LLVM CodeGen.
  1318. else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
  1319. V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
  1320. else if (const auto *FD = dyn_cast<FunctionDecl>(D))
  1321. V = CGM.GetAddrOfFunction(FD);
  1322. // Member data pointers have special handling too to compute the fixed
  1323. // offset within the object.
  1324. else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
  1325. // These five lines (& possibly the above member function pointer
  1326. // handling) might be able to be refactored to use similar code in
  1327. // CodeGenModule::getMemberPointerConstant
  1328. uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
  1329. CharUnits chars =
  1330. CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
  1331. V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
  1332. }
  1333. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1334. TheCU, Name, TTy,
  1335. cast_or_null<llvm::Constant>(V->stripPointerCasts())));
  1336. } break;
  1337. case TemplateArgument::NullPtr: {
  1338. QualType T = TA.getNullPtrType();
  1339. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1340. llvm::Constant *V = nullptr;
  1341. // Special case member data pointer null values since they're actually -1
  1342. // instead of zero.
  1343. if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
  1344. // But treat member function pointers as simple zero integers because
  1345. // it's easier than having a special case in LLVM's CodeGen. If LLVM
  1346. // CodeGen grows handling for values of non-null member function
  1347. // pointers then perhaps we could remove this special case and rely on
  1348. // EmitNullMemberPointer for member function pointers.
  1349. if (MPT->isMemberDataPointer())
  1350. V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1351. if (!V)
  1352. V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
  1353. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1354. TheCU, Name, TTy, V));
  1355. } break;
  1356. case TemplateArgument::Template:
  1357. TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
  1358. TheCU, Name, nullptr,
  1359. TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
  1360. break;
  1361. case TemplateArgument::Pack:
  1362. TemplateParams.push_back(DBuilder.createTemplateParameterPack(
  1363. TheCU, Name, nullptr,
  1364. CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
  1365. break;
  1366. case TemplateArgument::Expression: {
  1367. const Expr *E = TA.getAsExpr();
  1368. QualType T = E->getType();
  1369. if (E->isGLValue())
  1370. T = CGM.getContext().getLValueReferenceType(T);
  1371. llvm::Constant *V = CGM.EmitConstantExpr(E, T);
  1372. assert(V && "Expression in template argument isn't constant");
  1373. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1374. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1375. TheCU, Name, TTy, V->stripPointerCasts()));
  1376. } break;
  1377. // And the following should never occur:
  1378. case TemplateArgument::TemplateExpansion:
  1379. case TemplateArgument::Null:
  1380. llvm_unreachable(
  1381. "These argument types shouldn't exist in concrete types");
  1382. }
  1383. }
  1384. return DBuilder.getOrCreateArray(TemplateParams);
  1385. }
  1386. llvm::DINodeArray
  1387. CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
  1388. llvm::DIFile *Unit) {
  1389. if (FD->getTemplatedKind() ==
  1390. FunctionDecl::TK_FunctionTemplateSpecialization) {
  1391. const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
  1392. ->getTemplate()
  1393. ->getTemplateParameters();
  1394. return CollectTemplateParams(
  1395. TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
  1396. }
  1397. return llvm::DINodeArray();
  1398. }
  1399. llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
  1400. const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
  1401. // Always get the full list of parameters, not just the ones from
  1402. // the specialization.
  1403. TemplateParameterList *TPList =
  1404. TSpecial->getSpecializedTemplate()->getTemplateParameters();
  1405. const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
  1406. return CollectTemplateParams(TPList, TAList.asArray(), Unit);
  1407. }
  1408. llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
  1409. if (VTablePtrType)
  1410. return VTablePtrType;
  1411. ASTContext &Context = CGM.getContext();
  1412. /* Function type */
  1413. llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
  1414. llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
  1415. llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
  1416. unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
  1417. llvm::DIType *vtbl_ptr_type =
  1418. DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
  1419. VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
  1420. return VTablePtrType;
  1421. }
  1422. StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
  1423. // Copy the gdb compatible name on the side and use its reference.
  1424. return internString("_vptr$", RD->getNameAsString());
  1425. }
  1426. void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1427. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1428. llvm::DICompositeType *RecordTy) {
  1429. // If this class is not dynamic then there is not any vtable info to collect.
  1430. if (!RD->isDynamicClass())
  1431. return;
  1432. // Don't emit any vtable shape or vptr info if this class doesn't have an
  1433. // extendable vfptr. This can happen if the class doesn't have virtual
  1434. // methods, or in the MS ABI if those virtual methods only come from virtually
  1435. // inherited bases.
  1436. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1437. if (!RL.hasExtendableVFPtr())
  1438. return;
  1439. // CodeView needs to know how large the vtable of every dynamic class is, so
  1440. // emit a special named pointer type into the element list. The vptr type
  1441. // points to this type as well.
  1442. llvm::DIType *VPtrTy = nullptr;
  1443. bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
  1444. CGM.getTarget().getCXXABI().isMicrosoft();
  1445. if (NeedVTableShape) {
  1446. uint64_t PtrWidth =
  1447. CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1448. const VTableLayout &VFTLayout =
  1449. CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
  1450. unsigned VSlotCount =
  1451. VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
  1452. unsigned VTableWidth = PtrWidth * VSlotCount;
  1453. // Create a very wide void* type and insert it directly in the element list.
  1454. llvm::DIType *VTableType =
  1455. DBuilder.createPointerType(nullptr, VTableWidth, 0, "__vtbl_ptr_type");
  1456. EltTys.push_back(VTableType);
  1457. // The vptr is a pointer to this special vtable type.
  1458. VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
  1459. }
  1460. // If there is a primary base then the artificial vptr member lives there.
  1461. if (RL.getPrimaryBase())
  1462. return;
  1463. if (!VPtrTy)
  1464. VPtrTy = getOrCreateVTablePtrType(Unit);
  1465. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1466. llvm::DIType *VPtrMember = DBuilder.createMemberType(
  1467. Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
  1468. llvm::DINode::FlagArtificial, VPtrTy);
  1469. EltTys.push_back(VPtrMember);
  1470. }
  1471. llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
  1472. SourceLocation Loc) {
  1473. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  1474. llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
  1475. return T;
  1476. }
  1477. llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
  1478. SourceLocation Loc) {
  1479. return getOrCreateStandaloneType(D, Loc);
  1480. }
  1481. llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
  1482. SourceLocation Loc) {
  1483. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  1484. assert(!D.isNull() && "null type");
  1485. llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
  1486. assert(T && "could not create debug info for type");
  1487. RetainedTypes.push_back(D.getAsOpaquePtr());
  1488. return T;
  1489. }
  1490. void CGDebugInfo::completeType(const EnumDecl *ED) {
  1491. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  1492. return;
  1493. QualType Ty = CGM.getContext().getEnumType(ED);
  1494. void *TyPtr = Ty.getAsOpaquePtr();
  1495. auto I = TypeCache.find(TyPtr);
  1496. if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
  1497. return;
  1498. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
  1499. assert(!Res->isForwardDecl());
  1500. TypeCache[TyPtr].reset(Res);
  1501. }
  1502. void CGDebugInfo::completeType(const RecordDecl *RD) {
  1503. if (DebugKind > codegenoptions::LimitedDebugInfo ||
  1504. !CGM.getLangOpts().CPlusPlus)
  1505. completeRequiredType(RD);
  1506. }
  1507. /// Return true if the class or any of its methods are marked dllimport.
  1508. static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
  1509. if (RD->hasAttr<DLLImportAttr>())
  1510. return true;
  1511. for (const CXXMethodDecl *MD : RD->methods())
  1512. if (MD->hasAttr<DLLImportAttr>())
  1513. return true;
  1514. return false;
  1515. }
  1516. void CGDebugInfo::completeClassData(const RecordDecl *RD) {
  1517. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1518. if (CXXRD->isDynamicClass() &&
  1519. CGM.getVTableLinkage(CXXRD) ==
  1520. llvm::GlobalValue::AvailableExternallyLinkage &&
  1521. !isClassOrMethodDLLImport(CXXRD))
  1522. return;
  1523. completeClass(RD);
  1524. }
  1525. void CGDebugInfo::completeClass(const RecordDecl *RD) {
  1526. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  1527. return;
  1528. QualType Ty = CGM.getContext().getRecordType(RD);
  1529. void *TyPtr = Ty.getAsOpaquePtr();
  1530. auto I = TypeCache.find(TyPtr);
  1531. if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
  1532. return;
  1533. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
  1534. assert(!Res->isForwardDecl());
  1535. TypeCache[TyPtr].reset(Res);
  1536. }
  1537. static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
  1538. CXXRecordDecl::method_iterator End) {
  1539. for (CXXMethodDecl *MD : llvm::make_range(I, End))
  1540. if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
  1541. if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
  1542. !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
  1543. return true;
  1544. return false;
  1545. }
  1546. /// Does a type definition exist in an imported clang module?
  1547. static bool isDefinedInClangModule(const RecordDecl *RD) {
  1548. // Only definitions that where imported from an AST file come from a module.
  1549. if (!RD || !RD->isFromASTFile())
  1550. return false;
  1551. // Anonymous entities cannot be addressed. Treat them as not from module.
  1552. if (!RD->isExternallyVisible() && RD->getName().empty())
  1553. return false;
  1554. if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
  1555. if (!CXXDecl->isCompleteDefinition())
  1556. return false;
  1557. auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
  1558. if (TemplateKind != TSK_Undeclared) {
  1559. // This is a template, check the origin of the first member.
  1560. if (CXXDecl->field_begin() == CXXDecl->field_end())
  1561. return TemplateKind == TSK_ExplicitInstantiationDeclaration;
  1562. if (!CXXDecl->field_begin()->isFromASTFile())
  1563. return false;
  1564. }
  1565. }
  1566. return true;
  1567. }
  1568. static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
  1569. bool DebugTypeExtRefs, const RecordDecl *RD,
  1570. const LangOptions &LangOpts) {
  1571. if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
  1572. return true;
  1573. if (DebugKind > codegenoptions::LimitedDebugInfo)
  1574. return false;
  1575. if (!LangOpts.CPlusPlus)
  1576. return false;
  1577. if (!RD->isCompleteDefinitionRequired())
  1578. return true;
  1579. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1580. if (!CXXDecl)
  1581. return false;
  1582. // Only emit complete debug info for a dynamic class when its vtable is
  1583. // emitted. However, Microsoft debuggers don't resolve type information
  1584. // across DLL boundaries, so skip this optimization if the class or any of its
  1585. // methods are marked dllimport. This isn't a complete solution, since objects
  1586. // without any dllimport methods can be used in one DLL and constructed in
  1587. // another, but it is the current behavior of LimitedDebugInfo.
  1588. if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
  1589. !isClassOrMethodDLLImport(CXXDecl))
  1590. return true;
  1591. TemplateSpecializationKind Spec = TSK_Undeclared;
  1592. if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1593. Spec = SD->getSpecializationKind();
  1594. if (Spec == TSK_ExplicitInstantiationDeclaration &&
  1595. hasExplicitMemberDefinition(CXXDecl->method_begin(),
  1596. CXXDecl->method_end()))
  1597. return true;
  1598. return false;
  1599. }
  1600. void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
  1601. if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
  1602. return;
  1603. QualType Ty = CGM.getContext().getRecordType(RD);
  1604. llvm::DIType *T = getTypeOrNull(Ty);
  1605. if (T && T->isForwardDecl())
  1606. completeClassData(RD);
  1607. }
  1608. llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
  1609. RecordDecl *RD = Ty->getDecl();
  1610. llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
  1611. if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
  1612. CGM.getLangOpts())) {
  1613. if (!T)
  1614. T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
  1615. return T;
  1616. }
  1617. return CreateTypeDefinition(Ty);
  1618. }
  1619. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
  1620. RecordDecl *RD = Ty->getDecl();
  1621. // Get overall information about the record type for the debug info.
  1622. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1623. // Records and classes and unions can all be recursive. To handle them, we
  1624. // first generate a debug descriptor for the struct as a forward declaration.
  1625. // Then (if it is a definition) we go through and get debug info for all of
  1626. // its members. Finally, we create a descriptor for the complete type (which
  1627. // may refer to the forward decl if the struct is recursive) and replace all
  1628. // uses of the forward declaration with the final definition.
  1629. llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
  1630. const RecordDecl *D = RD->getDefinition();
  1631. if (!D || !D->isCompleteDefinition())
  1632. return FwdDecl;
  1633. if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1634. CollectContainingType(CXXDecl, FwdDecl);
  1635. // Push the struct on region stack.
  1636. LexicalBlockStack.emplace_back(&*FwdDecl);
  1637. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1638. // Convert all the elements.
  1639. SmallVector<llvm::Metadata *, 16> EltTys;
  1640. // what about nested types?
  1641. // Note: The split of CXXDecl information here is intentional, the
  1642. // gdb tests will depend on a certain ordering at printout. The debug
  1643. // information offsets are still correct if we merge them all together
  1644. // though.
  1645. const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1646. if (CXXDecl) {
  1647. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1648. CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
  1649. }
  1650. // Collect data fields (including static variables and any initializers).
  1651. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1652. if (CXXDecl)
  1653. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  1654. LexicalBlockStack.pop_back();
  1655. RegionMap.erase(Ty->getDecl());
  1656. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1657. DBuilder.replaceArrays(FwdDecl, Elements);
  1658. if (FwdDecl->isTemporary())
  1659. FwdDecl =
  1660. llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
  1661. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1662. return FwdDecl;
  1663. }
  1664. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  1665. llvm::DIFile *Unit) {
  1666. // Ignore protocols.
  1667. return getOrCreateType(Ty->getBaseType(), Unit);
  1668. }
  1669. llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
  1670. llvm::DIFile *Unit) {
  1671. // Ignore protocols.
  1672. SourceLocation Loc = Ty->getDecl()->getLocation();
  1673. // Use Typedefs to represent ObjCTypeParamType.
  1674. return DBuilder.createTypedef(
  1675. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
  1676. Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
  1677. getDeclContextDescriptor(Ty->getDecl()));
  1678. }
  1679. /// \return true if Getter has the default name for the property PD.
  1680. static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
  1681. const ObjCMethodDecl *Getter) {
  1682. assert(PD);
  1683. if (!Getter)
  1684. return true;
  1685. assert(Getter->getDeclName().isObjCZeroArgSelector());
  1686. return PD->getName() ==
  1687. Getter->getDeclName().getObjCSelector().getNameForSlot(0);
  1688. }
  1689. /// \return true if Setter has the default name for the property PD.
  1690. static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
  1691. const ObjCMethodDecl *Setter) {
  1692. assert(PD);
  1693. if (!Setter)
  1694. return true;
  1695. assert(Setter->getDeclName().isObjCOneArgSelector());
  1696. return SelectorTable::constructSetterName(PD->getName()) ==
  1697. Setter->getDeclName().getObjCSelector().getNameForSlot(0);
  1698. }
  1699. llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  1700. llvm::DIFile *Unit) {
  1701. ObjCInterfaceDecl *ID = Ty->getDecl();
  1702. if (!ID)
  1703. return nullptr;
  1704. // Return a forward declaration if this type was imported from a clang module,
  1705. // and this is not the compile unit with the implementation of the type (which
  1706. // may contain hidden ivars).
  1707. if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
  1708. !ID->getImplementation())
  1709. return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  1710. ID->getName(),
  1711. getDeclContextDescriptor(ID), Unit, 0);
  1712. // Get overall information about the record type for the debug info.
  1713. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1714. unsigned Line = getLineNumber(ID->getLocation());
  1715. auto RuntimeLang =
  1716. static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
  1717. // If this is just a forward declaration return a special forward-declaration
  1718. // debug type since we won't be able to lay out the entire type.
  1719. ObjCInterfaceDecl *Def = ID->getDefinition();
  1720. if (!Def || !Def->getImplementation()) {
  1721. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1722. llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
  1723. llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
  1724. DefUnit, Line, RuntimeLang);
  1725. ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
  1726. return FwdDecl;
  1727. }
  1728. return CreateTypeDefinition(Ty, Unit);
  1729. }
  1730. llvm::DIModule *
  1731. CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
  1732. bool CreateSkeletonCU) {
  1733. // Use the Module pointer as the key into the cache. This is a
  1734. // nullptr if the "Module" is a PCH, which is safe because we don't
  1735. // support chained PCH debug info, so there can only be a single PCH.
  1736. const Module *M = Mod.getModuleOrNull();
  1737. auto ModRef = ModuleCache.find(M);
  1738. if (ModRef != ModuleCache.end())
  1739. return cast<llvm::DIModule>(ModRef->second);
  1740. // Macro definitions that were defined with "-D" on the command line.
  1741. SmallString<128> ConfigMacros;
  1742. {
  1743. llvm::raw_svector_ostream OS(ConfigMacros);
  1744. const auto &PPOpts = CGM.getPreprocessorOpts();
  1745. unsigned I = 0;
  1746. // Translate the macro definitions back into a commmand line.
  1747. for (auto &M : PPOpts.Macros) {
  1748. if (++I > 1)
  1749. OS << " ";
  1750. const std::string &Macro = M.first;
  1751. bool Undef = M.second;
  1752. OS << "\"-" << (Undef ? 'U' : 'D');
  1753. for (char c : Macro)
  1754. switch (c) {
  1755. case '\\' : OS << "\\\\"; break;
  1756. case '"' : OS << "\\\""; break;
  1757. default: OS << c;
  1758. }
  1759. OS << '\"';
  1760. }
  1761. }
  1762. bool IsRootModule = M ? !M->Parent : true;
  1763. if (CreateSkeletonCU && IsRootModule) {
  1764. // PCH files don't have a signature field in the control block,
  1765. // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
  1766. uint64_t Signature = Mod.getSignature() ? Mod.getSignature() : ~1ULL;
  1767. llvm::DIBuilder DIB(CGM.getModule());
  1768. DIB.createCompileUnit(TheCU->getSourceLanguage(),
  1769. DIB.createFile(Mod.getModuleName(), Mod.getPath()),
  1770. TheCU->getProducer(), true, StringRef(), 0,
  1771. Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
  1772. Signature);
  1773. DIB.finalize();
  1774. }
  1775. llvm::DIModule *Parent =
  1776. IsRootModule ? nullptr
  1777. : getOrCreateModuleRef(
  1778. ExternalASTSource::ASTSourceDescriptor(*M->Parent),
  1779. CreateSkeletonCU);
  1780. llvm::DIModule *DIMod =
  1781. DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
  1782. Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
  1783. ModuleCache[M].reset(DIMod);
  1784. return DIMod;
  1785. }
  1786. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
  1787. llvm::DIFile *Unit) {
  1788. ObjCInterfaceDecl *ID = Ty->getDecl();
  1789. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1790. unsigned Line = getLineNumber(ID->getLocation());
  1791. unsigned RuntimeLang = TheCU->getSourceLanguage();
  1792. // Bit size, align and offset of the type.
  1793. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1794. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  1795. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1796. if (ID->getImplementation())
  1797. Flags |= llvm::DINode::FlagObjcClassComplete;
  1798. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1799. llvm::DICompositeType *RealDecl = DBuilder.createStructType(
  1800. Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
  1801. nullptr, llvm::DINodeArray(), RuntimeLang);
  1802. QualType QTy(Ty, 0);
  1803. TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
  1804. // Push the struct on region stack.
  1805. LexicalBlockStack.emplace_back(RealDecl);
  1806. RegionMap[Ty->getDecl()].reset(RealDecl);
  1807. // Convert all the elements.
  1808. SmallVector<llvm::Metadata *, 16> EltTys;
  1809. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  1810. if (SClass) {
  1811. llvm::DIType *SClassTy =
  1812. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  1813. if (!SClassTy)
  1814. return nullptr;
  1815. llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0,
  1816. llvm::DINode::FlagZero);
  1817. EltTys.push_back(InhTag);
  1818. }
  1819. // Create entries for all of the properties.
  1820. auto AddProperty = [&](const ObjCPropertyDecl *PD) {
  1821. SourceLocation Loc = PD->getLocation();
  1822. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1823. unsigned PLine = getLineNumber(Loc);
  1824. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1825. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1826. llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
  1827. PD->getName(), PUnit, PLine,
  1828. hasDefaultGetterName(PD, Getter) ? ""
  1829. : getSelectorName(PD->getGetterName()),
  1830. hasDefaultSetterName(PD, Setter) ? ""
  1831. : getSelectorName(PD->getSetterName()),
  1832. PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
  1833. EltTys.push_back(PropertyNode);
  1834. };
  1835. {
  1836. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  1837. for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
  1838. for (auto *PD : ClassExt->properties()) {
  1839. PropertySet.insert(PD->getIdentifier());
  1840. AddProperty(PD);
  1841. }
  1842. for (const auto *PD : ID->properties()) {
  1843. // Don't emit duplicate metadata for properties that were already in a
  1844. // class extension.
  1845. if (!PropertySet.insert(PD->getIdentifier()).second)
  1846. continue;
  1847. AddProperty(PD);
  1848. }
  1849. }
  1850. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  1851. unsigned FieldNo = 0;
  1852. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  1853. Field = Field->getNextIvar(), ++FieldNo) {
  1854. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  1855. if (!FieldTy)
  1856. return nullptr;
  1857. StringRef FieldName = Field->getName();
  1858. // Ignore unnamed fields.
  1859. if (FieldName.empty())
  1860. continue;
  1861. // Get the location for the field.
  1862. llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
  1863. unsigned FieldLine = getLineNumber(Field->getLocation());
  1864. QualType FType = Field->getType();
  1865. uint64_t FieldSize = 0;
  1866. uint32_t FieldAlign = 0;
  1867. if (!FType->isIncompleteArrayType()) {
  1868. // Bit size, align and offset of the type.
  1869. FieldSize = Field->isBitField()
  1870. ? Field->getBitWidthValue(CGM.getContext())
  1871. : CGM.getContext().getTypeSize(FType);
  1872. FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
  1873. }
  1874. uint64_t FieldOffset;
  1875. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  1876. // We don't know the runtime offset of an ivar if we're using the
  1877. // non-fragile ABI. For bitfields, use the bit offset into the first
  1878. // byte of storage of the bitfield. For other fields, use zero.
  1879. if (Field->isBitField()) {
  1880. FieldOffset =
  1881. CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
  1882. FieldOffset %= CGM.getContext().getCharWidth();
  1883. } else {
  1884. FieldOffset = 0;
  1885. }
  1886. } else {
  1887. FieldOffset = RL.getFieldOffset(FieldNo);
  1888. }
  1889. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  1890. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  1891. Flags = llvm::DINode::FlagProtected;
  1892. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  1893. Flags = llvm::DINode::FlagPrivate;
  1894. else if (Field->getAccessControl() == ObjCIvarDecl::Public)
  1895. Flags = llvm::DINode::FlagPublic;
  1896. llvm::MDNode *PropertyNode = nullptr;
  1897. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  1898. if (ObjCPropertyImplDecl *PImpD =
  1899. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  1900. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  1901. SourceLocation Loc = PD->getLocation();
  1902. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1903. unsigned PLine = getLineNumber(Loc);
  1904. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1905. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1906. PropertyNode = DBuilder.createObjCProperty(
  1907. PD->getName(), PUnit, PLine,
  1908. hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
  1909. PD->getGetterName()),
  1910. hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
  1911. PD->getSetterName()),
  1912. PD->getPropertyAttributes(),
  1913. getOrCreateType(PD->getType(), PUnit));
  1914. }
  1915. }
  1916. }
  1917. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
  1918. FieldSize, FieldAlign, FieldOffset, Flags,
  1919. FieldTy, PropertyNode);
  1920. EltTys.push_back(FieldTy);
  1921. }
  1922. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1923. DBuilder.replaceArrays(RealDecl, Elements);
  1924. LexicalBlockStack.pop_back();
  1925. return RealDecl;
  1926. }
  1927. llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
  1928. llvm::DIFile *Unit) {
  1929. llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  1930. int64_t Count = Ty->getNumElements();
  1931. if (Count == 0)
  1932. // If number of elements are not known then this is an unbounded array.
  1933. // Use Count == -1 to express such arrays.
  1934. Count = -1;
  1935. llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
  1936. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  1937. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1938. auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  1939. return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  1940. }
  1941. llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
  1942. uint64_t Size;
  1943. uint32_t Align;
  1944. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  1945. if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1946. Size = 0;
  1947. Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
  1948. CGM.getContext());
  1949. } else if (Ty->isIncompleteArrayType()) {
  1950. Size = 0;
  1951. if (Ty->getElementType()->isIncompleteType())
  1952. Align = 0;
  1953. else
  1954. Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
  1955. } else if (Ty->isIncompleteType()) {
  1956. Size = 0;
  1957. Align = 0;
  1958. } else {
  1959. // Size and align of the whole array, not the element type.
  1960. Size = CGM.getContext().getTypeSize(Ty);
  1961. Align = getTypeAlignIfRequired(Ty, CGM.getContext());
  1962. }
  1963. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  1964. // interior arrays, do we care? Why aren't nested arrays represented the
  1965. // obvious/recursive way?
  1966. SmallVector<llvm::Metadata *, 8> Subscripts;
  1967. QualType EltTy(Ty, 0);
  1968. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  1969. // If the number of elements is known, then count is that number. Otherwise,
  1970. // it's -1. This allows us to represent a subrange with an array of 0
  1971. // elements, like this:
  1972. //
  1973. // struct foo {
  1974. // int x[0];
  1975. // };
  1976. int64_t Count = -1; // Count == -1 is an unbounded array.
  1977. if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
  1978. Count = CAT->getSize().getZExtValue();
  1979. else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1980. if (Expr *Size = VAT->getSizeExpr()) {
  1981. llvm::APSInt V;
  1982. if (Size->EvaluateAsInt(V, CGM.getContext()))
  1983. Count = V.getExtValue();
  1984. }
  1985. }
  1986. // FIXME: Verify this is right for VLAs.
  1987. Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
  1988. EltTy = Ty->getElementType();
  1989. }
  1990. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  1991. return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  1992. SubscriptArray);
  1993. }
  1994. llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  1995. llvm::DIFile *Unit) {
  1996. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
  1997. Ty->getPointeeType(), Unit);
  1998. }
  1999. llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  2000. llvm::DIFile *Unit) {
  2001. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
  2002. Ty->getPointeeType(), Unit);
  2003. }
  2004. llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
  2005. llvm::DIFile *U) {
  2006. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2007. uint64_t Size = 0;
  2008. if (!Ty->isIncompleteType()) {
  2009. Size = CGM.getContext().getTypeSize(Ty);
  2010. // Set the MS inheritance model. There is no flag for the unspecified model.
  2011. if (CGM.getTarget().getCXXABI().isMicrosoft()) {
  2012. switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
  2013. case MSInheritanceAttr::Keyword_single_inheritance:
  2014. Flags |= llvm::DINode::FlagSingleInheritance;
  2015. break;
  2016. case MSInheritanceAttr::Keyword_multiple_inheritance:
  2017. Flags |= llvm::DINode::FlagMultipleInheritance;
  2018. break;
  2019. case MSInheritanceAttr::Keyword_virtual_inheritance:
  2020. Flags |= llvm::DINode::FlagVirtualInheritance;
  2021. break;
  2022. case MSInheritanceAttr::Keyword_unspecified_inheritance:
  2023. break;
  2024. }
  2025. }
  2026. }
  2027. llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
  2028. if (Ty->isMemberDataPointerType())
  2029. return DBuilder.createMemberPointerType(
  2030. getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
  2031. Flags);
  2032. const FunctionProtoType *FPT =
  2033. Ty->getPointeeType()->getAs<FunctionProtoType>();
  2034. return DBuilder.createMemberPointerType(
  2035. getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
  2036. Ty->getClass(), FPT->getTypeQuals())),
  2037. FPT, U),
  2038. ClassType, Size, /*Align=*/0, Flags);
  2039. }
  2040. llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
  2041. auto *FromTy = getOrCreateType(Ty->getValueType(), U);
  2042. return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
  2043. }
  2044. llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
  2045. llvm::DIFile *U) {
  2046. return getOrCreateType(Ty->getElementType(), U);
  2047. }
  2048. llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
  2049. const EnumDecl *ED = Ty->getDecl();
  2050. uint64_t Size = 0;
  2051. uint32_t Align = 0;
  2052. if (!ED->getTypeForDecl()->isIncompleteType()) {
  2053. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  2054. Align = getDeclAlignIfRequired(ED, CGM.getContext());
  2055. }
  2056. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  2057. bool isImportedFromModule =
  2058. DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
  2059. // If this is just a forward declaration, construct an appropriately
  2060. // marked node and just return it.
  2061. if (isImportedFromModule || !ED->getDefinition()) {
  2062. // Note that it is possible for enums to be created as part of
  2063. // their own declcontext. In this case a FwdDecl will be created
  2064. // twice. This doesn't cause a problem because both FwdDecls are
  2065. // entered into the ReplaceMap: finalize() will replace the first
  2066. // FwdDecl with the second and then replace the second with
  2067. // complete type.
  2068. llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
  2069. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  2070. llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
  2071. llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
  2072. unsigned Line = getLineNumber(ED->getLocation());
  2073. StringRef EDName = ED->getName();
  2074. llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
  2075. llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
  2076. 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
  2077. ReplaceMap.emplace_back(
  2078. std::piecewise_construct, std::make_tuple(Ty),
  2079. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  2080. return RetTy;
  2081. }
  2082. return CreateTypeDefinition(Ty);
  2083. }
  2084. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
  2085. const EnumDecl *ED = Ty->getDecl();
  2086. uint64_t Size = 0;
  2087. uint32_t Align = 0;
  2088. if (!ED->getTypeForDecl()->isIncompleteType()) {
  2089. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  2090. Align = getDeclAlignIfRequired(ED, CGM.getContext());
  2091. }
  2092. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  2093. // Create elements for each enumerator.
  2094. SmallVector<llvm::Metadata *, 16> Enumerators;
  2095. ED = ED->getDefinition();
  2096. for (const auto *Enum : ED->enumerators()) {
  2097. Enumerators.push_back(DBuilder.createEnumerator(
  2098. Enum->getName(), Enum->getInitVal().getSExtValue()));
  2099. }
  2100. // Return a CompositeType for the enum itself.
  2101. llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  2102. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  2103. unsigned Line = getLineNumber(ED->getLocation());
  2104. llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
  2105. llvm::DIType *ClassTy =
  2106. ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
  2107. return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
  2108. Line, Size, Align, EltArray, ClassTy,
  2109. FullName);
  2110. }
  2111. llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
  2112. unsigned MType, SourceLocation LineLoc,
  2113. StringRef Name, StringRef Value) {
  2114. unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
  2115. return DBuilder.createMacro(Parent, Line, MType, Name, Value);
  2116. }
  2117. llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
  2118. SourceLocation LineLoc,
  2119. SourceLocation FileLoc) {
  2120. llvm::DIFile *FName = getOrCreateFile(FileLoc);
  2121. unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
  2122. return DBuilder.createTempMacroFile(Parent, Line, FName);
  2123. }
  2124. static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
  2125. Qualifiers Quals;
  2126. do {
  2127. Qualifiers InnerQuals = T.getLocalQualifiers();
  2128. // Qualifiers::operator+() doesn't like it if you add a Qualifier
  2129. // that is already there.
  2130. Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
  2131. Quals += InnerQuals;
  2132. QualType LastT = T;
  2133. switch (T->getTypeClass()) {
  2134. default:
  2135. return C.getQualifiedType(T.getTypePtr(), Quals);
  2136. case Type::TemplateSpecialization: {
  2137. const auto *Spec = cast<TemplateSpecializationType>(T);
  2138. if (Spec->isTypeAlias())
  2139. return C.getQualifiedType(T.getTypePtr(), Quals);
  2140. T = Spec->desugar();
  2141. break;
  2142. }
  2143. case Type::TypeOfExpr:
  2144. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  2145. break;
  2146. case Type::TypeOf:
  2147. T = cast<TypeOfType>(T)->getUnderlyingType();
  2148. break;
  2149. case Type::Decltype:
  2150. T = cast<DecltypeType>(T)->getUnderlyingType();
  2151. break;
  2152. case Type::UnaryTransform:
  2153. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  2154. break;
  2155. case Type::Attributed:
  2156. T = cast<AttributedType>(T)->getEquivalentType();
  2157. break;
  2158. case Type::Elaborated:
  2159. T = cast<ElaboratedType>(T)->getNamedType();
  2160. break;
  2161. case Type::Paren:
  2162. T = cast<ParenType>(T)->getInnerType();
  2163. break;
  2164. case Type::SubstTemplateTypeParm:
  2165. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  2166. break;
  2167. case Type::Auto: {
  2168. QualType DT = cast<AutoType>(T)->getDeducedType();
  2169. assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
  2170. T = DT;
  2171. break;
  2172. }
  2173. case Type::Adjusted:
  2174. case Type::Decayed:
  2175. // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
  2176. T = cast<AdjustedType>(T)->getAdjustedType();
  2177. break;
  2178. }
  2179. assert(T != LastT && "Type unwrapping failed to unwrap!");
  2180. (void)LastT;
  2181. } while (true);
  2182. }
  2183. llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
  2184. // Unwrap the type as needed for debug information.
  2185. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  2186. auto it = TypeCache.find(Ty.getAsOpaquePtr());
  2187. if (it != TypeCache.end()) {
  2188. // Verify that the debug info still exists.
  2189. if (llvm::Metadata *V = it->second)
  2190. return cast<llvm::DIType>(V);
  2191. }
  2192. return nullptr;
  2193. }
  2194. void CGDebugInfo::completeTemplateDefinition(
  2195. const ClassTemplateSpecializationDecl &SD) {
  2196. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  2197. return;
  2198. completeClassData(&SD);
  2199. // In case this type has no member function definitions being emitted, ensure
  2200. // it is retained
  2201. RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
  2202. }
  2203. llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
  2204. if (Ty.isNull())
  2205. return nullptr;
  2206. // Unwrap the type as needed for debug information.
  2207. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  2208. if (auto *T = getTypeOrNull(Ty))
  2209. return T;
  2210. llvm::DIType *Res = CreateTypeNode(Ty, Unit);
  2211. void* TyPtr = Ty.getAsOpaquePtr();
  2212. // And update the type cache.
  2213. TypeCache[TyPtr].reset(Res);
  2214. return Res;
  2215. }
  2216. llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
  2217. // A forward declaration inside a module header does not belong to the module.
  2218. if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
  2219. return nullptr;
  2220. if (DebugTypeExtRefs && D->isFromASTFile()) {
  2221. // Record a reference to an imported clang module or precompiled header.
  2222. auto *Reader = CGM.getContext().getExternalSource();
  2223. auto Idx = D->getOwningModuleID();
  2224. auto Info = Reader->getSourceDescriptor(Idx);
  2225. if (Info)
  2226. return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
  2227. } else if (ClangModuleMap) {
  2228. // We are building a clang module or a precompiled header.
  2229. //
  2230. // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
  2231. // and it wouldn't be necessary to specify the parent scope
  2232. // because the type is already unique by definition (it would look
  2233. // like the output of -fno-standalone-debug). On the other hand,
  2234. // the parent scope helps a consumer to quickly locate the object
  2235. // file where the type's definition is located, so it might be
  2236. // best to make this behavior a command line or debugger tuning
  2237. // option.
  2238. FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
  2239. if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
  2240. // This is a (sub-)module.
  2241. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  2242. return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
  2243. } else {
  2244. // This the precompiled header being built.
  2245. return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
  2246. }
  2247. }
  2248. return nullptr;
  2249. }
  2250. llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
  2251. // Handle qualifiers, which recursively handles what they refer to.
  2252. if (Ty.hasLocalQualifiers())
  2253. return CreateQualifiedType(Ty, Unit);
  2254. // Work out details of type.
  2255. switch (Ty->getTypeClass()) {
  2256. #define TYPE(Class, Base)
  2257. #define ABSTRACT_TYPE(Class, Base)
  2258. #define NON_CANONICAL_TYPE(Class, Base)
  2259. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2260. #include "clang/AST/TypeNodes.def"
  2261. llvm_unreachable("Dependent types cannot show up in debug information");
  2262. case Type::ExtVector:
  2263. case Type::Vector:
  2264. return CreateType(cast<VectorType>(Ty), Unit);
  2265. case Type::ObjCObjectPointer:
  2266. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  2267. case Type::ObjCObject:
  2268. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  2269. case Type::ObjCTypeParam:
  2270. return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
  2271. case Type::ObjCInterface:
  2272. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  2273. case Type::Builtin:
  2274. return CreateType(cast<BuiltinType>(Ty));
  2275. case Type::Complex:
  2276. return CreateType(cast<ComplexType>(Ty));
  2277. case Type::Pointer:
  2278. return CreateType(cast<PointerType>(Ty), Unit);
  2279. case Type::BlockPointer:
  2280. return CreateType(cast<BlockPointerType>(Ty), Unit);
  2281. case Type::Typedef:
  2282. return CreateType(cast<TypedefType>(Ty), Unit);
  2283. case Type::Record:
  2284. return CreateType(cast<RecordType>(Ty));
  2285. case Type::Enum:
  2286. return CreateEnumType(cast<EnumType>(Ty));
  2287. case Type::FunctionProto:
  2288. case Type::FunctionNoProto:
  2289. return CreateType(cast<FunctionType>(Ty), Unit);
  2290. case Type::ConstantArray:
  2291. case Type::VariableArray:
  2292. case Type::IncompleteArray:
  2293. return CreateType(cast<ArrayType>(Ty), Unit);
  2294. case Type::LValueReference:
  2295. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  2296. case Type::RValueReference:
  2297. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  2298. case Type::MemberPointer:
  2299. return CreateType(cast<MemberPointerType>(Ty), Unit);
  2300. case Type::Atomic:
  2301. return CreateType(cast<AtomicType>(Ty), Unit);
  2302. case Type::Pipe:
  2303. return CreateType(cast<PipeType>(Ty), Unit);
  2304. case Type::TemplateSpecialization:
  2305. return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
  2306. case Type::Auto:
  2307. case Type::Attributed:
  2308. case Type::Adjusted:
  2309. case Type::Decayed:
  2310. case Type::DeducedTemplateSpecialization:
  2311. case Type::Elaborated:
  2312. case Type::Paren:
  2313. case Type::SubstTemplateTypeParm:
  2314. case Type::TypeOfExpr:
  2315. case Type::TypeOf:
  2316. case Type::Decltype:
  2317. case Type::UnaryTransform:
  2318. case Type::PackExpansion:
  2319. break;
  2320. }
  2321. llvm_unreachable("type should have been unwrapped!");
  2322. }
  2323. llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
  2324. llvm::DIFile *Unit) {
  2325. QualType QTy(Ty, 0);
  2326. auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
  2327. // We may have cached a forward decl when we could have created
  2328. // a non-forward decl. Go ahead and create a non-forward decl
  2329. // now.
  2330. if (T && !T->isForwardDecl())
  2331. return T;
  2332. // Otherwise create the type.
  2333. llvm::DICompositeType *Res = CreateLimitedType(Ty);
  2334. // Propagate members from the declaration to the definition
  2335. // CreateType(const RecordType*) will overwrite this with the members in the
  2336. // correct order if the full type is needed.
  2337. DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
  2338. // And update the type cache.
  2339. TypeCache[QTy.getAsOpaquePtr()].reset(Res);
  2340. return Res;
  2341. }
  2342. // TODO: Currently used for context chains when limiting debug info.
  2343. llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  2344. RecordDecl *RD = Ty->getDecl();
  2345. // Get overall information about the record type for the debug info.
  2346. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  2347. unsigned Line = getLineNumber(RD->getLocation());
  2348. StringRef RDName = getClassName(RD);
  2349. llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
  2350. // If we ended up creating the type during the context chain construction,
  2351. // just return that.
  2352. auto *T = cast_or_null<llvm::DICompositeType>(
  2353. getTypeOrNull(CGM.getContext().getRecordType(RD)));
  2354. if (T && (!T->isForwardDecl() || !RD->getDefinition()))
  2355. return T;
  2356. // If this is just a forward or incomplete declaration, construct an
  2357. // appropriately marked node and just return it.
  2358. const RecordDecl *D = RD->getDefinition();
  2359. if (!D || !D->isCompleteDefinition())
  2360. return getOrCreateRecordFwdDecl(Ty, RDContext);
  2361. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2362. auto Align = getDeclAlignIfRequired(D, CGM.getContext());
  2363. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  2364. llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
  2365. getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
  2366. llvm::DINode::FlagZero, FullName);
  2367. // Elements of composite types usually have back to the type, creating
  2368. // uniquing cycles. Distinct nodes are more efficient.
  2369. switch (RealDecl->getTag()) {
  2370. default:
  2371. llvm_unreachable("invalid composite type tag");
  2372. case llvm::dwarf::DW_TAG_array_type:
  2373. case llvm::dwarf::DW_TAG_enumeration_type:
  2374. // Array elements and most enumeration elements don't have back references,
  2375. // so they don't tend to be involved in uniquing cycles and there is some
  2376. // chance of merging them when linking together two modules. Only make
  2377. // them distinct if they are ODR-uniqued.
  2378. if (FullName.empty())
  2379. break;
  2380. case llvm::dwarf::DW_TAG_structure_type:
  2381. case llvm::dwarf::DW_TAG_union_type:
  2382. case llvm::dwarf::DW_TAG_class_type:
  2383. // Immediatley resolve to a distinct node.
  2384. RealDecl =
  2385. llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
  2386. break;
  2387. }
  2388. RegionMap[Ty->getDecl()].reset(RealDecl);
  2389. TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
  2390. if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  2391. DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
  2392. CollectCXXTemplateParams(TSpecial, DefUnit));
  2393. return RealDecl;
  2394. }
  2395. void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
  2396. llvm::DICompositeType *RealDecl) {
  2397. // A class's primary base or the class itself contains the vtable.
  2398. llvm::DICompositeType *ContainingType = nullptr;
  2399. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  2400. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  2401. // Seek non-virtual primary base root.
  2402. while (1) {
  2403. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  2404. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  2405. if (PBT && !BRL.isPrimaryBaseVirtual())
  2406. PBase = PBT;
  2407. else
  2408. break;
  2409. }
  2410. ContainingType = cast<llvm::DICompositeType>(
  2411. getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
  2412. getOrCreateFile(RD->getLocation())));
  2413. } else if (RD->isDynamicClass())
  2414. ContainingType = RealDecl;
  2415. DBuilder.replaceVTableHolder(RealDecl, ContainingType);
  2416. }
  2417. llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
  2418. StringRef Name, uint64_t *Offset) {
  2419. llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  2420. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  2421. auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
  2422. llvm::DIType *Ty =
  2423. DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
  2424. *Offset, llvm::DINode::FlagZero, FieldTy);
  2425. *Offset += FieldSize;
  2426. return Ty;
  2427. }
  2428. void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  2429. StringRef &Name,
  2430. StringRef &LinkageName,
  2431. llvm::DIScope *&FDContext,
  2432. llvm::DINodeArray &TParamsArray,
  2433. llvm::DINode::DIFlags &Flags) {
  2434. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2435. Name = getFunctionName(FD);
  2436. // Use mangled name as linkage name for C/C++ functions.
  2437. if (FD->hasPrototype()) {
  2438. LinkageName = CGM.getMangledName(GD);
  2439. Flags |= llvm::DINode::FlagPrototyped;
  2440. }
  2441. // No need to replicate the linkage name if it isn't different from the
  2442. // subprogram name, no need to have it at all unless coverage is enabled or
  2443. // debug is set to more than just line tables or extra debug info is needed.
  2444. if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
  2445. !CGM.getCodeGenOpts().EmitGcovNotes &&
  2446. !CGM.getCodeGenOpts().DebugInfoForProfiling &&
  2447. DebugKind <= codegenoptions::DebugLineTablesOnly))
  2448. LinkageName = StringRef();
  2449. if (DebugKind >= codegenoptions::LimitedDebugInfo) {
  2450. if (const NamespaceDecl *NSDecl =
  2451. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  2452. FDContext = getOrCreateNameSpace(NSDecl);
  2453. else if (const RecordDecl *RDecl =
  2454. dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
  2455. llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
  2456. FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
  2457. }
  2458. // Check if it is a noreturn-marked function
  2459. if (FD->isNoReturn())
  2460. Flags |= llvm::DINode::FlagNoReturn;
  2461. // Collect template parameters.
  2462. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  2463. }
  2464. }
  2465. void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  2466. unsigned &LineNo, QualType &T,
  2467. StringRef &Name, StringRef &LinkageName,
  2468. llvm::DIScope *&VDContext) {
  2469. Unit = getOrCreateFile(VD->getLocation());
  2470. LineNo = getLineNumber(VD->getLocation());
  2471. setLocation(VD->getLocation());
  2472. T = VD->getType();
  2473. if (T->isIncompleteArrayType()) {
  2474. // CodeGen turns int[] into int[1] so we'll do the same here.
  2475. llvm::APInt ConstVal(32, 1);
  2476. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2477. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2478. ArrayType::Normal, 0);
  2479. }
  2480. Name = VD->getName();
  2481. if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
  2482. !isa<ObjCMethodDecl>(VD->getDeclContext()))
  2483. LinkageName = CGM.getMangledName(VD);
  2484. if (LinkageName == Name)
  2485. LinkageName = StringRef();
  2486. // Since we emit declarations (DW_AT_members) for static members, place the
  2487. // definition of those static members in the namespace they were declared in
  2488. // in the source code (the lexical decl context).
  2489. // FIXME: Generalize this for even non-member global variables where the
  2490. // declaration and definition may have different lexical decl contexts, once
  2491. // we have support for emitting declarations of (non-member) global variables.
  2492. const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
  2493. : VD->getDeclContext();
  2494. // When a record type contains an in-line initialization of a static data
  2495. // member, and the record type is marked as __declspec(dllexport), an implicit
  2496. // definition of the member will be created in the record context. DWARF
  2497. // doesn't seem to have a nice way to describe this in a form that consumers
  2498. // are likely to understand, so fake the "normal" situation of a definition
  2499. // outside the class by putting it in the global scope.
  2500. if (DC->isRecord())
  2501. DC = CGM.getContext().getTranslationUnitDecl();
  2502. llvm::DIScope *Mod = getParentModuleOrNull(VD);
  2503. VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
  2504. }
  2505. llvm::DISubprogram *
  2506. CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
  2507. llvm::DINodeArray TParamsArray;
  2508. StringRef Name, LinkageName;
  2509. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2510. SourceLocation Loc = FD->getLocation();
  2511. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2512. llvm::DIScope *DContext = Unit;
  2513. unsigned Line = getLineNumber(Loc);
  2514. collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
  2515. TParamsArray, Flags);
  2516. // Build function type.
  2517. SmallVector<QualType, 16> ArgTypes;
  2518. for (const ParmVarDecl *Parm: FD->parameters())
  2519. ArgTypes.push_back(Parm->getType());
  2520. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  2521. QualType FnType = CGM.getContext().getFunctionType(
  2522. FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  2523. llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
  2524. DContext, Name, LinkageName, Unit, Line,
  2525. getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
  2526. /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
  2527. TParamsArray.get(), getFunctionDeclaration(FD));
  2528. const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
  2529. FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
  2530. std::make_tuple(CanonDecl),
  2531. std::make_tuple(SP));
  2532. return SP;
  2533. }
  2534. llvm::DIGlobalVariable *
  2535. CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
  2536. QualType T;
  2537. StringRef Name, LinkageName;
  2538. SourceLocation Loc = VD->getLocation();
  2539. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2540. llvm::DIScope *DContext = Unit;
  2541. unsigned Line = getLineNumber(Loc);
  2542. collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
  2543. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  2544. auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
  2545. DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
  2546. !VD->isExternallyVisible(), nullptr, Align);
  2547. FwdDeclReplaceMap.emplace_back(
  2548. std::piecewise_construct,
  2549. std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
  2550. std::make_tuple(static_cast<llvm::Metadata *>(GV)));
  2551. return GV;
  2552. }
  2553. llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
  2554. // We only need a declaration (not a definition) of the type - so use whatever
  2555. // we would otherwise do to get a type for a pointee. (forward declarations in
  2556. // limited debug info, full definitions (if the type definition is available)
  2557. // in unlimited debug info)
  2558. if (const auto *TD = dyn_cast<TypeDecl>(D))
  2559. return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
  2560. getOrCreateFile(TD->getLocation()));
  2561. auto I = DeclCache.find(D->getCanonicalDecl());
  2562. if (I != DeclCache.end()) {
  2563. auto N = I->second;
  2564. if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
  2565. return GVE->getVariable();
  2566. return dyn_cast_or_null<llvm::DINode>(N);
  2567. }
  2568. // No definition for now. Emit a forward definition that might be
  2569. // merged with a potential upcoming definition.
  2570. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  2571. return getFunctionForwardDeclaration(FD);
  2572. else if (const auto *VD = dyn_cast<VarDecl>(D))
  2573. return getGlobalVariableForwardDeclaration(VD);
  2574. return nullptr;
  2575. }
  2576. llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  2577. if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
  2578. return nullptr;
  2579. const auto *FD = dyn_cast<FunctionDecl>(D);
  2580. if (!FD)
  2581. return nullptr;
  2582. // Setup context.
  2583. auto *S = getDeclContextDescriptor(D);
  2584. auto MI = SPCache.find(FD->getCanonicalDecl());
  2585. if (MI == SPCache.end()) {
  2586. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
  2587. return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
  2588. cast<llvm::DICompositeType>(S));
  2589. }
  2590. }
  2591. if (MI != SPCache.end()) {
  2592. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2593. if (SP && !SP->isDefinition())
  2594. return SP;
  2595. }
  2596. for (auto NextFD : FD->redecls()) {
  2597. auto MI = SPCache.find(NextFD->getCanonicalDecl());
  2598. if (MI != SPCache.end()) {
  2599. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2600. if (SP && !SP->isDefinition())
  2601. return SP;
  2602. }
  2603. }
  2604. return nullptr;
  2605. }
  2606. // getOrCreateFunctionType - Construct type. If it is a c++ method, include
  2607. // implicit parameter "this".
  2608. llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
  2609. QualType FnType,
  2610. llvm::DIFile *F) {
  2611. if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
  2612. // Create fake but valid subroutine type. Otherwise -verify would fail, and
  2613. // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
  2614. return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
  2615. if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
  2616. return getOrCreateMethodType(Method, F);
  2617. const auto *FTy = FnType->getAs<FunctionType>();
  2618. CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
  2619. if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  2620. // Add "self" and "_cmd"
  2621. SmallVector<llvm::Metadata *, 16> Elts;
  2622. // First element is always return type. For 'void' functions it is NULL.
  2623. QualType ResultTy = OMethod->getReturnType();
  2624. // Replace the instancetype keyword with the actual type.
  2625. if (ResultTy == CGM.getContext().getObjCInstanceType())
  2626. ResultTy = CGM.getContext().getPointerType(
  2627. QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
  2628. Elts.push_back(getOrCreateType(ResultTy, F));
  2629. // "self" pointer is always first argument.
  2630. QualType SelfDeclTy;
  2631. if (auto *SelfDecl = OMethod->getSelfDecl())
  2632. SelfDeclTy = SelfDecl->getType();
  2633. else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  2634. if (FPT->getNumParams() > 1)
  2635. SelfDeclTy = FPT->getParamType(0);
  2636. if (!SelfDeclTy.isNull())
  2637. Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
  2638. // "_cmd" pointer is always second argument.
  2639. Elts.push_back(DBuilder.createArtificialType(
  2640. getOrCreateType(CGM.getContext().getObjCSelType(), F)));
  2641. // Get rest of the arguments.
  2642. for (const auto *PI : OMethod->parameters())
  2643. Elts.push_back(getOrCreateType(PI->getType(), F));
  2644. // Variadic methods need a special marker at the end of the type list.
  2645. if (OMethod->isVariadic())
  2646. Elts.push_back(DBuilder.createUnspecifiedParameter());
  2647. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  2648. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  2649. getDwarfCC(CC));
  2650. }
  2651. // Handle variadic function types; they need an additional
  2652. // unspecified parameter.
  2653. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  2654. if (FD->isVariadic()) {
  2655. SmallVector<llvm::Metadata *, 16> EltTys;
  2656. EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
  2657. if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  2658. for (QualType ParamType : FPT->param_types())
  2659. EltTys.push_back(getOrCreateType(ParamType, F));
  2660. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  2661. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  2662. return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
  2663. getDwarfCC(CC));
  2664. }
  2665. return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
  2666. }
  2667. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  2668. SourceLocation ScopeLoc, QualType FnType,
  2669. llvm::Function *Fn, CGBuilderTy &Builder) {
  2670. StringRef Name;
  2671. StringRef LinkageName;
  2672. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  2673. const Decl *D = GD.getDecl();
  2674. bool HasDecl = (D != nullptr);
  2675. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2676. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2677. llvm::DIScope *FDContext = Unit;
  2678. llvm::DINodeArray TParamsArray;
  2679. if (!HasDecl) {
  2680. // Use llvm function name.
  2681. LinkageName = Fn->getName();
  2682. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2683. // If there is a subprogram for this function available then use it.
  2684. auto FI = SPCache.find(FD->getCanonicalDecl());
  2685. if (FI != SPCache.end()) {
  2686. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  2687. if (SP && SP->isDefinition()) {
  2688. LexicalBlockStack.emplace_back(SP);
  2689. RegionMap[D].reset(SP);
  2690. return;
  2691. }
  2692. }
  2693. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2694. TParamsArray, Flags);
  2695. } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2696. Name = getObjCMethodName(OMD);
  2697. Flags |= llvm::DINode::FlagPrototyped;
  2698. } else {
  2699. // Use llvm function name.
  2700. Name = Fn->getName();
  2701. Flags |= llvm::DINode::FlagPrototyped;
  2702. }
  2703. if (Name.startswith("\01"))
  2704. Name = Name.substr(1);
  2705. if (!HasDecl || D->isImplicit()) {
  2706. Flags |= llvm::DINode::FlagArtificial;
  2707. // Artificial functions should not silently reuse CurLoc.
  2708. CurLoc = SourceLocation();
  2709. }
  2710. unsigned LineNo = getLineNumber(Loc);
  2711. unsigned ScopeLine = getLineNumber(ScopeLoc);
  2712. // FIXME: The function declaration we're constructing here is mostly reusing
  2713. // declarations from CXXMethodDecl and not constructing new ones for arbitrary
  2714. // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
  2715. // all subprograms instead of the actual context since subprogram definitions
  2716. // are emitted as CU level entities by the backend.
  2717. llvm::DISubprogram *SP = DBuilder.createFunction(
  2718. FDContext, Name, LinkageName, Unit, LineNo,
  2719. getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
  2720. true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2721. TParamsArray.get(), getFunctionDeclaration(D));
  2722. Fn->setSubprogram(SP);
  2723. // We might get here with a VarDecl in the case we're generating
  2724. // code for the initialization of globals. Do not record these decls
  2725. // as they will overwrite the actual VarDecl Decl in the cache.
  2726. if (HasDecl && isa<FunctionDecl>(D))
  2727. DeclCache[D->getCanonicalDecl()].reset(SP);
  2728. // Push the function onto the lexical block stack.
  2729. LexicalBlockStack.emplace_back(SP);
  2730. if (HasDecl)
  2731. RegionMap[D].reset(SP);
  2732. }
  2733. void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
  2734. QualType FnType) {
  2735. StringRef Name;
  2736. StringRef LinkageName;
  2737. const Decl *D = GD.getDecl();
  2738. if (!D)
  2739. return;
  2740. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2741. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2742. llvm::DIScope *FDContext = getDeclContextDescriptor(D);
  2743. llvm::DINodeArray TParamsArray;
  2744. if (isa<FunctionDecl>(D)) {
  2745. // If there is a DISubprogram for this function available then use it.
  2746. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2747. TParamsArray, Flags);
  2748. } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2749. Name = getObjCMethodName(OMD);
  2750. Flags |= llvm::DINode::FlagPrototyped;
  2751. } else {
  2752. llvm_unreachable("not a function or ObjC method");
  2753. }
  2754. if (!Name.empty() && Name[0] == '\01')
  2755. Name = Name.substr(1);
  2756. if (D->isImplicit()) {
  2757. Flags |= llvm::DINode::FlagArtificial;
  2758. // Artificial functions without a location should not silently reuse CurLoc.
  2759. if (Loc.isInvalid())
  2760. CurLoc = SourceLocation();
  2761. }
  2762. unsigned LineNo = getLineNumber(Loc);
  2763. unsigned ScopeLine = 0;
  2764. DBuilder.retainType(DBuilder.createFunction(
  2765. FDContext, Name, LinkageName, Unit, LineNo,
  2766. getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
  2767. false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2768. TParamsArray.get(), getFunctionDeclaration(D)));
  2769. }
  2770. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  2771. // Update our current location
  2772. setLocation(Loc);
  2773. if (CurLoc.isInvalid() || CurLoc.isMacroID())
  2774. return;
  2775. llvm::MDNode *Scope = LexicalBlockStack.back();
  2776. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2777. getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
  2778. }
  2779. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  2780. llvm::MDNode *Back = nullptr;
  2781. if (!LexicalBlockStack.empty())
  2782. Back = LexicalBlockStack.back().get();
  2783. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
  2784. cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
  2785. getColumnNumber(CurLoc)));
  2786. }
  2787. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
  2788. SourceLocation Loc) {
  2789. // Set our current location.
  2790. setLocation(Loc);
  2791. // Emit a line table change for the current location inside the new scope.
  2792. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2793. getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
  2794. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  2795. return;
  2796. // Create a new lexical block and push it on the stack.
  2797. CreateLexicalBlock(Loc);
  2798. }
  2799. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
  2800. SourceLocation Loc) {
  2801. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2802. // Provide an entry in the line table for the end of the block.
  2803. EmitLocation(Builder, Loc);
  2804. if (DebugKind <= codegenoptions::DebugLineTablesOnly)
  2805. return;
  2806. LexicalBlockStack.pop_back();
  2807. }
  2808. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
  2809. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2810. unsigned RCount = FnBeginRegionCount.back();
  2811. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  2812. // Pop all regions for this function.
  2813. while (LexicalBlockStack.size() != RCount) {
  2814. // Provide an entry in the line table for the end of the block.
  2815. EmitLocation(Builder, CurLoc);
  2816. LexicalBlockStack.pop_back();
  2817. }
  2818. FnBeginRegionCount.pop_back();
  2819. }
  2820. llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  2821. uint64_t *XOffset) {
  2822. SmallVector<llvm::Metadata *, 5> EltTys;
  2823. QualType FType;
  2824. uint64_t FieldSize, FieldOffset;
  2825. uint32_t FieldAlign;
  2826. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2827. QualType Type = VD->getType();
  2828. FieldOffset = 0;
  2829. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2830. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  2831. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  2832. FType = CGM.getContext().IntTy;
  2833. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  2834. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  2835. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
  2836. if (HasCopyAndDispose) {
  2837. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2838. EltTys.push_back(
  2839. CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
  2840. EltTys.push_back(
  2841. CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
  2842. }
  2843. bool HasByrefExtendedLayout;
  2844. Qualifiers::ObjCLifetime Lifetime;
  2845. if (CGM.getContext().getByrefLifetime(Type, Lifetime,
  2846. HasByrefExtendedLayout) &&
  2847. HasByrefExtendedLayout) {
  2848. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2849. EltTys.push_back(
  2850. CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
  2851. }
  2852. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2853. if (Align > CGM.getContext().toCharUnitsFromBits(
  2854. CGM.getTarget().getPointerAlign(0))) {
  2855. CharUnits FieldOffsetInBytes =
  2856. CGM.getContext().toCharUnitsFromBits(FieldOffset);
  2857. CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
  2858. CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
  2859. if (NumPaddingBytes.isPositive()) {
  2860. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  2861. FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
  2862. pad, ArrayType::Normal, 0);
  2863. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  2864. }
  2865. }
  2866. FType = Type;
  2867. llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
  2868. FieldSize = CGM.getContext().getTypeSize(FType);
  2869. FieldAlign = CGM.getContext().toBits(Align);
  2870. *XOffset = FieldOffset;
  2871. FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
  2872. FieldAlign, FieldOffset,
  2873. llvm::DINode::FlagZero, FieldTy);
  2874. EltTys.push_back(FieldTy);
  2875. FieldOffset += FieldSize;
  2876. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2877. llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct;
  2878. return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
  2879. nullptr, Elements);
  2880. }
  2881. void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
  2882. llvm::Optional<unsigned> ArgNo,
  2883. CGBuilderTy &Builder) {
  2884. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  2885. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2886. if (VD->hasAttr<NoDebugAttr>())
  2887. return;
  2888. bool Unwritten =
  2889. VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
  2890. cast<Decl>(VD->getDeclContext())->isImplicit());
  2891. llvm::DIFile *Unit = nullptr;
  2892. if (!Unwritten)
  2893. Unit = getOrCreateFile(VD->getLocation());
  2894. llvm::DIType *Ty;
  2895. uint64_t XOffset = 0;
  2896. if (VD->hasAttr<BlocksAttr>())
  2897. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2898. else
  2899. Ty = getOrCreateType(VD->getType(), Unit);
  2900. // If there is no debug info for this type then do not emit debug info
  2901. // for this variable.
  2902. if (!Ty)
  2903. return;
  2904. // Get location information.
  2905. unsigned Line = 0;
  2906. unsigned Column = 0;
  2907. if (!Unwritten) {
  2908. Line = getLineNumber(VD->getLocation());
  2909. Column = getColumnNumber(VD->getLocation());
  2910. }
  2911. SmallVector<int64_t, 9> Expr;
  2912. llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
  2913. if (VD->isImplicit())
  2914. Flags |= llvm::DINode::FlagArtificial;
  2915. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  2916. // If this is the first argument and it is implicit then
  2917. // give it an object pointer flag.
  2918. // FIXME: There has to be a better way to do this, but for static
  2919. // functions there won't be an implicit param at arg1 and
  2920. // otherwise it is 'self' or 'this'.
  2921. if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
  2922. Flags |= llvm::DINode::FlagObjectPointer;
  2923. if (auto *Arg = dyn_cast<llvm::Argument>(Storage))
  2924. if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
  2925. !VD->getType()->isPointerType())
  2926. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2927. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  2928. StringRef Name = VD->getName();
  2929. if (!Name.empty()) {
  2930. if (VD->hasAttr<BlocksAttr>()) {
  2931. CharUnits offset = CharUnits::fromQuantity(32);
  2932. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2933. // offset of __forwarding field
  2934. offset = CGM.getContext().toCharUnitsFromBits(
  2935. CGM.getTarget().getPointerWidth(0));
  2936. Expr.push_back(offset.getQuantity());
  2937. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2938. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2939. // offset of x field
  2940. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2941. Expr.push_back(offset.getQuantity());
  2942. // Create the descriptor for the variable.
  2943. auto *D = ArgNo
  2944. ? DBuilder.createParameterVariable(Scope, VD->getName(),
  2945. *ArgNo, Unit, Line, Ty)
  2946. : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
  2947. Line, Ty, Align);
  2948. // Insert an llvm.dbg.declare into the current block.
  2949. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2950. llvm::DebugLoc::get(Line, Column, Scope),
  2951. Builder.GetInsertBlock());
  2952. return;
  2953. } else if (isa<VariableArrayType>(VD->getType()))
  2954. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2955. } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
  2956. // If VD is an anonymous union then Storage represents value for
  2957. // all union fields.
  2958. const auto *RD = cast<RecordDecl>(RT->getDecl());
  2959. if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
  2960. // GDB has trouble finding local variables in anonymous unions, so we emit
  2961. // artifical local variables for each of the members.
  2962. //
  2963. // FIXME: Remove this code as soon as GDB supports this.
  2964. // The debug info verifier in LLVM operates based on the assumption that a
  2965. // variable has the same size as its storage and we had to disable the check
  2966. // for artificial variables.
  2967. for (const auto *Field : RD->fields()) {
  2968. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2969. StringRef FieldName = Field->getName();
  2970. // Ignore unnamed fields. Do not ignore unnamed records.
  2971. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  2972. continue;
  2973. // Use VarDecl's Tag, Scope and Line number.
  2974. auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
  2975. auto *D = DBuilder.createAutoVariable(
  2976. Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
  2977. Flags | llvm::DINode::FlagArtificial, FieldAlign);
  2978. // Insert an llvm.dbg.declare into the current block.
  2979. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2980. llvm::DebugLoc::get(Line, Column, Scope),
  2981. Builder.GetInsertBlock());
  2982. }
  2983. }
  2984. }
  2985. // Create the descriptor for the variable.
  2986. auto *D = ArgNo
  2987. ? DBuilder.createParameterVariable(
  2988. Scope, Name, *ArgNo, Unit, Line, Ty,
  2989. CGM.getLangOpts().Optimize, Flags)
  2990. : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
  2991. CGM.getLangOpts().Optimize, Flags,
  2992. Align);
  2993. // Insert an llvm.dbg.declare into the current block.
  2994. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2995. llvm::DebugLoc::get(Line, Column, Scope),
  2996. Builder.GetInsertBlock());
  2997. }
  2998. void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
  2999. llvm::Value *Storage,
  3000. CGBuilderTy &Builder) {
  3001. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3002. EmitDeclare(VD, Storage, llvm::None, Builder);
  3003. }
  3004. llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
  3005. llvm::DIType *Ty) {
  3006. llvm::DIType *CachedTy = getTypeOrNull(QualTy);
  3007. if (CachedTy)
  3008. Ty = CachedTy;
  3009. return DBuilder.createObjectPointerType(Ty);
  3010. }
  3011. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  3012. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  3013. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
  3014. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3015. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  3016. if (Builder.GetInsertBlock() == nullptr)
  3017. return;
  3018. if (VD->hasAttr<NoDebugAttr>())
  3019. return;
  3020. bool isByRef = VD->hasAttr<BlocksAttr>();
  3021. uint64_t XOffset = 0;
  3022. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  3023. llvm::DIType *Ty;
  3024. if (isByRef)
  3025. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  3026. else
  3027. Ty = getOrCreateType(VD->getType(), Unit);
  3028. // Self is passed along as an implicit non-arg variable in a
  3029. // block. Mark it as the object pointer.
  3030. if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
  3031. Ty = CreateSelfType(VD->getType(), Ty);
  3032. // Get location information.
  3033. unsigned Line = getLineNumber(VD->getLocation());
  3034. unsigned Column = getColumnNumber(VD->getLocation());
  3035. const llvm::DataLayout &target = CGM.getDataLayout();
  3036. CharUnits offset = CharUnits::fromQuantity(
  3037. target.getStructLayout(blockInfo.StructureType)
  3038. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  3039. SmallVector<int64_t, 9> addr;
  3040. if (isa<llvm::AllocaInst>(Storage))
  3041. addr.push_back(llvm::dwarf::DW_OP_deref);
  3042. addr.push_back(llvm::dwarf::DW_OP_plus);
  3043. addr.push_back(offset.getQuantity());
  3044. if (isByRef) {
  3045. addr.push_back(llvm::dwarf::DW_OP_deref);
  3046. addr.push_back(llvm::dwarf::DW_OP_plus);
  3047. // offset of __forwarding field
  3048. offset =
  3049. CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
  3050. addr.push_back(offset.getQuantity());
  3051. addr.push_back(llvm::dwarf::DW_OP_deref);
  3052. addr.push_back(llvm::dwarf::DW_OP_plus);
  3053. // offset of x field
  3054. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  3055. addr.push_back(offset.getQuantity());
  3056. }
  3057. // Create the descriptor for the variable.
  3058. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  3059. auto *D = DBuilder.createAutoVariable(
  3060. cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
  3061. Line, Ty, false, llvm::DINode::FlagZero, Align);
  3062. // Insert an llvm.dbg.declare into the current block.
  3063. auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
  3064. if (InsertPoint)
  3065. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  3066. InsertPoint);
  3067. else
  3068. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  3069. Builder.GetInsertBlock());
  3070. }
  3071. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  3072. unsigned ArgNo,
  3073. CGBuilderTy &Builder) {
  3074. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3075. EmitDeclare(VD, AI, ArgNo, Builder);
  3076. }
  3077. namespace {
  3078. struct BlockLayoutChunk {
  3079. uint64_t OffsetInBits;
  3080. const BlockDecl::Capture *Capture;
  3081. };
  3082. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  3083. return l.OffsetInBits < r.OffsetInBits;
  3084. }
  3085. }
  3086. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  3087. llvm::Value *Arg,
  3088. unsigned ArgNo,
  3089. llvm::Value *LocalAddr,
  3090. CGBuilderTy &Builder) {
  3091. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3092. ASTContext &C = CGM.getContext();
  3093. const BlockDecl *blockDecl = block.getBlockDecl();
  3094. // Collect some general information about the block's location.
  3095. SourceLocation loc = blockDecl->getCaretLocation();
  3096. llvm::DIFile *tunit = getOrCreateFile(loc);
  3097. unsigned line = getLineNumber(loc);
  3098. unsigned column = getColumnNumber(loc);
  3099. // Build the debug-info type for the block literal.
  3100. getDeclContextDescriptor(blockDecl);
  3101. const llvm::StructLayout *blockLayout =
  3102. CGM.getDataLayout().getStructLayout(block.StructureType);
  3103. SmallVector<llvm::Metadata *, 16> fields;
  3104. fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
  3105. blockLayout->getElementOffsetInBits(0),
  3106. tunit, tunit));
  3107. fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
  3108. blockLayout->getElementOffsetInBits(1),
  3109. tunit, tunit));
  3110. fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
  3111. blockLayout->getElementOffsetInBits(2),
  3112. tunit, tunit));
  3113. auto *FnTy = block.getBlockExpr()->getFunctionType();
  3114. auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
  3115. fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
  3116. blockLayout->getElementOffsetInBits(3),
  3117. tunit, tunit));
  3118. fields.push_back(createFieldType(
  3119. "__descriptor", C.getPointerType(block.NeedsCopyDispose
  3120. ? C.getBlockDescriptorExtendedType()
  3121. : C.getBlockDescriptorType()),
  3122. loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
  3123. // We want to sort the captures by offset, not because DWARF
  3124. // requires this, but because we're paranoid about debuggers.
  3125. SmallVector<BlockLayoutChunk, 8> chunks;
  3126. // 'this' capture.
  3127. if (blockDecl->capturesCXXThis()) {
  3128. BlockLayoutChunk chunk;
  3129. chunk.OffsetInBits =
  3130. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  3131. chunk.Capture = nullptr;
  3132. chunks.push_back(chunk);
  3133. }
  3134. // Variable captures.
  3135. for (const auto &capture : blockDecl->captures()) {
  3136. const VarDecl *variable = capture.getVariable();
  3137. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  3138. // Ignore constant captures.
  3139. if (captureInfo.isConstant())
  3140. continue;
  3141. BlockLayoutChunk chunk;
  3142. chunk.OffsetInBits =
  3143. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  3144. chunk.Capture = &capture;
  3145. chunks.push_back(chunk);
  3146. }
  3147. // Sort by offset.
  3148. llvm::array_pod_sort(chunks.begin(), chunks.end());
  3149. for (const BlockLayoutChunk &Chunk : chunks) {
  3150. uint64_t offsetInBits = Chunk.OffsetInBits;
  3151. const BlockDecl::Capture *capture = Chunk.Capture;
  3152. // If we have a null capture, this must be the C++ 'this' capture.
  3153. if (!capture) {
  3154. QualType type;
  3155. if (auto *Method =
  3156. cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
  3157. type = Method->getThisType(C);
  3158. else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
  3159. type = QualType(RDecl->getTypeForDecl(), 0);
  3160. else
  3161. llvm_unreachable("unexpected block declcontext");
  3162. fields.push_back(createFieldType("this", type, loc, AS_public,
  3163. offsetInBits, tunit, tunit));
  3164. continue;
  3165. }
  3166. const VarDecl *variable = capture->getVariable();
  3167. StringRef name = variable->getName();
  3168. llvm::DIType *fieldType;
  3169. if (capture->isByRef()) {
  3170. TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
  3171. auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
  3172. // FIXME: this creates a second copy of this type!
  3173. uint64_t xoffset;
  3174. fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
  3175. fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
  3176. fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
  3177. PtrInfo.Width, Align, offsetInBits,
  3178. llvm::DINode::FlagZero, fieldType);
  3179. } else {
  3180. auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
  3181. fieldType = createFieldType(name, variable->getType(), loc, AS_public,
  3182. offsetInBits, Align, tunit, tunit);
  3183. }
  3184. fields.push_back(fieldType);
  3185. }
  3186. SmallString<36> typeName;
  3187. llvm::raw_svector_ostream(typeName) << "__block_literal_"
  3188. << CGM.getUniqueBlockCount();
  3189. llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
  3190. llvm::DIType *type =
  3191. DBuilder.createStructType(tunit, typeName.str(), tunit, line,
  3192. CGM.getContext().toBits(block.BlockSize), 0,
  3193. llvm::DINode::FlagZero, nullptr, fieldsArray);
  3194. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  3195. // Get overall information about the block.
  3196. llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
  3197. auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
  3198. // Create the descriptor for the parameter.
  3199. auto *debugVar = DBuilder.createParameterVariable(
  3200. scope, Arg->getName(), ArgNo, tunit, line, type,
  3201. CGM.getLangOpts().Optimize, flags);
  3202. if (LocalAddr) {
  3203. // Insert an llvm.dbg.value into the current block.
  3204. DBuilder.insertDbgValueIntrinsic(
  3205. LocalAddr, 0, debugVar, DBuilder.createExpression(),
  3206. llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
  3207. }
  3208. // Insert an llvm.dbg.declare into the current block.
  3209. DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
  3210. llvm::DebugLoc::get(line, column, scope),
  3211. Builder.GetInsertBlock());
  3212. }
  3213. llvm::DIDerivedType *
  3214. CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
  3215. if (!D->isStaticDataMember())
  3216. return nullptr;
  3217. auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
  3218. if (MI != StaticDataMemberCache.end()) {
  3219. assert(MI->second && "Static data member declaration should still exist");
  3220. return MI->second;
  3221. }
  3222. // If the member wasn't found in the cache, lazily construct and add it to the
  3223. // type (used when a limited form of the type is emitted).
  3224. auto DC = D->getDeclContext();
  3225. auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
  3226. return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
  3227. }
  3228. llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
  3229. const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
  3230. StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
  3231. llvm::DIGlobalVariableExpression *GVE = nullptr;
  3232. for (const auto *Field : RD->fields()) {
  3233. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  3234. StringRef FieldName = Field->getName();
  3235. // Ignore unnamed fields, but recurse into anonymous records.
  3236. if (FieldName.empty()) {
  3237. if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
  3238. GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
  3239. Var, DContext);
  3240. continue;
  3241. }
  3242. // Use VarDecl's Tag, Scope and Line number.
  3243. GVE = DBuilder.createGlobalVariableExpression(
  3244. DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
  3245. Var->hasLocalLinkage());
  3246. Var->addDebugInfo(GVE);
  3247. }
  3248. return GVE;
  3249. }
  3250. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  3251. const VarDecl *D) {
  3252. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3253. if (D->hasAttr<NoDebugAttr>())
  3254. return;
  3255. // If we already created a DIGlobalVariable for this declaration, just attach
  3256. // it to the llvm::GlobalVariable.
  3257. auto Cached = DeclCache.find(D->getCanonicalDecl());
  3258. if (Cached != DeclCache.end())
  3259. return Var->addDebugInfo(
  3260. cast<llvm::DIGlobalVariableExpression>(Cached->second));
  3261. // Create global variable debug descriptor.
  3262. llvm::DIFile *Unit = nullptr;
  3263. llvm::DIScope *DContext = nullptr;
  3264. unsigned LineNo;
  3265. StringRef DeclName, LinkageName;
  3266. QualType T;
  3267. collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
  3268. // Attempt to store one global variable for the declaration - even if we
  3269. // emit a lot of fields.
  3270. llvm::DIGlobalVariableExpression *GVE = nullptr;
  3271. // If this is an anonymous union then we'll want to emit a global
  3272. // variable for each member of the anonymous union so that it's possible
  3273. // to find the name of any field in the union.
  3274. if (T->isUnionType() && DeclName.empty()) {
  3275. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  3276. assert(RD->isAnonymousStructOrUnion() &&
  3277. "unnamed non-anonymous struct or union?");
  3278. GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
  3279. } else {
  3280. auto Align = getDeclAlignIfRequired(D, CGM.getContext());
  3281. GVE = DBuilder.createGlobalVariableExpression(
  3282. DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
  3283. Var->hasLocalLinkage(), /*Expr=*/nullptr,
  3284. getOrCreateStaticDataMemberDeclarationOrNull(D), Align);
  3285. Var->addDebugInfo(GVE);
  3286. }
  3287. DeclCache[D->getCanonicalDecl()].reset(GVE);
  3288. }
  3289. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
  3290. assert(DebugKind >= codegenoptions::LimitedDebugInfo);
  3291. if (VD->hasAttr<NoDebugAttr>())
  3292. return;
  3293. auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
  3294. // Create the descriptor for the variable.
  3295. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  3296. StringRef Name = VD->getName();
  3297. llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
  3298. if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  3299. const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
  3300. assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
  3301. Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
  3302. }
  3303. // Do not use global variables for enums.
  3304. //
  3305. // FIXME: why not?
  3306. if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
  3307. return;
  3308. // Do not emit separate definitions for function local const/statics.
  3309. if (isa<FunctionDecl>(VD->getDeclContext()))
  3310. return;
  3311. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  3312. auto *VarD = cast<VarDecl>(VD);
  3313. if (VarD->isStaticDataMember()) {
  3314. auto *RD = cast<RecordDecl>(VarD->getDeclContext());
  3315. getDeclContextDescriptor(VarD);
  3316. // Ensure that the type is retained even though it's otherwise unreferenced.
  3317. //
  3318. // FIXME: This is probably unnecessary, since Ty should reference RD
  3319. // through its scope.
  3320. RetainedTypes.push_back(
  3321. CGM.getContext().getRecordType(RD).getAsOpaquePtr());
  3322. return;
  3323. }
  3324. llvm::DIScope *DContext = getDeclContextDescriptor(VD);
  3325. auto &GV = DeclCache[VD];
  3326. if (GV)
  3327. return;
  3328. llvm::DIExpression *InitExpr = nullptr;
  3329. if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
  3330. // FIXME: Add a representation for integer constants wider than 64 bits.
  3331. if (Init.isInt())
  3332. InitExpr =
  3333. DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
  3334. else if (Init.isFloat())
  3335. InitExpr = DBuilder.createConstantValueExpression(
  3336. Init.getFloat().bitcastToAPInt().getZExtValue());
  3337. }
  3338. GV.reset(DBuilder.createGlobalVariableExpression(
  3339. DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
  3340. true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
  3341. Align));
  3342. }
  3343. llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
  3344. if (!LexicalBlockStack.empty())
  3345. return LexicalBlockStack.back();
  3346. llvm::DIScope *Mod = getParentModuleOrNull(D);
  3347. return getContextDescriptor(D, Mod ? Mod : TheCU);
  3348. }
  3349. void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
  3350. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3351. return;
  3352. const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
  3353. if (!NSDecl->isAnonymousNamespace() ||
  3354. CGM.getCodeGenOpts().DebugExplicitImport) {
  3355. DBuilder.createImportedModule(
  3356. getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
  3357. getOrCreateNameSpace(NSDecl),
  3358. getLineNumber(UD.getLocation()));
  3359. }
  3360. }
  3361. void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
  3362. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3363. return;
  3364. assert(UD.shadow_size() &&
  3365. "We shouldn't be codegening an invalid UsingDecl containing no decls");
  3366. // Emitting one decl is sufficient - debuggers can detect that this is an
  3367. // overloaded name & provide lookup for all the overloads.
  3368. const UsingShadowDecl &USD = **UD.shadow_begin();
  3369. // FIXME: Skip functions with undeduced auto return type for now since we
  3370. // don't currently have the plumbing for separate declarations & definitions
  3371. // of free functions and mismatched types (auto in the declaration, concrete
  3372. // return type in the definition)
  3373. if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
  3374. if (const auto *AT =
  3375. FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
  3376. if (AT->getDeducedType().isNull())
  3377. return;
  3378. if (llvm::DINode *Target =
  3379. getDeclarationOrDefinition(USD.getUnderlyingDecl()))
  3380. DBuilder.createImportedDeclaration(
  3381. getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
  3382. getLineNumber(USD.getLocation()));
  3383. }
  3384. void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
  3385. if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
  3386. return;
  3387. if (Module *M = ID.getImportedModule()) {
  3388. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  3389. DBuilder.createImportedDeclaration(
  3390. getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
  3391. getOrCreateModuleRef(Info, DebugTypeExtRefs),
  3392. getLineNumber(ID.getLocation()));
  3393. }
  3394. }
  3395. llvm::DIImportedEntity *
  3396. CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
  3397. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3398. return nullptr;
  3399. auto &VH = NamespaceAliasCache[&NA];
  3400. if (VH)
  3401. return cast<llvm::DIImportedEntity>(VH);
  3402. llvm::DIImportedEntity *R;
  3403. if (const auto *Underlying =
  3404. dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
  3405. // This could cache & dedup here rather than relying on metadata deduping.
  3406. R = DBuilder.createImportedDeclaration(
  3407. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3408. EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
  3409. NA.getName());
  3410. else
  3411. R = DBuilder.createImportedDeclaration(
  3412. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3413. getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
  3414. getLineNumber(NA.getLocation()), NA.getName());
  3415. VH.reset(R);
  3416. return R;
  3417. }
  3418. llvm::DINamespace *
  3419. CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
  3420. NSDecl = NSDecl->getCanonicalDecl();
  3421. auto I = NameSpaceCache.find(NSDecl);
  3422. if (I != NameSpaceCache.end())
  3423. return cast<llvm::DINamespace>(I->second);
  3424. unsigned LineNo = getLineNumber(NSDecl->getLocation());
  3425. llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
  3426. llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
  3427. llvm::DINamespace *NS = DBuilder.createNameSpace(
  3428. Context, NSDecl->getName(), FileD, LineNo, NSDecl->isInline());
  3429. NameSpaceCache[NSDecl].reset(NS);
  3430. return NS;
  3431. }
  3432. void CGDebugInfo::setDwoId(uint64_t Signature) {
  3433. assert(TheCU && "no main compile unit");
  3434. TheCU->setDWOId(Signature);
  3435. }
  3436. void CGDebugInfo::finalize() {
  3437. // Creating types might create further types - invalidating the current
  3438. // element and the size(), so don't cache/reference them.
  3439. for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
  3440. ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
  3441. llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
  3442. ? CreateTypeDefinition(E.Type, E.Unit)
  3443. : E.Decl;
  3444. DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
  3445. }
  3446. for (auto p : ReplaceMap) {
  3447. assert(p.second);
  3448. auto *Ty = cast<llvm::DIType>(p.second);
  3449. assert(Ty->isForwardDecl());
  3450. auto it = TypeCache.find(p.first);
  3451. assert(it != TypeCache.end());
  3452. assert(it->second);
  3453. DBuilder.replaceTemporary(llvm::TempDIType(Ty),
  3454. cast<llvm::DIType>(it->second));
  3455. }
  3456. for (const auto &p : FwdDeclReplaceMap) {
  3457. assert(p.second);
  3458. llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
  3459. llvm::Metadata *Repl;
  3460. auto it = DeclCache.find(p.first);
  3461. // If there has been no definition for the declaration, call RAUW
  3462. // with ourselves, that will destroy the temporary MDNode and
  3463. // replace it with a standard one, avoiding leaking memory.
  3464. if (it == DeclCache.end())
  3465. Repl = p.second;
  3466. else
  3467. Repl = it->second;
  3468. if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
  3469. Repl = GVE->getVariable();
  3470. DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
  3471. }
  3472. // We keep our own list of retained types, because we need to look
  3473. // up the final type in the type cache.
  3474. for (auto &RT : RetainedTypes)
  3475. if (auto MD = TypeCache[RT])
  3476. DBuilder.retainType(cast<llvm::DIType>(MD));
  3477. DBuilder.finalize();
  3478. }
  3479. void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
  3480. if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
  3481. return;
  3482. if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
  3483. // Don't ignore in case of explicit cast where it is referenced indirectly.
  3484. DBuilder.retainType(DieTy);
  3485. }
  3486. llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
  3487. if (LexicalBlockStack.empty())
  3488. return llvm::DebugLoc();
  3489. llvm::MDNode *Scope = LexicalBlockStack.back();
  3490. return llvm::DebugLoc::get(
  3491. getLineNumber(Loc), getColumnNumber(Loc), Scope);
  3492. }