CGDebugInfo.cpp 135 KB

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