CGDebugInfo.cpp 152 KB

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