ASTReaderDecl.cpp 150 KB

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