ASTReaderDecl.cpp 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613
  1. //===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the ASTReader::ReadDeclRecord method, which is the
  10. // entrypoint for loading a decl.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ASTCommon.h"
  14. #include "ASTReaderInternals.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclFriend.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclOpenMP.h"
  24. #include "clang/AST/DeclTemplate.h"
  25. #include "clang/AST/DeclVisitor.h"
  26. #include "clang/AST/DeclarationName.h"
  27. #include "clang/AST/Expr.h"
  28. #include "clang/AST/ExternalASTSource.h"
  29. #include "clang/AST/LambdaCapture.h"
  30. #include "clang/AST/NestedNameSpecifier.h"
  31. #include "clang/AST/OpenMPClause.h"
  32. #include "clang/AST/Redeclarable.h"
  33. #include "clang/AST/Stmt.h"
  34. #include "clang/AST/TemplateBase.h"
  35. #include "clang/AST/Type.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Basic/AttrKinds.h"
  38. #include "clang/Basic/ExceptionSpecificationType.h"
  39. #include "clang/Basic/IdentifierTable.h"
  40. #include "clang/Basic/LLVM.h"
  41. #include "clang/Basic/Lambda.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/Linkage.h"
  44. #include "clang/Basic/Module.h"
  45. #include "clang/Basic/PragmaKinds.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/Specifiers.h"
  48. #include "clang/Sema/IdentifierResolver.h"
  49. #include "clang/Serialization/ASTBitCodes.h"
  50. #include "clang/Serialization/ASTReader.h"
  51. #include "clang/Serialization/ContinuousRangeMap.h"
  52. #include "clang/Serialization/Module.h"
  53. #include "llvm/ADT/DenseMap.h"
  54. #include "llvm/ADT/FoldingSet.h"
  55. #include "llvm/ADT/STLExtras.h"
  56. #include "llvm/ADT/SmallPtrSet.h"
  57. #include "llvm/ADT/SmallVector.h"
  58. #include "llvm/ADT/iterator_range.h"
  59. #include "llvm/Bitstream/BitstreamReader.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/SaveAndRestore.h"
  63. #include <algorithm>
  64. #include <cassert>
  65. #include <cstdint>
  66. #include <cstring>
  67. #include <string>
  68. #include <utility>
  69. using namespace clang;
  70. using namespace serialization;
  71. //===----------------------------------------------------------------------===//
  72. // Declaration deserialization
  73. //===----------------------------------------------------------------------===//
  74. namespace clang {
  75. class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
  76. ASTReader &Reader;
  77. ASTRecordReader &Record;
  78. ASTReader::RecordLocation Loc;
  79. const DeclID ThisDeclID;
  80. const SourceLocation ThisDeclLoc;
  81. using RecordData = ASTReader::RecordData;
  82. TypeID DeferredTypeID = 0;
  83. unsigned AnonymousDeclNumber;
  84. GlobalDeclID NamedDeclForTagDecl = 0;
  85. IdentifierInfo *TypedefNameForLinkage = nullptr;
  86. bool HasPendingBody = false;
  87. ///A flag to carry the information for a decl from the entity is
  88. /// used. We use it to delay the marking of the canonical decl as used until
  89. /// the entire declaration is deserialized and merged.
  90. bool IsDeclMarkedUsed = false;
  91. uint64_t GetCurrentCursorOffset();
  92. uint64_t ReadLocalOffset() {
  93. uint64_t LocalOffset = Record.readInt();
  94. assert(LocalOffset < Loc.Offset && "offset point after current record");
  95. return LocalOffset ? Loc.Offset - LocalOffset : 0;
  96. }
  97. uint64_t ReadGlobalOffset() {
  98. uint64_t Local = ReadLocalOffset();
  99. return Local ? Record.getGlobalBitOffset(Local) : 0;
  100. }
  101. SourceLocation ReadSourceLocation() {
  102. return Record.readSourceLocation();
  103. }
  104. SourceRange ReadSourceRange() {
  105. return Record.readSourceRange();
  106. }
  107. TypeSourceInfo *GetTypeSourceInfo() {
  108. return Record.getTypeSourceInfo();
  109. }
  110. serialization::DeclID ReadDeclID() {
  111. return Record.readDeclID();
  112. }
  113. std::string ReadString() {
  114. return Record.readString();
  115. }
  116. void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
  117. for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
  118. IDs.push_back(ReadDeclID());
  119. }
  120. Decl *ReadDecl() {
  121. return Record.readDecl();
  122. }
  123. template<typename T>
  124. T *ReadDeclAs() {
  125. return Record.readDeclAs<T>();
  126. }
  127. void ReadQualifierInfo(QualifierInfo &Info) {
  128. Record.readQualifierInfo(Info);
  129. }
  130. void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
  131. Record.readDeclarationNameLoc(DNLoc, Name);
  132. }
  133. serialization::SubmoduleID readSubmoduleID() {
  134. if (Record.getIdx() == Record.size())
  135. return 0;
  136. return Record.getGlobalSubmoduleID(Record.readInt());
  137. }
  138. Module *readModule() {
  139. return Record.getSubmodule(readSubmoduleID());
  140. }
  141. void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
  142. void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
  143. const CXXRecordDecl *D);
  144. void MergeDefinitionData(CXXRecordDecl *D,
  145. struct CXXRecordDecl::DefinitionData &&NewDD);
  146. void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
  147. void MergeDefinitionData(ObjCInterfaceDecl *D,
  148. struct ObjCInterfaceDecl::DefinitionData &&NewDD);
  149. void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
  150. void MergeDefinitionData(ObjCProtocolDecl *D,
  151. struct ObjCProtocolDecl::DefinitionData &&NewDD);
  152. static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
  153. static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
  154. DeclContext *DC,
  155. unsigned Index);
  156. static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
  157. unsigned Index, NamedDecl *D);
  158. /// Results from loading a RedeclarableDecl.
  159. class RedeclarableResult {
  160. Decl *MergeWith;
  161. GlobalDeclID FirstID;
  162. bool IsKeyDecl;
  163. public:
  164. RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
  165. : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
  166. /// Retrieve the first ID.
  167. GlobalDeclID getFirstID() const { return FirstID; }
  168. /// Is this declaration a key declaration?
  169. bool isKeyDecl() const { return IsKeyDecl; }
  170. /// Get a known declaration that this should be merged with, if
  171. /// any.
  172. Decl *getKnownMergeTarget() const { return MergeWith; }
  173. };
  174. /// Class used to capture the result of searching for an existing
  175. /// declaration of a specific kind and name, along with the ability
  176. /// to update the place where this result was found (the declaration
  177. /// chain hanging off an identifier or the DeclContext we searched in)
  178. /// if requested.
  179. class FindExistingResult {
  180. ASTReader &Reader;
  181. NamedDecl *New = nullptr;
  182. NamedDecl *Existing = nullptr;
  183. bool AddResult = false;
  184. unsigned AnonymousDeclNumber = 0;
  185. IdentifierInfo *TypedefNameForLinkage = nullptr;
  186. public:
  187. FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
  188. FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
  189. unsigned AnonymousDeclNumber,
  190. IdentifierInfo *TypedefNameForLinkage)
  191. : Reader(Reader), New(New), Existing(Existing), AddResult(true),
  192. AnonymousDeclNumber(AnonymousDeclNumber),
  193. TypedefNameForLinkage(TypedefNameForLinkage) {}
  194. FindExistingResult(FindExistingResult &&Other)
  195. : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
  196. AddResult(Other.AddResult),
  197. AnonymousDeclNumber(Other.AnonymousDeclNumber),
  198. TypedefNameForLinkage(Other.TypedefNameForLinkage) {
  199. Other.AddResult = false;
  200. }
  201. FindExistingResult &operator=(FindExistingResult &&) = delete;
  202. ~FindExistingResult();
  203. /// Suppress the addition of this result into the known set of
  204. /// names.
  205. void suppress() { AddResult = false; }
  206. operator NamedDecl*() const { return Existing; }
  207. template<typename T>
  208. operator T*() const { return dyn_cast_or_null<T>(Existing); }
  209. };
  210. static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
  211. DeclContext *DC);
  212. FindExistingResult findExisting(NamedDecl *D);
  213. public:
  214. ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
  215. ASTReader::RecordLocation Loc,
  216. DeclID thisDeclID, SourceLocation ThisDeclLoc)
  217. : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
  218. ThisDeclLoc(ThisDeclLoc) {}
  219. template <typename T> static
  220. void AddLazySpecializations(T *D,
  221. SmallVectorImpl<serialization::DeclID>& IDs) {
  222. if (IDs.empty())
  223. return;
  224. // FIXME: We should avoid this pattern of getting the ASTContext.
  225. ASTContext &C = D->getASTContext();
  226. auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
  227. if (auto &Old = LazySpecializations) {
  228. IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
  229. llvm::sort(IDs);
  230. IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
  231. }
  232. auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
  233. *Result = IDs.size();
  234. std::copy(IDs.begin(), IDs.end(), Result + 1);
  235. LazySpecializations = Result;
  236. }
  237. template <typename DeclT>
  238. static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
  239. static Decl *getMostRecentDeclImpl(...);
  240. static Decl *getMostRecentDecl(Decl *D);
  241. template <typename DeclT>
  242. static void attachPreviousDeclImpl(ASTReader &Reader,
  243. Redeclarable<DeclT> *D, Decl *Previous,
  244. Decl *Canon);
  245. static void attachPreviousDeclImpl(ASTReader &Reader, ...);
  246. static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
  247. Decl *Canon);
  248. template <typename DeclT>
  249. static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
  250. static void attachLatestDeclImpl(...);
  251. static void attachLatestDecl(Decl *D, Decl *latest);
  252. template <typename DeclT>
  253. static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
  254. static void markIncompleteDeclChainImpl(...);
  255. /// Determine whether this declaration has a pending body.
  256. bool hasPendingBody() const { return HasPendingBody; }
  257. void ReadFunctionDefinition(FunctionDecl *FD);
  258. void Visit(Decl *D);
  259. void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
  260. static void setNextObjCCategory(ObjCCategoryDecl *Cat,
  261. ObjCCategoryDecl *Next) {
  262. Cat->NextClassCategory = Next;
  263. }
  264. void VisitDecl(Decl *D);
  265. void VisitPragmaCommentDecl(PragmaCommentDecl *D);
  266. void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
  267. void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
  268. void VisitNamedDecl(NamedDecl *ND);
  269. void VisitLabelDecl(LabelDecl *LD);
  270. void VisitNamespaceDecl(NamespaceDecl *D);
  271. void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
  272. void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
  273. void VisitTypeDecl(TypeDecl *TD);
  274. RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
  275. void VisitTypedefDecl(TypedefDecl *TD);
  276. void VisitTypeAliasDecl(TypeAliasDecl *TD);
  277. void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
  278. RedeclarableResult VisitTagDecl(TagDecl *TD);
  279. void VisitEnumDecl(EnumDecl *ED);
  280. RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
  281. void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
  282. RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
  283. void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
  284. RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
  285. ClassTemplateSpecializationDecl *D);
  286. void VisitClassTemplateSpecializationDecl(
  287. ClassTemplateSpecializationDecl *D) {
  288. VisitClassTemplateSpecializationDeclImpl(D);
  289. }
  290. void VisitClassTemplatePartialSpecializationDecl(
  291. ClassTemplatePartialSpecializationDecl *D);
  292. void VisitClassScopeFunctionSpecializationDecl(
  293. ClassScopeFunctionSpecializationDecl *D);
  294. RedeclarableResult
  295. VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
  296. void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
  297. VisitVarTemplateSpecializationDeclImpl(D);
  298. }
  299. void VisitVarTemplatePartialSpecializationDecl(
  300. VarTemplatePartialSpecializationDecl *D);
  301. void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
  302. void VisitValueDecl(ValueDecl *VD);
  303. void VisitEnumConstantDecl(EnumConstantDecl *ECD);
  304. void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
  305. void VisitDeclaratorDecl(DeclaratorDecl *DD);
  306. void VisitFunctionDecl(FunctionDecl *FD);
  307. void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
  308. void VisitCXXMethodDecl(CXXMethodDecl *D);
  309. void VisitCXXConstructorDecl(CXXConstructorDecl *D);
  310. void VisitCXXDestructorDecl(CXXDestructorDecl *D);
  311. void VisitCXXConversionDecl(CXXConversionDecl *D);
  312. void VisitFieldDecl(FieldDecl *FD);
  313. void VisitMSPropertyDecl(MSPropertyDecl *FD);
  314. void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
  315. RedeclarableResult VisitVarDeclImpl(VarDecl *D);
  316. void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
  317. void VisitImplicitParamDecl(ImplicitParamDecl *PD);
  318. void VisitParmVarDecl(ParmVarDecl *PD);
  319. void VisitDecompositionDecl(DecompositionDecl *DD);
  320. void VisitBindingDecl(BindingDecl *BD);
  321. void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
  322. DeclID VisitTemplateDecl(TemplateDecl *D);
  323. void VisitConceptDecl(ConceptDecl *D);
  324. RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
  325. void VisitClassTemplateDecl(ClassTemplateDecl *D);
  326. void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
  327. void VisitVarTemplateDecl(VarTemplateDecl *D);
  328. void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
  329. void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
  330. void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
  331. void VisitUsingDecl(UsingDecl *D);
  332. void VisitUsingPackDecl(UsingPackDecl *D);
  333. void VisitUsingShadowDecl(UsingShadowDecl *D);
  334. void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
  335. void VisitLinkageSpecDecl(LinkageSpecDecl *D);
  336. void VisitExportDecl(ExportDecl *D);
  337. void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
  338. void VisitImportDecl(ImportDecl *D);
  339. void VisitAccessSpecDecl(AccessSpecDecl *D);
  340. void VisitFriendDecl(FriendDecl *D);
  341. void VisitFriendTemplateDecl(FriendTemplateDecl *D);
  342. void VisitStaticAssertDecl(StaticAssertDecl *D);
  343. void VisitBlockDecl(BlockDecl *BD);
  344. void VisitCapturedDecl(CapturedDecl *CD);
  345. void VisitEmptyDecl(EmptyDecl *D);
  346. std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
  347. template<typename T>
  348. RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
  349. template<typename T>
  350. void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
  351. DeclID TemplatePatternID = 0);
  352. template<typename T>
  353. void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
  354. RedeclarableResult &Redecl,
  355. DeclID TemplatePatternID = 0);
  356. template<typename T>
  357. void mergeMergeable(Mergeable<T> *D);
  358. void mergeTemplatePattern(RedeclarableTemplateDecl *D,
  359. RedeclarableTemplateDecl *Existing,
  360. DeclID DsID, bool IsKeyDecl);
  361. ObjCTypeParamList *ReadObjCTypeParamList();
  362. // FIXME: Reorder according to DeclNodes.td?
  363. void VisitObjCMethodDecl(ObjCMethodDecl *D);
  364. void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
  365. void VisitObjCContainerDecl(ObjCContainerDecl *D);
  366. void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
  367. void VisitObjCIvarDecl(ObjCIvarDecl *D);
  368. void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
  369. void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
  370. void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
  371. void VisitObjCImplDecl(ObjCImplDecl *D);
  372. void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
  373. void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
  374. void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
  375. void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
  376. void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
  377. void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
  378. void VisitOMPAllocateDecl(OMPAllocateDecl *D);
  379. void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
  380. void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
  381. void VisitOMPRequiresDecl(OMPRequiresDecl *D);
  382. void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
  383. };
  384. } // namespace clang
  385. namespace {
  386. /// Iterator over the redeclarations of a declaration that have already
  387. /// been merged into the same redeclaration chain.
  388. template<typename DeclT>
  389. class MergedRedeclIterator {
  390. DeclT *Start;
  391. DeclT *Canonical = nullptr;
  392. DeclT *Current = nullptr;
  393. public:
  394. MergedRedeclIterator() = default;
  395. MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
  396. DeclT *operator*() { return Current; }
  397. MergedRedeclIterator &operator++() {
  398. if (Current->isFirstDecl()) {
  399. Canonical = Current;
  400. Current = Current->getMostRecentDecl();
  401. } else
  402. Current = Current->getPreviousDecl();
  403. // If we started in the merged portion, we'll reach our start position
  404. // eventually. Otherwise, we'll never reach it, but the second declaration
  405. // we reached was the canonical declaration, so stop when we see that one
  406. // again.
  407. if (Current == Start || Current == Canonical)
  408. Current = nullptr;
  409. return *this;
  410. }
  411. friend bool operator!=(const MergedRedeclIterator &A,
  412. const MergedRedeclIterator &B) {
  413. return A.Current != B.Current;
  414. }
  415. };
  416. } // namespace
  417. template <typename DeclT>
  418. static llvm::iterator_range<MergedRedeclIterator<DeclT>>
  419. merged_redecls(DeclT *D) {
  420. return llvm::make_range(MergedRedeclIterator<DeclT>(D),
  421. MergedRedeclIterator<DeclT>());
  422. }
  423. uint64_t ASTDeclReader::GetCurrentCursorOffset() {
  424. return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
  425. }
  426. void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
  427. if (Record.readInt())
  428. Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
  429. if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  430. CD->setNumCtorInitializers(Record.readInt());
  431. if (CD->getNumCtorInitializers())
  432. CD->CtorInitializers = ReadGlobalOffset();
  433. }
  434. // Store the offset of the body so we can lazily load it later.
  435. Reader.PendingBodies[FD] = GetCurrentCursorOffset();
  436. HasPendingBody = true;
  437. }
  438. void ASTDeclReader::Visit(Decl *D) {
  439. DeclVisitor<ASTDeclReader, void>::Visit(D);
  440. // At this point we have deserialized and merged the decl and it is safe to
  441. // update its canonical decl to signal that the entire entity is used.
  442. D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
  443. IsDeclMarkedUsed = false;
  444. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  445. if (auto *TInfo = DD->getTypeSourceInfo())
  446. Record.readTypeLoc(TInfo->getTypeLoc());
  447. }
  448. if (auto *TD = dyn_cast<TypeDecl>(D)) {
  449. // We have a fully initialized TypeDecl. Read its type now.
  450. TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
  451. // If this is a tag declaration with a typedef name for linkage, it's safe
  452. // to load that typedef now.
  453. if (NamedDeclForTagDecl)
  454. cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
  455. cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
  456. } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  457. // if we have a fully initialized TypeDecl, we can safely read its type now.
  458. ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
  459. } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  460. // FunctionDecl's body was written last after all other Stmts/Exprs.
  461. // We only read it if FD doesn't already have a body (e.g., from another
  462. // module).
  463. // FIXME: Can we diagnose ODR violations somehow?
  464. if (Record.readInt())
  465. ReadFunctionDefinition(FD);
  466. }
  467. }
  468. void ASTDeclReader::VisitDecl(Decl *D) {
  469. if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
  470. isa<ParmVarDecl>(D)) {
  471. // We don't want to deserialize the DeclContext of a template
  472. // parameter or of a parameter of a function template immediately. These
  473. // entities might be used in the formulation of its DeclContext (for
  474. // example, a function parameter can be used in decltype() in trailing
  475. // return type of the function). Use the translation unit DeclContext as a
  476. // placeholder.
  477. GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID();
  478. GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID();
  479. if (!LexicalDCIDForTemplateParmDecl)
  480. LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
  481. Reader.addPendingDeclContextInfo(D,
  482. SemaDCIDForTemplateParmDecl,
  483. LexicalDCIDForTemplateParmDecl);
  484. D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
  485. } else {
  486. auto *SemaDC = ReadDeclAs<DeclContext>();
  487. auto *LexicalDC = ReadDeclAs<DeclContext>();
  488. if (!LexicalDC)
  489. LexicalDC = SemaDC;
  490. DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
  491. // Avoid calling setLexicalDeclContext() directly because it uses
  492. // Decl::getASTContext() internally which is unsafe during derialization.
  493. D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
  494. Reader.getContext());
  495. }
  496. D->setLocation(ThisDeclLoc);
  497. D->setInvalidDecl(Record.readInt());
  498. if (Record.readInt()) { // hasAttrs
  499. AttrVec Attrs;
  500. Record.readAttributes(Attrs);
  501. // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
  502. // internally which is unsafe during derialization.
  503. D->setAttrsImpl(Attrs, Reader.getContext());
  504. }
  505. D->setImplicit(Record.readInt());
  506. D->Used = Record.readInt();
  507. IsDeclMarkedUsed |= D->Used;
  508. D->setReferenced(Record.readInt());
  509. D->setTopLevelDeclInObjCContainer(Record.readInt());
  510. D->setAccess((AccessSpecifier)Record.readInt());
  511. D->FromASTFile = true;
  512. bool ModulePrivate = Record.readInt();
  513. // Determine whether this declaration is part of a (sub)module. If so, it
  514. // may not yet be visible.
  515. if (unsigned SubmoduleID = readSubmoduleID()) {
  516. // Store the owning submodule ID in the declaration.
  517. D->setModuleOwnershipKind(
  518. ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
  519. : Decl::ModuleOwnershipKind::VisibleWhenImported);
  520. D->setOwningModuleID(SubmoduleID);
  521. if (ModulePrivate) {
  522. // Module-private declarations are never visible, so there is no work to
  523. // do.
  524. } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
  525. // If local visibility is being tracked, this declaration will become
  526. // hidden and visible as the owning module does.
  527. } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
  528. // Mark the declaration as visible when its owning module becomes visible.
  529. if (Owner->NameVisibility == Module::AllVisible)
  530. D->setVisibleDespiteOwningModule();
  531. else
  532. Reader.HiddenNamesMap[Owner].push_back(D);
  533. }
  534. } else if (ModulePrivate) {
  535. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  536. }
  537. }
  538. void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
  539. VisitDecl(D);
  540. D->setLocation(ReadSourceLocation());
  541. D->CommentKind = (PragmaMSCommentKind)Record.readInt();
  542. std::string Arg = ReadString();
  543. memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
  544. D->getTrailingObjects<char>()[Arg.size()] = '\0';
  545. }
  546. void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
  547. VisitDecl(D);
  548. D->setLocation(ReadSourceLocation());
  549. std::string Name = ReadString();
  550. memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
  551. D->getTrailingObjects<char>()[Name.size()] = '\0';
  552. D->ValueStart = Name.size() + 1;
  553. std::string Value = ReadString();
  554. memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
  555. Value.size());
  556. D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
  557. }
  558. void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
  559. llvm_unreachable("Translation units are not serialized");
  560. }
  561. void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
  562. VisitDecl(ND);
  563. ND->setDeclName(Record.readDeclarationName());
  564. AnonymousDeclNumber = Record.readInt();
  565. }
  566. void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
  567. VisitNamedDecl(TD);
  568. TD->setLocStart(ReadSourceLocation());
  569. // Delay type reading until after we have fully initialized the decl.
  570. DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
  571. }
  572. ASTDeclReader::RedeclarableResult
  573. ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
  574. RedeclarableResult Redecl = VisitRedeclarable(TD);
  575. VisitTypeDecl(TD);
  576. TypeSourceInfo *TInfo = GetTypeSourceInfo();
  577. if (Record.readInt()) { // isModed
  578. QualType modedT = Record.readType();
  579. TD->setModedTypeSourceInfo(TInfo, modedT);
  580. } else
  581. TD->setTypeSourceInfo(TInfo);
  582. // Read and discard the declaration for which this is a typedef name for
  583. // linkage, if it exists. We cannot rely on our type to pull in this decl,
  584. // because it might have been merged with a type from another module and
  585. // thus might not refer to our version of the declaration.
  586. ReadDecl();
  587. return Redecl;
  588. }
  589. void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
  590. RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
  591. mergeRedeclarable(TD, Redecl);
  592. }
  593. void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
  594. RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
  595. if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>())
  596. // Merged when we merge the template.
  597. TD->setDescribedAliasTemplate(Template);
  598. else
  599. mergeRedeclarable(TD, Redecl);
  600. }
  601. ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
  602. RedeclarableResult Redecl = VisitRedeclarable(TD);
  603. VisitTypeDecl(TD);
  604. TD->IdentifierNamespace = Record.readInt();
  605. TD->setTagKind((TagDecl::TagKind)Record.readInt());
  606. if (!isa<CXXRecordDecl>(TD))
  607. TD->setCompleteDefinition(Record.readInt());
  608. TD->setEmbeddedInDeclarator(Record.readInt());
  609. TD->setFreeStanding(Record.readInt());
  610. TD->setCompleteDefinitionRequired(Record.readInt());
  611. TD->setBraceRange(ReadSourceRange());
  612. switch (Record.readInt()) {
  613. case 0:
  614. break;
  615. case 1: { // ExtInfo
  616. auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
  617. ReadQualifierInfo(*Info);
  618. TD->TypedefNameDeclOrQualifier = Info;
  619. break;
  620. }
  621. case 2: // TypedefNameForAnonDecl
  622. NamedDeclForTagDecl = ReadDeclID();
  623. TypedefNameForLinkage = Record.getIdentifierInfo();
  624. break;
  625. default:
  626. llvm_unreachable("unexpected tag info kind");
  627. }
  628. if (!isa<CXXRecordDecl>(TD))
  629. mergeRedeclarable(TD, Redecl);
  630. return Redecl;
  631. }
  632. void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
  633. VisitTagDecl(ED);
  634. if (TypeSourceInfo *TI = GetTypeSourceInfo())
  635. ED->setIntegerTypeSourceInfo(TI);
  636. else
  637. ED->setIntegerType(Record.readType());
  638. ED->setPromotionType(Record.readType());
  639. ED->setNumPositiveBits(Record.readInt());
  640. ED->setNumNegativeBits(Record.readInt());
  641. ED->setScoped(Record.readInt());
  642. ED->setScopedUsingClassTag(Record.readInt());
  643. ED->setFixed(Record.readInt());
  644. ED->setHasODRHash(true);
  645. ED->ODRHash = Record.readInt();
  646. // If this is a definition subject to the ODR, and we already have a
  647. // definition, merge this one into it.
  648. if (ED->isCompleteDefinition() &&
  649. Reader.getContext().getLangOpts().Modules &&
  650. Reader.getContext().getLangOpts().CPlusPlus) {
  651. EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
  652. if (!OldDef) {
  653. // This is the first time we've seen an imported definition. Look for a
  654. // local definition before deciding that we are the first definition.
  655. for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
  656. if (!D->isFromASTFile() && D->isCompleteDefinition()) {
  657. OldDef = D;
  658. break;
  659. }
  660. }
  661. }
  662. if (OldDef) {
  663. Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
  664. ED->setCompleteDefinition(false);
  665. Reader.mergeDefinitionVisibility(OldDef, ED);
  666. if (OldDef->getODRHash() != ED->getODRHash())
  667. Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
  668. } else {
  669. OldDef = ED;
  670. }
  671. }
  672. if (auto *InstED = ReadDeclAs<EnumDecl>()) {
  673. auto TSK = (TemplateSpecializationKind)Record.readInt();
  674. SourceLocation POI = ReadSourceLocation();
  675. ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
  676. ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  677. }
  678. }
  679. ASTDeclReader::RedeclarableResult
  680. ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
  681. RedeclarableResult Redecl = VisitTagDecl(RD);
  682. RD->setHasFlexibleArrayMember(Record.readInt());
  683. RD->setAnonymousStructOrUnion(Record.readInt());
  684. RD->setHasObjectMember(Record.readInt());
  685. RD->setHasVolatileMember(Record.readInt());
  686. RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
  687. RD->setNonTrivialToPrimitiveCopy(Record.readInt());
  688. RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
  689. RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
  690. RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
  691. RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
  692. RD->setParamDestroyedInCallee(Record.readInt());
  693. RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
  694. return Redecl;
  695. }
  696. void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
  697. VisitNamedDecl(VD);
  698. // For function declarations, defer reading the type in case the function has
  699. // a deduced return type that references an entity declared within the
  700. // function.
  701. if (isa<FunctionDecl>(VD))
  702. DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
  703. else
  704. VD->setType(Record.readType());
  705. }
  706. void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
  707. VisitValueDecl(ECD);
  708. if (Record.readInt())
  709. ECD->setInitExpr(Record.readExpr());
  710. ECD->setInitVal(Record.readAPSInt());
  711. mergeMergeable(ECD);
  712. }
  713. void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
  714. VisitValueDecl(DD);
  715. DD->setInnerLocStart(ReadSourceLocation());
  716. if (Record.readInt()) { // hasExtInfo
  717. auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
  718. ReadQualifierInfo(*Info);
  719. DD->DeclInfo = Info;
  720. }
  721. QualType TSIType = Record.readType();
  722. DD->setTypeSourceInfo(
  723. TSIType.isNull() ? nullptr
  724. : Reader.getContext().CreateTypeSourceInfo(TSIType));
  725. }
  726. void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
  727. RedeclarableResult Redecl = VisitRedeclarable(FD);
  728. VisitDeclaratorDecl(FD);
  729. // Attach a type to this function. Use the real type if possible, but fall
  730. // back to the type as written if it involves a deduced return type.
  731. if (FD->getTypeSourceInfo() &&
  732. FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  733. ->getReturnType()->getContainedAutoType()) {
  734. // We'll set up the real type in Visit, once we've finished loading the
  735. // function.
  736. FD->setType(FD->getTypeSourceInfo()->getType());
  737. Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
  738. } else {
  739. FD->setType(Reader.GetType(DeferredTypeID));
  740. }
  741. DeferredTypeID = 0;
  742. ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName());
  743. FD->IdentifierNamespace = Record.readInt();
  744. // FunctionDecl's body is handled last at ASTDeclReader::Visit,
  745. // after everything else is read.
  746. FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
  747. FD->setInlineSpecified(Record.readInt());
  748. FD->setImplicitlyInline(Record.readInt());
  749. FD->setVirtualAsWritten(Record.readInt());
  750. FD->setPure(Record.readInt());
  751. FD->setHasInheritedPrototype(Record.readInt());
  752. FD->setHasWrittenPrototype(Record.readInt());
  753. FD->setDeletedAsWritten(Record.readInt());
  754. FD->setTrivial(Record.readInt());
  755. FD->setTrivialForCall(Record.readInt());
  756. FD->setDefaulted(Record.readInt());
  757. FD->setExplicitlyDefaulted(Record.readInt());
  758. FD->setHasImplicitReturnZero(Record.readInt());
  759. FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
  760. FD->setUsesSEHTry(Record.readInt());
  761. FD->setHasSkippedBody(Record.readInt());
  762. FD->setIsMultiVersion(Record.readInt());
  763. FD->setLateTemplateParsed(Record.readInt());
  764. FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
  765. FD->EndRangeLoc = ReadSourceLocation();
  766. FD->ODRHash = Record.readInt();
  767. FD->setHasODRHash(true);
  768. switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
  769. case FunctionDecl::TK_NonTemplate:
  770. mergeRedeclarable(FD, Redecl);
  771. break;
  772. case FunctionDecl::TK_FunctionTemplate:
  773. // Merged when we merge the template.
  774. FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>());
  775. break;
  776. case FunctionDecl::TK_MemberSpecialization: {
  777. auto *InstFD = ReadDeclAs<FunctionDecl>();
  778. auto TSK = (TemplateSpecializationKind)Record.readInt();
  779. SourceLocation POI = ReadSourceLocation();
  780. FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
  781. FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  782. mergeRedeclarable(FD, Redecl);
  783. break;
  784. }
  785. case FunctionDecl::TK_FunctionTemplateSpecialization: {
  786. auto *Template = ReadDeclAs<FunctionTemplateDecl>();
  787. auto TSK = (TemplateSpecializationKind)Record.readInt();
  788. // Template arguments.
  789. SmallVector<TemplateArgument, 8> TemplArgs;
  790. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  791. // Template args as written.
  792. SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
  793. SourceLocation LAngleLoc, RAngleLoc;
  794. bool HasTemplateArgumentsAsWritten = Record.readInt();
  795. if (HasTemplateArgumentsAsWritten) {
  796. unsigned NumTemplateArgLocs = Record.readInt();
  797. TemplArgLocs.reserve(NumTemplateArgLocs);
  798. for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
  799. TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
  800. LAngleLoc = ReadSourceLocation();
  801. RAngleLoc = ReadSourceLocation();
  802. }
  803. SourceLocation POI = ReadSourceLocation();
  804. ASTContext &C = Reader.getContext();
  805. TemplateArgumentList *TemplArgList
  806. = TemplateArgumentList::CreateCopy(C, TemplArgs);
  807. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  808. for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
  809. TemplArgsInfo.addArgument(TemplArgLocs[i]);
  810. MemberSpecializationInfo *MSInfo = nullptr;
  811. if (Record.readInt()) {
  812. auto *FD = ReadDeclAs<FunctionDecl>();
  813. auto TSK = (TemplateSpecializationKind)Record.readInt();
  814. SourceLocation POI = ReadSourceLocation();
  815. MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
  816. MSInfo->setPointOfInstantiation(POI);
  817. }
  818. FunctionTemplateSpecializationInfo *FTInfo =
  819. FunctionTemplateSpecializationInfo::Create(
  820. C, FD, Template, TSK, TemplArgList,
  821. HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
  822. MSInfo);
  823. FD->TemplateOrSpecialization = FTInfo;
  824. if (FD->isCanonicalDecl()) { // if canonical add to template's set.
  825. // The template that contains the specializations set. It's not safe to
  826. // use getCanonicalDecl on Template since it may still be initializing.
  827. auto *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>();
  828. // Get the InsertPos by FindNodeOrInsertPos() instead of calling
  829. // InsertNode(FTInfo) directly to avoid the getASTContext() call in
  830. // FunctionTemplateSpecializationInfo's Profile().
  831. // We avoid getASTContext because a decl in the parent hierarchy may
  832. // be initializing.
  833. llvm::FoldingSetNodeID ID;
  834. FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
  835. void *InsertPos = nullptr;
  836. FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
  837. FunctionTemplateSpecializationInfo *ExistingInfo =
  838. CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
  839. if (InsertPos)
  840. CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
  841. else {
  842. assert(Reader.getContext().getLangOpts().Modules &&
  843. "already deserialized this template specialization");
  844. mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
  845. }
  846. }
  847. break;
  848. }
  849. case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
  850. // Templates.
  851. UnresolvedSet<8> TemplDecls;
  852. unsigned NumTemplates = Record.readInt();
  853. while (NumTemplates--)
  854. TemplDecls.addDecl(ReadDeclAs<NamedDecl>());
  855. // Templates args.
  856. TemplateArgumentListInfo TemplArgs;
  857. unsigned NumArgs = Record.readInt();
  858. while (NumArgs--)
  859. TemplArgs.addArgument(Record.readTemplateArgumentLoc());
  860. TemplArgs.setLAngleLoc(ReadSourceLocation());
  861. TemplArgs.setRAngleLoc(ReadSourceLocation());
  862. FD->setDependentTemplateSpecialization(Reader.getContext(),
  863. TemplDecls, TemplArgs);
  864. // These are not merged; we don't need to merge redeclarations of dependent
  865. // template friends.
  866. break;
  867. }
  868. }
  869. // Read in the parameters.
  870. unsigned NumParams = Record.readInt();
  871. SmallVector<ParmVarDecl *, 16> Params;
  872. Params.reserve(NumParams);
  873. for (unsigned I = 0; I != NumParams; ++I)
  874. Params.push_back(ReadDeclAs<ParmVarDecl>());
  875. FD->setParams(Reader.getContext(), Params);
  876. }
  877. void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
  878. VisitNamedDecl(MD);
  879. if (Record.readInt()) {
  880. // Load the body on-demand. Most clients won't care, because method
  881. // definitions rarely show up in headers.
  882. Reader.PendingBodies[MD] = GetCurrentCursorOffset();
  883. HasPendingBody = true;
  884. MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>());
  885. MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>());
  886. }
  887. MD->setInstanceMethod(Record.readInt());
  888. MD->setVariadic(Record.readInt());
  889. MD->setPropertyAccessor(Record.readInt());
  890. MD->setDefined(Record.readInt());
  891. MD->setOverriding(Record.readInt());
  892. MD->setHasSkippedBody(Record.readInt());
  893. MD->setIsRedeclaration(Record.readInt());
  894. MD->setHasRedeclaration(Record.readInt());
  895. if (MD->hasRedeclaration())
  896. Reader.getContext().setObjCMethodRedeclaration(MD,
  897. ReadDeclAs<ObjCMethodDecl>());
  898. MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
  899. MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
  900. MD->setRelatedResultType(Record.readInt());
  901. MD->setReturnType(Record.readType());
  902. MD->setReturnTypeSourceInfo(GetTypeSourceInfo());
  903. MD->DeclEndLoc = ReadSourceLocation();
  904. unsigned NumParams = Record.readInt();
  905. SmallVector<ParmVarDecl *, 16> Params;
  906. Params.reserve(NumParams);
  907. for (unsigned I = 0; I != NumParams; ++I)
  908. Params.push_back(ReadDeclAs<ParmVarDecl>());
  909. MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
  910. unsigned NumStoredSelLocs = Record.readInt();
  911. SmallVector<SourceLocation, 16> SelLocs;
  912. SelLocs.reserve(NumStoredSelLocs);
  913. for (unsigned i = 0; i != NumStoredSelLocs; ++i)
  914. SelLocs.push_back(ReadSourceLocation());
  915. MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
  916. }
  917. void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
  918. VisitTypedefNameDecl(D);
  919. D->Variance = Record.readInt();
  920. D->Index = Record.readInt();
  921. D->VarianceLoc = ReadSourceLocation();
  922. D->ColonLoc = ReadSourceLocation();
  923. }
  924. void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
  925. VisitNamedDecl(CD);
  926. CD->setAtStartLoc(ReadSourceLocation());
  927. CD->setAtEndRange(ReadSourceRange());
  928. }
  929. ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
  930. unsigned numParams = Record.readInt();
  931. if (numParams == 0)
  932. return nullptr;
  933. SmallVector<ObjCTypeParamDecl *, 4> typeParams;
  934. typeParams.reserve(numParams);
  935. for (unsigned i = 0; i != numParams; ++i) {
  936. auto *typeParam = ReadDeclAs<ObjCTypeParamDecl>();
  937. if (!typeParam)
  938. return nullptr;
  939. typeParams.push_back(typeParam);
  940. }
  941. SourceLocation lAngleLoc = ReadSourceLocation();
  942. SourceLocation rAngleLoc = ReadSourceLocation();
  943. return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
  944. typeParams, rAngleLoc);
  945. }
  946. void ASTDeclReader::ReadObjCDefinitionData(
  947. struct ObjCInterfaceDecl::DefinitionData &Data) {
  948. // Read the superclass.
  949. Data.SuperClassTInfo = GetTypeSourceInfo();
  950. Data.EndLoc = ReadSourceLocation();
  951. Data.HasDesignatedInitializers = Record.readInt();
  952. // Read the directly referenced protocols and their SourceLocations.
  953. unsigned NumProtocols = Record.readInt();
  954. SmallVector<ObjCProtocolDecl *, 16> Protocols;
  955. Protocols.reserve(NumProtocols);
  956. for (unsigned I = 0; I != NumProtocols; ++I)
  957. Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
  958. SmallVector<SourceLocation, 16> ProtoLocs;
  959. ProtoLocs.reserve(NumProtocols);
  960. for (unsigned I = 0; I != NumProtocols; ++I)
  961. ProtoLocs.push_back(ReadSourceLocation());
  962. Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
  963. Reader.getContext());
  964. // Read the transitive closure of protocols referenced by this class.
  965. NumProtocols = Record.readInt();
  966. Protocols.clear();
  967. Protocols.reserve(NumProtocols);
  968. for (unsigned I = 0; I != NumProtocols; ++I)
  969. Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
  970. Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
  971. Reader.getContext());
  972. }
  973. void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
  974. struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
  975. // FIXME: odr checking?
  976. }
  977. void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
  978. RedeclarableResult Redecl = VisitRedeclarable(ID);
  979. VisitObjCContainerDecl(ID);
  980. DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
  981. mergeRedeclarable(ID, Redecl);
  982. ID->TypeParamList = ReadObjCTypeParamList();
  983. if (Record.readInt()) {
  984. // Read the definition.
  985. ID->allocateDefinitionData();
  986. ReadObjCDefinitionData(ID->data());
  987. ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
  988. if (Canon->Data.getPointer()) {
  989. // If we already have a definition, keep the definition invariant and
  990. // merge the data.
  991. MergeDefinitionData(Canon, std::move(ID->data()));
  992. ID->Data = Canon->Data;
  993. } else {
  994. // Set the definition data of the canonical declaration, so other
  995. // redeclarations will see it.
  996. ID->getCanonicalDecl()->Data = ID->Data;
  997. // We will rebuild this list lazily.
  998. ID->setIvarList(nullptr);
  999. }
  1000. // Note that we have deserialized a definition.
  1001. Reader.PendingDefinitions.insert(ID);
  1002. // Note that we've loaded this Objective-C class.
  1003. Reader.ObjCClassesLoaded.push_back(ID);
  1004. } else {
  1005. ID->Data = ID->getCanonicalDecl()->Data;
  1006. }
  1007. }
  1008. void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
  1009. VisitFieldDecl(IVD);
  1010. IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
  1011. // This field will be built lazily.
  1012. IVD->setNextIvar(nullptr);
  1013. bool synth = Record.readInt();
  1014. IVD->setSynthesize(synth);
  1015. }
  1016. void ASTDeclReader::ReadObjCDefinitionData(
  1017. struct ObjCProtocolDecl::DefinitionData &Data) {
  1018. unsigned NumProtoRefs = Record.readInt();
  1019. SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
  1020. ProtoRefs.reserve(NumProtoRefs);
  1021. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1022. ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
  1023. SmallVector<SourceLocation, 16> ProtoLocs;
  1024. ProtoLocs.reserve(NumProtoRefs);
  1025. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1026. ProtoLocs.push_back(ReadSourceLocation());
  1027. Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
  1028. ProtoLocs.data(), Reader.getContext());
  1029. }
  1030. void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
  1031. struct ObjCProtocolDecl::DefinitionData &&NewDD) {
  1032. // FIXME: odr checking?
  1033. }
  1034. void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
  1035. RedeclarableResult Redecl = VisitRedeclarable(PD);
  1036. VisitObjCContainerDecl(PD);
  1037. mergeRedeclarable(PD, Redecl);
  1038. if (Record.readInt()) {
  1039. // Read the definition.
  1040. PD->allocateDefinitionData();
  1041. ReadObjCDefinitionData(PD->data());
  1042. ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
  1043. if (Canon->Data.getPointer()) {
  1044. // If we already have a definition, keep the definition invariant and
  1045. // merge the data.
  1046. MergeDefinitionData(Canon, std::move(PD->data()));
  1047. PD->Data = Canon->Data;
  1048. } else {
  1049. // Set the definition data of the canonical declaration, so other
  1050. // redeclarations will see it.
  1051. PD->getCanonicalDecl()->Data = PD->Data;
  1052. }
  1053. // Note that we have deserialized a definition.
  1054. Reader.PendingDefinitions.insert(PD);
  1055. } else {
  1056. PD->Data = PD->getCanonicalDecl()->Data;
  1057. }
  1058. }
  1059. void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
  1060. VisitFieldDecl(FD);
  1061. }
  1062. void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
  1063. VisitObjCContainerDecl(CD);
  1064. CD->setCategoryNameLoc(ReadSourceLocation());
  1065. CD->setIvarLBraceLoc(ReadSourceLocation());
  1066. CD->setIvarRBraceLoc(ReadSourceLocation());
  1067. // Note that this category has been deserialized. We do this before
  1068. // deserializing the interface declaration, so that it will consider this
  1069. /// category.
  1070. Reader.CategoriesDeserialized.insert(CD);
  1071. CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>();
  1072. CD->TypeParamList = ReadObjCTypeParamList();
  1073. unsigned NumProtoRefs = Record.readInt();
  1074. SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
  1075. ProtoRefs.reserve(NumProtoRefs);
  1076. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1077. ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
  1078. SmallVector<SourceLocation, 16> ProtoLocs;
  1079. ProtoLocs.reserve(NumProtoRefs);
  1080. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1081. ProtoLocs.push_back(ReadSourceLocation());
  1082. CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
  1083. Reader.getContext());
  1084. // Protocols in the class extension belong to the class.
  1085. if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
  1086. CD->ClassInterface->mergeClassExtensionProtocolList(
  1087. (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
  1088. Reader.getContext());
  1089. }
  1090. void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
  1091. VisitNamedDecl(CAD);
  1092. CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
  1093. }
  1094. void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
  1095. VisitNamedDecl(D);
  1096. D->setAtLoc(ReadSourceLocation());
  1097. D->setLParenLoc(ReadSourceLocation());
  1098. QualType T = Record.readType();
  1099. TypeSourceInfo *TSI = GetTypeSourceInfo();
  1100. D->setType(T, TSI);
  1101. D->setPropertyAttributes(
  1102. (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
  1103. D->setPropertyAttributesAsWritten(
  1104. (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
  1105. D->setPropertyImplementation(
  1106. (ObjCPropertyDecl::PropertyControl)Record.readInt());
  1107. DeclarationName GetterName = Record.readDeclarationName();
  1108. SourceLocation GetterLoc = ReadSourceLocation();
  1109. D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
  1110. DeclarationName SetterName = Record.readDeclarationName();
  1111. SourceLocation SetterLoc = ReadSourceLocation();
  1112. D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
  1113. D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
  1114. D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
  1115. D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>());
  1116. }
  1117. void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
  1118. VisitObjCContainerDecl(D);
  1119. D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
  1120. }
  1121. void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
  1122. VisitObjCImplDecl(D);
  1123. D->CategoryNameLoc = ReadSourceLocation();
  1124. }
  1125. void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
  1126. VisitObjCImplDecl(D);
  1127. D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
  1128. D->SuperLoc = ReadSourceLocation();
  1129. D->setIvarLBraceLoc(ReadSourceLocation());
  1130. D->setIvarRBraceLoc(ReadSourceLocation());
  1131. D->setHasNonZeroConstructors(Record.readInt());
  1132. D->setHasDestructors(Record.readInt());
  1133. D->NumIvarInitializers = Record.readInt();
  1134. if (D->NumIvarInitializers)
  1135. D->IvarInitializers = ReadGlobalOffset();
  1136. }
  1137. void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
  1138. VisitDecl(D);
  1139. D->setAtLoc(ReadSourceLocation());
  1140. D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
  1141. D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
  1142. D->IvarLoc = ReadSourceLocation();
  1143. D->setGetterCXXConstructor(Record.readExpr());
  1144. D->setSetterCXXAssignment(Record.readExpr());
  1145. }
  1146. void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
  1147. VisitDeclaratorDecl(FD);
  1148. FD->Mutable = Record.readInt();
  1149. if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
  1150. FD->InitStorage.setInt(ISK);
  1151. FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
  1152. ? Record.readType().getAsOpaquePtr()
  1153. : Record.readExpr());
  1154. }
  1155. if (auto *BW = Record.readExpr())
  1156. FD->setBitWidth(BW);
  1157. if (!FD->getDeclName()) {
  1158. if (auto *Tmpl = ReadDeclAs<FieldDecl>())
  1159. Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
  1160. }
  1161. mergeMergeable(FD);
  1162. }
  1163. void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
  1164. VisitDeclaratorDecl(PD);
  1165. PD->GetterId = Record.getIdentifierInfo();
  1166. PD->SetterId = Record.getIdentifierInfo();
  1167. }
  1168. void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
  1169. VisitValueDecl(FD);
  1170. FD->ChainingSize = Record.readInt();
  1171. assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
  1172. FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
  1173. for (unsigned I = 0; I != FD->ChainingSize; ++I)
  1174. FD->Chaining[I] = ReadDeclAs<NamedDecl>();
  1175. mergeMergeable(FD);
  1176. }
  1177. ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
  1178. RedeclarableResult Redecl = VisitRedeclarable(VD);
  1179. VisitDeclaratorDecl(VD);
  1180. VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
  1181. VD->VarDeclBits.TSCSpec = Record.readInt();
  1182. VD->VarDeclBits.InitStyle = Record.readInt();
  1183. VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
  1184. if (!isa<ParmVarDecl>(VD)) {
  1185. VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
  1186. Record.readInt();
  1187. VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
  1188. VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
  1189. VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
  1190. VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
  1191. VD->NonParmVarDeclBits.IsInline = Record.readInt();
  1192. VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
  1193. VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
  1194. VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
  1195. VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
  1196. VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
  1197. VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
  1198. }
  1199. auto VarLinkage = Linkage(Record.readInt());
  1200. VD->setCachedLinkage(VarLinkage);
  1201. // Reconstruct the one piece of the IdentifierNamespace that we need.
  1202. if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
  1203. VD->getLexicalDeclContext()->isFunctionOrMethod())
  1204. VD->setLocalExternDecl();
  1205. if (uint64_t Val = Record.readInt()) {
  1206. VD->setInit(Record.readExpr());
  1207. if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
  1208. EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
  1209. Eval->CheckedICE = true;
  1210. Eval->IsICE = Val == 3;
  1211. }
  1212. }
  1213. if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
  1214. Expr *CopyExpr = Record.readExpr();
  1215. if (CopyExpr)
  1216. Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
  1217. }
  1218. if (VD->getStorageDuration() == SD_Static && Record.readInt())
  1219. Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
  1220. enum VarKind {
  1221. VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
  1222. };
  1223. switch ((VarKind)Record.readInt()) {
  1224. case VarNotTemplate:
  1225. // Only true variables (not parameters or implicit parameters) can be
  1226. // merged; the other kinds are not really redeclarable at all.
  1227. if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
  1228. !isa<VarTemplateSpecializationDecl>(VD))
  1229. mergeRedeclarable(VD, Redecl);
  1230. break;
  1231. case VarTemplate:
  1232. // Merged when we merge the template.
  1233. VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
  1234. break;
  1235. case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
  1236. auto *Tmpl = ReadDeclAs<VarDecl>();
  1237. auto TSK = (TemplateSpecializationKind)Record.readInt();
  1238. SourceLocation POI = ReadSourceLocation();
  1239. Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
  1240. mergeRedeclarable(VD, Redecl);
  1241. break;
  1242. }
  1243. }
  1244. return Redecl;
  1245. }
  1246. void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
  1247. VisitVarDecl(PD);
  1248. }
  1249. void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
  1250. VisitVarDecl(PD);
  1251. unsigned isObjCMethodParam = Record.readInt();
  1252. unsigned scopeDepth = Record.readInt();
  1253. unsigned scopeIndex = Record.readInt();
  1254. unsigned declQualifier = Record.readInt();
  1255. if (isObjCMethodParam) {
  1256. assert(scopeDepth == 0);
  1257. PD->setObjCMethodScopeInfo(scopeIndex);
  1258. PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
  1259. } else {
  1260. PD->setScopeInfo(scopeDepth, scopeIndex);
  1261. }
  1262. PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
  1263. PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
  1264. if (Record.readInt()) // hasUninstantiatedDefaultArg.
  1265. PD->setUninstantiatedDefaultArg(Record.readExpr());
  1266. // FIXME: If this is a redeclaration of a function from another module, handle
  1267. // inheritance of default arguments.
  1268. }
  1269. void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
  1270. VisitVarDecl(DD);
  1271. auto **BDs = DD->getTrailingObjects<BindingDecl *>();
  1272. for (unsigned I = 0; I != DD->NumBindings; ++I) {
  1273. BDs[I] = ReadDeclAs<BindingDecl>();
  1274. BDs[I]->setDecomposedDecl(DD);
  1275. }
  1276. }
  1277. void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
  1278. VisitValueDecl(BD);
  1279. BD->Binding = Record.readExpr();
  1280. }
  1281. void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
  1282. VisitDecl(AD);
  1283. AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
  1284. AD->setRParenLoc(ReadSourceLocation());
  1285. }
  1286. void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
  1287. VisitDecl(BD);
  1288. BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
  1289. BD->setSignatureAsWritten(GetTypeSourceInfo());
  1290. unsigned NumParams = Record.readInt();
  1291. SmallVector<ParmVarDecl *, 16> Params;
  1292. Params.reserve(NumParams);
  1293. for (unsigned I = 0; I != NumParams; ++I)
  1294. Params.push_back(ReadDeclAs<ParmVarDecl>());
  1295. BD->setParams(Params);
  1296. BD->setIsVariadic(Record.readInt());
  1297. BD->setBlockMissingReturnType(Record.readInt());
  1298. BD->setIsConversionFromLambda(Record.readInt());
  1299. BD->setDoesNotEscape(Record.readInt());
  1300. BD->setCanAvoidCopyToHeap(Record.readInt());
  1301. bool capturesCXXThis = Record.readInt();
  1302. unsigned numCaptures = Record.readInt();
  1303. SmallVector<BlockDecl::Capture, 16> captures;
  1304. captures.reserve(numCaptures);
  1305. for (unsigned i = 0; i != numCaptures; ++i) {
  1306. auto *decl = ReadDeclAs<VarDecl>();
  1307. unsigned flags = Record.readInt();
  1308. bool byRef = (flags & 1);
  1309. bool nested = (flags & 2);
  1310. Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
  1311. captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
  1312. }
  1313. BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
  1314. }
  1315. void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
  1316. VisitDecl(CD);
  1317. unsigned ContextParamPos = Record.readInt();
  1318. CD->setNothrow(Record.readInt() != 0);
  1319. // Body is set by VisitCapturedStmt.
  1320. for (unsigned I = 0; I < CD->NumParams; ++I) {
  1321. if (I != ContextParamPos)
  1322. CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
  1323. else
  1324. CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
  1325. }
  1326. }
  1327. void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
  1328. VisitDecl(D);
  1329. D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
  1330. D->setExternLoc(ReadSourceLocation());
  1331. D->setRBraceLoc(ReadSourceLocation());
  1332. }
  1333. void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
  1334. VisitDecl(D);
  1335. D->RBraceLoc = ReadSourceLocation();
  1336. }
  1337. void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
  1338. VisitNamedDecl(D);
  1339. D->setLocStart(ReadSourceLocation());
  1340. }
  1341. void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
  1342. RedeclarableResult Redecl = VisitRedeclarable(D);
  1343. VisitNamedDecl(D);
  1344. D->setInline(Record.readInt());
  1345. D->LocStart = ReadSourceLocation();
  1346. D->RBraceLoc = ReadSourceLocation();
  1347. // Defer loading the anonymous namespace until we've finished merging
  1348. // this namespace; loading it might load a later declaration of the
  1349. // same namespace, and we have an invariant that older declarations
  1350. // get merged before newer ones try to merge.
  1351. GlobalDeclID AnonNamespace = 0;
  1352. if (Redecl.getFirstID() == ThisDeclID) {
  1353. AnonNamespace = ReadDeclID();
  1354. } else {
  1355. // Link this namespace back to the first declaration, which has already
  1356. // been deserialized.
  1357. D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
  1358. }
  1359. mergeRedeclarable(D, Redecl);
  1360. if (AnonNamespace) {
  1361. // Each module has its own anonymous namespace, which is disjoint from
  1362. // any other module's anonymous namespaces, so don't attach the anonymous
  1363. // namespace at all.
  1364. auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
  1365. if (!Record.isModule())
  1366. D->setAnonymousNamespace(Anon);
  1367. }
  1368. }
  1369. void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  1370. RedeclarableResult Redecl = VisitRedeclarable(D);
  1371. VisitNamedDecl(D);
  1372. D->NamespaceLoc = ReadSourceLocation();
  1373. D->IdentLoc = ReadSourceLocation();
  1374. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1375. D->Namespace = ReadDeclAs<NamedDecl>();
  1376. mergeRedeclarable(D, Redecl);
  1377. }
  1378. void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
  1379. VisitNamedDecl(D);
  1380. D->setUsingLoc(ReadSourceLocation());
  1381. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1382. ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
  1383. D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
  1384. D->setTypename(Record.readInt());
  1385. if (auto *Pattern = ReadDeclAs<NamedDecl>())
  1386. Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
  1387. mergeMergeable(D);
  1388. }
  1389. void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
  1390. VisitNamedDecl(D);
  1391. D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
  1392. auto **Expansions = D->getTrailingObjects<NamedDecl *>();
  1393. for (unsigned I = 0; I != D->NumExpansions; ++I)
  1394. Expansions[I] = ReadDeclAs<NamedDecl>();
  1395. mergeMergeable(D);
  1396. }
  1397. void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
  1398. RedeclarableResult Redecl = VisitRedeclarable(D);
  1399. VisitNamedDecl(D);
  1400. D->Underlying = ReadDeclAs<NamedDecl>();
  1401. D->IdentifierNamespace = Record.readInt();
  1402. D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
  1403. auto *Pattern = ReadDeclAs<UsingShadowDecl>();
  1404. if (Pattern)
  1405. Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
  1406. mergeRedeclarable(D, Redecl);
  1407. }
  1408. void ASTDeclReader::VisitConstructorUsingShadowDecl(
  1409. ConstructorUsingShadowDecl *D) {
  1410. VisitUsingShadowDecl(D);
  1411. D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
  1412. D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
  1413. D->IsVirtual = Record.readInt();
  1414. }
  1415. void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1416. VisitNamedDecl(D);
  1417. D->UsingLoc = ReadSourceLocation();
  1418. D->NamespaceLoc = ReadSourceLocation();
  1419. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1420. D->NominatedNamespace = ReadDeclAs<NamedDecl>();
  1421. D->CommonAncestor = ReadDeclAs<DeclContext>();
  1422. }
  1423. void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1424. VisitValueDecl(D);
  1425. D->setUsingLoc(ReadSourceLocation());
  1426. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1427. ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
  1428. D->EllipsisLoc = ReadSourceLocation();
  1429. mergeMergeable(D);
  1430. }
  1431. void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
  1432. UnresolvedUsingTypenameDecl *D) {
  1433. VisitTypeDecl(D);
  1434. D->TypenameLocation = ReadSourceLocation();
  1435. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1436. D->EllipsisLoc = ReadSourceLocation();
  1437. mergeMergeable(D);
  1438. }
  1439. void ASTDeclReader::ReadCXXDefinitionData(
  1440. struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
  1441. // Note: the caller has deserialized the IsLambda bit already.
  1442. Data.UserDeclaredConstructor = Record.readInt();
  1443. Data.UserDeclaredSpecialMembers = Record.readInt();
  1444. Data.Aggregate = Record.readInt();
  1445. Data.PlainOldData = Record.readInt();
  1446. Data.Empty = Record.readInt();
  1447. Data.Polymorphic = Record.readInt();
  1448. Data.Abstract = Record.readInt();
  1449. Data.IsStandardLayout = Record.readInt();
  1450. Data.IsCXX11StandardLayout = Record.readInt();
  1451. Data.HasBasesWithFields = Record.readInt();
  1452. Data.HasBasesWithNonStaticDataMembers = Record.readInt();
  1453. Data.HasPrivateFields = Record.readInt();
  1454. Data.HasProtectedFields = Record.readInt();
  1455. Data.HasPublicFields = Record.readInt();
  1456. Data.HasMutableFields = Record.readInt();
  1457. Data.HasVariantMembers = Record.readInt();
  1458. Data.HasOnlyCMembers = Record.readInt();
  1459. Data.HasInClassInitializer = Record.readInt();
  1460. Data.HasUninitializedReferenceMember = Record.readInt();
  1461. Data.HasUninitializedFields = Record.readInt();
  1462. Data.HasInheritedConstructor = Record.readInt();
  1463. Data.HasInheritedAssignment = Record.readInt();
  1464. Data.NeedOverloadResolutionForCopyConstructor = Record.readInt();
  1465. Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
  1466. Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
  1467. Data.NeedOverloadResolutionForDestructor = Record.readInt();
  1468. Data.DefaultedCopyConstructorIsDeleted = Record.readInt();
  1469. Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
  1470. Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
  1471. Data.DefaultedDestructorIsDeleted = Record.readInt();
  1472. Data.HasTrivialSpecialMembers = Record.readInt();
  1473. Data.HasTrivialSpecialMembersForCall = Record.readInt();
  1474. Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
  1475. Data.DeclaredNonTrivialSpecialMembersForCall = Record.readInt();
  1476. Data.HasIrrelevantDestructor = Record.readInt();
  1477. Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
  1478. Data.HasDefaultedDefaultConstructor = Record.readInt();
  1479. Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
  1480. Data.HasConstexprDefaultConstructor = Record.readInt();
  1481. Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
  1482. Data.ComputedVisibleConversions = Record.readInt();
  1483. Data.UserProvidedDefaultConstructor = Record.readInt();
  1484. Data.DeclaredSpecialMembers = Record.readInt();
  1485. Data.ImplicitCopyConstructorCanHaveConstParamForVBase = Record.readInt();
  1486. Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase = Record.readInt();
  1487. Data.ImplicitCopyAssignmentHasConstParam = Record.readInt();
  1488. Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt();
  1489. Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt();
  1490. Data.ODRHash = Record.readInt();
  1491. Data.HasODRHash = true;
  1492. if (Record.readInt())
  1493. Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
  1494. Data.NumBases = Record.readInt();
  1495. if (Data.NumBases)
  1496. Data.Bases = ReadGlobalOffset();
  1497. Data.NumVBases = Record.readInt();
  1498. if (Data.NumVBases)
  1499. Data.VBases = ReadGlobalOffset();
  1500. Record.readUnresolvedSet(Data.Conversions);
  1501. Record.readUnresolvedSet(Data.VisibleConversions);
  1502. assert(Data.Definition && "Data.Definition should be already set!");
  1503. Data.FirstFriend = ReadDeclID();
  1504. if (Data.IsLambda) {
  1505. using Capture = LambdaCapture;
  1506. auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
  1507. Lambda.Dependent = Record.readInt();
  1508. Lambda.IsGenericLambda = Record.readInt();
  1509. Lambda.CaptureDefault = Record.readInt();
  1510. Lambda.NumCaptures = Record.readInt();
  1511. Lambda.NumExplicitCaptures = Record.readInt();
  1512. Lambda.ManglingNumber = Record.readInt();
  1513. Lambda.ContextDecl = ReadDeclID();
  1514. Lambda.Captures = (Capture *)Reader.getContext().Allocate(
  1515. sizeof(Capture) * Lambda.NumCaptures);
  1516. Capture *ToCapture = Lambda.Captures;
  1517. Lambda.MethodTyInfo = GetTypeSourceInfo();
  1518. for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
  1519. SourceLocation Loc = ReadSourceLocation();
  1520. bool IsImplicit = Record.readInt();
  1521. auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
  1522. switch (Kind) {
  1523. case LCK_StarThis:
  1524. case LCK_This:
  1525. case LCK_VLAType:
  1526. *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
  1527. break;
  1528. case LCK_ByCopy:
  1529. case LCK_ByRef:
  1530. auto *Var = ReadDeclAs<VarDecl>();
  1531. SourceLocation EllipsisLoc = ReadSourceLocation();
  1532. *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
  1533. break;
  1534. }
  1535. }
  1536. }
  1537. }
  1538. void ASTDeclReader::MergeDefinitionData(
  1539. CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
  1540. assert(D->DefinitionData &&
  1541. "merging class definition into non-definition");
  1542. auto &DD = *D->DefinitionData;
  1543. if (DD.Definition != MergeDD.Definition) {
  1544. // Track that we merged the definitions.
  1545. Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
  1546. DD.Definition));
  1547. Reader.PendingDefinitions.erase(MergeDD.Definition);
  1548. MergeDD.Definition->setCompleteDefinition(false);
  1549. Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
  1550. assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
  1551. "already loaded pending lookups for merged definition");
  1552. }
  1553. auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
  1554. if (PFDI != Reader.PendingFakeDefinitionData.end() &&
  1555. PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
  1556. // We faked up this definition data because we found a class for which we'd
  1557. // not yet loaded the definition. Replace it with the real thing now.
  1558. assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
  1559. PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
  1560. // Don't change which declaration is the definition; that is required
  1561. // to be invariant once we select it.
  1562. auto *Def = DD.Definition;
  1563. DD = std::move(MergeDD);
  1564. DD.Definition = Def;
  1565. return;
  1566. }
  1567. // FIXME: Move this out into a .def file?
  1568. bool DetectedOdrViolation = false;
  1569. #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
  1570. #define MATCH_FIELD(Field) \
  1571. DetectedOdrViolation |= DD.Field != MergeDD.Field; \
  1572. OR_FIELD(Field)
  1573. MATCH_FIELD(UserDeclaredConstructor)
  1574. MATCH_FIELD(UserDeclaredSpecialMembers)
  1575. MATCH_FIELD(Aggregate)
  1576. MATCH_FIELD(PlainOldData)
  1577. MATCH_FIELD(Empty)
  1578. MATCH_FIELD(Polymorphic)
  1579. MATCH_FIELD(Abstract)
  1580. MATCH_FIELD(IsStandardLayout)
  1581. MATCH_FIELD(IsCXX11StandardLayout)
  1582. MATCH_FIELD(HasBasesWithFields)
  1583. MATCH_FIELD(HasBasesWithNonStaticDataMembers)
  1584. MATCH_FIELD(HasPrivateFields)
  1585. MATCH_FIELD(HasProtectedFields)
  1586. MATCH_FIELD(HasPublicFields)
  1587. MATCH_FIELD(HasMutableFields)
  1588. MATCH_FIELD(HasVariantMembers)
  1589. MATCH_FIELD(HasOnlyCMembers)
  1590. MATCH_FIELD(HasInClassInitializer)
  1591. MATCH_FIELD(HasUninitializedReferenceMember)
  1592. MATCH_FIELD(HasUninitializedFields)
  1593. MATCH_FIELD(HasInheritedConstructor)
  1594. MATCH_FIELD(HasInheritedAssignment)
  1595. MATCH_FIELD(NeedOverloadResolutionForCopyConstructor)
  1596. MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
  1597. MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
  1598. MATCH_FIELD(NeedOverloadResolutionForDestructor)
  1599. MATCH_FIELD(DefaultedCopyConstructorIsDeleted)
  1600. MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
  1601. MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
  1602. MATCH_FIELD(DefaultedDestructorIsDeleted)
  1603. OR_FIELD(HasTrivialSpecialMembers)
  1604. OR_FIELD(HasTrivialSpecialMembersForCall)
  1605. OR_FIELD(DeclaredNonTrivialSpecialMembers)
  1606. OR_FIELD(DeclaredNonTrivialSpecialMembersForCall)
  1607. MATCH_FIELD(HasIrrelevantDestructor)
  1608. OR_FIELD(HasConstexprNonCopyMoveConstructor)
  1609. OR_FIELD(HasDefaultedDefaultConstructor)
  1610. MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
  1611. OR_FIELD(HasConstexprDefaultConstructor)
  1612. MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
  1613. // ComputedVisibleConversions is handled below.
  1614. MATCH_FIELD(UserProvidedDefaultConstructor)
  1615. OR_FIELD(DeclaredSpecialMembers)
  1616. MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForVBase)
  1617. MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForNonVBase)
  1618. MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
  1619. OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
  1620. OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
  1621. MATCH_FIELD(IsLambda)
  1622. #undef OR_FIELD
  1623. #undef MATCH_FIELD
  1624. if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
  1625. DetectedOdrViolation = true;
  1626. // FIXME: Issue a diagnostic if the base classes don't match when we come
  1627. // to lazily load them.
  1628. // FIXME: Issue a diagnostic if the list of conversion functions doesn't
  1629. // match when we come to lazily load them.
  1630. if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
  1631. DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
  1632. DD.ComputedVisibleConversions = true;
  1633. }
  1634. // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
  1635. // lazily load it.
  1636. if (DD.IsLambda) {
  1637. // FIXME: ODR-checking for merging lambdas (this happens, for instance,
  1638. // when they occur within the body of a function template specialization).
  1639. }
  1640. if (D->getODRHash() != MergeDD.ODRHash) {
  1641. DetectedOdrViolation = true;
  1642. }
  1643. if (DetectedOdrViolation)
  1644. Reader.PendingOdrMergeFailures[DD.Definition].push_back(
  1645. {MergeDD.Definition, &MergeDD});
  1646. }
  1647. void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
  1648. struct CXXRecordDecl::DefinitionData *DD;
  1649. ASTContext &C = Reader.getContext();
  1650. // Determine whether this is a lambda closure type, so that we can
  1651. // allocate the appropriate DefinitionData structure.
  1652. bool IsLambda = Record.readInt();
  1653. if (IsLambda)
  1654. DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
  1655. LCD_None);
  1656. else
  1657. DD = new (C) struct CXXRecordDecl::DefinitionData(D);
  1658. CXXRecordDecl *Canon = D->getCanonicalDecl();
  1659. // Set decl definition data before reading it, so that during deserialization
  1660. // when we read CXXRecordDecl, it already has definition data and we don't
  1661. // set fake one.
  1662. if (!Canon->DefinitionData)
  1663. Canon->DefinitionData = DD;
  1664. D->DefinitionData = Canon->DefinitionData;
  1665. ReadCXXDefinitionData(*DD, D);
  1666. // We might already have a different definition for this record. This can
  1667. // happen either because we're reading an update record, or because we've
  1668. // already done some merging. Either way, just merge into it.
  1669. if (Canon->DefinitionData != DD) {
  1670. MergeDefinitionData(Canon, std::move(*DD));
  1671. return;
  1672. }
  1673. // Mark this declaration as being a definition.
  1674. D->setCompleteDefinition(true);
  1675. // If this is not the first declaration or is an update record, we can have
  1676. // other redeclarations already. Make a note that we need to propagate the
  1677. // DefinitionData pointer onto them.
  1678. if (Update || Canon != D)
  1679. Reader.PendingDefinitions.insert(D);
  1680. }
  1681. ASTDeclReader::RedeclarableResult
  1682. ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
  1683. RedeclarableResult Redecl = VisitRecordDeclImpl(D);
  1684. ASTContext &C = Reader.getContext();
  1685. enum CXXRecKind {
  1686. CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
  1687. };
  1688. switch ((CXXRecKind)Record.readInt()) {
  1689. case CXXRecNotTemplate:
  1690. // Merged when we merge the folding set entry in the primary template.
  1691. if (!isa<ClassTemplateSpecializationDecl>(D))
  1692. mergeRedeclarable(D, Redecl);
  1693. break;
  1694. case CXXRecTemplate: {
  1695. // Merged when we merge the template.
  1696. auto *Template = ReadDeclAs<ClassTemplateDecl>();
  1697. D->TemplateOrInstantiation = Template;
  1698. if (!Template->getTemplatedDecl()) {
  1699. // We've not actually loaded the ClassTemplateDecl yet, because we're
  1700. // currently being loaded as its pattern. Rely on it to set up our
  1701. // TypeForDecl (see VisitClassTemplateDecl).
  1702. //
  1703. // Beware: we do not yet know our canonical declaration, and may still
  1704. // get merged once the surrounding class template has got off the ground.
  1705. DeferredTypeID = 0;
  1706. }
  1707. break;
  1708. }
  1709. case CXXRecMemberSpecialization: {
  1710. auto *RD = ReadDeclAs<CXXRecordDecl>();
  1711. auto TSK = (TemplateSpecializationKind)Record.readInt();
  1712. SourceLocation POI = ReadSourceLocation();
  1713. MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
  1714. MSI->setPointOfInstantiation(POI);
  1715. D->TemplateOrInstantiation = MSI;
  1716. mergeRedeclarable(D, Redecl);
  1717. break;
  1718. }
  1719. }
  1720. bool WasDefinition = Record.readInt();
  1721. if (WasDefinition)
  1722. ReadCXXRecordDefinition(D, /*Update*/false);
  1723. else
  1724. // Propagate DefinitionData pointer from the canonical declaration.
  1725. D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
  1726. // Lazily load the key function to avoid deserializing every method so we can
  1727. // compute it.
  1728. if (WasDefinition) {
  1729. DeclID KeyFn = ReadDeclID();
  1730. if (KeyFn && D->isCompleteDefinition())
  1731. // FIXME: This is wrong for the ARM ABI, where some other module may have
  1732. // made this function no longer be a key function. We need an update
  1733. // record or similar for that case.
  1734. C.KeyFunctions[D] = KeyFn;
  1735. }
  1736. return Redecl;
  1737. }
  1738. void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  1739. D->setExplicitSpecifier(Record.readExplicitSpec());
  1740. VisitFunctionDecl(D);
  1741. D->setIsCopyDeductionCandidate(Record.readInt());
  1742. }
  1743. void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
  1744. VisitFunctionDecl(D);
  1745. unsigned NumOverridenMethods = Record.readInt();
  1746. if (D->isCanonicalDecl()) {
  1747. while (NumOverridenMethods--) {
  1748. // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
  1749. // MD may be initializing.
  1750. if (auto *MD = ReadDeclAs<CXXMethodDecl>())
  1751. Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
  1752. }
  1753. } else {
  1754. // We don't care about which declarations this used to override; we get
  1755. // the relevant information from the canonical declaration.
  1756. Record.skipInts(NumOverridenMethods);
  1757. }
  1758. }
  1759. void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1760. // We need the inherited constructor information to merge the declaration,
  1761. // so we have to read it before we call VisitCXXMethodDecl.
  1762. D->setExplicitSpecifier(Record.readExplicitSpec());
  1763. if (D->isInheritingConstructor()) {
  1764. auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
  1765. auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
  1766. *D->getTrailingObjects<InheritedConstructor>() =
  1767. InheritedConstructor(Shadow, Ctor);
  1768. }
  1769. VisitCXXMethodDecl(D);
  1770. }
  1771. void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1772. VisitCXXMethodDecl(D);
  1773. if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
  1774. CXXDestructorDecl *Canon = D->getCanonicalDecl();
  1775. auto *ThisArg = Record.readExpr();
  1776. // FIXME: Check consistency if we have an old and new operator delete.
  1777. if (!Canon->OperatorDelete) {
  1778. Canon->OperatorDelete = OperatorDelete;
  1779. Canon->OperatorDeleteThisArg = ThisArg;
  1780. }
  1781. }
  1782. }
  1783. void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1784. D->setExplicitSpecifier(Record.readExplicitSpec());
  1785. VisitCXXMethodDecl(D);
  1786. }
  1787. void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
  1788. VisitDecl(D);
  1789. D->ImportedAndComplete.setPointer(readModule());
  1790. D->ImportedAndComplete.setInt(Record.readInt());
  1791. auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
  1792. for (unsigned I = 0, N = Record.back(); I != N; ++I)
  1793. StoredLocs[I] = ReadSourceLocation();
  1794. Record.skipInts(1); // The number of stored source locations.
  1795. }
  1796. void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
  1797. VisitDecl(D);
  1798. D->setColonLoc(ReadSourceLocation());
  1799. }
  1800. void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
  1801. VisitDecl(D);
  1802. if (Record.readInt()) // hasFriendDecl
  1803. D->Friend = ReadDeclAs<NamedDecl>();
  1804. else
  1805. D->Friend = GetTypeSourceInfo();
  1806. for (unsigned i = 0; i != D->NumTPLists; ++i)
  1807. D->getTrailingObjects<TemplateParameterList *>()[i] =
  1808. Record.readTemplateParameterList();
  1809. D->NextFriend = ReadDeclID();
  1810. D->UnsupportedFriend = (Record.readInt() != 0);
  1811. D->FriendLoc = ReadSourceLocation();
  1812. }
  1813. void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  1814. VisitDecl(D);
  1815. unsigned NumParams = Record.readInt();
  1816. D->NumParams = NumParams;
  1817. D->Params = new TemplateParameterList*[NumParams];
  1818. for (unsigned i = 0; i != NumParams; ++i)
  1819. D->Params[i] = Record.readTemplateParameterList();
  1820. if (Record.readInt()) // HasFriendDecl
  1821. D->Friend = ReadDeclAs<NamedDecl>();
  1822. else
  1823. D->Friend = GetTypeSourceInfo();
  1824. D->FriendLoc = ReadSourceLocation();
  1825. }
  1826. DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
  1827. VisitNamedDecl(D);
  1828. DeclID PatternID = ReadDeclID();
  1829. auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
  1830. TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
  1831. // FIXME handle associated constraints
  1832. D->init(TemplatedDecl, TemplateParams);
  1833. return PatternID;
  1834. }
  1835. void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
  1836. VisitTemplateDecl(D);
  1837. D->ConstraintExpr = Record.readExpr();
  1838. mergeMergeable(D);
  1839. }
  1840. ASTDeclReader::RedeclarableResult
  1841. ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
  1842. RedeclarableResult Redecl = VisitRedeclarable(D);
  1843. // Make sure we've allocated the Common pointer first. We do this before
  1844. // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
  1845. RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
  1846. if (!CanonD->Common) {
  1847. CanonD->Common = CanonD->newCommon(Reader.getContext());
  1848. Reader.PendingDefinitions.insert(CanonD);
  1849. }
  1850. D->Common = CanonD->Common;
  1851. // If this is the first declaration of the template, fill in the information
  1852. // for the 'common' pointer.
  1853. if (ThisDeclID == Redecl.getFirstID()) {
  1854. if (auto *RTD = ReadDeclAs<RedeclarableTemplateDecl>()) {
  1855. assert(RTD->getKind() == D->getKind() &&
  1856. "InstantiatedFromMemberTemplate kind mismatch");
  1857. D->setInstantiatedFromMemberTemplate(RTD);
  1858. if (Record.readInt())
  1859. D->setMemberSpecialization();
  1860. }
  1861. }
  1862. DeclID PatternID = VisitTemplateDecl(D);
  1863. D->IdentifierNamespace = Record.readInt();
  1864. mergeRedeclarable(D, Redecl, PatternID);
  1865. // If we merged the template with a prior declaration chain, merge the common
  1866. // pointer.
  1867. // FIXME: Actually merge here, don't just overwrite.
  1868. D->Common = D->getCanonicalDecl()->Common;
  1869. return Redecl;
  1870. }
  1871. void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  1872. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1873. if (ThisDeclID == Redecl.getFirstID()) {
  1874. // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
  1875. // the specializations.
  1876. SmallVector<serialization::DeclID, 32> SpecIDs;
  1877. ReadDeclIDList(SpecIDs);
  1878. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1879. }
  1880. if (D->getTemplatedDecl()->TemplateOrInstantiation) {
  1881. // We were loaded before our templated declaration was. We've not set up
  1882. // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
  1883. // it now.
  1884. Reader.getContext().getInjectedClassNameType(
  1885. D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
  1886. }
  1887. }
  1888. void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  1889. llvm_unreachable("BuiltinTemplates are not serialized");
  1890. }
  1891. /// TODO: Unify with ClassTemplateDecl version?
  1892. /// May require unifying ClassTemplateDecl and
  1893. /// VarTemplateDecl beyond TemplateDecl...
  1894. void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
  1895. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1896. if (ThisDeclID == Redecl.getFirstID()) {
  1897. // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
  1898. // the specializations.
  1899. SmallVector<serialization::DeclID, 32> SpecIDs;
  1900. ReadDeclIDList(SpecIDs);
  1901. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1902. }
  1903. }
  1904. ASTDeclReader::RedeclarableResult
  1905. ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
  1906. ClassTemplateSpecializationDecl *D) {
  1907. RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
  1908. ASTContext &C = Reader.getContext();
  1909. if (Decl *InstD = ReadDecl()) {
  1910. if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
  1911. D->SpecializedTemplate = CTD;
  1912. } else {
  1913. SmallVector<TemplateArgument, 8> TemplArgs;
  1914. Record.readTemplateArgumentList(TemplArgs);
  1915. TemplateArgumentList *ArgList
  1916. = TemplateArgumentList::CreateCopy(C, TemplArgs);
  1917. auto *PS =
  1918. new (C) ClassTemplateSpecializationDecl::
  1919. SpecializedPartialSpecialization();
  1920. PS->PartialSpecialization
  1921. = cast<ClassTemplatePartialSpecializationDecl>(InstD);
  1922. PS->TemplateArgs = ArgList;
  1923. D->SpecializedTemplate = PS;
  1924. }
  1925. }
  1926. SmallVector<TemplateArgument, 8> TemplArgs;
  1927. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  1928. D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
  1929. D->PointOfInstantiation = ReadSourceLocation();
  1930. D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
  1931. bool writtenAsCanonicalDecl = Record.readInt();
  1932. if (writtenAsCanonicalDecl) {
  1933. auto *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
  1934. if (D->isCanonicalDecl()) { // It's kept in the folding set.
  1935. // Set this as, or find, the canonical declaration for this specialization
  1936. ClassTemplateSpecializationDecl *CanonSpec;
  1937. if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
  1938. CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
  1939. .GetOrInsertNode(Partial);
  1940. } else {
  1941. CanonSpec =
  1942. CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
  1943. }
  1944. // If there was already a canonical specialization, merge into it.
  1945. if (CanonSpec != D) {
  1946. mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
  1947. // This declaration might be a definition. Merge with any existing
  1948. // definition.
  1949. if (auto *DDD = D->DefinitionData) {
  1950. if (CanonSpec->DefinitionData)
  1951. MergeDefinitionData(CanonSpec, std::move(*DDD));
  1952. else
  1953. CanonSpec->DefinitionData = D->DefinitionData;
  1954. }
  1955. D->DefinitionData = CanonSpec->DefinitionData;
  1956. }
  1957. }
  1958. }
  1959. // Explicit info.
  1960. if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
  1961. auto *ExplicitInfo =
  1962. new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
  1963. ExplicitInfo->TypeAsWritten = TyInfo;
  1964. ExplicitInfo->ExternLoc = ReadSourceLocation();
  1965. ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
  1966. D->ExplicitInfo = ExplicitInfo;
  1967. }
  1968. return Redecl;
  1969. }
  1970. void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
  1971. ClassTemplatePartialSpecializationDecl *D) {
  1972. RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
  1973. D->TemplateParams = Record.readTemplateParameterList();
  1974. D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
  1975. // These are read/set from/to the first declaration.
  1976. if (ThisDeclID == Redecl.getFirstID()) {
  1977. D->InstantiatedFromMember.setPointer(
  1978. ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
  1979. D->InstantiatedFromMember.setInt(Record.readInt());
  1980. }
  1981. }
  1982. void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
  1983. ClassScopeFunctionSpecializationDecl *D) {
  1984. VisitDecl(D);
  1985. D->Specialization = ReadDeclAs<CXXMethodDecl>();
  1986. if (Record.readInt())
  1987. D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
  1988. }
  1989. void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1990. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1991. if (ThisDeclID == Redecl.getFirstID()) {
  1992. // This FunctionTemplateDecl owns a CommonPtr; read it.
  1993. SmallVector<serialization::DeclID, 32> SpecIDs;
  1994. ReadDeclIDList(SpecIDs);
  1995. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1996. }
  1997. }
  1998. /// TODO: Unify with ClassTemplateSpecializationDecl version?
  1999. /// May require unifying ClassTemplate(Partial)SpecializationDecl and
  2000. /// VarTemplate(Partial)SpecializationDecl with a new data
  2001. /// structure Template(Partial)SpecializationDecl, and
  2002. /// using Template(Partial)SpecializationDecl as input type.
  2003. ASTDeclReader::RedeclarableResult
  2004. ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
  2005. VarTemplateSpecializationDecl *D) {
  2006. RedeclarableResult Redecl = VisitVarDeclImpl(D);
  2007. ASTContext &C = Reader.getContext();
  2008. if (Decl *InstD = ReadDecl()) {
  2009. if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
  2010. D->SpecializedTemplate = VTD;
  2011. } else {
  2012. SmallVector<TemplateArgument, 8> TemplArgs;
  2013. Record.readTemplateArgumentList(TemplArgs);
  2014. TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
  2015. C, TemplArgs);
  2016. auto *PS =
  2017. new (C)
  2018. VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
  2019. PS->PartialSpecialization =
  2020. cast<VarTemplatePartialSpecializationDecl>(InstD);
  2021. PS->TemplateArgs = ArgList;
  2022. D->SpecializedTemplate = PS;
  2023. }
  2024. }
  2025. // Explicit info.
  2026. if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
  2027. auto *ExplicitInfo =
  2028. new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
  2029. ExplicitInfo->TypeAsWritten = TyInfo;
  2030. ExplicitInfo->ExternLoc = ReadSourceLocation();
  2031. ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
  2032. D->ExplicitInfo = ExplicitInfo;
  2033. }
  2034. SmallVector<TemplateArgument, 8> TemplArgs;
  2035. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  2036. D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
  2037. D->PointOfInstantiation = ReadSourceLocation();
  2038. D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
  2039. D->IsCompleteDefinition = Record.readInt();
  2040. bool writtenAsCanonicalDecl = Record.readInt();
  2041. if (writtenAsCanonicalDecl) {
  2042. auto *CanonPattern = ReadDeclAs<VarTemplateDecl>();
  2043. if (D->isCanonicalDecl()) { // It's kept in the folding set.
  2044. // FIXME: If it's already present, merge it.
  2045. if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
  2046. CanonPattern->getCommonPtr()->PartialSpecializations
  2047. .GetOrInsertNode(Partial);
  2048. } else {
  2049. CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
  2050. }
  2051. }
  2052. }
  2053. return Redecl;
  2054. }
  2055. /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
  2056. /// May require unifying ClassTemplate(Partial)SpecializationDecl and
  2057. /// VarTemplate(Partial)SpecializationDecl with a new data
  2058. /// structure Template(Partial)SpecializationDecl, and
  2059. /// using Template(Partial)SpecializationDecl as input type.
  2060. void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
  2061. VarTemplatePartialSpecializationDecl *D) {
  2062. RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
  2063. D->TemplateParams = Record.readTemplateParameterList();
  2064. D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
  2065. // These are read/set from/to the first declaration.
  2066. if (ThisDeclID == Redecl.getFirstID()) {
  2067. D->InstantiatedFromMember.setPointer(
  2068. ReadDeclAs<VarTemplatePartialSpecializationDecl>());
  2069. D->InstantiatedFromMember.setInt(Record.readInt());
  2070. }
  2071. }
  2072. void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
  2073. VisitTypeDecl(D);
  2074. D->setDeclaredWithTypename(Record.readInt());
  2075. if (Record.readInt())
  2076. D->setDefaultArgument(GetTypeSourceInfo());
  2077. }
  2078. void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  2079. VisitDeclaratorDecl(D);
  2080. // TemplateParmPosition.
  2081. D->setDepth(Record.readInt());
  2082. D->setPosition(Record.readInt());
  2083. if (D->isExpandedParameterPack()) {
  2084. auto TypesAndInfos =
  2085. D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
  2086. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  2087. new (&TypesAndInfos[I].first) QualType(Record.readType());
  2088. TypesAndInfos[I].second = GetTypeSourceInfo();
  2089. }
  2090. } else {
  2091. // Rest of NonTypeTemplateParmDecl.
  2092. D->ParameterPack = Record.readInt();
  2093. if (Record.readInt())
  2094. D->setDefaultArgument(Record.readExpr());
  2095. }
  2096. }
  2097. void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
  2098. VisitTemplateDecl(D);
  2099. // TemplateParmPosition.
  2100. D->setDepth(Record.readInt());
  2101. D->setPosition(Record.readInt());
  2102. if (D->isExpandedParameterPack()) {
  2103. auto **Data = D->getTrailingObjects<TemplateParameterList *>();
  2104. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  2105. I != N; ++I)
  2106. Data[I] = Record.readTemplateParameterList();
  2107. } else {
  2108. // Rest of TemplateTemplateParmDecl.
  2109. D->ParameterPack = Record.readInt();
  2110. if (Record.readInt())
  2111. D->setDefaultArgument(Reader.getContext(),
  2112. Record.readTemplateArgumentLoc());
  2113. }
  2114. }
  2115. void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  2116. VisitRedeclarableTemplateDecl(D);
  2117. }
  2118. void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
  2119. VisitDecl(D);
  2120. D->AssertExprAndFailed.setPointer(Record.readExpr());
  2121. D->AssertExprAndFailed.setInt(Record.readInt());
  2122. D->Message = cast_or_null<StringLiteral>(Record.readExpr());
  2123. D->RParenLoc = ReadSourceLocation();
  2124. }
  2125. void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
  2126. VisitDecl(D);
  2127. }
  2128. std::pair<uint64_t, uint64_t>
  2129. ASTDeclReader::VisitDeclContext(DeclContext *DC) {
  2130. uint64_t LexicalOffset = ReadLocalOffset();
  2131. uint64_t VisibleOffset = ReadLocalOffset();
  2132. return std::make_pair(LexicalOffset, VisibleOffset);
  2133. }
  2134. template <typename T>
  2135. ASTDeclReader::RedeclarableResult
  2136. ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
  2137. DeclID FirstDeclID = ReadDeclID();
  2138. Decl *MergeWith = nullptr;
  2139. bool IsKeyDecl = ThisDeclID == FirstDeclID;
  2140. bool IsFirstLocalDecl = false;
  2141. uint64_t RedeclOffset = 0;
  2142. // 0 indicates that this declaration was the only declaration of its entity,
  2143. // and is used for space optimization.
  2144. if (FirstDeclID == 0) {
  2145. FirstDeclID = ThisDeclID;
  2146. IsKeyDecl = true;
  2147. IsFirstLocalDecl = true;
  2148. } else if (unsigned N = Record.readInt()) {
  2149. // This declaration was the first local declaration, but may have imported
  2150. // other declarations.
  2151. IsKeyDecl = N == 1;
  2152. IsFirstLocalDecl = true;
  2153. // We have some declarations that must be before us in our redeclaration
  2154. // chain. Read them now, and remember that we ought to merge with one of
  2155. // them.
  2156. // FIXME: Provide a known merge target to the second and subsequent such
  2157. // declaration.
  2158. for (unsigned I = 0; I != N - 1; ++I)
  2159. MergeWith = ReadDecl();
  2160. RedeclOffset = ReadLocalOffset();
  2161. } else {
  2162. // This declaration was not the first local declaration. Read the first
  2163. // local declaration now, to trigger the import of other redeclarations.
  2164. (void)ReadDecl();
  2165. }
  2166. auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
  2167. if (FirstDecl != D) {
  2168. // We delay loading of the redeclaration chain to avoid deeply nested calls.
  2169. // We temporarily set the first (canonical) declaration as the previous one
  2170. // which is the one that matters and mark the real previous DeclID to be
  2171. // loaded & attached later on.
  2172. D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
  2173. D->First = FirstDecl->getCanonicalDecl();
  2174. }
  2175. auto *DAsT = static_cast<T *>(D);
  2176. // Note that we need to load local redeclarations of this decl and build a
  2177. // decl chain for them. This must happen *after* we perform the preloading
  2178. // above; this ensures that the redeclaration chain is built in the correct
  2179. // order.
  2180. if (IsFirstLocalDecl)
  2181. Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
  2182. return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
  2183. }
  2184. /// Attempts to merge the given declaration (D) with another declaration
  2185. /// of the same entity.
  2186. template<typename T>
  2187. void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
  2188. RedeclarableResult &Redecl,
  2189. DeclID TemplatePatternID) {
  2190. // If modules are not available, there is no reason to perform this merge.
  2191. if (!Reader.getContext().getLangOpts().Modules)
  2192. return;
  2193. // If we're not the canonical declaration, we don't need to merge.
  2194. if (!DBase->isFirstDecl())
  2195. return;
  2196. auto *D = static_cast<T *>(DBase);
  2197. if (auto *Existing = Redecl.getKnownMergeTarget())
  2198. // We already know of an existing declaration we should merge with.
  2199. mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
  2200. else if (FindExistingResult ExistingRes = findExisting(D))
  2201. if (T *Existing = ExistingRes)
  2202. mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
  2203. }
  2204. /// "Cast" to type T, asserting if we don't have an implicit conversion.
  2205. /// We use this to put code in a template that will only be valid for certain
  2206. /// instantiations.
  2207. template<typename T> static T assert_cast(T t) { return t; }
  2208. template<typename T> static T assert_cast(...) {
  2209. llvm_unreachable("bad assert_cast");
  2210. }
  2211. /// Merge together the pattern declarations from two template
  2212. /// declarations.
  2213. void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
  2214. RedeclarableTemplateDecl *Existing,
  2215. DeclID DsID, bool IsKeyDecl) {
  2216. auto *DPattern = D->getTemplatedDecl();
  2217. auto *ExistingPattern = Existing->getTemplatedDecl();
  2218. RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
  2219. DPattern->getCanonicalDecl()->getGlobalID(),
  2220. IsKeyDecl);
  2221. if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
  2222. // Merge with any existing definition.
  2223. // FIXME: This is duplicated in several places. Refactor.
  2224. auto *ExistingClass =
  2225. cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
  2226. if (auto *DDD = DClass->DefinitionData) {
  2227. if (ExistingClass->DefinitionData) {
  2228. MergeDefinitionData(ExistingClass, std::move(*DDD));
  2229. } else {
  2230. ExistingClass->DefinitionData = DClass->DefinitionData;
  2231. // We may have skipped this before because we thought that DClass
  2232. // was the canonical declaration.
  2233. Reader.PendingDefinitions.insert(DClass);
  2234. }
  2235. }
  2236. DClass->DefinitionData = ExistingClass->DefinitionData;
  2237. return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
  2238. Result);
  2239. }
  2240. if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
  2241. return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
  2242. Result);
  2243. if (auto *DVar = dyn_cast<VarDecl>(DPattern))
  2244. return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
  2245. if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
  2246. return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
  2247. Result);
  2248. llvm_unreachable("merged an unknown kind of redeclarable template");
  2249. }
  2250. /// Attempts to merge the given declaration (D) with another declaration
  2251. /// of the same entity.
  2252. template<typename T>
  2253. void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
  2254. RedeclarableResult &Redecl,
  2255. DeclID TemplatePatternID) {
  2256. auto *D = static_cast<T *>(DBase);
  2257. T *ExistingCanon = Existing->getCanonicalDecl();
  2258. T *DCanon = D->getCanonicalDecl();
  2259. if (ExistingCanon != DCanon) {
  2260. assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
  2261. "already merged this declaration");
  2262. // Have our redeclaration link point back at the canonical declaration
  2263. // of the existing declaration, so that this declaration has the
  2264. // appropriate canonical declaration.
  2265. D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
  2266. D->First = ExistingCanon;
  2267. ExistingCanon->Used |= D->Used;
  2268. D->Used = false;
  2269. // When we merge a namespace, update its pointer to the first namespace.
  2270. // We cannot have loaded any redeclarations of this declaration yet, so
  2271. // there's nothing else that needs to be updated.
  2272. if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
  2273. Namespace->AnonOrFirstNamespaceAndInline.setPointer(
  2274. assert_cast<NamespaceDecl*>(ExistingCanon));
  2275. // When we merge a template, merge its pattern.
  2276. if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
  2277. mergeTemplatePattern(
  2278. DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
  2279. TemplatePatternID, Redecl.isKeyDecl());
  2280. // If this declaration is a key declaration, make a note of that.
  2281. if (Redecl.isKeyDecl())
  2282. Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
  2283. }
  2284. }
  2285. /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
  2286. /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
  2287. /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
  2288. /// that some types are mergeable during deserialization, otherwise name
  2289. /// lookup fails. This is the case for EnumConstantDecl.
  2290. static bool allowODRLikeMergeInC(NamedDecl *ND) {
  2291. if (!ND)
  2292. return false;
  2293. // TODO: implement merge for other necessary decls.
  2294. if (isa<EnumConstantDecl>(ND))
  2295. return true;
  2296. return false;
  2297. }
  2298. /// Attempts to merge the given declaration (D) with another declaration
  2299. /// of the same entity, for the case where the entity is not actually
  2300. /// redeclarable. This happens, for instance, when merging the fields of
  2301. /// identical class definitions from two different modules.
  2302. template<typename T>
  2303. void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
  2304. // If modules are not available, there is no reason to perform this merge.
  2305. if (!Reader.getContext().getLangOpts().Modules)
  2306. return;
  2307. // ODR-based merging is performed in C++ and in some cases (tag types) in C.
  2308. // Note that C identically-named things in different translation units are
  2309. // not redeclarations, but may still have compatible types, where ODR-like
  2310. // semantics may apply.
  2311. if (!Reader.getContext().getLangOpts().CPlusPlus &&
  2312. !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
  2313. return;
  2314. if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
  2315. if (T *Existing = ExistingRes)
  2316. Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
  2317. Existing->getCanonicalDecl());
  2318. }
  2319. void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
  2320. VisitDecl(D);
  2321. unsigned NumVars = D->varlist_size();
  2322. SmallVector<Expr *, 16> Vars;
  2323. Vars.reserve(NumVars);
  2324. for (unsigned i = 0; i != NumVars; ++i) {
  2325. Vars.push_back(Record.readExpr());
  2326. }
  2327. D->setVars(Vars);
  2328. }
  2329. void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
  2330. VisitDecl(D);
  2331. unsigned NumVars = D->varlist_size();
  2332. unsigned NumClauses = D->clauselist_size();
  2333. SmallVector<Expr *, 16> Vars;
  2334. Vars.reserve(NumVars);
  2335. for (unsigned i = 0; i != NumVars; ++i) {
  2336. Vars.push_back(Record.readExpr());
  2337. }
  2338. D->setVars(Vars);
  2339. SmallVector<OMPClause *, 8> Clauses;
  2340. Clauses.reserve(NumClauses);
  2341. OMPClauseReader ClauseReader(Record);
  2342. for (unsigned I = 0; I != NumClauses; ++I)
  2343. Clauses.push_back(ClauseReader.readClause());
  2344. D->setClauses(Clauses);
  2345. }
  2346. void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
  2347. VisitDecl(D);
  2348. unsigned NumClauses = D->clauselist_size();
  2349. SmallVector<OMPClause *, 8> Clauses;
  2350. Clauses.reserve(NumClauses);
  2351. OMPClauseReader ClauseReader(Record);
  2352. for (unsigned I = 0; I != NumClauses; ++I)
  2353. Clauses.push_back(ClauseReader.readClause());
  2354. D->setClauses(Clauses);
  2355. }
  2356. void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
  2357. VisitValueDecl(D);
  2358. D->setLocation(ReadSourceLocation());
  2359. Expr *In = Record.readExpr();
  2360. Expr *Out = Record.readExpr();
  2361. D->setCombinerData(In, Out);
  2362. Expr *Combiner = Record.readExpr();
  2363. D->setCombiner(Combiner);
  2364. Expr *Orig = Record.readExpr();
  2365. Expr *Priv = Record.readExpr();
  2366. D->setInitializerData(Orig, Priv);
  2367. Expr *Init = Record.readExpr();
  2368. auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
  2369. D->setInitializer(Init, IK);
  2370. D->PrevDeclInScope = ReadDeclID();
  2371. }
  2372. void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
  2373. VisitValueDecl(D);
  2374. D->setLocation(ReadSourceLocation());
  2375. Expr *MapperVarRefE = Record.readExpr();
  2376. D->setMapperVarRef(MapperVarRefE);
  2377. D->VarName = Record.readDeclarationName();
  2378. D->PrevDeclInScope = ReadDeclID();
  2379. unsigned NumClauses = D->clauselist_size();
  2380. SmallVector<OMPClause *, 8> Clauses;
  2381. Clauses.reserve(NumClauses);
  2382. OMPClauseReader ClauseReader(Record);
  2383. for (unsigned I = 0; I != NumClauses; ++I)
  2384. Clauses.push_back(ClauseReader.readClause());
  2385. D->setClauses(Clauses);
  2386. }
  2387. void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
  2388. VisitVarDecl(D);
  2389. }
  2390. //===----------------------------------------------------------------------===//
  2391. // Attribute Reading
  2392. //===----------------------------------------------------------------------===//
  2393. namespace {
  2394. class AttrReader {
  2395. ModuleFile *F;
  2396. ASTReader *Reader;
  2397. const ASTReader::RecordData &Record;
  2398. unsigned &Idx;
  2399. public:
  2400. AttrReader(ModuleFile &F, ASTReader &Reader,
  2401. const ASTReader::RecordData &Record, unsigned &Idx)
  2402. : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
  2403. const uint64_t &readInt() { return Record[Idx++]; }
  2404. SourceRange readSourceRange() {
  2405. return Reader->ReadSourceRange(*F, Record, Idx);
  2406. }
  2407. SourceLocation readSourceLocation() {
  2408. return Reader->ReadSourceLocation(*F, Record, Idx);
  2409. }
  2410. Expr *readExpr() { return Reader->ReadExpr(*F); }
  2411. std::string readString() {
  2412. return Reader->ReadString(Record, Idx);
  2413. }
  2414. TypeSourceInfo *getTypeSourceInfo() {
  2415. return Reader->GetTypeSourceInfo(*F, Record, Idx);
  2416. }
  2417. IdentifierInfo *getIdentifierInfo() {
  2418. return Reader->GetIdentifierInfo(*F, Record, Idx);
  2419. }
  2420. VersionTuple readVersionTuple() {
  2421. return ASTReader::ReadVersionTuple(Record, Idx);
  2422. }
  2423. template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
  2424. return cast_or_null<T>(Reader->GetLocalDecl(*F, LocalID));
  2425. }
  2426. };
  2427. }
  2428. Attr *ASTReader::ReadAttr(ModuleFile &M, const RecordData &Rec,
  2429. unsigned &Idx) {
  2430. AttrReader Record(M, *this, Rec, Idx);
  2431. auto V = Record.readInt();
  2432. if (!V)
  2433. return nullptr;
  2434. Attr *New = nullptr;
  2435. // Kind is stored as a 1-based integer because 0 is used to indicate a null
  2436. // Attr pointer.
  2437. auto Kind = static_cast<attr::Kind>(V - 1);
  2438. ASTContext &Context = getContext();
  2439. IdentifierInfo *AttrName = Record.getIdentifierInfo();
  2440. IdentifierInfo *ScopeName = Record.getIdentifierInfo();
  2441. SourceRange AttrRange = Record.readSourceRange();
  2442. SourceLocation ScopeLoc = Record.readSourceLocation();
  2443. unsigned ParsedKind = Record.readInt();
  2444. unsigned Syntax = Record.readInt();
  2445. unsigned SpellingIndex = Record.readInt();
  2446. AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
  2447. AttributeCommonInfo::Kind(ParsedKind),
  2448. AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
  2449. #include "clang/Serialization/AttrPCHRead.inc"
  2450. assert(New && "Unable to decode attribute?");
  2451. return New;
  2452. }
  2453. /// Reads attributes from the current stream position.
  2454. void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
  2455. for (unsigned I = 0, E = Record.readInt(); I != E; ++I)
  2456. Attrs.push_back(Record.readAttr());
  2457. }
  2458. //===----------------------------------------------------------------------===//
  2459. // ASTReader Implementation
  2460. //===----------------------------------------------------------------------===//
  2461. /// Note that we have loaded the declaration with the given
  2462. /// Index.
  2463. ///
  2464. /// This routine notes that this declaration has already been loaded,
  2465. /// so that future GetDecl calls will return this declaration rather
  2466. /// than trying to load a new declaration.
  2467. inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
  2468. assert(!DeclsLoaded[Index] && "Decl loaded twice?");
  2469. DeclsLoaded[Index] = D;
  2470. }
  2471. /// Determine whether the consumer will be interested in seeing
  2472. /// this declaration (via HandleTopLevelDecl).
  2473. ///
  2474. /// This routine should return true for anything that might affect
  2475. /// code generation, e.g., inline function definitions, Objective-C
  2476. /// declarations with metadata, etc.
  2477. static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
  2478. // An ObjCMethodDecl is never considered as "interesting" because its
  2479. // implementation container always is.
  2480. // An ImportDecl or VarDecl imported from a module map module will get
  2481. // emitted when we import the relevant module.
  2482. if (isPartOfPerModuleInitializer(D)) {
  2483. auto *M = D->getImportedOwningModule();
  2484. if (M && M->Kind == Module::ModuleMapModule &&
  2485. Ctx.DeclMustBeEmitted(D))
  2486. return false;
  2487. }
  2488. if (isa<FileScopeAsmDecl>(D) ||
  2489. isa<ObjCProtocolDecl>(D) ||
  2490. isa<ObjCImplDecl>(D) ||
  2491. isa<ImportDecl>(D) ||
  2492. isa<PragmaCommentDecl>(D) ||
  2493. isa<PragmaDetectMismatchDecl>(D))
  2494. return true;
  2495. if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
  2496. isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D))
  2497. return !D->getDeclContext()->isFunctionOrMethod();
  2498. if (const auto *Var = dyn_cast<VarDecl>(D))
  2499. return Var->isFileVarDecl() &&
  2500. (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
  2501. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
  2502. if (const auto *Func = dyn_cast<FunctionDecl>(D))
  2503. return Func->doesThisDeclarationHaveABody() || HasBody;
  2504. if (auto *ES = D->getASTContext().getExternalSource())
  2505. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  2506. return true;
  2507. return false;
  2508. }
  2509. /// Get the correct cursor and offset for loading a declaration.
  2510. ASTReader::RecordLocation
  2511. ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
  2512. GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
  2513. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  2514. ModuleFile *M = I->second;
  2515. const DeclOffset &DOffs =
  2516. M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
  2517. Loc = TranslateSourceLocation(*M, DOffs.getLocation());
  2518. return RecordLocation(M, DOffs.BitOffset);
  2519. }
  2520. ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
  2521. auto I = GlobalBitOffsetsMap.find(GlobalOffset);
  2522. assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
  2523. return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
  2524. }
  2525. uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
  2526. return LocalOffset + M.GlobalBitOffset;
  2527. }
  2528. static bool isSameTemplateParameterList(const TemplateParameterList *X,
  2529. const TemplateParameterList *Y);
  2530. /// Determine whether two template parameters are similar enough
  2531. /// that they may be used in declarations of the same template.
  2532. static bool isSameTemplateParameter(const NamedDecl *X,
  2533. const NamedDecl *Y) {
  2534. if (X->getKind() != Y->getKind())
  2535. return false;
  2536. if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
  2537. const auto *TY = cast<TemplateTypeParmDecl>(Y);
  2538. return TX->isParameterPack() == TY->isParameterPack();
  2539. }
  2540. if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
  2541. const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
  2542. return TX->isParameterPack() == TY->isParameterPack() &&
  2543. TX->getASTContext().hasSameType(TX->getType(), TY->getType());
  2544. }
  2545. const auto *TX = cast<TemplateTemplateParmDecl>(X);
  2546. const auto *TY = cast<TemplateTemplateParmDecl>(Y);
  2547. return TX->isParameterPack() == TY->isParameterPack() &&
  2548. isSameTemplateParameterList(TX->getTemplateParameters(),
  2549. TY->getTemplateParameters());
  2550. }
  2551. static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
  2552. if (auto *NS = X->getAsNamespace())
  2553. return NS;
  2554. if (auto *NAS = X->getAsNamespaceAlias())
  2555. return NAS->getNamespace();
  2556. return nullptr;
  2557. }
  2558. static bool isSameQualifier(const NestedNameSpecifier *X,
  2559. const NestedNameSpecifier *Y) {
  2560. if (auto *NSX = getNamespace(X)) {
  2561. auto *NSY = getNamespace(Y);
  2562. if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
  2563. return false;
  2564. } else if (X->getKind() != Y->getKind())
  2565. return false;
  2566. // FIXME: For namespaces and types, we're permitted to check that the entity
  2567. // is named via the same tokens. We should probably do so.
  2568. switch (X->getKind()) {
  2569. case NestedNameSpecifier::Identifier:
  2570. if (X->getAsIdentifier() != Y->getAsIdentifier())
  2571. return false;
  2572. break;
  2573. case NestedNameSpecifier::Namespace:
  2574. case NestedNameSpecifier::NamespaceAlias:
  2575. // We've already checked that we named the same namespace.
  2576. break;
  2577. case NestedNameSpecifier::TypeSpec:
  2578. case NestedNameSpecifier::TypeSpecWithTemplate:
  2579. if (X->getAsType()->getCanonicalTypeInternal() !=
  2580. Y->getAsType()->getCanonicalTypeInternal())
  2581. return false;
  2582. break;
  2583. case NestedNameSpecifier::Global:
  2584. case NestedNameSpecifier::Super:
  2585. return true;
  2586. }
  2587. // Recurse into earlier portion of NNS, if any.
  2588. auto *PX = X->getPrefix();
  2589. auto *PY = Y->getPrefix();
  2590. if (PX && PY)
  2591. return isSameQualifier(PX, PY);
  2592. return !PX && !PY;
  2593. }
  2594. /// Determine whether two template parameter lists are similar enough
  2595. /// that they may be used in declarations of the same template.
  2596. static bool isSameTemplateParameterList(const TemplateParameterList *X,
  2597. const TemplateParameterList *Y) {
  2598. if (X->size() != Y->size())
  2599. return false;
  2600. for (unsigned I = 0, N = X->size(); I != N; ++I)
  2601. if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
  2602. return false;
  2603. return true;
  2604. }
  2605. /// Determine whether the attributes we can overload on are identical for A and
  2606. /// B. Will ignore any overloadable attrs represented in the type of A and B.
  2607. static bool hasSameOverloadableAttrs(const FunctionDecl *A,
  2608. const FunctionDecl *B) {
  2609. // Note that pass_object_size attributes are represented in the function's
  2610. // ExtParameterInfo, so we don't need to check them here.
  2611. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  2612. auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
  2613. auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
  2614. for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
  2615. Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  2616. Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  2617. // Return false if the number of enable_if attributes is different.
  2618. if (!Cand1A || !Cand2A)
  2619. return false;
  2620. Cand1ID.clear();
  2621. Cand2ID.clear();
  2622. (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
  2623. (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
  2624. // Return false if any of the enable_if expressions of A and B are
  2625. // different.
  2626. if (Cand1ID != Cand2ID)
  2627. return false;
  2628. }
  2629. return true;
  2630. }
  2631. /// Determine whether the two declarations refer to the same entity.
  2632. static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
  2633. assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
  2634. if (X == Y)
  2635. return true;
  2636. // Must be in the same context.
  2637. //
  2638. // Note that we can't use DeclContext::Equals here, because the DeclContexts
  2639. // could be two different declarations of the same function. (We will fix the
  2640. // semantic DC to refer to the primary definition after merging.)
  2641. if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
  2642. cast<Decl>(Y->getDeclContext()->getRedeclContext())))
  2643. return false;
  2644. // Two typedefs refer to the same entity if they have the same underlying
  2645. // type.
  2646. if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
  2647. if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
  2648. return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
  2649. TypedefY->getUnderlyingType());
  2650. // Must have the same kind.
  2651. if (X->getKind() != Y->getKind())
  2652. return false;
  2653. // Objective-C classes and protocols with the same name always match.
  2654. if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
  2655. return true;
  2656. if (isa<ClassTemplateSpecializationDecl>(X)) {
  2657. // No need to handle these here: we merge them when adding them to the
  2658. // template.
  2659. return false;
  2660. }
  2661. // Compatible tags match.
  2662. if (const auto *TagX = dyn_cast<TagDecl>(X)) {
  2663. const auto *TagY = cast<TagDecl>(Y);
  2664. return (TagX->getTagKind() == TagY->getTagKind()) ||
  2665. ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
  2666. TagX->getTagKind() == TTK_Interface) &&
  2667. (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
  2668. TagY->getTagKind() == TTK_Interface));
  2669. }
  2670. // Functions with the same type and linkage match.
  2671. // FIXME: This needs to cope with merging of prototyped/non-prototyped
  2672. // functions, etc.
  2673. if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
  2674. const auto *FuncY = cast<FunctionDecl>(Y);
  2675. if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
  2676. const auto *CtorY = cast<CXXConstructorDecl>(Y);
  2677. if (CtorX->getInheritedConstructor() &&
  2678. !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
  2679. CtorY->getInheritedConstructor().getConstructor()))
  2680. return false;
  2681. }
  2682. if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
  2683. return false;
  2684. // Multiversioned functions with different feature strings are represented
  2685. // as separate declarations.
  2686. if (FuncX->isMultiVersion()) {
  2687. const auto *TAX = FuncX->getAttr<TargetAttr>();
  2688. const auto *TAY = FuncY->getAttr<TargetAttr>();
  2689. assert(TAX && TAY && "Multiversion Function without target attribute");
  2690. if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
  2691. return false;
  2692. }
  2693. ASTContext &C = FuncX->getASTContext();
  2694. auto GetTypeAsWritten = [](const FunctionDecl *FD) {
  2695. // Map to the first declaration that we've already merged into this one.
  2696. // The TSI of redeclarations might not match (due to calling conventions
  2697. // being inherited onto the type but not the TSI), but the TSI type of
  2698. // the first declaration of the function should match across modules.
  2699. FD = FD->getCanonicalDecl();
  2700. return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
  2701. : FD->getType();
  2702. };
  2703. QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
  2704. if (!C.hasSameType(XT, YT)) {
  2705. // We can get functions with different types on the redecl chain in C++17
  2706. // if they have differing exception specifications and at least one of
  2707. // the excpetion specs is unresolved.
  2708. auto *XFPT = XT->getAs<FunctionProtoType>();
  2709. auto *YFPT = YT->getAs<FunctionProtoType>();
  2710. if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
  2711. (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
  2712. isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
  2713. C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
  2714. return true;
  2715. return false;
  2716. }
  2717. return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
  2718. hasSameOverloadableAttrs(FuncX, FuncY);
  2719. }
  2720. // Variables with the same type and linkage match.
  2721. if (const auto *VarX = dyn_cast<VarDecl>(X)) {
  2722. const auto *VarY = cast<VarDecl>(Y);
  2723. if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
  2724. ASTContext &C = VarX->getASTContext();
  2725. if (C.hasSameType(VarX->getType(), VarY->getType()))
  2726. return true;
  2727. // We can get decls with different types on the redecl chain. Eg.
  2728. // template <typename T> struct S { static T Var[]; }; // #1
  2729. // template <typename T> T S<T>::Var[sizeof(T)]; // #2
  2730. // Only? happens when completing an incomplete array type. In this case
  2731. // when comparing #1 and #2 we should go through their element type.
  2732. const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
  2733. const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
  2734. if (!VarXTy || !VarYTy)
  2735. return false;
  2736. if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
  2737. return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
  2738. }
  2739. return false;
  2740. }
  2741. // Namespaces with the same name and inlinedness match.
  2742. if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
  2743. const auto *NamespaceY = cast<NamespaceDecl>(Y);
  2744. return NamespaceX->isInline() == NamespaceY->isInline();
  2745. }
  2746. // Identical template names and kinds match if their template parameter lists
  2747. // and patterns match.
  2748. if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
  2749. const auto *TemplateY = cast<TemplateDecl>(Y);
  2750. return isSameEntity(TemplateX->getTemplatedDecl(),
  2751. TemplateY->getTemplatedDecl()) &&
  2752. isSameTemplateParameterList(TemplateX->getTemplateParameters(),
  2753. TemplateY->getTemplateParameters());
  2754. }
  2755. // Fields with the same name and the same type match.
  2756. if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
  2757. const auto *FDY = cast<FieldDecl>(Y);
  2758. // FIXME: Also check the bitwidth is odr-equivalent, if any.
  2759. return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
  2760. }
  2761. // Indirect fields with the same target field match.
  2762. if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
  2763. const auto *IFDY = cast<IndirectFieldDecl>(Y);
  2764. return IFDX->getAnonField()->getCanonicalDecl() ==
  2765. IFDY->getAnonField()->getCanonicalDecl();
  2766. }
  2767. // Enumerators with the same name match.
  2768. if (isa<EnumConstantDecl>(X))
  2769. // FIXME: Also check the value is odr-equivalent.
  2770. return true;
  2771. // Using shadow declarations with the same target match.
  2772. if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
  2773. const auto *USY = cast<UsingShadowDecl>(Y);
  2774. return USX->getTargetDecl() == USY->getTargetDecl();
  2775. }
  2776. // Using declarations with the same qualifier match. (We already know that
  2777. // the name matches.)
  2778. if (const auto *UX = dyn_cast<UsingDecl>(X)) {
  2779. const auto *UY = cast<UsingDecl>(Y);
  2780. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  2781. UX->hasTypename() == UY->hasTypename() &&
  2782. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  2783. }
  2784. if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
  2785. const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
  2786. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  2787. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  2788. }
  2789. if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
  2790. return isSameQualifier(
  2791. UX->getQualifier(),
  2792. cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
  2793. // Namespace alias definitions with the same target match.
  2794. if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
  2795. const auto *NAY = cast<NamespaceAliasDecl>(Y);
  2796. return NAX->getNamespace()->Equals(NAY->getNamespace());
  2797. }
  2798. return false;
  2799. }
  2800. /// Find the context in which we should search for previous declarations when
  2801. /// looking for declarations to merge.
  2802. DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
  2803. DeclContext *DC) {
  2804. if (auto *ND = dyn_cast<NamespaceDecl>(DC))
  2805. return ND->getOriginalNamespace();
  2806. if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
  2807. // Try to dig out the definition.
  2808. auto *DD = RD->DefinitionData;
  2809. if (!DD)
  2810. DD = RD->getCanonicalDecl()->DefinitionData;
  2811. // If there's no definition yet, then DC's definition is added by an update
  2812. // record, but we've not yet loaded that update record. In this case, we
  2813. // commit to DC being the canonical definition now, and will fix this when
  2814. // we load the update record.
  2815. if (!DD) {
  2816. DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
  2817. RD->setCompleteDefinition(true);
  2818. RD->DefinitionData = DD;
  2819. RD->getCanonicalDecl()->DefinitionData = DD;
  2820. // Track that we did this horrible thing so that we can fix it later.
  2821. Reader.PendingFakeDefinitionData.insert(
  2822. std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
  2823. }
  2824. return DD->Definition;
  2825. }
  2826. if (auto *ED = dyn_cast<EnumDecl>(DC))
  2827. return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
  2828. : nullptr;
  2829. // We can see the TU here only if we have no Sema object. In that case,
  2830. // there's no TU scope to look in, so using the DC alone is sufficient.
  2831. if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
  2832. return TU;
  2833. return nullptr;
  2834. }
  2835. ASTDeclReader::FindExistingResult::~FindExistingResult() {
  2836. // Record that we had a typedef name for linkage whether or not we merge
  2837. // with that declaration.
  2838. if (TypedefNameForLinkage) {
  2839. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  2840. Reader.ImportedTypedefNamesForLinkage.insert(
  2841. std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
  2842. return;
  2843. }
  2844. if (!AddResult || Existing)
  2845. return;
  2846. DeclarationName Name = New->getDeclName();
  2847. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  2848. if (needsAnonymousDeclarationNumber(New)) {
  2849. setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
  2850. AnonymousDeclNumber, New);
  2851. } else if (DC->isTranslationUnit() &&
  2852. !Reader.getContext().getLangOpts().CPlusPlus) {
  2853. if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
  2854. Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
  2855. .push_back(New);
  2856. } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
  2857. // Add the declaration to its redeclaration context so later merging
  2858. // lookups will find it.
  2859. MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
  2860. }
  2861. }
  2862. /// Find the declaration that should be merged into, given the declaration found
  2863. /// by name lookup. If we're merging an anonymous declaration within a typedef,
  2864. /// we need a matching typedef, and we merge with the type inside it.
  2865. static NamedDecl *getDeclForMerging(NamedDecl *Found,
  2866. bool IsTypedefNameForLinkage) {
  2867. if (!IsTypedefNameForLinkage)
  2868. return Found;
  2869. // If we found a typedef declaration that gives a name to some other
  2870. // declaration, then we want that inner declaration. Declarations from
  2871. // AST files are handled via ImportedTypedefNamesForLinkage.
  2872. if (Found->isFromASTFile())
  2873. return nullptr;
  2874. if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
  2875. return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  2876. return nullptr;
  2877. }
  2878. /// Find the declaration to use to populate the anonymous declaration table
  2879. /// for the given lexical DeclContext. We only care about finding local
  2880. /// definitions of the context; we'll merge imported ones as we go.
  2881. DeclContext *
  2882. ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
  2883. // For classes, we track the definition as we merge.
  2884. if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
  2885. auto *DD = RD->getCanonicalDecl()->DefinitionData;
  2886. return DD ? DD->Definition : nullptr;
  2887. }
  2888. // For anything else, walk its merged redeclarations looking for a definition.
  2889. // Note that we can't just call getDefinition here because the redeclaration
  2890. // chain isn't wired up.
  2891. for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
  2892. if (auto *FD = dyn_cast<FunctionDecl>(D))
  2893. if (FD->isThisDeclarationADefinition())
  2894. return FD;
  2895. if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
  2896. if (MD->isThisDeclarationADefinition())
  2897. return MD;
  2898. }
  2899. // No merged definition yet.
  2900. return nullptr;
  2901. }
  2902. NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
  2903. DeclContext *DC,
  2904. unsigned Index) {
  2905. // If the lexical context has been merged, look into the now-canonical
  2906. // definition.
  2907. auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
  2908. // If we've seen this before, return the canonical declaration.
  2909. auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
  2910. if (Index < Previous.size() && Previous[Index])
  2911. return Previous[Index];
  2912. // If this is the first time, but we have parsed a declaration of the context,
  2913. // build the anonymous declaration list from the parsed declaration.
  2914. auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
  2915. if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
  2916. numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
  2917. if (Previous.size() == Number)
  2918. Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
  2919. else
  2920. Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
  2921. });
  2922. }
  2923. return Index < Previous.size() ? Previous[Index] : nullptr;
  2924. }
  2925. void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
  2926. DeclContext *DC, unsigned Index,
  2927. NamedDecl *D) {
  2928. auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
  2929. auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
  2930. if (Index >= Previous.size())
  2931. Previous.resize(Index + 1);
  2932. if (!Previous[Index])
  2933. Previous[Index] = D;
  2934. }
  2935. ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
  2936. DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
  2937. : D->getDeclName();
  2938. if (!Name && !needsAnonymousDeclarationNumber(D)) {
  2939. // Don't bother trying to find unnamed declarations that are in
  2940. // unmergeable contexts.
  2941. FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
  2942. AnonymousDeclNumber, TypedefNameForLinkage);
  2943. Result.suppress();
  2944. return Result;
  2945. }
  2946. DeclContext *DC = D->getDeclContext()->getRedeclContext();
  2947. if (TypedefNameForLinkage) {
  2948. auto It = Reader.ImportedTypedefNamesForLinkage.find(
  2949. std::make_pair(DC, TypedefNameForLinkage));
  2950. if (It != Reader.ImportedTypedefNamesForLinkage.end())
  2951. if (isSameEntity(It->second, D))
  2952. return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
  2953. TypedefNameForLinkage);
  2954. // Go on to check in other places in case an existing typedef name
  2955. // was not imported.
  2956. }
  2957. if (needsAnonymousDeclarationNumber(D)) {
  2958. // This is an anonymous declaration that we may need to merge. Look it up
  2959. // in its context by number.
  2960. if (auto *Existing = getAnonymousDeclForMerging(
  2961. Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
  2962. if (isSameEntity(Existing, D))
  2963. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  2964. TypedefNameForLinkage);
  2965. } else if (DC->isTranslationUnit() &&
  2966. !Reader.getContext().getLangOpts().CPlusPlus) {
  2967. IdentifierResolver &IdResolver = Reader.getIdResolver();
  2968. // Temporarily consider the identifier to be up-to-date. We don't want to
  2969. // cause additional lookups here.
  2970. class UpToDateIdentifierRAII {
  2971. IdentifierInfo *II;
  2972. bool WasOutToDate = false;
  2973. public:
  2974. explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
  2975. if (II) {
  2976. WasOutToDate = II->isOutOfDate();
  2977. if (WasOutToDate)
  2978. II->setOutOfDate(false);
  2979. }
  2980. }
  2981. ~UpToDateIdentifierRAII() {
  2982. if (WasOutToDate)
  2983. II->setOutOfDate(true);
  2984. }
  2985. } UpToDate(Name.getAsIdentifierInfo());
  2986. for (IdentifierResolver::iterator I = IdResolver.begin(Name),
  2987. IEnd = IdResolver.end();
  2988. I != IEnd; ++I) {
  2989. if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
  2990. if (isSameEntity(Existing, D))
  2991. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  2992. TypedefNameForLinkage);
  2993. }
  2994. } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
  2995. DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
  2996. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2997. if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
  2998. if (isSameEntity(Existing, D))
  2999. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  3000. TypedefNameForLinkage);
  3001. }
  3002. } else {
  3003. // Not in a mergeable context.
  3004. return FindExistingResult(Reader);
  3005. }
  3006. // If this declaration is from a merged context, make a note that we need to
  3007. // check that the canonical definition of that context contains the decl.
  3008. //
  3009. // FIXME: We should do something similar if we merge two definitions of the
  3010. // same template specialization into the same CXXRecordDecl.
  3011. auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
  3012. if (MergedDCIt != Reader.MergedDeclContexts.end() &&
  3013. MergedDCIt->second == D->getDeclContext())
  3014. Reader.PendingOdrMergeChecks.push_back(D);
  3015. return FindExistingResult(Reader, D, /*Existing=*/nullptr,
  3016. AnonymousDeclNumber, TypedefNameForLinkage);
  3017. }
  3018. template<typename DeclT>
  3019. Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
  3020. return D->RedeclLink.getLatestNotUpdated();
  3021. }
  3022. Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
  3023. llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
  3024. }
  3025. Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
  3026. assert(D);
  3027. switch (D->getKind()) {
  3028. #define ABSTRACT_DECL(TYPE)
  3029. #define DECL(TYPE, BASE) \
  3030. case Decl::TYPE: \
  3031. return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
  3032. #include "clang/AST/DeclNodes.inc"
  3033. }
  3034. llvm_unreachable("unknown decl kind");
  3035. }
  3036. Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
  3037. return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
  3038. }
  3039. template<typename DeclT>
  3040. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  3041. Redeclarable<DeclT> *D,
  3042. Decl *Previous, Decl *Canon) {
  3043. D->RedeclLink.setPrevious(cast<DeclT>(Previous));
  3044. D->First = cast<DeclT>(Previous)->First;
  3045. }
  3046. namespace clang {
  3047. template<>
  3048. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  3049. Redeclarable<VarDecl> *D,
  3050. Decl *Previous, Decl *Canon) {
  3051. auto *VD = static_cast<VarDecl *>(D);
  3052. auto *PrevVD = cast<VarDecl>(Previous);
  3053. D->RedeclLink.setPrevious(PrevVD);
  3054. D->First = PrevVD->First;
  3055. // We should keep at most one definition on the chain.
  3056. // FIXME: Cache the definition once we've found it. Building a chain with
  3057. // N definitions currently takes O(N^2) time here.
  3058. if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
  3059. for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
  3060. if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
  3061. Reader.mergeDefinitionVisibility(CurD, VD);
  3062. VD->demoteThisDefinitionToDeclaration();
  3063. break;
  3064. }
  3065. }
  3066. }
  3067. }
  3068. static bool isUndeducedReturnType(QualType T) {
  3069. auto *DT = T->getContainedDeducedType();
  3070. return DT && !DT->isDeduced();
  3071. }
  3072. template<>
  3073. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  3074. Redeclarable<FunctionDecl> *D,
  3075. Decl *Previous, Decl *Canon) {
  3076. auto *FD = static_cast<FunctionDecl *>(D);
  3077. auto *PrevFD = cast<FunctionDecl>(Previous);
  3078. FD->RedeclLink.setPrevious(PrevFD);
  3079. FD->First = PrevFD->First;
  3080. // If the previous declaration is an inline function declaration, then this
  3081. // declaration is too.
  3082. if (PrevFD->isInlined() != FD->isInlined()) {
  3083. // FIXME: [dcl.fct.spec]p4:
  3084. // If a function with external linkage is declared inline in one
  3085. // translation unit, it shall be declared inline in all translation
  3086. // units in which it appears.
  3087. //
  3088. // Be careful of this case:
  3089. //
  3090. // module A:
  3091. // template<typename T> struct X { void f(); };
  3092. // template<typename T> inline void X<T>::f() {}
  3093. //
  3094. // module B instantiates the declaration of X<int>::f
  3095. // module C instantiates the definition of X<int>::f
  3096. //
  3097. // If module B and C are merged, we do not have a violation of this rule.
  3098. FD->setImplicitlyInline(true);
  3099. }
  3100. auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  3101. auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
  3102. if (FPT && PrevFPT) {
  3103. // If we need to propagate an exception specification along the redecl
  3104. // chain, make a note of that so that we can do so later.
  3105. bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
  3106. bool WasUnresolved =
  3107. isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
  3108. if (IsUnresolved != WasUnresolved)
  3109. Reader.PendingExceptionSpecUpdates.insert(
  3110. {Canon, IsUnresolved ? PrevFD : FD});
  3111. // If we need to propagate a deduced return type along the redecl chain,
  3112. // make a note of that so that we can do it later.
  3113. bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
  3114. bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
  3115. if (IsUndeduced != WasUndeduced)
  3116. Reader.PendingDeducedTypeUpdates.insert(
  3117. {cast<FunctionDecl>(Canon),
  3118. (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
  3119. }
  3120. }
  3121. } // namespace clang
  3122. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
  3123. llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
  3124. }
  3125. /// Inherit the default template argument from \p From to \p To. Returns
  3126. /// \c false if there is no default template for \p From.
  3127. template <typename ParmDecl>
  3128. static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
  3129. Decl *ToD) {
  3130. auto *To = cast<ParmDecl>(ToD);
  3131. if (!From->hasDefaultArgument())
  3132. return false;
  3133. To->setInheritedDefaultArgument(Context, From);
  3134. return true;
  3135. }
  3136. static void inheritDefaultTemplateArguments(ASTContext &Context,
  3137. TemplateDecl *From,
  3138. TemplateDecl *To) {
  3139. auto *FromTP = From->getTemplateParameters();
  3140. auto *ToTP = To->getTemplateParameters();
  3141. assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
  3142. for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
  3143. NamedDecl *FromParam = FromTP->getParam(I);
  3144. NamedDecl *ToParam = ToTP->getParam(I);
  3145. if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
  3146. inheritDefaultTemplateArgument(Context, FTTP, ToParam);
  3147. else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
  3148. inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
  3149. else
  3150. inheritDefaultTemplateArgument(
  3151. Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
  3152. }
  3153. }
  3154. void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
  3155. Decl *Previous, Decl *Canon) {
  3156. assert(D && Previous);
  3157. switch (D->getKind()) {
  3158. #define ABSTRACT_DECL(TYPE)
  3159. #define DECL(TYPE, BASE) \
  3160. case Decl::TYPE: \
  3161. attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
  3162. break;
  3163. #include "clang/AST/DeclNodes.inc"
  3164. }
  3165. // If the declaration was visible in one module, a redeclaration of it in
  3166. // another module remains visible even if it wouldn't be visible by itself.
  3167. //
  3168. // FIXME: In this case, the declaration should only be visible if a module
  3169. // that makes it visible has been imported.
  3170. D->IdentifierNamespace |=
  3171. Previous->IdentifierNamespace &
  3172. (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
  3173. // If the declaration declares a template, it may inherit default arguments
  3174. // from the previous declaration.
  3175. if (auto *TD = dyn_cast<TemplateDecl>(D))
  3176. inheritDefaultTemplateArguments(Reader.getContext(),
  3177. cast<TemplateDecl>(Previous), TD);
  3178. }
  3179. template<typename DeclT>
  3180. void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
  3181. D->RedeclLink.setLatest(cast<DeclT>(Latest));
  3182. }
  3183. void ASTDeclReader::attachLatestDeclImpl(...) {
  3184. llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
  3185. }
  3186. void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
  3187. assert(D && Latest);
  3188. switch (D->getKind()) {
  3189. #define ABSTRACT_DECL(TYPE)
  3190. #define DECL(TYPE, BASE) \
  3191. case Decl::TYPE: \
  3192. attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
  3193. break;
  3194. #include "clang/AST/DeclNodes.inc"
  3195. }
  3196. }
  3197. template<typename DeclT>
  3198. void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
  3199. D->RedeclLink.markIncomplete();
  3200. }
  3201. void ASTDeclReader::markIncompleteDeclChainImpl(...) {
  3202. llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
  3203. }
  3204. void ASTReader::markIncompleteDeclChain(Decl *D) {
  3205. switch (D->getKind()) {
  3206. #define ABSTRACT_DECL(TYPE)
  3207. #define DECL(TYPE, BASE) \
  3208. case Decl::TYPE: \
  3209. ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
  3210. break;
  3211. #include "clang/AST/DeclNodes.inc"
  3212. }
  3213. }
  3214. /// Read the declaration at the given offset from the AST file.
  3215. Decl *ASTReader::ReadDeclRecord(DeclID ID) {
  3216. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  3217. SourceLocation DeclLoc;
  3218. RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
  3219. llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  3220. // Keep track of where we are in the stream, then jump back there
  3221. // after reading this declaration.
  3222. SavedStreamPosition SavedPosition(DeclsCursor);
  3223. ReadingKindTracker ReadingKind(Read_Decl, *this);
  3224. // Note that we are loading a declaration record.
  3225. Deserializing ADecl(this);
  3226. auto Fail = [](const char *what, llvm::Error &&Err) {
  3227. llvm::report_fatal_error(Twine("ASTReader::ReadDeclRecord failed ") + what +
  3228. ": " + toString(std::move(Err)));
  3229. };
  3230. if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
  3231. Fail("jumping", std::move(JumpFailed));
  3232. ASTRecordReader Record(*this, *Loc.F);
  3233. ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
  3234. Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
  3235. if (!MaybeCode)
  3236. Fail("reading code", MaybeCode.takeError());
  3237. unsigned Code = MaybeCode.get();
  3238. ASTContext &Context = getContext();
  3239. Decl *D = nullptr;
  3240. Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
  3241. if (!MaybeDeclCode)
  3242. llvm::report_fatal_error(
  3243. "ASTReader::ReadDeclRecord failed reading decl code: " +
  3244. toString(MaybeDeclCode.takeError()));
  3245. switch ((DeclCode)MaybeDeclCode.get()) {
  3246. case DECL_CONTEXT_LEXICAL:
  3247. case DECL_CONTEXT_VISIBLE:
  3248. llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
  3249. case DECL_TYPEDEF:
  3250. D = TypedefDecl::CreateDeserialized(Context, ID);
  3251. break;
  3252. case DECL_TYPEALIAS:
  3253. D = TypeAliasDecl::CreateDeserialized(Context, ID);
  3254. break;
  3255. case DECL_ENUM:
  3256. D = EnumDecl::CreateDeserialized(Context, ID);
  3257. break;
  3258. case DECL_RECORD:
  3259. D = RecordDecl::CreateDeserialized(Context, ID);
  3260. break;
  3261. case DECL_ENUM_CONSTANT:
  3262. D = EnumConstantDecl::CreateDeserialized(Context, ID);
  3263. break;
  3264. case DECL_FUNCTION:
  3265. D = FunctionDecl::CreateDeserialized(Context, ID);
  3266. break;
  3267. case DECL_LINKAGE_SPEC:
  3268. D = LinkageSpecDecl::CreateDeserialized(Context, ID);
  3269. break;
  3270. case DECL_EXPORT:
  3271. D = ExportDecl::CreateDeserialized(Context, ID);
  3272. break;
  3273. case DECL_LABEL:
  3274. D = LabelDecl::CreateDeserialized(Context, ID);
  3275. break;
  3276. case DECL_NAMESPACE:
  3277. D = NamespaceDecl::CreateDeserialized(Context, ID);
  3278. break;
  3279. case DECL_NAMESPACE_ALIAS:
  3280. D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
  3281. break;
  3282. case DECL_USING:
  3283. D = UsingDecl::CreateDeserialized(Context, ID);
  3284. break;
  3285. case DECL_USING_PACK:
  3286. D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
  3287. break;
  3288. case DECL_USING_SHADOW:
  3289. D = UsingShadowDecl::CreateDeserialized(Context, ID);
  3290. break;
  3291. case DECL_CONSTRUCTOR_USING_SHADOW:
  3292. D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
  3293. break;
  3294. case DECL_USING_DIRECTIVE:
  3295. D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
  3296. break;
  3297. case DECL_UNRESOLVED_USING_VALUE:
  3298. D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
  3299. break;
  3300. case DECL_UNRESOLVED_USING_TYPENAME:
  3301. D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
  3302. break;
  3303. case DECL_CXX_RECORD:
  3304. D = CXXRecordDecl::CreateDeserialized(Context, ID);
  3305. break;
  3306. case DECL_CXX_DEDUCTION_GUIDE:
  3307. D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
  3308. break;
  3309. case DECL_CXX_METHOD:
  3310. D = CXXMethodDecl::CreateDeserialized(Context, ID);
  3311. break;
  3312. case DECL_CXX_CONSTRUCTOR:
  3313. D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
  3314. break;
  3315. case DECL_CXX_DESTRUCTOR:
  3316. D = CXXDestructorDecl::CreateDeserialized(Context, ID);
  3317. break;
  3318. case DECL_CXX_CONVERSION:
  3319. D = CXXConversionDecl::CreateDeserialized(Context, ID);
  3320. break;
  3321. case DECL_ACCESS_SPEC:
  3322. D = AccessSpecDecl::CreateDeserialized(Context, ID);
  3323. break;
  3324. case DECL_FRIEND:
  3325. D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
  3326. break;
  3327. case DECL_FRIEND_TEMPLATE:
  3328. D = FriendTemplateDecl::CreateDeserialized(Context, ID);
  3329. break;
  3330. case DECL_CLASS_TEMPLATE:
  3331. D = ClassTemplateDecl::CreateDeserialized(Context, ID);
  3332. break;
  3333. case DECL_CLASS_TEMPLATE_SPECIALIZATION:
  3334. D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
  3335. break;
  3336. case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
  3337. D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
  3338. break;
  3339. case DECL_VAR_TEMPLATE:
  3340. D = VarTemplateDecl::CreateDeserialized(Context, ID);
  3341. break;
  3342. case DECL_VAR_TEMPLATE_SPECIALIZATION:
  3343. D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
  3344. break;
  3345. case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
  3346. D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
  3347. break;
  3348. case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
  3349. D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
  3350. break;
  3351. case DECL_FUNCTION_TEMPLATE:
  3352. D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
  3353. break;
  3354. case DECL_TEMPLATE_TYPE_PARM:
  3355. D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
  3356. break;
  3357. case DECL_NON_TYPE_TEMPLATE_PARM:
  3358. D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
  3359. break;
  3360. case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
  3361. D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
  3362. Record.readInt());
  3363. break;
  3364. case DECL_TEMPLATE_TEMPLATE_PARM:
  3365. D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
  3366. break;
  3367. case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
  3368. D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
  3369. Record.readInt());
  3370. break;
  3371. case DECL_TYPE_ALIAS_TEMPLATE:
  3372. D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
  3373. break;
  3374. case DECL_CONCEPT:
  3375. D = ConceptDecl::CreateDeserialized(Context, ID);
  3376. break;
  3377. case DECL_STATIC_ASSERT:
  3378. D = StaticAssertDecl::CreateDeserialized(Context, ID);
  3379. break;
  3380. case DECL_OBJC_METHOD:
  3381. D = ObjCMethodDecl::CreateDeserialized(Context, ID);
  3382. break;
  3383. case DECL_OBJC_INTERFACE:
  3384. D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
  3385. break;
  3386. case DECL_OBJC_IVAR:
  3387. D = ObjCIvarDecl::CreateDeserialized(Context, ID);
  3388. break;
  3389. case DECL_OBJC_PROTOCOL:
  3390. D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
  3391. break;
  3392. case DECL_OBJC_AT_DEFS_FIELD:
  3393. D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
  3394. break;
  3395. case DECL_OBJC_CATEGORY:
  3396. D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
  3397. break;
  3398. case DECL_OBJC_CATEGORY_IMPL:
  3399. D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
  3400. break;
  3401. case DECL_OBJC_IMPLEMENTATION:
  3402. D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
  3403. break;
  3404. case DECL_OBJC_COMPATIBLE_ALIAS:
  3405. D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
  3406. break;
  3407. case DECL_OBJC_PROPERTY:
  3408. D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
  3409. break;
  3410. case DECL_OBJC_PROPERTY_IMPL:
  3411. D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
  3412. break;
  3413. case DECL_FIELD:
  3414. D = FieldDecl::CreateDeserialized(Context, ID);
  3415. break;
  3416. case DECL_INDIRECTFIELD:
  3417. D = IndirectFieldDecl::CreateDeserialized(Context, ID);
  3418. break;
  3419. case DECL_VAR:
  3420. D = VarDecl::CreateDeserialized(Context, ID);
  3421. break;
  3422. case DECL_IMPLICIT_PARAM:
  3423. D = ImplicitParamDecl::CreateDeserialized(Context, ID);
  3424. break;
  3425. case DECL_PARM_VAR:
  3426. D = ParmVarDecl::CreateDeserialized(Context, ID);
  3427. break;
  3428. case DECL_DECOMPOSITION:
  3429. D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
  3430. break;
  3431. case DECL_BINDING:
  3432. D = BindingDecl::CreateDeserialized(Context, ID);
  3433. break;
  3434. case DECL_FILE_SCOPE_ASM:
  3435. D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
  3436. break;
  3437. case DECL_BLOCK:
  3438. D = BlockDecl::CreateDeserialized(Context, ID);
  3439. break;
  3440. case DECL_MS_PROPERTY:
  3441. D = MSPropertyDecl::CreateDeserialized(Context, ID);
  3442. break;
  3443. case DECL_CAPTURED:
  3444. D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
  3445. break;
  3446. case DECL_CXX_BASE_SPECIFIERS:
  3447. Error("attempt to read a C++ base-specifier record as a declaration");
  3448. return nullptr;
  3449. case DECL_CXX_CTOR_INITIALIZERS:
  3450. Error("attempt to read a C++ ctor initializer record as a declaration");
  3451. return nullptr;
  3452. case DECL_IMPORT:
  3453. // Note: last entry of the ImportDecl record is the number of stored source
  3454. // locations.
  3455. D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
  3456. break;
  3457. case DECL_OMP_THREADPRIVATE:
  3458. D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
  3459. break;
  3460. case DECL_OMP_ALLOCATE: {
  3461. unsigned NumVars = Record.readInt();
  3462. unsigned NumClauses = Record.readInt();
  3463. D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
  3464. break;
  3465. }
  3466. case DECL_OMP_REQUIRES:
  3467. D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
  3468. break;
  3469. case DECL_OMP_DECLARE_REDUCTION:
  3470. D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
  3471. break;
  3472. case DECL_OMP_DECLARE_MAPPER:
  3473. D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
  3474. break;
  3475. case DECL_OMP_CAPTUREDEXPR:
  3476. D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
  3477. break;
  3478. case DECL_PRAGMA_COMMENT:
  3479. D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
  3480. break;
  3481. case DECL_PRAGMA_DETECT_MISMATCH:
  3482. D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
  3483. Record.readInt());
  3484. break;
  3485. case DECL_EMPTY:
  3486. D = EmptyDecl::CreateDeserialized(Context, ID);
  3487. break;
  3488. case DECL_OBJC_TYPE_PARAM:
  3489. D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
  3490. break;
  3491. }
  3492. assert(D && "Unknown declaration reading AST file");
  3493. LoadedDecl(Index, D);
  3494. // Set the DeclContext before doing any deserialization, to make sure internal
  3495. // calls to Decl::getASTContext() by Decl's methods will find the
  3496. // TranslationUnitDecl without crashing.
  3497. D->setDeclContext(Context.getTranslationUnitDecl());
  3498. Reader.Visit(D);
  3499. // If this declaration is also a declaration context, get the
  3500. // offsets for its tables of lexical and visible declarations.
  3501. if (auto *DC = dyn_cast<DeclContext>(D)) {
  3502. std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
  3503. if (Offsets.first &&
  3504. ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
  3505. return nullptr;
  3506. if (Offsets.second &&
  3507. ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
  3508. return nullptr;
  3509. }
  3510. assert(Record.getIdx() == Record.size());
  3511. // Load any relevant update records.
  3512. PendingUpdateRecords.push_back(
  3513. PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
  3514. // Load the categories after recursive loading is finished.
  3515. if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
  3516. // If we already have a definition when deserializing the ObjCInterfaceDecl,
  3517. // we put the Decl in PendingDefinitions so we can pull the categories here.
  3518. if (Class->isThisDeclarationADefinition() ||
  3519. PendingDefinitions.count(Class))
  3520. loadObjCCategories(ID, Class);
  3521. // If we have deserialized a declaration that has a definition the
  3522. // AST consumer might need to know about, queue it.
  3523. // We don't pass it to the consumer immediately because we may be in recursive
  3524. // loading, and some declarations may still be initializing.
  3525. PotentiallyInterestingDecls.push_back(
  3526. InterestingDecl(D, Reader.hasPendingBody()));
  3527. return D;
  3528. }
  3529. void ASTReader::PassInterestingDeclsToConsumer() {
  3530. assert(Consumer);
  3531. if (PassingDeclsToConsumer)
  3532. return;
  3533. // Guard variable to avoid recursively redoing the process of passing
  3534. // decls to consumer.
  3535. SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
  3536. true);
  3537. // Ensure that we've loaded all potentially-interesting declarations
  3538. // that need to be eagerly loaded.
  3539. for (auto ID : EagerlyDeserializedDecls)
  3540. GetDecl(ID);
  3541. EagerlyDeserializedDecls.clear();
  3542. while (!PotentiallyInterestingDecls.empty()) {
  3543. InterestingDecl D = PotentiallyInterestingDecls.front();
  3544. PotentiallyInterestingDecls.pop_front();
  3545. if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
  3546. PassInterestingDeclToConsumer(D.getDecl());
  3547. }
  3548. }
  3549. void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
  3550. // The declaration may have been modified by files later in the chain.
  3551. // If this is the case, read the record containing the updates from each file
  3552. // and pass it to ASTDeclReader to make the modifications.
  3553. serialization::GlobalDeclID ID = Record.ID;
  3554. Decl *D = Record.D;
  3555. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  3556. DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
  3557. SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
  3558. if (UpdI != DeclUpdateOffsets.end()) {
  3559. auto UpdateOffsets = std::move(UpdI->second);
  3560. DeclUpdateOffsets.erase(UpdI);
  3561. // Check if this decl was interesting to the consumer. If we just loaded
  3562. // the declaration, then we know it was interesting and we skip the call
  3563. // to isConsumerInterestedIn because it is unsafe to call in the
  3564. // current ASTReader state.
  3565. bool WasInteresting =
  3566. Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
  3567. for (auto &FileAndOffset : UpdateOffsets) {
  3568. ModuleFile *F = FileAndOffset.first;
  3569. uint64_t Offset = FileAndOffset.second;
  3570. llvm::BitstreamCursor &Cursor = F->DeclsCursor;
  3571. SavedStreamPosition SavedPosition(Cursor);
  3572. if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
  3573. // FIXME don't do a fatal error.
  3574. llvm::report_fatal_error(
  3575. "ASTReader::loadDeclUpdateRecords failed jumping: " +
  3576. toString(std::move(JumpFailed)));
  3577. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  3578. if (!MaybeCode)
  3579. llvm::report_fatal_error(
  3580. "ASTReader::loadDeclUpdateRecords failed reading code: " +
  3581. toString(MaybeCode.takeError()));
  3582. unsigned Code = MaybeCode.get();
  3583. ASTRecordReader Record(*this, *F);
  3584. if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
  3585. assert(MaybeRecCode.get() == DECL_UPDATES &&
  3586. "Expected DECL_UPDATES record!");
  3587. else
  3588. llvm::report_fatal_error(
  3589. "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
  3590. toString(MaybeCode.takeError()));
  3591. ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
  3592. SourceLocation());
  3593. Reader.UpdateDecl(D, PendingLazySpecializationIDs);
  3594. // We might have made this declaration interesting. If so, remember that
  3595. // we need to hand it off to the consumer.
  3596. if (!WasInteresting &&
  3597. isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
  3598. PotentiallyInterestingDecls.push_back(
  3599. InterestingDecl(D, Reader.hasPendingBody()));
  3600. WasInteresting = true;
  3601. }
  3602. }
  3603. }
  3604. // Add the lazy specializations to the template.
  3605. assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
  3606. isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
  3607. "Must not have pending specializations");
  3608. if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
  3609. ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
  3610. else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  3611. ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
  3612. else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
  3613. ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
  3614. PendingLazySpecializationIDs.clear();
  3615. // Load the pending visible updates for this decl context, if it has any.
  3616. auto I = PendingVisibleUpdates.find(ID);
  3617. if (I != PendingVisibleUpdates.end()) {
  3618. auto VisibleUpdates = std::move(I->second);
  3619. PendingVisibleUpdates.erase(I);
  3620. auto *DC = cast<DeclContext>(D)->getPrimaryContext();
  3621. for (const auto &Update : VisibleUpdates)
  3622. Lookups[DC].Table.add(
  3623. Update.Mod, Update.Data,
  3624. reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
  3625. DC->setHasExternalVisibleStorage(true);
  3626. }
  3627. }
  3628. void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
  3629. // Attach FirstLocal to the end of the decl chain.
  3630. Decl *CanonDecl = FirstLocal->getCanonicalDecl();
  3631. if (FirstLocal != CanonDecl) {
  3632. Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
  3633. ASTDeclReader::attachPreviousDecl(
  3634. *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
  3635. CanonDecl);
  3636. }
  3637. if (!LocalOffset) {
  3638. ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
  3639. return;
  3640. }
  3641. // Load the list of other redeclarations from this module file.
  3642. ModuleFile *M = getOwningModuleFile(FirstLocal);
  3643. assert(M && "imported decl from no module file");
  3644. llvm::BitstreamCursor &Cursor = M->DeclsCursor;
  3645. SavedStreamPosition SavedPosition(Cursor);
  3646. if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
  3647. llvm::report_fatal_error(
  3648. "ASTReader::loadPendingDeclChain failed jumping: " +
  3649. toString(std::move(JumpFailed)));
  3650. RecordData Record;
  3651. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  3652. if (!MaybeCode)
  3653. llvm::report_fatal_error(
  3654. "ASTReader::loadPendingDeclChain failed reading code: " +
  3655. toString(MaybeCode.takeError()));
  3656. unsigned Code = MaybeCode.get();
  3657. if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
  3658. assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
  3659. "expected LOCAL_REDECLARATIONS record!");
  3660. else
  3661. llvm::report_fatal_error(
  3662. "ASTReader::loadPendingDeclChain failed reading rec code: " +
  3663. toString(MaybeCode.takeError()));
  3664. // FIXME: We have several different dispatches on decl kind here; maybe
  3665. // we should instead generate one loop per kind and dispatch up-front?
  3666. Decl *MostRecent = FirstLocal;
  3667. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  3668. auto *D = GetLocalDecl(*M, Record[N - I - 1]);
  3669. ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
  3670. MostRecent = D;
  3671. }
  3672. ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
  3673. }
  3674. namespace {
  3675. /// Given an ObjC interface, goes through the modules and links to the
  3676. /// interface all the categories for it.
  3677. class ObjCCategoriesVisitor {
  3678. ASTReader &Reader;
  3679. ObjCInterfaceDecl *Interface;
  3680. llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
  3681. ObjCCategoryDecl *Tail = nullptr;
  3682. llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
  3683. serialization::GlobalDeclID InterfaceID;
  3684. unsigned PreviousGeneration;
  3685. void add(ObjCCategoryDecl *Cat) {
  3686. // Only process each category once.
  3687. if (!Deserialized.erase(Cat))
  3688. return;
  3689. // Check for duplicate categories.
  3690. if (Cat->getDeclName()) {
  3691. ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
  3692. if (Existing &&
  3693. Reader.getOwningModuleFile(Existing)
  3694. != Reader.getOwningModuleFile(Cat)) {
  3695. // FIXME: We should not warn for duplicates in diamond:
  3696. //
  3697. // MT //
  3698. // / \ //
  3699. // ML MR //
  3700. // \ / //
  3701. // MB //
  3702. //
  3703. // If there are duplicates in ML/MR, there will be warning when
  3704. // creating MB *and* when importing MB. We should not warn when
  3705. // importing.
  3706. Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
  3707. << Interface->getDeclName() << Cat->getDeclName();
  3708. Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
  3709. } else if (!Existing) {
  3710. // Record this category.
  3711. Existing = Cat;
  3712. }
  3713. }
  3714. // Add this category to the end of the chain.
  3715. if (Tail)
  3716. ASTDeclReader::setNextObjCCategory(Tail, Cat);
  3717. else
  3718. Interface->setCategoryListRaw(Cat);
  3719. Tail = Cat;
  3720. }
  3721. public:
  3722. ObjCCategoriesVisitor(ASTReader &Reader,
  3723. ObjCInterfaceDecl *Interface,
  3724. llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
  3725. serialization::GlobalDeclID InterfaceID,
  3726. unsigned PreviousGeneration)
  3727. : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
  3728. InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
  3729. // Populate the name -> category map with the set of known categories.
  3730. for (auto *Cat : Interface->known_categories()) {
  3731. if (Cat->getDeclName())
  3732. NameCategoryMap[Cat->getDeclName()] = Cat;
  3733. // Keep track of the tail of the category list.
  3734. Tail = Cat;
  3735. }
  3736. }
  3737. bool operator()(ModuleFile &M) {
  3738. // If we've loaded all of the category information we care about from
  3739. // this module file, we're done.
  3740. if (M.Generation <= PreviousGeneration)
  3741. return true;
  3742. // Map global ID of the definition down to the local ID used in this
  3743. // module file. If there is no such mapping, we'll find nothing here
  3744. // (or in any module it imports).
  3745. DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
  3746. if (!LocalID)
  3747. return true;
  3748. // Perform a binary search to find the local redeclarations for this
  3749. // declaration (if any).
  3750. const ObjCCategoriesInfo Compare = { LocalID, 0 };
  3751. const ObjCCategoriesInfo *Result
  3752. = std::lower_bound(M.ObjCCategoriesMap,
  3753. M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
  3754. Compare);
  3755. if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
  3756. Result->DefinitionID != LocalID) {
  3757. // We didn't find anything. If the class definition is in this module
  3758. // file, then the module files it depends on cannot have any categories,
  3759. // so suppress further lookup.
  3760. return Reader.isDeclIDFromModule(InterfaceID, M);
  3761. }
  3762. // We found something. Dig out all of the categories.
  3763. unsigned Offset = Result->Offset;
  3764. unsigned N = M.ObjCCategories[Offset];
  3765. M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
  3766. for (unsigned I = 0; I != N; ++I)
  3767. add(cast_or_null<ObjCCategoryDecl>(
  3768. Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
  3769. return true;
  3770. }
  3771. };
  3772. } // namespace
  3773. void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
  3774. ObjCInterfaceDecl *D,
  3775. unsigned PreviousGeneration) {
  3776. ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
  3777. PreviousGeneration);
  3778. ModuleMgr.visit(Visitor);
  3779. }
  3780. template<typename DeclT, typename Fn>
  3781. static void forAllLaterRedecls(DeclT *D, Fn F) {
  3782. F(D);
  3783. // Check whether we've already merged D into its redeclaration chain.
  3784. // MostRecent may or may not be nullptr if D has not been merged. If
  3785. // not, walk the merged redecl chain and see if it's there.
  3786. auto *MostRecent = D->getMostRecentDecl();
  3787. bool Found = false;
  3788. for (auto *Redecl = MostRecent; Redecl && !Found;
  3789. Redecl = Redecl->getPreviousDecl())
  3790. Found = (Redecl == D);
  3791. // If this declaration is merged, apply the functor to all later decls.
  3792. if (Found) {
  3793. for (auto *Redecl = MostRecent; Redecl != D;
  3794. Redecl = Redecl->getPreviousDecl())
  3795. F(Redecl);
  3796. }
  3797. }
  3798. void ASTDeclReader::UpdateDecl(Decl *D,
  3799. llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
  3800. while (Record.getIdx() < Record.size()) {
  3801. switch ((DeclUpdateKind)Record.readInt()) {
  3802. case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
  3803. auto *RD = cast<CXXRecordDecl>(D);
  3804. // FIXME: If we also have an update record for instantiating the
  3805. // definition of D, we need that to happen before we get here.
  3806. Decl *MD = Record.readDecl();
  3807. assert(MD && "couldn't read decl from update record");
  3808. // FIXME: We should call addHiddenDecl instead, to add the member
  3809. // to its DeclContext.
  3810. RD->addedMember(MD);
  3811. break;
  3812. }
  3813. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  3814. // It will be added to the template's lazy specialization set.
  3815. PendingLazySpecializationIDs.push_back(ReadDeclID());
  3816. break;
  3817. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
  3818. auto *Anon = ReadDeclAs<NamespaceDecl>();
  3819. // Each module has its own anonymous namespace, which is disjoint from
  3820. // any other module's anonymous namespaces, so don't attach the anonymous
  3821. // namespace at all.
  3822. if (!Record.isModule()) {
  3823. if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
  3824. TU->setAnonymousNamespace(Anon);
  3825. else
  3826. cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
  3827. }
  3828. break;
  3829. }
  3830. case UPD_CXX_ADDED_VAR_DEFINITION: {
  3831. auto *VD = cast<VarDecl>(D);
  3832. VD->NonParmVarDeclBits.IsInline = Record.readInt();
  3833. VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
  3834. uint64_t Val = Record.readInt();
  3835. if (Val && !VD->getInit()) {
  3836. VD->setInit(Record.readExpr());
  3837. if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
  3838. EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
  3839. Eval->CheckedICE = true;
  3840. Eval->IsICE = Val == 3;
  3841. }
  3842. }
  3843. break;
  3844. }
  3845. case UPD_CXX_POINT_OF_INSTANTIATION: {
  3846. SourceLocation POI = Record.readSourceLocation();
  3847. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
  3848. VTSD->setPointOfInstantiation(POI);
  3849. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  3850. VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  3851. } else {
  3852. auto *FD = cast<FunctionDecl>(D);
  3853. if (auto *FTSInfo = FD->TemplateOrSpecialization
  3854. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  3855. FTSInfo->setPointOfInstantiation(POI);
  3856. else
  3857. FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
  3858. ->setPointOfInstantiation(POI);
  3859. }
  3860. break;
  3861. }
  3862. case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
  3863. auto *Param = cast<ParmVarDecl>(D);
  3864. // We have to read the default argument regardless of whether we use it
  3865. // so that hypothetical further update records aren't messed up.
  3866. // TODO: Add a function to skip over the next expr record.
  3867. auto *DefaultArg = Record.readExpr();
  3868. // Only apply the update if the parameter still has an uninstantiated
  3869. // default argument.
  3870. if (Param->hasUninstantiatedDefaultArg())
  3871. Param->setDefaultArg(DefaultArg);
  3872. break;
  3873. }
  3874. case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
  3875. auto *FD = cast<FieldDecl>(D);
  3876. auto *DefaultInit = Record.readExpr();
  3877. // Only apply the update if the field still has an uninstantiated
  3878. // default member initializer.
  3879. if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
  3880. if (DefaultInit)
  3881. FD->setInClassInitializer(DefaultInit);
  3882. else
  3883. // Instantiation failed. We can get here if we serialized an AST for
  3884. // an invalid program.
  3885. FD->removeInClassInitializer();
  3886. }
  3887. break;
  3888. }
  3889. case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
  3890. auto *FD = cast<FunctionDecl>(D);
  3891. if (Reader.PendingBodies[FD]) {
  3892. // FIXME: Maybe check for ODR violations.
  3893. // It's safe to stop now because this update record is always last.
  3894. return;
  3895. }
  3896. if (Record.readInt()) {
  3897. // Maintain AST consistency: any later redeclarations of this function
  3898. // are inline if this one is. (We might have merged another declaration
  3899. // into this one.)
  3900. forAllLaterRedecls(FD, [](FunctionDecl *FD) {
  3901. FD->setImplicitlyInline();
  3902. });
  3903. }
  3904. FD->setInnerLocStart(ReadSourceLocation());
  3905. ReadFunctionDefinition(FD);
  3906. assert(Record.getIdx() == Record.size() && "lazy body must be last");
  3907. break;
  3908. }
  3909. case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
  3910. auto *RD = cast<CXXRecordDecl>(D);
  3911. auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
  3912. bool HadRealDefinition =
  3913. OldDD && (OldDD->Definition != RD ||
  3914. !Reader.PendingFakeDefinitionData.count(OldDD));
  3915. RD->setParamDestroyedInCallee(Record.readInt());
  3916. RD->setArgPassingRestrictions(
  3917. (RecordDecl::ArgPassingKind)Record.readInt());
  3918. ReadCXXRecordDefinition(RD, /*Update*/true);
  3919. // Visible update is handled separately.
  3920. uint64_t LexicalOffset = ReadLocalOffset();
  3921. if (!HadRealDefinition && LexicalOffset) {
  3922. Record.readLexicalDeclContextStorage(LexicalOffset, RD);
  3923. Reader.PendingFakeDefinitionData.erase(OldDD);
  3924. }
  3925. auto TSK = (TemplateSpecializationKind)Record.readInt();
  3926. SourceLocation POI = ReadSourceLocation();
  3927. if (MemberSpecializationInfo *MSInfo =
  3928. RD->getMemberSpecializationInfo()) {
  3929. MSInfo->setTemplateSpecializationKind(TSK);
  3930. MSInfo->setPointOfInstantiation(POI);
  3931. } else {
  3932. auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
  3933. Spec->setTemplateSpecializationKind(TSK);
  3934. Spec->setPointOfInstantiation(POI);
  3935. if (Record.readInt()) {
  3936. auto *PartialSpec =
  3937. ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
  3938. SmallVector<TemplateArgument, 8> TemplArgs;
  3939. Record.readTemplateArgumentList(TemplArgs);
  3940. auto *TemplArgList = TemplateArgumentList::CreateCopy(
  3941. Reader.getContext(), TemplArgs);
  3942. // FIXME: If we already have a partial specialization set,
  3943. // check that it matches.
  3944. if (!Spec->getSpecializedTemplateOrPartial()
  3945. .is<ClassTemplatePartialSpecializationDecl *>())
  3946. Spec->setInstantiationOf(PartialSpec, TemplArgList);
  3947. }
  3948. }
  3949. RD->setTagKind((TagTypeKind)Record.readInt());
  3950. RD->setLocation(ReadSourceLocation());
  3951. RD->setLocStart(ReadSourceLocation());
  3952. RD->setBraceRange(ReadSourceRange());
  3953. if (Record.readInt()) {
  3954. AttrVec Attrs;
  3955. Record.readAttributes(Attrs);
  3956. // If the declaration already has attributes, we assume that some other
  3957. // AST file already loaded them.
  3958. if (!D->hasAttrs())
  3959. D->setAttrsImpl(Attrs, Reader.getContext());
  3960. }
  3961. break;
  3962. }
  3963. case UPD_CXX_RESOLVED_DTOR_DELETE: {
  3964. // Set the 'operator delete' directly to avoid emitting another update
  3965. // record.
  3966. auto *Del = ReadDeclAs<FunctionDecl>();
  3967. auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
  3968. auto *ThisArg = Record.readExpr();
  3969. // FIXME: Check consistency if we have an old and new operator delete.
  3970. if (!First->OperatorDelete) {
  3971. First->OperatorDelete = Del;
  3972. First->OperatorDeleteThisArg = ThisArg;
  3973. }
  3974. break;
  3975. }
  3976. case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
  3977. FunctionProtoType::ExceptionSpecInfo ESI;
  3978. SmallVector<QualType, 8> ExceptionStorage;
  3979. Record.readExceptionSpec(ExceptionStorage, ESI);
  3980. // Update this declaration's exception specification, if needed.
  3981. auto *FD = cast<FunctionDecl>(D);
  3982. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  3983. // FIXME: If the exception specification is already present, check that it
  3984. // matches.
  3985. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
  3986. FD->setType(Reader.getContext().getFunctionType(
  3987. FPT->getReturnType(), FPT->getParamTypes(),
  3988. FPT->getExtProtoInfo().withExceptionSpec(ESI)));
  3989. // When we get to the end of deserializing, see if there are other decls
  3990. // that we need to propagate this exception specification onto.
  3991. Reader.PendingExceptionSpecUpdates.insert(
  3992. std::make_pair(FD->getCanonicalDecl(), FD));
  3993. }
  3994. break;
  3995. }
  3996. case UPD_CXX_DEDUCED_RETURN_TYPE: {
  3997. auto *FD = cast<FunctionDecl>(D);
  3998. QualType DeducedResultType = Record.readType();
  3999. Reader.PendingDeducedTypeUpdates.insert(
  4000. {FD->getCanonicalDecl(), DeducedResultType});
  4001. break;
  4002. }
  4003. case UPD_DECL_MARKED_USED:
  4004. // Maintain AST consistency: any later redeclarations are used too.
  4005. D->markUsed(Reader.getContext());
  4006. break;
  4007. case UPD_MANGLING_NUMBER:
  4008. Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
  4009. Record.readInt());
  4010. break;
  4011. case UPD_STATIC_LOCAL_NUMBER:
  4012. Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
  4013. Record.readInt());
  4014. break;
  4015. case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
  4016. D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  4017. Reader.getContext(), ReadSourceRange(),
  4018. AttributeCommonInfo::AS_Pragma));
  4019. break;
  4020. case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
  4021. auto AllocatorKind =
  4022. static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
  4023. Expr *Allocator = Record.readExpr();
  4024. SourceRange SR = ReadSourceRange();
  4025. D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
  4026. Reader.getContext(), AllocatorKind, Allocator, SR,
  4027. AttributeCommonInfo::AS_Pragma));
  4028. break;
  4029. }
  4030. case UPD_DECL_EXPORTED: {
  4031. unsigned SubmoduleID = readSubmoduleID();
  4032. auto *Exported = cast<NamedDecl>(D);
  4033. Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
  4034. Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
  4035. Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
  4036. break;
  4037. }
  4038. case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
  4039. OMPDeclareTargetDeclAttr::MapTypeTy MapType =
  4040. static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt());
  4041. OMPDeclareTargetDeclAttr::DevTypeTy DevType =
  4042. static_cast<OMPDeclareTargetDeclAttr::DevTypeTy>(Record.readInt());
  4043. D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
  4044. Reader.getContext(), MapType, DevType, ReadSourceRange(),
  4045. AttributeCommonInfo::AS_Pragma));
  4046. break;
  4047. }
  4048. case UPD_ADDED_ATTR_TO_RECORD:
  4049. AttrVec Attrs;
  4050. Record.readAttributes(Attrs);
  4051. assert(Attrs.size() == 1);
  4052. D->addAttr(Attrs[0]);
  4053. break;
  4054. }
  4055. }
  4056. }