ASTReaderDecl.cpp 161 KB

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