ASTReaderDecl.cpp 163 KB

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