ASTWriter.cpp 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503
  1. //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the ASTWriter class, which writes AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTWriter.h"
  14. #include "ASTCommon.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/IdentifierResolver.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclContextInternals.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/DeclFriend.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/Type.h"
  25. #include "clang/AST/TypeLocVisitor.h"
  26. #include "clang/Serialization/ASTReader.h"
  27. #include "clang/Lex/MacroInfo.h"
  28. #include "clang/Lex/PreprocessingRecord.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Basic/FileManager.h"
  32. #include "clang/Basic/FileSystemStatCache.h"
  33. #include "clang/Basic/OnDiskHashTable.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/SourceManagerInternals.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Basic/Version.h"
  38. #include "clang/Basic/VersionTuple.h"
  39. #include "llvm/ADT/APFloat.h"
  40. #include "llvm/ADT/APInt.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include "llvm/Bitcode/BitstreamWriter.h"
  43. #include "llvm/Support/FileSystem.h"
  44. #include "llvm/Support/MemoryBuffer.h"
  45. #include "llvm/Support/Path.h"
  46. #include <algorithm>
  47. #include <cstdio>
  48. #include <string.h>
  49. #include <utility>
  50. using namespace clang;
  51. using namespace clang::serialization;
  52. template <typename T, typename Allocator>
  53. static StringRef data(const std::vector<T, Allocator> &v) {
  54. if (v.empty()) return StringRef();
  55. return StringRef(reinterpret_cast<const char*>(&v[0]),
  56. sizeof(T) * v.size());
  57. }
  58. template <typename T>
  59. static StringRef data(const SmallVectorImpl<T> &v) {
  60. return StringRef(reinterpret_cast<const char*>(v.data()),
  61. sizeof(T) * v.size());
  62. }
  63. //===----------------------------------------------------------------------===//
  64. // Type serialization
  65. //===----------------------------------------------------------------------===//
  66. namespace {
  67. class ASTTypeWriter {
  68. ASTWriter &Writer;
  69. ASTWriter::RecordDataImpl &Record;
  70. public:
  71. /// \brief Type code that corresponds to the record generated.
  72. TypeCode Code;
  73. ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  74. : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
  75. void VisitArrayType(const ArrayType *T);
  76. void VisitFunctionType(const FunctionType *T);
  77. void VisitTagType(const TagType *T);
  78. #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
  79. #define ABSTRACT_TYPE(Class, Base)
  80. #include "clang/AST/TypeNodes.def"
  81. };
  82. }
  83. void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
  84. llvm_unreachable("Built-in types are never serialized");
  85. }
  86. void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
  87. Writer.AddTypeRef(T->getElementType(), Record);
  88. Code = TYPE_COMPLEX;
  89. }
  90. void ASTTypeWriter::VisitPointerType(const PointerType *T) {
  91. Writer.AddTypeRef(T->getPointeeType(), Record);
  92. Code = TYPE_POINTER;
  93. }
  94. void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
  95. Writer.AddTypeRef(T->getPointeeType(), Record);
  96. Code = TYPE_BLOCK_POINTER;
  97. }
  98. void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
  99. Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
  100. Record.push_back(T->isSpelledAsLValue());
  101. Code = TYPE_LVALUE_REFERENCE;
  102. }
  103. void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
  104. Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
  105. Code = TYPE_RVALUE_REFERENCE;
  106. }
  107. void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
  108. Writer.AddTypeRef(T->getPointeeType(), Record);
  109. Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
  110. Code = TYPE_MEMBER_POINTER;
  111. }
  112. void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
  113. Writer.AddTypeRef(T->getElementType(), Record);
  114. Record.push_back(T->getSizeModifier()); // FIXME: stable values
  115. Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
  116. }
  117. void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
  118. VisitArrayType(T);
  119. Writer.AddAPInt(T->getSize(), Record);
  120. Code = TYPE_CONSTANT_ARRAY;
  121. }
  122. void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
  123. VisitArrayType(T);
  124. Code = TYPE_INCOMPLETE_ARRAY;
  125. }
  126. void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
  127. VisitArrayType(T);
  128. Writer.AddSourceLocation(T->getLBracketLoc(), Record);
  129. Writer.AddSourceLocation(T->getRBracketLoc(), Record);
  130. Writer.AddStmt(T->getSizeExpr());
  131. Code = TYPE_VARIABLE_ARRAY;
  132. }
  133. void ASTTypeWriter::VisitVectorType(const VectorType *T) {
  134. Writer.AddTypeRef(T->getElementType(), Record);
  135. Record.push_back(T->getNumElements());
  136. Record.push_back(T->getVectorKind());
  137. Code = TYPE_VECTOR;
  138. }
  139. void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
  140. VisitVectorType(T);
  141. Code = TYPE_EXT_VECTOR;
  142. }
  143. void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
  144. Writer.AddTypeRef(T->getResultType(), Record);
  145. FunctionType::ExtInfo C = T->getExtInfo();
  146. Record.push_back(C.getNoReturn());
  147. Record.push_back(C.getHasRegParm());
  148. Record.push_back(C.getRegParm());
  149. // FIXME: need to stabilize encoding of calling convention...
  150. Record.push_back(C.getCC());
  151. Record.push_back(C.getProducesResult());
  152. }
  153. void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  154. VisitFunctionType(T);
  155. Code = TYPE_FUNCTION_NO_PROTO;
  156. }
  157. void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
  158. VisitFunctionType(T);
  159. Record.push_back(T->getNumArgs());
  160. for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
  161. Writer.AddTypeRef(T->getArgType(I), Record);
  162. Record.push_back(T->isVariadic());
  163. Record.push_back(T->getTypeQuals());
  164. Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
  165. Record.push_back(T->getExceptionSpecType());
  166. if (T->getExceptionSpecType() == EST_Dynamic) {
  167. Record.push_back(T->getNumExceptions());
  168. for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
  169. Writer.AddTypeRef(T->getExceptionType(I), Record);
  170. } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
  171. Writer.AddStmt(T->getNoexceptExpr());
  172. }
  173. Code = TYPE_FUNCTION_PROTO;
  174. }
  175. void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
  176. Writer.AddDeclRef(T->getDecl(), Record);
  177. Code = TYPE_UNRESOLVED_USING;
  178. }
  179. void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
  180. Writer.AddDeclRef(T->getDecl(), Record);
  181. assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
  182. Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
  183. Code = TYPE_TYPEDEF;
  184. }
  185. void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
  186. Writer.AddStmt(T->getUnderlyingExpr());
  187. Code = TYPE_TYPEOF_EXPR;
  188. }
  189. void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
  190. Writer.AddTypeRef(T->getUnderlyingType(), Record);
  191. Code = TYPE_TYPEOF;
  192. }
  193. void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
  194. Writer.AddStmt(T->getUnderlyingExpr());
  195. Code = TYPE_DECLTYPE;
  196. }
  197. void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
  198. Writer.AddTypeRef(T->getBaseType(), Record);
  199. Writer.AddTypeRef(T->getUnderlyingType(), Record);
  200. Record.push_back(T->getUTTKind());
  201. Code = TYPE_UNARY_TRANSFORM;
  202. }
  203. void ASTTypeWriter::VisitAutoType(const AutoType *T) {
  204. Writer.AddTypeRef(T->getDeducedType(), Record);
  205. Code = TYPE_AUTO;
  206. }
  207. void ASTTypeWriter::VisitTagType(const TagType *T) {
  208. Record.push_back(T->isDependentType());
  209. Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
  210. assert(!T->isBeingDefined() &&
  211. "Cannot serialize in the middle of a type definition");
  212. }
  213. void ASTTypeWriter::VisitRecordType(const RecordType *T) {
  214. VisitTagType(T);
  215. Code = TYPE_RECORD;
  216. }
  217. void ASTTypeWriter::VisitEnumType(const EnumType *T) {
  218. VisitTagType(T);
  219. Code = TYPE_ENUM;
  220. }
  221. void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
  222. Writer.AddTypeRef(T->getModifiedType(), Record);
  223. Writer.AddTypeRef(T->getEquivalentType(), Record);
  224. Record.push_back(T->getAttrKind());
  225. Code = TYPE_ATTRIBUTED;
  226. }
  227. void
  228. ASTTypeWriter::VisitSubstTemplateTypeParmType(
  229. const SubstTemplateTypeParmType *T) {
  230. Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
  231. Writer.AddTypeRef(T->getReplacementType(), Record);
  232. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
  233. }
  234. void
  235. ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
  236. const SubstTemplateTypeParmPackType *T) {
  237. Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
  238. Writer.AddTemplateArgument(T->getArgumentPack(), Record);
  239. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
  240. }
  241. void
  242. ASTTypeWriter::VisitTemplateSpecializationType(
  243. const TemplateSpecializationType *T) {
  244. Record.push_back(T->isDependentType());
  245. Writer.AddTemplateName(T->getTemplateName(), Record);
  246. Record.push_back(T->getNumArgs());
  247. for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
  248. ArgI != ArgE; ++ArgI)
  249. Writer.AddTemplateArgument(*ArgI, Record);
  250. Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
  251. T->isCanonicalUnqualified() ? QualType()
  252. : T->getCanonicalTypeInternal(),
  253. Record);
  254. Code = TYPE_TEMPLATE_SPECIALIZATION;
  255. }
  256. void
  257. ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
  258. VisitArrayType(T);
  259. Writer.AddStmt(T->getSizeExpr());
  260. Writer.AddSourceRange(T->getBracketsRange(), Record);
  261. Code = TYPE_DEPENDENT_SIZED_ARRAY;
  262. }
  263. void
  264. ASTTypeWriter::VisitDependentSizedExtVectorType(
  265. const DependentSizedExtVectorType *T) {
  266. // FIXME: Serialize this type (C++ only)
  267. llvm_unreachable("Cannot serialize dependent sized extended vector types");
  268. }
  269. void
  270. ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  271. Record.push_back(T->getDepth());
  272. Record.push_back(T->getIndex());
  273. Record.push_back(T->isParameterPack());
  274. Writer.AddDeclRef(T->getDecl(), Record);
  275. Code = TYPE_TEMPLATE_TYPE_PARM;
  276. }
  277. void
  278. ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
  279. Record.push_back(T->getKeyword());
  280. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  281. Writer.AddIdentifierRef(T->getIdentifier(), Record);
  282. Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
  283. : T->getCanonicalTypeInternal(),
  284. Record);
  285. Code = TYPE_DEPENDENT_NAME;
  286. }
  287. void
  288. ASTTypeWriter::VisitDependentTemplateSpecializationType(
  289. const DependentTemplateSpecializationType *T) {
  290. Record.push_back(T->getKeyword());
  291. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  292. Writer.AddIdentifierRef(T->getIdentifier(), Record);
  293. Record.push_back(T->getNumArgs());
  294. for (DependentTemplateSpecializationType::iterator
  295. I = T->begin(), E = T->end(); I != E; ++I)
  296. Writer.AddTemplateArgument(*I, Record);
  297. Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
  298. }
  299. void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
  300. Writer.AddTypeRef(T->getPattern(), Record);
  301. if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
  302. Record.push_back(*NumExpansions + 1);
  303. else
  304. Record.push_back(0);
  305. Code = TYPE_PACK_EXPANSION;
  306. }
  307. void ASTTypeWriter::VisitParenType(const ParenType *T) {
  308. Writer.AddTypeRef(T->getInnerType(), Record);
  309. Code = TYPE_PAREN;
  310. }
  311. void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
  312. Record.push_back(T->getKeyword());
  313. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  314. Writer.AddTypeRef(T->getNamedType(), Record);
  315. Code = TYPE_ELABORATED;
  316. }
  317. void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
  318. Writer.AddDeclRef(T->getDecl(), Record);
  319. Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
  320. Code = TYPE_INJECTED_CLASS_NAME;
  321. }
  322. void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
  323. Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
  324. Code = TYPE_OBJC_INTERFACE;
  325. }
  326. void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
  327. Writer.AddTypeRef(T->getBaseType(), Record);
  328. Record.push_back(T->getNumProtocols());
  329. for (ObjCObjectType::qual_iterator I = T->qual_begin(),
  330. E = T->qual_end(); I != E; ++I)
  331. Writer.AddDeclRef(*I, Record);
  332. Code = TYPE_OBJC_OBJECT;
  333. }
  334. void
  335. ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  336. Writer.AddTypeRef(T->getPointeeType(), Record);
  337. Code = TYPE_OBJC_OBJECT_POINTER;
  338. }
  339. void
  340. ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
  341. Writer.AddTypeRef(T->getValueType(), Record);
  342. Code = TYPE_ATOMIC;
  343. }
  344. namespace {
  345. class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
  346. ASTWriter &Writer;
  347. ASTWriter::RecordDataImpl &Record;
  348. public:
  349. TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  350. : Writer(Writer), Record(Record) { }
  351. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  352. #define TYPELOC(CLASS, PARENT) \
  353. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  354. #include "clang/AST/TypeLocNodes.def"
  355. void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
  356. void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
  357. };
  358. }
  359. void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  360. // nothing to do
  361. }
  362. void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  363. Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
  364. if (TL.needsExtraLocalData()) {
  365. Record.push_back(TL.getWrittenTypeSpec());
  366. Record.push_back(TL.getWrittenSignSpec());
  367. Record.push_back(TL.getWrittenWidthSpec());
  368. Record.push_back(TL.hasModeAttr());
  369. }
  370. }
  371. void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  372. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  373. }
  374. void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
  375. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  376. }
  377. void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  378. Writer.AddSourceLocation(TL.getCaretLoc(), Record);
  379. }
  380. void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  381. Writer.AddSourceLocation(TL.getAmpLoc(), Record);
  382. }
  383. void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  384. Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
  385. }
  386. void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  387. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  388. Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
  389. }
  390. void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  391. Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
  392. Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
  393. Record.push_back(TL.getSizeExpr() ? 1 : 0);
  394. if (TL.getSizeExpr())
  395. Writer.AddStmt(TL.getSizeExpr());
  396. }
  397. void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  398. VisitArrayTypeLoc(TL);
  399. }
  400. void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  401. VisitArrayTypeLoc(TL);
  402. }
  403. void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  404. VisitArrayTypeLoc(TL);
  405. }
  406. void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
  407. DependentSizedArrayTypeLoc TL) {
  408. VisitArrayTypeLoc(TL);
  409. }
  410. void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
  411. DependentSizedExtVectorTypeLoc TL) {
  412. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  413. }
  414. void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
  415. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  416. }
  417. void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  418. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  419. }
  420. void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  421. Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
  422. Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
  423. Record.push_back(TL.getTrailingReturn());
  424. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  425. Writer.AddDeclRef(TL.getArg(i), Record);
  426. }
  427. void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  428. VisitFunctionTypeLoc(TL);
  429. }
  430. void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  431. VisitFunctionTypeLoc(TL);
  432. }
  433. void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  434. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  435. }
  436. void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  437. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  438. }
  439. void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  440. Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
  441. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  442. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  443. }
  444. void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  445. Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
  446. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  447. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  448. Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
  449. }
  450. void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  451. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  452. }
  453. void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  454. Writer.AddSourceLocation(TL.getKWLoc(), Record);
  455. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  456. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  457. Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
  458. }
  459. void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
  460. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  461. }
  462. void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
  463. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  464. }
  465. void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
  466. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  467. }
  468. void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  469. Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
  470. if (TL.hasAttrOperand()) {
  471. SourceRange range = TL.getAttrOperandParensRange();
  472. Writer.AddSourceLocation(range.getBegin(), Record);
  473. Writer.AddSourceLocation(range.getEnd(), Record);
  474. }
  475. if (TL.hasAttrExprOperand()) {
  476. Expr *operand = TL.getAttrExprOperand();
  477. Record.push_back(operand ? 1 : 0);
  478. if (operand) Writer.AddStmt(operand);
  479. } else if (TL.hasAttrEnumOperand()) {
  480. Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
  481. }
  482. }
  483. void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  484. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  485. }
  486. void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
  487. SubstTemplateTypeParmTypeLoc TL) {
  488. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  489. }
  490. void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
  491. SubstTemplateTypeParmPackTypeLoc TL) {
  492. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  493. }
  494. void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
  495. TemplateSpecializationTypeLoc TL) {
  496. Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
  497. Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
  498. Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
  499. Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
  500. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  501. Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
  502. TL.getArgLoc(i).getLocInfo(), Record);
  503. }
  504. void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
  505. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  506. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  507. }
  508. void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  509. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  510. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  511. }
  512. void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  513. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  514. }
  515. void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  516. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  517. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  518. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  519. }
  520. void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
  521. DependentTemplateSpecializationTypeLoc TL) {
  522. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  523. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  524. Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
  525. Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
  526. Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
  527. Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
  528. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  529. Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
  530. TL.getArgLoc(I).getLocInfo(), Record);
  531. }
  532. void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  533. Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
  534. }
  535. void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  536. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  537. }
  538. void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  539. Record.push_back(TL.hasBaseTypeAsWritten());
  540. Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
  541. Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
  542. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  543. Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
  544. }
  545. void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  546. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  547. }
  548. void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  549. Writer.AddSourceLocation(TL.getKWLoc(), Record);
  550. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  551. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  552. }
  553. //===----------------------------------------------------------------------===//
  554. // ASTWriter Implementation
  555. //===----------------------------------------------------------------------===//
  556. static void EmitBlockID(unsigned ID, const char *Name,
  557. llvm::BitstreamWriter &Stream,
  558. ASTWriter::RecordDataImpl &Record) {
  559. Record.clear();
  560. Record.push_back(ID);
  561. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  562. // Emit the block name if present.
  563. if (Name == 0 || Name[0] == 0) return;
  564. Record.clear();
  565. while (*Name)
  566. Record.push_back(*Name++);
  567. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  568. }
  569. static void EmitRecordID(unsigned ID, const char *Name,
  570. llvm::BitstreamWriter &Stream,
  571. ASTWriter::RecordDataImpl &Record) {
  572. Record.clear();
  573. Record.push_back(ID);
  574. while (*Name)
  575. Record.push_back(*Name++);
  576. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  577. }
  578. static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
  579. ASTWriter::RecordDataImpl &Record) {
  580. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  581. RECORD(STMT_STOP);
  582. RECORD(STMT_NULL_PTR);
  583. RECORD(STMT_NULL);
  584. RECORD(STMT_COMPOUND);
  585. RECORD(STMT_CASE);
  586. RECORD(STMT_DEFAULT);
  587. RECORD(STMT_LABEL);
  588. RECORD(STMT_IF);
  589. RECORD(STMT_SWITCH);
  590. RECORD(STMT_WHILE);
  591. RECORD(STMT_DO);
  592. RECORD(STMT_FOR);
  593. RECORD(STMT_GOTO);
  594. RECORD(STMT_INDIRECT_GOTO);
  595. RECORD(STMT_CONTINUE);
  596. RECORD(STMT_BREAK);
  597. RECORD(STMT_RETURN);
  598. RECORD(STMT_DECL);
  599. RECORD(STMT_ASM);
  600. RECORD(EXPR_PREDEFINED);
  601. RECORD(EXPR_DECL_REF);
  602. RECORD(EXPR_INTEGER_LITERAL);
  603. RECORD(EXPR_FLOATING_LITERAL);
  604. RECORD(EXPR_IMAGINARY_LITERAL);
  605. RECORD(EXPR_STRING_LITERAL);
  606. RECORD(EXPR_CHARACTER_LITERAL);
  607. RECORD(EXPR_PAREN);
  608. RECORD(EXPR_UNARY_OPERATOR);
  609. RECORD(EXPR_SIZEOF_ALIGN_OF);
  610. RECORD(EXPR_ARRAY_SUBSCRIPT);
  611. RECORD(EXPR_CALL);
  612. RECORD(EXPR_MEMBER);
  613. RECORD(EXPR_BINARY_OPERATOR);
  614. RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
  615. RECORD(EXPR_CONDITIONAL_OPERATOR);
  616. RECORD(EXPR_IMPLICIT_CAST);
  617. RECORD(EXPR_CSTYLE_CAST);
  618. RECORD(EXPR_COMPOUND_LITERAL);
  619. RECORD(EXPR_EXT_VECTOR_ELEMENT);
  620. RECORD(EXPR_INIT_LIST);
  621. RECORD(EXPR_DESIGNATED_INIT);
  622. RECORD(EXPR_IMPLICIT_VALUE_INIT);
  623. RECORD(EXPR_VA_ARG);
  624. RECORD(EXPR_ADDR_LABEL);
  625. RECORD(EXPR_STMT);
  626. RECORD(EXPR_CHOOSE);
  627. RECORD(EXPR_GNU_NULL);
  628. RECORD(EXPR_SHUFFLE_VECTOR);
  629. RECORD(EXPR_BLOCK);
  630. RECORD(EXPR_BLOCK_DECL_REF);
  631. RECORD(EXPR_GENERIC_SELECTION);
  632. RECORD(EXPR_OBJC_STRING_LITERAL);
  633. RECORD(EXPR_OBJC_ENCODE);
  634. RECORD(EXPR_OBJC_SELECTOR_EXPR);
  635. RECORD(EXPR_OBJC_PROTOCOL_EXPR);
  636. RECORD(EXPR_OBJC_IVAR_REF_EXPR);
  637. RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
  638. RECORD(EXPR_OBJC_KVC_REF_EXPR);
  639. RECORD(EXPR_OBJC_MESSAGE_EXPR);
  640. RECORD(STMT_OBJC_FOR_COLLECTION);
  641. RECORD(STMT_OBJC_CATCH);
  642. RECORD(STMT_OBJC_FINALLY);
  643. RECORD(STMT_OBJC_AT_TRY);
  644. RECORD(STMT_OBJC_AT_SYNCHRONIZED);
  645. RECORD(STMT_OBJC_AT_THROW);
  646. RECORD(EXPR_CXX_OPERATOR_CALL);
  647. RECORD(EXPR_CXX_CONSTRUCT);
  648. RECORD(EXPR_CXX_STATIC_CAST);
  649. RECORD(EXPR_CXX_DYNAMIC_CAST);
  650. RECORD(EXPR_CXX_REINTERPRET_CAST);
  651. RECORD(EXPR_CXX_CONST_CAST);
  652. RECORD(EXPR_CXX_FUNCTIONAL_CAST);
  653. RECORD(EXPR_CXX_BOOL_LITERAL);
  654. RECORD(EXPR_CXX_NULL_PTR_LITERAL);
  655. RECORD(EXPR_CXX_TYPEID_EXPR);
  656. RECORD(EXPR_CXX_TYPEID_TYPE);
  657. RECORD(EXPR_CXX_UUIDOF_EXPR);
  658. RECORD(EXPR_CXX_UUIDOF_TYPE);
  659. RECORD(EXPR_CXX_THIS);
  660. RECORD(EXPR_CXX_THROW);
  661. RECORD(EXPR_CXX_DEFAULT_ARG);
  662. RECORD(EXPR_CXX_BIND_TEMPORARY);
  663. RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
  664. RECORD(EXPR_CXX_NEW);
  665. RECORD(EXPR_CXX_DELETE);
  666. RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
  667. RECORD(EXPR_EXPR_WITH_CLEANUPS);
  668. RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
  669. RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
  670. RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
  671. RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
  672. RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
  673. RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
  674. RECORD(EXPR_CXX_NOEXCEPT);
  675. RECORD(EXPR_OPAQUE_VALUE);
  676. RECORD(EXPR_BINARY_TYPE_TRAIT);
  677. RECORD(EXPR_PACK_EXPANSION);
  678. RECORD(EXPR_SIZEOF_PACK);
  679. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
  680. RECORD(EXPR_CUDA_KERNEL_CALL);
  681. #undef RECORD
  682. }
  683. void ASTWriter::WriteBlockInfoBlock() {
  684. RecordData Record;
  685. Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
  686. #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
  687. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  688. // AST Top-Level Block.
  689. BLOCK(AST_BLOCK);
  690. RECORD(ORIGINAL_FILE_NAME);
  691. RECORD(ORIGINAL_FILE_ID);
  692. RECORD(TYPE_OFFSET);
  693. RECORD(DECL_OFFSET);
  694. RECORD(LANGUAGE_OPTIONS);
  695. RECORD(METADATA);
  696. RECORD(IDENTIFIER_OFFSET);
  697. RECORD(IDENTIFIER_TABLE);
  698. RECORD(EXTERNAL_DEFINITIONS);
  699. RECORD(SPECIAL_TYPES);
  700. RECORD(STATISTICS);
  701. RECORD(TENTATIVE_DEFINITIONS);
  702. RECORD(UNUSED_FILESCOPED_DECLS);
  703. RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
  704. RECORD(SELECTOR_OFFSETS);
  705. RECORD(METHOD_POOL);
  706. RECORD(PP_COUNTER_VALUE);
  707. RECORD(SOURCE_LOCATION_OFFSETS);
  708. RECORD(SOURCE_LOCATION_PRELOADS);
  709. RECORD(STAT_CACHE);
  710. RECORD(EXT_VECTOR_DECLS);
  711. RECORD(VERSION_CONTROL_BRANCH_REVISION);
  712. RECORD(PPD_ENTITIES_OFFSETS);
  713. RECORD(IMPORTS);
  714. RECORD(REFERENCED_SELECTOR_POOL);
  715. RECORD(TU_UPDATE_LEXICAL);
  716. RECORD(LOCAL_REDECLARATIONS_MAP);
  717. RECORD(SEMA_DECL_REFS);
  718. RECORD(WEAK_UNDECLARED_IDENTIFIERS);
  719. RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
  720. RECORD(DECL_REPLACEMENTS);
  721. RECORD(UPDATE_VISIBLE);
  722. RECORD(DECL_UPDATE_OFFSETS);
  723. RECORD(DECL_UPDATES);
  724. RECORD(CXX_BASE_SPECIFIER_OFFSETS);
  725. RECORD(DIAG_PRAGMA_MAPPINGS);
  726. RECORD(CUDA_SPECIAL_DECL_REFS);
  727. RECORD(HEADER_SEARCH_TABLE);
  728. RECORD(ORIGINAL_PCH_DIR);
  729. RECORD(FP_PRAGMA_OPTIONS);
  730. RECORD(OPENCL_EXTENSIONS);
  731. RECORD(DELEGATING_CTORS);
  732. RECORD(FILE_SOURCE_LOCATION_OFFSETS);
  733. RECORD(KNOWN_NAMESPACES);
  734. RECORD(MODULE_OFFSET_MAP);
  735. RECORD(SOURCE_MANAGER_LINE_TABLE);
  736. RECORD(OBJC_CATEGORIES_MAP);
  737. RECORD(FILE_SORTED_DECLS);
  738. RECORD(IMPORTED_MODULES);
  739. RECORD(MERGED_DECLARATIONS);
  740. RECORD(LOCAL_REDECLARATIONS);
  741. RECORD(OBJC_CATEGORIES);
  742. // SourceManager Block.
  743. BLOCK(SOURCE_MANAGER_BLOCK);
  744. RECORD(SM_SLOC_FILE_ENTRY);
  745. RECORD(SM_SLOC_BUFFER_ENTRY);
  746. RECORD(SM_SLOC_BUFFER_BLOB);
  747. RECORD(SM_SLOC_EXPANSION_ENTRY);
  748. // Preprocessor Block.
  749. BLOCK(PREPROCESSOR_BLOCK);
  750. RECORD(PP_MACRO_OBJECT_LIKE);
  751. RECORD(PP_MACRO_FUNCTION_LIKE);
  752. RECORD(PP_TOKEN);
  753. // Decls and Types block.
  754. BLOCK(DECLTYPES_BLOCK);
  755. RECORD(TYPE_EXT_QUAL);
  756. RECORD(TYPE_COMPLEX);
  757. RECORD(TYPE_POINTER);
  758. RECORD(TYPE_BLOCK_POINTER);
  759. RECORD(TYPE_LVALUE_REFERENCE);
  760. RECORD(TYPE_RVALUE_REFERENCE);
  761. RECORD(TYPE_MEMBER_POINTER);
  762. RECORD(TYPE_CONSTANT_ARRAY);
  763. RECORD(TYPE_INCOMPLETE_ARRAY);
  764. RECORD(TYPE_VARIABLE_ARRAY);
  765. RECORD(TYPE_VECTOR);
  766. RECORD(TYPE_EXT_VECTOR);
  767. RECORD(TYPE_FUNCTION_PROTO);
  768. RECORD(TYPE_FUNCTION_NO_PROTO);
  769. RECORD(TYPE_TYPEDEF);
  770. RECORD(TYPE_TYPEOF_EXPR);
  771. RECORD(TYPE_TYPEOF);
  772. RECORD(TYPE_RECORD);
  773. RECORD(TYPE_ENUM);
  774. RECORD(TYPE_OBJC_INTERFACE);
  775. RECORD(TYPE_OBJC_OBJECT);
  776. RECORD(TYPE_OBJC_OBJECT_POINTER);
  777. RECORD(TYPE_DECLTYPE);
  778. RECORD(TYPE_ELABORATED);
  779. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
  780. RECORD(TYPE_UNRESOLVED_USING);
  781. RECORD(TYPE_INJECTED_CLASS_NAME);
  782. RECORD(TYPE_OBJC_OBJECT);
  783. RECORD(TYPE_TEMPLATE_TYPE_PARM);
  784. RECORD(TYPE_TEMPLATE_SPECIALIZATION);
  785. RECORD(TYPE_DEPENDENT_NAME);
  786. RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
  787. RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
  788. RECORD(TYPE_PAREN);
  789. RECORD(TYPE_PACK_EXPANSION);
  790. RECORD(TYPE_ATTRIBUTED);
  791. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
  792. RECORD(TYPE_ATOMIC);
  793. RECORD(DECL_TYPEDEF);
  794. RECORD(DECL_ENUM);
  795. RECORD(DECL_RECORD);
  796. RECORD(DECL_ENUM_CONSTANT);
  797. RECORD(DECL_FUNCTION);
  798. RECORD(DECL_OBJC_METHOD);
  799. RECORD(DECL_OBJC_INTERFACE);
  800. RECORD(DECL_OBJC_PROTOCOL);
  801. RECORD(DECL_OBJC_IVAR);
  802. RECORD(DECL_OBJC_AT_DEFS_FIELD);
  803. RECORD(DECL_OBJC_CATEGORY);
  804. RECORD(DECL_OBJC_CATEGORY_IMPL);
  805. RECORD(DECL_OBJC_IMPLEMENTATION);
  806. RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
  807. RECORD(DECL_OBJC_PROPERTY);
  808. RECORD(DECL_OBJC_PROPERTY_IMPL);
  809. RECORD(DECL_FIELD);
  810. RECORD(DECL_VAR);
  811. RECORD(DECL_IMPLICIT_PARAM);
  812. RECORD(DECL_PARM_VAR);
  813. RECORD(DECL_FILE_SCOPE_ASM);
  814. RECORD(DECL_BLOCK);
  815. RECORD(DECL_CONTEXT_LEXICAL);
  816. RECORD(DECL_CONTEXT_VISIBLE);
  817. RECORD(DECL_NAMESPACE);
  818. RECORD(DECL_NAMESPACE_ALIAS);
  819. RECORD(DECL_USING);
  820. RECORD(DECL_USING_SHADOW);
  821. RECORD(DECL_USING_DIRECTIVE);
  822. RECORD(DECL_UNRESOLVED_USING_VALUE);
  823. RECORD(DECL_UNRESOLVED_USING_TYPENAME);
  824. RECORD(DECL_LINKAGE_SPEC);
  825. RECORD(DECL_CXX_RECORD);
  826. RECORD(DECL_CXX_METHOD);
  827. RECORD(DECL_CXX_CONSTRUCTOR);
  828. RECORD(DECL_CXX_DESTRUCTOR);
  829. RECORD(DECL_CXX_CONVERSION);
  830. RECORD(DECL_ACCESS_SPEC);
  831. RECORD(DECL_FRIEND);
  832. RECORD(DECL_FRIEND_TEMPLATE);
  833. RECORD(DECL_CLASS_TEMPLATE);
  834. RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
  835. RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
  836. RECORD(DECL_FUNCTION_TEMPLATE);
  837. RECORD(DECL_TEMPLATE_TYPE_PARM);
  838. RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
  839. RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
  840. RECORD(DECL_STATIC_ASSERT);
  841. RECORD(DECL_CXX_BASE_SPECIFIERS);
  842. RECORD(DECL_INDIRECTFIELD);
  843. RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
  844. // Statements and Exprs can occur in the Decls and Types block.
  845. AddStmtsExprs(Stream, Record);
  846. BLOCK(PREPROCESSOR_DETAIL_BLOCK);
  847. RECORD(PPD_MACRO_EXPANSION);
  848. RECORD(PPD_MACRO_DEFINITION);
  849. RECORD(PPD_INCLUSION_DIRECTIVE);
  850. #undef RECORD
  851. #undef BLOCK
  852. Stream.ExitBlock();
  853. }
  854. /// \brief Adjusts the given filename to only write out the portion of the
  855. /// filename that is not part of the system root directory.
  856. ///
  857. /// \param Filename the file name to adjust.
  858. ///
  859. /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
  860. /// the returned filename will be adjusted by this system root.
  861. ///
  862. /// \returns either the original filename (if it needs no adjustment) or the
  863. /// adjusted filename (which points into the @p Filename parameter).
  864. static const char *
  865. adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
  866. assert(Filename && "No file name to adjust?");
  867. if (isysroot.empty())
  868. return Filename;
  869. // Verify that the filename and the system root have the same prefix.
  870. unsigned Pos = 0;
  871. for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
  872. if (Filename[Pos] != isysroot[Pos])
  873. return Filename; // Prefixes don't match.
  874. // We hit the end of the filename before we hit the end of the system root.
  875. if (!Filename[Pos])
  876. return Filename;
  877. // If the file name has a '/' at the current position, skip over the '/'.
  878. // We distinguish sysroot-based includes from absolute includes by the
  879. // absence of '/' at the beginning of sysroot-based includes.
  880. if (Filename[Pos] == '/')
  881. ++Pos;
  882. return Filename + Pos;
  883. }
  884. /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
  885. void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot,
  886. const std::string &OutputFile) {
  887. using namespace llvm;
  888. // Metadata
  889. const TargetInfo &Target = Context.getTargetInfo();
  890. BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
  891. MetaAbbrev->Add(BitCodeAbbrevOp(METADATA));
  892. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
  893. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
  894. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
  895. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
  896. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
  897. MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
  898. unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
  899. RecordData Record;
  900. Record.push_back(METADATA);
  901. Record.push_back(VERSION_MAJOR);
  902. Record.push_back(VERSION_MINOR);
  903. Record.push_back(CLANG_VERSION_MAJOR);
  904. Record.push_back(CLANG_VERSION_MINOR);
  905. Record.push_back(!isysroot.empty());
  906. const std::string &Triple = Target.getTriple().getTriple();
  907. Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple);
  908. if (Chain) {
  909. serialization::ModuleManager &Mgr = Chain->getModuleManager();
  910. llvm::SmallVector<char, 128> ModulePaths;
  911. Record.clear();
  912. for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
  913. M != MEnd; ++M) {
  914. // Skip modules that weren't directly imported.
  915. if (!(*M)->isDirectlyImported())
  916. continue;
  917. Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
  918. // FIXME: Write import location, once it matters.
  919. // FIXME: This writes the absolute path for AST files we depend on.
  920. const std::string &FileName = (*M)->FileName;
  921. Record.push_back(FileName.size());
  922. Record.append(FileName.begin(), FileName.end());
  923. }
  924. Stream.EmitRecord(IMPORTS, Record);
  925. }
  926. // Original file name and file ID
  927. SourceManager &SM = Context.getSourceManager();
  928. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  929. BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
  930. FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
  931. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  932. unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
  933. SmallString<128> MainFilePath(MainFile->getName());
  934. llvm::sys::fs::make_absolute(MainFilePath);
  935. const char *MainFileNameStr = MainFilePath.c_str();
  936. MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
  937. isysroot);
  938. RecordData Record;
  939. Record.push_back(ORIGINAL_FILE_NAME);
  940. Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
  941. Record.clear();
  942. Record.push_back(SM.getMainFileID().getOpaqueValue());
  943. Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
  944. }
  945. // Original PCH directory
  946. if (!OutputFile.empty() && OutputFile != "-") {
  947. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  948. Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
  949. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  950. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  951. SmallString<128> OutputPath(OutputFile);
  952. llvm::sys::fs::make_absolute(OutputPath);
  953. StringRef origDir = llvm::sys::path::parent_path(OutputPath);
  954. RecordData Record;
  955. Record.push_back(ORIGINAL_PCH_DIR);
  956. Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
  957. }
  958. // Repository branch/version information.
  959. BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
  960. RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
  961. RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
  962. unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
  963. Record.clear();
  964. Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
  965. Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
  966. getClangFullRepositoryVersion());
  967. }
  968. /// \brief Write the LangOptions structure.
  969. void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
  970. RecordData Record;
  971. #define LANGOPT(Name, Bits, Default, Description) \
  972. Record.push_back(LangOpts.Name);
  973. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  974. Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
  975. #include "clang/Basic/LangOptions.def"
  976. Record.push_back(LangOpts.CurrentModule.size());
  977. Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
  978. Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
  979. }
  980. //===----------------------------------------------------------------------===//
  981. // stat cache Serialization
  982. //===----------------------------------------------------------------------===//
  983. namespace {
  984. // Trait used for the on-disk hash table of stat cache results.
  985. class ASTStatCacheTrait {
  986. public:
  987. typedef const char * key_type;
  988. typedef key_type key_type_ref;
  989. typedef struct stat data_type;
  990. typedef const data_type &data_type_ref;
  991. static unsigned ComputeHash(const char *path) {
  992. return llvm::HashString(path);
  993. }
  994. std::pair<unsigned,unsigned>
  995. EmitKeyDataLength(raw_ostream& Out, const char *path,
  996. data_type_ref Data) {
  997. unsigned StrLen = strlen(path);
  998. clang::io::Emit16(Out, StrLen);
  999. unsigned DataLen = 4 + 4 + 2 + 8 + 8;
  1000. clang::io::Emit8(Out, DataLen);
  1001. return std::make_pair(StrLen + 1, DataLen);
  1002. }
  1003. void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
  1004. Out.write(path, KeyLen);
  1005. }
  1006. void EmitData(raw_ostream &Out, key_type_ref,
  1007. data_type_ref Data, unsigned DataLen) {
  1008. using namespace clang::io;
  1009. uint64_t Start = Out.tell(); (void)Start;
  1010. Emit32(Out, (uint32_t) Data.st_ino);
  1011. Emit32(Out, (uint32_t) Data.st_dev);
  1012. Emit16(Out, (uint16_t) Data.st_mode);
  1013. Emit64(Out, (uint64_t) Data.st_mtime);
  1014. Emit64(Out, (uint64_t) Data.st_size);
  1015. assert(Out.tell() - Start == DataLen && "Wrong data length");
  1016. }
  1017. };
  1018. } // end anonymous namespace
  1019. /// \brief Write the stat() system call cache to the AST file.
  1020. void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
  1021. // Build the on-disk hash table containing information about every
  1022. // stat() call.
  1023. OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
  1024. unsigned NumStatEntries = 0;
  1025. for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
  1026. StatEnd = StatCalls.end();
  1027. Stat != StatEnd; ++Stat, ++NumStatEntries) {
  1028. StringRef Filename = Stat->first();
  1029. Generator.insert(Filename.data(), Stat->second);
  1030. }
  1031. // Create the on-disk hash table in a buffer.
  1032. SmallString<4096> StatCacheData;
  1033. uint32_t BucketOffset;
  1034. {
  1035. llvm::raw_svector_ostream Out(StatCacheData);
  1036. // Make sure that no bucket is at offset 0
  1037. clang::io::Emit32(Out, 0);
  1038. BucketOffset = Generator.Emit(Out);
  1039. }
  1040. // Create a blob abbreviation
  1041. using namespace llvm;
  1042. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1043. Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
  1044. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1045. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1046. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1047. unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
  1048. // Write the stat cache
  1049. RecordData Record;
  1050. Record.push_back(STAT_CACHE);
  1051. Record.push_back(BucketOffset);
  1052. Record.push_back(NumStatEntries);
  1053. Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
  1054. }
  1055. //===----------------------------------------------------------------------===//
  1056. // Source Manager Serialization
  1057. //===----------------------------------------------------------------------===//
  1058. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1059. /// file.
  1060. static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
  1061. using namespace llvm;
  1062. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1063. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
  1064. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1065. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1066. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
  1067. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1068. // FileEntry fields.
  1069. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
  1070. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
  1071. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden
  1072. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
  1073. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
  1074. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
  1075. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1076. return Stream.EmitAbbrev(Abbrev);
  1077. }
  1078. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1079. /// buffer.
  1080. static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
  1081. using namespace llvm;
  1082. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1083. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
  1084. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1085. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1086. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
  1087. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1088. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
  1089. return Stream.EmitAbbrev(Abbrev);
  1090. }
  1091. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1092. /// buffer's blob.
  1093. static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
  1094. using namespace llvm;
  1095. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1096. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
  1097. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
  1098. return Stream.EmitAbbrev(Abbrev);
  1099. }
  1100. /// \brief Create an abbreviation for the SLocEntry that refers to a macro
  1101. /// expansion.
  1102. static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
  1103. using namespace llvm;
  1104. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1105. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
  1106. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1107. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
  1108. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
  1109. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
  1110. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
  1111. return Stream.EmitAbbrev(Abbrev);
  1112. }
  1113. namespace {
  1114. // Trait used for the on-disk hash table of header search information.
  1115. class HeaderFileInfoTrait {
  1116. ASTWriter &Writer;
  1117. const HeaderSearch &HS;
  1118. // Keep track of the framework names we've used during serialization.
  1119. SmallVector<char, 128> FrameworkStringData;
  1120. llvm::StringMap<unsigned> FrameworkNameOffset;
  1121. public:
  1122. HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
  1123. : Writer(Writer), HS(HS) { }
  1124. typedef const char *key_type;
  1125. typedef key_type key_type_ref;
  1126. typedef HeaderFileInfo data_type;
  1127. typedef const data_type &data_type_ref;
  1128. static unsigned ComputeHash(const char *path) {
  1129. // The hash is based only on the filename portion of the key, so that the
  1130. // reader can match based on filenames when symlinking or excess path
  1131. // elements ("foo/../", "../") change the form of the name. However,
  1132. // complete path is still the key.
  1133. return llvm::HashString(llvm::sys::path::filename(path));
  1134. }
  1135. std::pair<unsigned,unsigned>
  1136. EmitKeyDataLength(raw_ostream& Out, const char *path,
  1137. data_type_ref Data) {
  1138. unsigned StrLen = strlen(path);
  1139. clang::io::Emit16(Out, StrLen);
  1140. unsigned DataLen = 1 + 2 + 4 + 4;
  1141. clang::io::Emit8(Out, DataLen);
  1142. return std::make_pair(StrLen + 1, DataLen);
  1143. }
  1144. void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
  1145. Out.write(path, KeyLen);
  1146. }
  1147. void EmitData(raw_ostream &Out, key_type_ref,
  1148. data_type_ref Data, unsigned DataLen) {
  1149. using namespace clang::io;
  1150. uint64_t Start = Out.tell(); (void)Start;
  1151. unsigned char Flags = (Data.isImport << 5)
  1152. | (Data.isPragmaOnce << 4)
  1153. | (Data.DirInfo << 2)
  1154. | (Data.Resolved << 1)
  1155. | Data.IndexHeaderMapHeader;
  1156. Emit8(Out, (uint8_t)Flags);
  1157. Emit16(Out, (uint16_t) Data.NumIncludes);
  1158. if (!Data.ControllingMacro)
  1159. Emit32(Out, (uint32_t)Data.ControllingMacroID);
  1160. else
  1161. Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
  1162. unsigned Offset = 0;
  1163. if (!Data.Framework.empty()) {
  1164. // If this header refers into a framework, save the framework name.
  1165. llvm::StringMap<unsigned>::iterator Pos
  1166. = FrameworkNameOffset.find(Data.Framework);
  1167. if (Pos == FrameworkNameOffset.end()) {
  1168. Offset = FrameworkStringData.size() + 1;
  1169. FrameworkStringData.append(Data.Framework.begin(),
  1170. Data.Framework.end());
  1171. FrameworkStringData.push_back(0);
  1172. FrameworkNameOffset[Data.Framework] = Offset;
  1173. } else
  1174. Offset = Pos->second;
  1175. }
  1176. Emit32(Out, Offset);
  1177. assert(Out.tell() - Start == DataLen && "Wrong data length");
  1178. }
  1179. const char *strings_begin() const { return FrameworkStringData.begin(); }
  1180. const char *strings_end() const { return FrameworkStringData.end(); }
  1181. };
  1182. } // end anonymous namespace
  1183. /// \brief Write the header search block for the list of files that
  1184. ///
  1185. /// \param HS The header search structure to save.
  1186. ///
  1187. /// \param Chain Whether we're creating a chained AST file.
  1188. void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
  1189. SmallVector<const FileEntry *, 16> FilesByUID;
  1190. HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
  1191. if (FilesByUID.size() > HS.header_file_size())
  1192. FilesByUID.resize(HS.header_file_size());
  1193. HeaderFileInfoTrait GeneratorTrait(*this, HS);
  1194. OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
  1195. SmallVector<const char *, 4> SavedStrings;
  1196. unsigned NumHeaderSearchEntries = 0;
  1197. for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
  1198. const FileEntry *File = FilesByUID[UID];
  1199. if (!File)
  1200. continue;
  1201. // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
  1202. // from the external source if it was not provided already.
  1203. const HeaderFileInfo &HFI = HS.getFileInfo(File);
  1204. if (HFI.External && Chain)
  1205. continue;
  1206. // Turn the file name into an absolute path, if it isn't already.
  1207. const char *Filename = File->getName();
  1208. Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
  1209. // If we performed any translation on the file name at all, we need to
  1210. // save this string, since the generator will refer to it later.
  1211. if (Filename != File->getName()) {
  1212. Filename = strdup(Filename);
  1213. SavedStrings.push_back(Filename);
  1214. }
  1215. Generator.insert(Filename, HFI, GeneratorTrait);
  1216. ++NumHeaderSearchEntries;
  1217. }
  1218. // Create the on-disk hash table in a buffer.
  1219. SmallString<4096> TableData;
  1220. uint32_t BucketOffset;
  1221. {
  1222. llvm::raw_svector_ostream Out(TableData);
  1223. // Make sure that no bucket is at offset 0
  1224. clang::io::Emit32(Out, 0);
  1225. BucketOffset = Generator.Emit(Out, GeneratorTrait);
  1226. }
  1227. // Create a blob abbreviation
  1228. using namespace llvm;
  1229. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1230. Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
  1231. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1232. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1233. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1234. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1235. unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
  1236. // Write the header search table
  1237. RecordData Record;
  1238. Record.push_back(HEADER_SEARCH_TABLE);
  1239. Record.push_back(BucketOffset);
  1240. Record.push_back(NumHeaderSearchEntries);
  1241. Record.push_back(TableData.size());
  1242. TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
  1243. Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
  1244. // Free all of the strings we had to duplicate.
  1245. for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
  1246. free((void*)SavedStrings[I]);
  1247. }
  1248. /// \brief Writes the block containing the serialized form of the
  1249. /// source manager.
  1250. ///
  1251. /// TODO: We should probably use an on-disk hash table (stored in a
  1252. /// blob), indexed based on the file name, so that we only create
  1253. /// entries for files that we actually need. In the common case (no
  1254. /// errors), we probably won't have to create file entries for any of
  1255. /// the files in the AST.
  1256. void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
  1257. const Preprocessor &PP,
  1258. StringRef isysroot) {
  1259. RecordData Record;
  1260. // Enter the source manager block.
  1261. Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
  1262. // Abbreviations for the various kinds of source-location entries.
  1263. unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
  1264. unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
  1265. unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
  1266. unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
  1267. // Write out the source location entry table. We skip the first
  1268. // entry, which is always the same dummy entry.
  1269. std::vector<uint32_t> SLocEntryOffsets;
  1270. // Write out the offsets of only source location file entries.
  1271. // We will go through them in ASTReader::validateFileEntries().
  1272. std::vector<uint32_t> SLocFileEntryOffsets;
  1273. RecordData PreloadSLocs;
  1274. SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
  1275. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
  1276. I != N; ++I) {
  1277. // Get this source location entry.
  1278. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1279. // Record the offset of this source-location entry.
  1280. SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
  1281. // Figure out which record code to use.
  1282. unsigned Code;
  1283. if (SLoc->isFile()) {
  1284. const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
  1285. if (Cache->OrigEntry) {
  1286. Code = SM_SLOC_FILE_ENTRY;
  1287. SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
  1288. } else
  1289. Code = SM_SLOC_BUFFER_ENTRY;
  1290. } else
  1291. Code = SM_SLOC_EXPANSION_ENTRY;
  1292. Record.clear();
  1293. Record.push_back(Code);
  1294. // Starting offset of this entry within this module, so skip the dummy.
  1295. Record.push_back(SLoc->getOffset() - 2);
  1296. if (SLoc->isFile()) {
  1297. const SrcMgr::FileInfo &File = SLoc->getFile();
  1298. Record.push_back(File.getIncludeLoc().getRawEncoding());
  1299. Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
  1300. Record.push_back(File.hasLineDirectives());
  1301. const SrcMgr::ContentCache *Content = File.getContentCache();
  1302. if (Content->OrigEntry) {
  1303. assert(Content->OrigEntry == Content->ContentsEntry &&
  1304. "Writing to AST an overridden file is not supported");
  1305. // The source location entry is a file. The blob associated
  1306. // with this entry is the file name.
  1307. // Emit size/modification time for this file.
  1308. Record.push_back(Content->OrigEntry->getSize());
  1309. Record.push_back(Content->OrigEntry->getModificationTime());
  1310. Record.push_back(Content->BufferOverridden);
  1311. Record.push_back(File.NumCreatedFIDs);
  1312. FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc);
  1313. if (FDI != FileDeclIDs.end()) {
  1314. Record.push_back(FDI->second->FirstDeclIndex);
  1315. Record.push_back(FDI->second->DeclIDs.size());
  1316. } else {
  1317. Record.push_back(0);
  1318. Record.push_back(0);
  1319. }
  1320. // Turn the file name into an absolute path, if it isn't already.
  1321. const char *Filename = Content->OrigEntry->getName();
  1322. SmallString<128> FilePath(Filename);
  1323. // Ask the file manager to fixup the relative path for us. This will
  1324. // honor the working directory.
  1325. SourceMgr.getFileManager().FixupRelativePath(FilePath);
  1326. // FIXME: This call to make_absolute shouldn't be necessary, the
  1327. // call to FixupRelativePath should always return an absolute path.
  1328. llvm::sys::fs::make_absolute(FilePath);
  1329. Filename = FilePath.c_str();
  1330. Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
  1331. Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
  1332. if (Content->BufferOverridden) {
  1333. Record.clear();
  1334. Record.push_back(SM_SLOC_BUFFER_BLOB);
  1335. const llvm::MemoryBuffer *Buffer
  1336. = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  1337. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
  1338. StringRef(Buffer->getBufferStart(),
  1339. Buffer->getBufferSize() + 1));
  1340. }
  1341. } else {
  1342. // The source location entry is a buffer. The blob associated
  1343. // with this entry contains the contents of the buffer.
  1344. // We add one to the size so that we capture the trailing NULL
  1345. // that is required by llvm::MemoryBuffer::getMemBuffer (on
  1346. // the reader side).
  1347. const llvm::MemoryBuffer *Buffer
  1348. = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  1349. const char *Name = Buffer->getBufferIdentifier();
  1350. Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
  1351. StringRef(Name, strlen(Name) + 1));
  1352. Record.clear();
  1353. Record.push_back(SM_SLOC_BUFFER_BLOB);
  1354. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
  1355. StringRef(Buffer->getBufferStart(),
  1356. Buffer->getBufferSize() + 1));
  1357. if (strcmp(Name, "<built-in>") == 0) {
  1358. PreloadSLocs.push_back(SLocEntryOffsets.size());
  1359. }
  1360. }
  1361. } else {
  1362. // The source location entry is a macro expansion.
  1363. const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
  1364. Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
  1365. Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
  1366. Record.push_back(Expansion.isMacroArgExpansion() ? 0
  1367. : Expansion.getExpansionLocEnd().getRawEncoding());
  1368. // Compute the token length for this macro expansion.
  1369. unsigned NextOffset = SourceMgr.getNextLocalOffset();
  1370. if (I + 1 != N)
  1371. NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
  1372. Record.push_back(NextOffset - SLoc->getOffset() - 1);
  1373. Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
  1374. }
  1375. }
  1376. Stream.ExitBlock();
  1377. if (SLocEntryOffsets.empty())
  1378. return;
  1379. // Write the source-location offsets table into the AST block. This
  1380. // table is used for lazily loading source-location information.
  1381. using namespace llvm;
  1382. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1383. Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
  1384. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
  1385. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
  1386. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
  1387. unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
  1388. Record.clear();
  1389. Record.push_back(SOURCE_LOCATION_OFFSETS);
  1390. Record.push_back(SLocEntryOffsets.size());
  1391. Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
  1392. Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
  1393. Abbrev = new BitCodeAbbrev();
  1394. Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
  1395. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
  1396. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
  1397. unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
  1398. Record.clear();
  1399. Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
  1400. Record.push_back(SLocFileEntryOffsets.size());
  1401. Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
  1402. data(SLocFileEntryOffsets));
  1403. // Write the source location entry preloads array, telling the AST
  1404. // reader which source locations entries it should load eagerly.
  1405. Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
  1406. // Write the line table. It depends on remapping working, so it must come
  1407. // after the source location offsets.
  1408. if (SourceMgr.hasLineTable()) {
  1409. LineTableInfo &LineTable = SourceMgr.getLineTable();
  1410. Record.clear();
  1411. // Emit the file names
  1412. Record.push_back(LineTable.getNumFilenames());
  1413. for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
  1414. // Emit the file name
  1415. const char *Filename = LineTable.getFilename(I);
  1416. Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
  1417. unsigned FilenameLen = Filename? strlen(Filename) : 0;
  1418. Record.push_back(FilenameLen);
  1419. if (FilenameLen)
  1420. Record.insert(Record.end(), Filename, Filename + FilenameLen);
  1421. }
  1422. // Emit the line entries
  1423. for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
  1424. L != LEnd; ++L) {
  1425. // Only emit entries for local files.
  1426. if (L->first < 0)
  1427. continue;
  1428. // Emit the file ID
  1429. Record.push_back(L->first);
  1430. // Emit the line entries
  1431. Record.push_back(L->second.size());
  1432. for (std::vector<LineEntry>::iterator LE = L->second.begin(),
  1433. LEEnd = L->second.end();
  1434. LE != LEEnd; ++LE) {
  1435. Record.push_back(LE->FileOffset);
  1436. Record.push_back(LE->LineNo);
  1437. Record.push_back(LE->FilenameID);
  1438. Record.push_back((unsigned)LE->FileKind);
  1439. Record.push_back(LE->IncludeOffset);
  1440. }
  1441. }
  1442. Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
  1443. }
  1444. }
  1445. //===----------------------------------------------------------------------===//
  1446. // Preprocessor Serialization
  1447. //===----------------------------------------------------------------------===//
  1448. static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
  1449. const std::pair<const IdentifierInfo *, MacroInfo *> &X =
  1450. *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
  1451. const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
  1452. *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
  1453. return X.first->getName().compare(Y.first->getName());
  1454. }
  1455. /// \brief Writes the block containing the serialized form of the
  1456. /// preprocessor.
  1457. ///
  1458. void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
  1459. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  1460. if (PPRec)
  1461. WritePreprocessorDetail(*PPRec);
  1462. RecordData Record;
  1463. // If the preprocessor __COUNTER__ value has been bumped, remember it.
  1464. if (PP.getCounterValue() != 0) {
  1465. Record.push_back(PP.getCounterValue());
  1466. Stream.EmitRecord(PP_COUNTER_VALUE, Record);
  1467. Record.clear();
  1468. }
  1469. // Enter the preprocessor block.
  1470. Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
  1471. // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
  1472. // FIXME: use diagnostics subsystem for localization etc.
  1473. if (PP.SawDateOrTime())
  1474. fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
  1475. // Loop over all the macro definitions that are live at the end of the file,
  1476. // emitting each to the PP section.
  1477. // Construct the list of macro definitions that need to be serialized.
  1478. SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
  1479. MacrosToEmit;
  1480. llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
  1481. for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
  1482. E = PP.macro_end(Chain == 0);
  1483. I != E; ++I) {
  1484. const IdentifierInfo *Name = I->first;
  1485. if (!IsModule || I->second->isPublic()) {
  1486. MacroDefinitionsSeen.insert(Name);
  1487. MacrosToEmit.push_back(std::make_pair(I->first, I->second));
  1488. }
  1489. }
  1490. // Sort the set of macro definitions that need to be serialized by the
  1491. // name of the macro, to provide a stable ordering.
  1492. llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
  1493. &compareMacroDefinitions);
  1494. // Resolve any identifiers that defined macros at the time they were
  1495. // deserialized, adding them to the list of macros to emit (if appropriate).
  1496. for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
  1497. IdentifierInfo *Name
  1498. = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
  1499. if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
  1500. MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
  1501. }
  1502. for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
  1503. const IdentifierInfo *Name = MacrosToEmit[I].first;
  1504. MacroInfo *MI = MacrosToEmit[I].second;
  1505. if (!MI)
  1506. continue;
  1507. // Don't emit builtin macros like __LINE__ to the AST file unless they have
  1508. // been redefined by the header (in which case they are not isBuiltinMacro).
  1509. // Also skip macros from a AST file if we're chaining.
  1510. // FIXME: There is a (probably minor) optimization we could do here, if
  1511. // the macro comes from the original PCH but the identifier comes from a
  1512. // chained PCH, by storing the offset into the original PCH rather than
  1513. // writing the macro definition a second time.
  1514. if (MI->isBuiltinMacro() ||
  1515. (Chain &&
  1516. Name->isFromAST() && !Name->hasChangedSinceDeserialization() &&
  1517. MI->isFromAST() && !MI->hasChangedAfterLoad()))
  1518. continue;
  1519. AddIdentifierRef(Name, Record);
  1520. MacroOffsets[Name] = Stream.GetCurrentBitNo();
  1521. Record.push_back(MI->getDefinitionLoc().getRawEncoding());
  1522. Record.push_back(MI->isUsed());
  1523. Record.push_back(MI->isPublic());
  1524. AddSourceLocation(MI->getVisibilityLocation(), Record);
  1525. unsigned Code;
  1526. if (MI->isObjectLike()) {
  1527. Code = PP_MACRO_OBJECT_LIKE;
  1528. } else {
  1529. Code = PP_MACRO_FUNCTION_LIKE;
  1530. Record.push_back(MI->isC99Varargs());
  1531. Record.push_back(MI->isGNUVarargs());
  1532. Record.push_back(MI->getNumArgs());
  1533. for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
  1534. I != E; ++I)
  1535. AddIdentifierRef(*I, Record);
  1536. }
  1537. // If we have a detailed preprocessing record, record the macro definition
  1538. // ID that corresponds to this macro.
  1539. if (PPRec)
  1540. Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
  1541. Stream.EmitRecord(Code, Record);
  1542. Record.clear();
  1543. // Emit the tokens array.
  1544. for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
  1545. // Note that we know that the preprocessor does not have any annotation
  1546. // tokens in it because they are created by the parser, and thus can't be
  1547. // in a macro definition.
  1548. const Token &Tok = MI->getReplacementToken(TokNo);
  1549. Record.push_back(Tok.getLocation().getRawEncoding());
  1550. Record.push_back(Tok.getLength());
  1551. // FIXME: When reading literal tokens, reconstruct the literal pointer if
  1552. // it is needed.
  1553. AddIdentifierRef(Tok.getIdentifierInfo(), Record);
  1554. // FIXME: Should translate token kind to a stable encoding.
  1555. Record.push_back(Tok.getKind());
  1556. // FIXME: Should translate token flags to a stable encoding.
  1557. Record.push_back(Tok.getFlags());
  1558. Stream.EmitRecord(PP_TOKEN, Record);
  1559. Record.clear();
  1560. }
  1561. ++NumMacros;
  1562. }
  1563. Stream.ExitBlock();
  1564. }
  1565. void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
  1566. if (PPRec.local_begin() == PPRec.local_end())
  1567. return;
  1568. SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
  1569. // Enter the preprocessor block.
  1570. Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
  1571. // If the preprocessor has a preprocessing record, emit it.
  1572. unsigned NumPreprocessingRecords = 0;
  1573. using namespace llvm;
  1574. // Set up the abbreviation for
  1575. unsigned InclusionAbbrev = 0;
  1576. {
  1577. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1578. Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
  1579. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
  1580. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
  1581. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
  1582. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1583. InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
  1584. }
  1585. unsigned FirstPreprocessorEntityID
  1586. = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
  1587. + NUM_PREDEF_PP_ENTITY_IDS;
  1588. unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
  1589. RecordData Record;
  1590. for (PreprocessingRecord::iterator E = PPRec.local_begin(),
  1591. EEnd = PPRec.local_end();
  1592. E != EEnd;
  1593. (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
  1594. Record.clear();
  1595. PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
  1596. Stream.GetCurrentBitNo()));
  1597. if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
  1598. // Record this macro definition's ID.
  1599. MacroDefinitions[MD] = NextPreprocessorEntityID;
  1600. AddIdentifierRef(MD->getName(), Record);
  1601. Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
  1602. continue;
  1603. }
  1604. if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
  1605. Record.push_back(ME->isBuiltinMacro());
  1606. if (ME->isBuiltinMacro())
  1607. AddIdentifierRef(ME->getName(), Record);
  1608. else
  1609. Record.push_back(MacroDefinitions[ME->getDefinition()]);
  1610. Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
  1611. continue;
  1612. }
  1613. if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
  1614. Record.push_back(PPD_INCLUSION_DIRECTIVE);
  1615. Record.push_back(ID->getFileName().size());
  1616. Record.push_back(ID->wasInQuotes());
  1617. Record.push_back(static_cast<unsigned>(ID->getKind()));
  1618. SmallString<64> Buffer;
  1619. Buffer += ID->getFileName();
  1620. Buffer += ID->getFile()->getName();
  1621. Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
  1622. continue;
  1623. }
  1624. llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
  1625. }
  1626. Stream.ExitBlock();
  1627. // Write the offsets table for the preprocessing record.
  1628. if (NumPreprocessingRecords > 0) {
  1629. assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
  1630. // Write the offsets table for identifier IDs.
  1631. using namespace llvm;
  1632. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1633. Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
  1634. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
  1635. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1636. unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  1637. Record.clear();
  1638. Record.push_back(PPD_ENTITIES_OFFSETS);
  1639. Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
  1640. Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
  1641. data(PreprocessedEntityOffsets));
  1642. }
  1643. }
  1644. unsigned ASTWriter::getSubmoduleID(Module *Mod) {
  1645. llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
  1646. if (Known != SubmoduleIDs.end())
  1647. return Known->second;
  1648. return SubmoduleIDs[Mod] = NextSubmoduleID++;
  1649. }
  1650. /// \brief Compute the number of modules within the given tree (including the
  1651. /// given module).
  1652. static unsigned getNumberOfModules(Module *Mod) {
  1653. unsigned ChildModules = 0;
  1654. for (Module::submodule_iterator Sub = Mod->submodule_begin(),
  1655. SubEnd = Mod->submodule_end();
  1656. Sub != SubEnd; ++Sub)
  1657. ChildModules += getNumberOfModules(*Sub);
  1658. return ChildModules + 1;
  1659. }
  1660. void ASTWriter::WriteSubmodules(Module *WritingModule) {
  1661. // Determine the dependencies of our module and each of it's submodules.
  1662. // FIXME: This feels like it belongs somewhere else, but there are no
  1663. // other consumers of this information.
  1664. SourceManager &SrcMgr = PP->getSourceManager();
  1665. ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
  1666. for (ASTContext::import_iterator I = Context->local_import_begin(),
  1667. IEnd = Context->local_import_end();
  1668. I != IEnd; ++I) {
  1669. if (Module *ImportedFrom
  1670. = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
  1671. SrcMgr))) {
  1672. ImportedFrom->Imports.push_back(I->getImportedModule());
  1673. }
  1674. }
  1675. // Enter the submodule description block.
  1676. Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
  1677. // Write the abbreviations needed for the submodules block.
  1678. using namespace llvm;
  1679. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1680. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
  1681. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  1682. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
  1683. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  1684. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
  1685. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
  1686. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
  1687. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
  1688. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
  1689. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1690. unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
  1691. Abbrev = new BitCodeAbbrev();
  1692. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
  1693. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1694. unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
  1695. Abbrev = new BitCodeAbbrev();
  1696. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
  1697. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1698. unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  1699. Abbrev = new BitCodeAbbrev();
  1700. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
  1701. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1702. unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
  1703. Abbrev = new BitCodeAbbrev();
  1704. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
  1705. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
  1706. unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
  1707. // Write the submodule metadata block.
  1708. RecordData Record;
  1709. Record.push_back(getNumberOfModules(WritingModule));
  1710. Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
  1711. Stream.EmitRecord(SUBMODULE_METADATA, Record);
  1712. // Write all of the submodules.
  1713. std::queue<Module *> Q;
  1714. Q.push(WritingModule);
  1715. while (!Q.empty()) {
  1716. Module *Mod = Q.front();
  1717. Q.pop();
  1718. unsigned ID = getSubmoduleID(Mod);
  1719. // Emit the definition of the block.
  1720. Record.clear();
  1721. Record.push_back(SUBMODULE_DEFINITION);
  1722. Record.push_back(ID);
  1723. if (Mod->Parent) {
  1724. assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
  1725. Record.push_back(SubmoduleIDs[Mod->Parent]);
  1726. } else {
  1727. Record.push_back(0);
  1728. }
  1729. Record.push_back(Mod->IsFramework);
  1730. Record.push_back(Mod->IsExplicit);
  1731. Record.push_back(Mod->IsSystem);
  1732. Record.push_back(Mod->InferSubmodules);
  1733. Record.push_back(Mod->InferExplicitSubmodules);
  1734. Record.push_back(Mod->InferExportWildcard);
  1735. Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
  1736. // Emit the requirements.
  1737. for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
  1738. Record.clear();
  1739. Record.push_back(SUBMODULE_REQUIRES);
  1740. Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
  1741. Mod->Requires[I].data(),
  1742. Mod->Requires[I].size());
  1743. }
  1744. // Emit the umbrella header, if there is one.
  1745. if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
  1746. Record.clear();
  1747. Record.push_back(SUBMODULE_UMBRELLA_HEADER);
  1748. Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
  1749. UmbrellaHeader->getName());
  1750. } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
  1751. Record.clear();
  1752. Record.push_back(SUBMODULE_UMBRELLA_DIR);
  1753. Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
  1754. UmbrellaDir->getName());
  1755. }
  1756. // Emit the headers.
  1757. for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
  1758. Record.clear();
  1759. Record.push_back(SUBMODULE_HEADER);
  1760. Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
  1761. Mod->Headers[I]->getName());
  1762. }
  1763. // Emit the imports.
  1764. if (!Mod->Imports.empty()) {
  1765. Record.clear();
  1766. for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
  1767. unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
  1768. assert(ImportedID && "Unknown submodule!");
  1769. Record.push_back(ImportedID);
  1770. }
  1771. Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
  1772. }
  1773. // Emit the exports.
  1774. if (!Mod->Exports.empty()) {
  1775. Record.clear();
  1776. for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
  1777. if (Module *Exported = Mod->Exports[I].getPointer()) {
  1778. unsigned ExportedID = SubmoduleIDs[Exported];
  1779. assert(ExportedID > 0 && "Unknown submodule ID?");
  1780. Record.push_back(ExportedID);
  1781. } else {
  1782. Record.push_back(0);
  1783. }
  1784. Record.push_back(Mod->Exports[I].getInt());
  1785. }
  1786. Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
  1787. }
  1788. // Queue up the submodules of this module.
  1789. for (Module::submodule_iterator Sub = Mod->submodule_begin(),
  1790. SubEnd = Mod->submodule_end();
  1791. Sub != SubEnd; ++Sub)
  1792. Q.push(*Sub);
  1793. }
  1794. Stream.ExitBlock();
  1795. assert((NextSubmoduleID - FirstSubmoduleID
  1796. == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
  1797. }
  1798. serialization::SubmoduleID
  1799. ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
  1800. if (Loc.isInvalid() || !WritingModule)
  1801. return 0; // No submodule
  1802. // Find the module that owns this location.
  1803. ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
  1804. Module *OwningMod
  1805. = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
  1806. if (!OwningMod)
  1807. return 0;
  1808. // Check whether this submodule is part of our own module.
  1809. if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
  1810. return 0;
  1811. return getSubmoduleID(OwningMod);
  1812. }
  1813. void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) {
  1814. RecordData Record;
  1815. for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
  1816. I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
  1817. I != E; ++I) {
  1818. const DiagnosticsEngine::DiagStatePoint &point = *I;
  1819. if (point.Loc.isInvalid())
  1820. continue;
  1821. Record.push_back(point.Loc.getRawEncoding());
  1822. for (DiagnosticsEngine::DiagState::const_iterator
  1823. I = point.State->begin(), E = point.State->end(); I != E; ++I) {
  1824. if (I->second.isPragma()) {
  1825. Record.push_back(I->first);
  1826. Record.push_back(I->second.getMapping());
  1827. }
  1828. }
  1829. Record.push_back(-1); // mark the end of the diag/map pairs for this
  1830. // location.
  1831. }
  1832. if (!Record.empty())
  1833. Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
  1834. }
  1835. void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
  1836. if (CXXBaseSpecifiersOffsets.empty())
  1837. return;
  1838. RecordData Record;
  1839. // Create a blob abbreviation for the C++ base specifiers offsets.
  1840. using namespace llvm;
  1841. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1842. Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
  1843. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  1844. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1845. unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  1846. // Write the base specifier offsets table.
  1847. Record.clear();
  1848. Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
  1849. Record.push_back(CXXBaseSpecifiersOffsets.size());
  1850. Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
  1851. data(CXXBaseSpecifiersOffsets));
  1852. }
  1853. //===----------------------------------------------------------------------===//
  1854. // Type Serialization
  1855. //===----------------------------------------------------------------------===//
  1856. /// \brief Write the representation of a type to the AST stream.
  1857. void ASTWriter::WriteType(QualType T) {
  1858. TypeIdx &Idx = TypeIdxs[T];
  1859. if (Idx.getIndex() == 0) // we haven't seen this type before.
  1860. Idx = TypeIdx(NextTypeID++);
  1861. assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
  1862. // Record the offset for this type.
  1863. unsigned Index = Idx.getIndex() - FirstTypeID;
  1864. if (TypeOffsets.size() == Index)
  1865. TypeOffsets.push_back(Stream.GetCurrentBitNo());
  1866. else if (TypeOffsets.size() < Index) {
  1867. TypeOffsets.resize(Index + 1);
  1868. TypeOffsets[Index] = Stream.GetCurrentBitNo();
  1869. }
  1870. RecordData Record;
  1871. // Emit the type's representation.
  1872. ASTTypeWriter W(*this, Record);
  1873. if (T.hasLocalNonFastQualifiers()) {
  1874. Qualifiers Qs = T.getLocalQualifiers();
  1875. AddTypeRef(T.getLocalUnqualifiedType(), Record);
  1876. Record.push_back(Qs.getAsOpaqueValue());
  1877. W.Code = TYPE_EXT_QUAL;
  1878. } else {
  1879. switch (T->getTypeClass()) {
  1880. // For all of the concrete, non-dependent types, call the
  1881. // appropriate visitor function.
  1882. #define TYPE(Class, Base) \
  1883. case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
  1884. #define ABSTRACT_TYPE(Class, Base)
  1885. #include "clang/AST/TypeNodes.def"
  1886. }
  1887. }
  1888. // Emit the serialized record.
  1889. Stream.EmitRecord(W.Code, Record);
  1890. // Flush any expressions that were written as part of this type.
  1891. FlushStmts();
  1892. }
  1893. //===----------------------------------------------------------------------===//
  1894. // Declaration Serialization
  1895. //===----------------------------------------------------------------------===//
  1896. /// \brief Write the block containing all of the declaration IDs
  1897. /// lexically declared within the given DeclContext.
  1898. ///
  1899. /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
  1900. /// bistream, or 0 if no block was written.
  1901. uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
  1902. DeclContext *DC) {
  1903. if (DC->decls_empty())
  1904. return 0;
  1905. uint64_t Offset = Stream.GetCurrentBitNo();
  1906. RecordData Record;
  1907. Record.push_back(DECL_CONTEXT_LEXICAL);
  1908. SmallVector<KindDeclIDPair, 64> Decls;
  1909. for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
  1910. D != DEnd; ++D)
  1911. Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
  1912. ++NumLexicalDeclContexts;
  1913. Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
  1914. return Offset;
  1915. }
  1916. void ASTWriter::WriteTypeDeclOffsets() {
  1917. using namespace llvm;
  1918. RecordData Record;
  1919. // Write the type offsets array
  1920. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1921. Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
  1922. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
  1923. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
  1924. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
  1925. unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  1926. Record.clear();
  1927. Record.push_back(TYPE_OFFSET);
  1928. Record.push_back(TypeOffsets.size());
  1929. Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
  1930. Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
  1931. // Write the declaration offsets array
  1932. Abbrev = new BitCodeAbbrev();
  1933. Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
  1934. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
  1935. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
  1936. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
  1937. unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  1938. Record.clear();
  1939. Record.push_back(DECL_OFFSET);
  1940. Record.push_back(DeclOffsets.size());
  1941. Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
  1942. Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
  1943. }
  1944. void ASTWriter::WriteFileDeclIDsMap() {
  1945. using namespace llvm;
  1946. RecordData Record;
  1947. // Join the vectors of DeclIDs from all files.
  1948. SmallVector<DeclID, 256> FileSortedIDs;
  1949. for (FileDeclIDsTy::iterator
  1950. FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
  1951. DeclIDInFileInfo &Info = *FI->second;
  1952. Info.FirstDeclIndex = FileSortedIDs.size();
  1953. for (LocDeclIDsTy::iterator
  1954. DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
  1955. FileSortedIDs.push_back(DI->second);
  1956. }
  1957. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1958. Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
  1959. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1960. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  1961. Record.push_back(FILE_SORTED_DECLS);
  1962. Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
  1963. }
  1964. //===----------------------------------------------------------------------===//
  1965. // Global Method Pool and Selector Serialization
  1966. //===----------------------------------------------------------------------===//
  1967. namespace {
  1968. // Trait used for the on-disk hash table used in the method pool.
  1969. class ASTMethodPoolTrait {
  1970. ASTWriter &Writer;
  1971. public:
  1972. typedef Selector key_type;
  1973. typedef key_type key_type_ref;
  1974. struct data_type {
  1975. SelectorID ID;
  1976. ObjCMethodList Instance, Factory;
  1977. };
  1978. typedef const data_type& data_type_ref;
  1979. explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
  1980. static unsigned ComputeHash(Selector Sel) {
  1981. return serialization::ComputeHash(Sel);
  1982. }
  1983. std::pair<unsigned,unsigned>
  1984. EmitKeyDataLength(raw_ostream& Out, Selector Sel,
  1985. data_type_ref Methods) {
  1986. unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
  1987. clang::io::Emit16(Out, KeyLen);
  1988. unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
  1989. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  1990. Method = Method->Next)
  1991. if (Method->Method)
  1992. DataLen += 4;
  1993. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  1994. Method = Method->Next)
  1995. if (Method->Method)
  1996. DataLen += 4;
  1997. clang::io::Emit16(Out, DataLen);
  1998. return std::make_pair(KeyLen, DataLen);
  1999. }
  2000. void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
  2001. uint64_t Start = Out.tell();
  2002. assert((Start >> 32) == 0 && "Selector key offset too large");
  2003. Writer.SetSelectorOffset(Sel, Start);
  2004. unsigned N = Sel.getNumArgs();
  2005. clang::io::Emit16(Out, N);
  2006. if (N == 0)
  2007. N = 1;
  2008. for (unsigned I = 0; I != N; ++I)
  2009. clang::io::Emit32(Out,
  2010. Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
  2011. }
  2012. void EmitData(raw_ostream& Out, key_type_ref,
  2013. data_type_ref Methods, unsigned DataLen) {
  2014. uint64_t Start = Out.tell(); (void)Start;
  2015. clang::io::Emit32(Out, Methods.ID);
  2016. unsigned NumInstanceMethods = 0;
  2017. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2018. Method = Method->Next)
  2019. if (Method->Method)
  2020. ++NumInstanceMethods;
  2021. unsigned NumFactoryMethods = 0;
  2022. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2023. Method = Method->Next)
  2024. if (Method->Method)
  2025. ++NumFactoryMethods;
  2026. clang::io::Emit16(Out, NumInstanceMethods);
  2027. clang::io::Emit16(Out, NumFactoryMethods);
  2028. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2029. Method = Method->Next)
  2030. if (Method->Method)
  2031. clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
  2032. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2033. Method = Method->Next)
  2034. if (Method->Method)
  2035. clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
  2036. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  2037. }
  2038. };
  2039. } // end anonymous namespace
  2040. /// \brief Write ObjC data: selectors and the method pool.
  2041. ///
  2042. /// The method pool contains both instance and factory methods, stored
  2043. /// in an on-disk hash table indexed by the selector. The hash table also
  2044. /// contains an empty entry for every other selector known to Sema.
  2045. void ASTWriter::WriteSelectors(Sema &SemaRef) {
  2046. using namespace llvm;
  2047. // Do we have to do anything at all?
  2048. if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
  2049. return;
  2050. unsigned NumTableEntries = 0;
  2051. // Create and write out the blob that contains selectors and the method pool.
  2052. {
  2053. OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
  2054. ASTMethodPoolTrait Trait(*this);
  2055. // Create the on-disk hash table representation. We walk through every
  2056. // selector we've seen and look it up in the method pool.
  2057. SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
  2058. for (llvm::DenseMap<Selector, SelectorID>::iterator
  2059. I = SelectorIDs.begin(), E = SelectorIDs.end();
  2060. I != E; ++I) {
  2061. Selector S = I->first;
  2062. Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
  2063. ASTMethodPoolTrait::data_type Data = {
  2064. I->second,
  2065. ObjCMethodList(),
  2066. ObjCMethodList()
  2067. };
  2068. if (F != SemaRef.MethodPool.end()) {
  2069. Data.Instance = F->second.first;
  2070. Data.Factory = F->second.second;
  2071. }
  2072. // Only write this selector if it's not in an existing AST or something
  2073. // changed.
  2074. if (Chain && I->second < FirstSelectorID) {
  2075. // Selector already exists. Did it change?
  2076. bool changed = false;
  2077. for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
  2078. M = M->Next) {
  2079. if (!M->Method->isFromASTFile())
  2080. changed = true;
  2081. }
  2082. for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
  2083. M = M->Next) {
  2084. if (!M->Method->isFromASTFile())
  2085. changed = true;
  2086. }
  2087. if (!changed)
  2088. continue;
  2089. } else if (Data.Instance.Method || Data.Factory.Method) {
  2090. // A new method pool entry.
  2091. ++NumTableEntries;
  2092. }
  2093. Generator.insert(S, Data, Trait);
  2094. }
  2095. // Create the on-disk hash table in a buffer.
  2096. SmallString<4096> MethodPool;
  2097. uint32_t BucketOffset;
  2098. {
  2099. ASTMethodPoolTrait Trait(*this);
  2100. llvm::raw_svector_ostream Out(MethodPool);
  2101. // Make sure that no bucket is at offset 0
  2102. clang::io::Emit32(Out, 0);
  2103. BucketOffset = Generator.Emit(Out, Trait);
  2104. }
  2105. // Create a blob abbreviation
  2106. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2107. Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
  2108. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2109. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2110. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2111. unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
  2112. // Write the method pool
  2113. RecordData Record;
  2114. Record.push_back(METHOD_POOL);
  2115. Record.push_back(BucketOffset);
  2116. Record.push_back(NumTableEntries);
  2117. Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
  2118. // Create a blob abbreviation for the selector table offsets.
  2119. Abbrev = new BitCodeAbbrev();
  2120. Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
  2121. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  2122. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2123. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2124. unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2125. // Write the selector offsets table.
  2126. Record.clear();
  2127. Record.push_back(SELECTOR_OFFSETS);
  2128. Record.push_back(SelectorOffsets.size());
  2129. Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
  2130. Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
  2131. data(SelectorOffsets));
  2132. }
  2133. }
  2134. /// \brief Write the selectors referenced in @selector expression into AST file.
  2135. void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
  2136. using namespace llvm;
  2137. if (SemaRef.ReferencedSelectors.empty())
  2138. return;
  2139. RecordData Record;
  2140. // Note: this writes out all references even for a dependent AST. But it is
  2141. // very tricky to fix, and given that @selector shouldn't really appear in
  2142. // headers, probably not worth it. It's not a correctness issue.
  2143. for (DenseMap<Selector, SourceLocation>::iterator S =
  2144. SemaRef.ReferencedSelectors.begin(),
  2145. E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
  2146. Selector Sel = (*S).first;
  2147. SourceLocation Loc = (*S).second;
  2148. AddSelectorRef(Sel, Record);
  2149. AddSourceLocation(Loc, Record);
  2150. }
  2151. Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
  2152. }
  2153. //===----------------------------------------------------------------------===//
  2154. // Identifier Table Serialization
  2155. //===----------------------------------------------------------------------===//
  2156. namespace {
  2157. class ASTIdentifierTableTrait {
  2158. ASTWriter &Writer;
  2159. Preprocessor &PP;
  2160. IdentifierResolver &IdResolver;
  2161. bool IsModule;
  2162. /// \brief Determines whether this is an "interesting" identifier
  2163. /// that needs a full IdentifierInfo structure written into the hash
  2164. /// table.
  2165. bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) {
  2166. if (II->isPoisoned() ||
  2167. II->isExtensionToken() ||
  2168. II->getObjCOrBuiltinID() ||
  2169. II->hasRevertedTokenIDToIdentifier() ||
  2170. II->getFETokenInfo<void>())
  2171. return true;
  2172. return hasMacroDefinition(II, Macro);
  2173. }
  2174. bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) {
  2175. if (!II->hasMacroDefinition())
  2176. return false;
  2177. if (Macro || (Macro = PP.getMacroInfo(II)))
  2178. return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
  2179. return false;
  2180. }
  2181. public:
  2182. typedef IdentifierInfo* key_type;
  2183. typedef key_type key_type_ref;
  2184. typedef IdentID data_type;
  2185. typedef data_type data_type_ref;
  2186. ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
  2187. IdentifierResolver &IdResolver, bool IsModule)
  2188. : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
  2189. static unsigned ComputeHash(const IdentifierInfo* II) {
  2190. return llvm::HashString(II->getName());
  2191. }
  2192. std::pair<unsigned,unsigned>
  2193. EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
  2194. unsigned KeyLen = II->getLength() + 1;
  2195. unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
  2196. MacroInfo *Macro = 0;
  2197. if (isInterestingIdentifier(II, Macro)) {
  2198. DataLen += 2; // 2 bytes for builtin ID, flags
  2199. if (hasMacroDefinition(II, Macro))
  2200. DataLen += 8;
  2201. for (IdentifierResolver::iterator D = IdResolver.begin(II),
  2202. DEnd = IdResolver.end();
  2203. D != DEnd; ++D)
  2204. DataLen += sizeof(DeclID);
  2205. }
  2206. clang::io::Emit16(Out, DataLen);
  2207. // We emit the key length after the data length so that every
  2208. // string is preceded by a 16-bit length. This matches the PTH
  2209. // format for storing identifiers.
  2210. clang::io::Emit16(Out, KeyLen);
  2211. return std::make_pair(KeyLen, DataLen);
  2212. }
  2213. void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
  2214. unsigned KeyLen) {
  2215. // Record the location of the key data. This is used when generating
  2216. // the mapping from persistent IDs to strings.
  2217. Writer.SetIdentifierOffset(II, Out.tell());
  2218. Out.write(II->getNameStart(), KeyLen);
  2219. }
  2220. void EmitData(raw_ostream& Out, IdentifierInfo* II,
  2221. IdentID ID, unsigned) {
  2222. MacroInfo *Macro = 0;
  2223. if (!isInterestingIdentifier(II, Macro)) {
  2224. clang::io::Emit32(Out, ID << 1);
  2225. return;
  2226. }
  2227. clang::io::Emit32(Out, (ID << 1) | 0x01);
  2228. uint32_t Bits = 0;
  2229. bool HasMacroDefinition = hasMacroDefinition(II, Macro);
  2230. Bits = (uint32_t)II->getObjCOrBuiltinID();
  2231. assert((Bits & 0x7ff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
  2232. Bits = (Bits << 1) | unsigned(HasMacroDefinition);
  2233. Bits = (Bits << 1) | unsigned(II->isExtensionToken());
  2234. Bits = (Bits << 1) | unsigned(II->isPoisoned());
  2235. Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
  2236. Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
  2237. clang::io::Emit16(Out, Bits);
  2238. if (HasMacroDefinition) {
  2239. clang::io::Emit32(Out, Writer.getMacroOffset(II));
  2240. clang::io::Emit32(Out,
  2241. Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc()));
  2242. }
  2243. // Emit the declaration IDs in reverse order, because the
  2244. // IdentifierResolver provides the declarations as they would be
  2245. // visible (e.g., the function "stat" would come before the struct
  2246. // "stat"), but the ASTReader adds declarations to the end of the list
  2247. // (so we need to see the struct "status" before the function "status").
  2248. // Only emit declarations that aren't from a chained PCH, though.
  2249. SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
  2250. IdResolver.end());
  2251. for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
  2252. DEnd = Decls.rend();
  2253. D != DEnd; ++D)
  2254. clang::io::Emit32(Out, Writer.getDeclID(*D));
  2255. }
  2256. };
  2257. } // end anonymous namespace
  2258. /// \brief Write the identifier table into the AST file.
  2259. ///
  2260. /// The identifier table consists of a blob containing string data
  2261. /// (the actual identifiers themselves) and a separate "offsets" index
  2262. /// that maps identifier IDs to locations within the blob.
  2263. void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
  2264. IdentifierResolver &IdResolver,
  2265. bool IsModule) {
  2266. using namespace llvm;
  2267. // Create and write out the blob that contains the identifier
  2268. // strings.
  2269. {
  2270. OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
  2271. ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
  2272. // Look for any identifiers that were named while processing the
  2273. // headers, but are otherwise not needed. We add these to the hash
  2274. // table to enable checking of the predefines buffer in the case
  2275. // where the user adds new macro definitions when building the AST
  2276. // file.
  2277. for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
  2278. IDEnd = PP.getIdentifierTable().end();
  2279. ID != IDEnd; ++ID)
  2280. getIdentifierRef(ID->second);
  2281. // Create the on-disk hash table representation. We only store offsets
  2282. // for identifiers that appear here for the first time.
  2283. IdentifierOffsets.resize(NextIdentID - FirstIdentID);
  2284. for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
  2285. ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
  2286. ID != IDEnd; ++ID) {
  2287. assert(ID->first && "NULL identifier in identifier table");
  2288. if (!Chain || !ID->first->isFromAST() ||
  2289. ID->first->hasChangedSinceDeserialization())
  2290. Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
  2291. Trait);
  2292. }
  2293. // Create the on-disk hash table in a buffer.
  2294. SmallString<4096> IdentifierTable;
  2295. uint32_t BucketOffset;
  2296. {
  2297. ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
  2298. llvm::raw_svector_ostream Out(IdentifierTable);
  2299. // Make sure that no bucket is at offset 0
  2300. clang::io::Emit32(Out, 0);
  2301. BucketOffset = Generator.Emit(Out, Trait);
  2302. }
  2303. // Create a blob abbreviation
  2304. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2305. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
  2306. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2307. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2308. unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
  2309. // Write the identifier table
  2310. RecordData Record;
  2311. Record.push_back(IDENTIFIER_TABLE);
  2312. Record.push_back(BucketOffset);
  2313. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
  2314. }
  2315. // Write the offsets table for identifier IDs.
  2316. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2317. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
  2318. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
  2319. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2320. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2321. unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2322. RecordData Record;
  2323. Record.push_back(IDENTIFIER_OFFSET);
  2324. Record.push_back(IdentifierOffsets.size());
  2325. Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
  2326. Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
  2327. data(IdentifierOffsets));
  2328. }
  2329. //===----------------------------------------------------------------------===//
  2330. // DeclContext's Name Lookup Table Serialization
  2331. //===----------------------------------------------------------------------===//
  2332. namespace {
  2333. // Trait used for the on-disk hash table used in the method pool.
  2334. class ASTDeclContextNameLookupTrait {
  2335. ASTWriter &Writer;
  2336. public:
  2337. typedef DeclarationName key_type;
  2338. typedef key_type key_type_ref;
  2339. typedef DeclContext::lookup_result data_type;
  2340. typedef const data_type& data_type_ref;
  2341. explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
  2342. unsigned ComputeHash(DeclarationName Name) {
  2343. llvm::FoldingSetNodeID ID;
  2344. ID.AddInteger(Name.getNameKind());
  2345. switch (Name.getNameKind()) {
  2346. case DeclarationName::Identifier:
  2347. ID.AddString(Name.getAsIdentifierInfo()->getName());
  2348. break;
  2349. case DeclarationName::ObjCZeroArgSelector:
  2350. case DeclarationName::ObjCOneArgSelector:
  2351. case DeclarationName::ObjCMultiArgSelector:
  2352. ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
  2353. break;
  2354. case DeclarationName::CXXConstructorName:
  2355. case DeclarationName::CXXDestructorName:
  2356. case DeclarationName::CXXConversionFunctionName:
  2357. break;
  2358. case DeclarationName::CXXOperatorName:
  2359. ID.AddInteger(Name.getCXXOverloadedOperator());
  2360. break;
  2361. case DeclarationName::CXXLiteralOperatorName:
  2362. ID.AddString(Name.getCXXLiteralIdentifier()->getName());
  2363. case DeclarationName::CXXUsingDirective:
  2364. break;
  2365. }
  2366. return ID.ComputeHash();
  2367. }
  2368. std::pair<unsigned,unsigned>
  2369. EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
  2370. data_type_ref Lookup) {
  2371. unsigned KeyLen = 1;
  2372. switch (Name.getNameKind()) {
  2373. case DeclarationName::Identifier:
  2374. case DeclarationName::ObjCZeroArgSelector:
  2375. case DeclarationName::ObjCOneArgSelector:
  2376. case DeclarationName::ObjCMultiArgSelector:
  2377. case DeclarationName::CXXLiteralOperatorName:
  2378. KeyLen += 4;
  2379. break;
  2380. case DeclarationName::CXXOperatorName:
  2381. KeyLen += 1;
  2382. break;
  2383. case DeclarationName::CXXConstructorName:
  2384. case DeclarationName::CXXDestructorName:
  2385. case DeclarationName::CXXConversionFunctionName:
  2386. case DeclarationName::CXXUsingDirective:
  2387. break;
  2388. }
  2389. clang::io::Emit16(Out, KeyLen);
  2390. // 2 bytes for num of decls and 4 for each DeclID.
  2391. unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
  2392. clang::io::Emit16(Out, DataLen);
  2393. return std::make_pair(KeyLen, DataLen);
  2394. }
  2395. void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
  2396. using namespace clang::io;
  2397. assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
  2398. Emit8(Out, Name.getNameKind());
  2399. switch (Name.getNameKind()) {
  2400. case DeclarationName::Identifier:
  2401. Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
  2402. break;
  2403. case DeclarationName::ObjCZeroArgSelector:
  2404. case DeclarationName::ObjCOneArgSelector:
  2405. case DeclarationName::ObjCMultiArgSelector:
  2406. Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
  2407. break;
  2408. case DeclarationName::CXXOperatorName:
  2409. assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
  2410. Emit8(Out, Name.getCXXOverloadedOperator());
  2411. break;
  2412. case DeclarationName::CXXLiteralOperatorName:
  2413. Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
  2414. break;
  2415. case DeclarationName::CXXConstructorName:
  2416. case DeclarationName::CXXDestructorName:
  2417. case DeclarationName::CXXConversionFunctionName:
  2418. case DeclarationName::CXXUsingDirective:
  2419. break;
  2420. }
  2421. }
  2422. void EmitData(raw_ostream& Out, key_type_ref,
  2423. data_type Lookup, unsigned DataLen) {
  2424. uint64_t Start = Out.tell(); (void)Start;
  2425. clang::io::Emit16(Out, Lookup.second - Lookup.first);
  2426. for (; Lookup.first != Lookup.second; ++Lookup.first)
  2427. clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
  2428. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  2429. }
  2430. };
  2431. } // end anonymous namespace
  2432. /// \brief Write the block containing all of the declaration IDs
  2433. /// visible from the given DeclContext.
  2434. ///
  2435. /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
  2436. /// bitstream, or 0 if no block was written.
  2437. uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
  2438. DeclContext *DC) {
  2439. if (DC->getPrimaryContext() != DC)
  2440. return 0;
  2441. // Since there is no name lookup into functions or methods, don't bother to
  2442. // build a visible-declarations table for these entities.
  2443. if (DC->isFunctionOrMethod())
  2444. return 0;
  2445. // If not in C++, we perform name lookup for the translation unit via the
  2446. // IdentifierInfo chains, don't bother to build a visible-declarations table.
  2447. // FIXME: In C++ we need the visible declarations in order to "see" the
  2448. // friend declarations, is there a way to do this without writing the table ?
  2449. if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
  2450. return 0;
  2451. // Force the DeclContext to build a its name-lookup table.
  2452. if (!DC->hasExternalVisibleStorage())
  2453. DC->lookup(DeclarationName());
  2454. // Serialize the contents of the mapping used for lookup. Note that,
  2455. // although we have two very different code paths, the serialized
  2456. // representation is the same for both cases: a declaration name,
  2457. // followed by a size, followed by references to the visible
  2458. // declarations that have that name.
  2459. uint64_t Offset = Stream.GetCurrentBitNo();
  2460. StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
  2461. if (!Map || Map->empty())
  2462. return 0;
  2463. OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
  2464. ASTDeclContextNameLookupTrait Trait(*this);
  2465. // Create the on-disk hash table representation.
  2466. DeclarationName ConversionName;
  2467. llvm::SmallVector<NamedDecl *, 4> ConversionDecls;
  2468. for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
  2469. D != DEnd; ++D) {
  2470. DeclarationName Name = D->first;
  2471. DeclContext::lookup_result Result = D->second.getLookupResult();
  2472. if (Result.first != Result.second) {
  2473. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  2474. // Hash all conversion function names to the same name. The actual
  2475. // type information in conversion function name is not used in the
  2476. // key (since such type information is not stable across different
  2477. // modules), so the intended effect is to coalesce all of the conversion
  2478. // functions under a single key.
  2479. if (!ConversionName)
  2480. ConversionName = Name;
  2481. ConversionDecls.append(Result.first, Result.second);
  2482. continue;
  2483. }
  2484. Generator.insert(Name, Result, Trait);
  2485. }
  2486. }
  2487. // Add the conversion functions
  2488. if (!ConversionDecls.empty()) {
  2489. Generator.insert(ConversionName,
  2490. DeclContext::lookup_result(ConversionDecls.begin(),
  2491. ConversionDecls.end()),
  2492. Trait);
  2493. }
  2494. // Create the on-disk hash table in a buffer.
  2495. SmallString<4096> LookupTable;
  2496. uint32_t BucketOffset;
  2497. {
  2498. llvm::raw_svector_ostream Out(LookupTable);
  2499. // Make sure that no bucket is at offset 0
  2500. clang::io::Emit32(Out, 0);
  2501. BucketOffset = Generator.Emit(Out, Trait);
  2502. }
  2503. // Write the lookup table
  2504. RecordData Record;
  2505. Record.push_back(DECL_CONTEXT_VISIBLE);
  2506. Record.push_back(BucketOffset);
  2507. Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
  2508. LookupTable.str());
  2509. Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
  2510. ++NumVisibleDeclContexts;
  2511. return Offset;
  2512. }
  2513. /// \brief Write an UPDATE_VISIBLE block for the given context.
  2514. ///
  2515. /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
  2516. /// DeclContext in a dependent AST file. As such, they only exist for the TU
  2517. /// (in C++) and for namespaces.
  2518. void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
  2519. StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
  2520. if (!Map || Map->empty())
  2521. return;
  2522. OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
  2523. ASTDeclContextNameLookupTrait Trait(*this);
  2524. // Create the hash table.
  2525. for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
  2526. D != DEnd; ++D) {
  2527. DeclarationName Name = D->first;
  2528. DeclContext::lookup_result Result = D->second.getLookupResult();
  2529. // For any name that appears in this table, the results are complete, i.e.
  2530. // they overwrite results from previous PCHs. Merging is always a mess.
  2531. if (Result.first != Result.second)
  2532. Generator.insert(Name, Result, Trait);
  2533. }
  2534. // Create the on-disk hash table in a buffer.
  2535. SmallString<4096> LookupTable;
  2536. uint32_t BucketOffset;
  2537. {
  2538. llvm::raw_svector_ostream Out(LookupTable);
  2539. // Make sure that no bucket is at offset 0
  2540. clang::io::Emit32(Out, 0);
  2541. BucketOffset = Generator.Emit(Out, Trait);
  2542. }
  2543. // Write the lookup table
  2544. RecordData Record;
  2545. Record.push_back(UPDATE_VISIBLE);
  2546. Record.push_back(getDeclID(cast<Decl>(DC)));
  2547. Record.push_back(BucketOffset);
  2548. Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
  2549. }
  2550. /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
  2551. void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
  2552. RecordData Record;
  2553. Record.push_back(Opts.fp_contract);
  2554. Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
  2555. }
  2556. /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
  2557. void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
  2558. if (!SemaRef.Context.getLangOptions().OpenCL)
  2559. return;
  2560. const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
  2561. RecordData Record;
  2562. #define OPENCLEXT(nm) Record.push_back(Opts.nm);
  2563. #include "clang/Basic/OpenCLExtensions.def"
  2564. Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
  2565. }
  2566. void ASTWriter::WriteRedeclarations() {
  2567. RecordData LocalRedeclChains;
  2568. SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
  2569. for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
  2570. Decl *First = Redeclarations[I];
  2571. assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
  2572. Decl *MostRecent = First->getMostRecentDecl();
  2573. // If we only have a single declaration, there is no point in storing
  2574. // a redeclaration chain.
  2575. if (First == MostRecent)
  2576. continue;
  2577. unsigned Offset = LocalRedeclChains.size();
  2578. unsigned Size = 0;
  2579. LocalRedeclChains.push_back(0); // Placeholder for the size.
  2580. // Collect the set of local redeclarations of this declaration.
  2581. for (Decl *Prev = MostRecent; Prev != First;
  2582. Prev = Prev->getPreviousDecl()) {
  2583. if (!Prev->isFromASTFile()) {
  2584. AddDeclRef(Prev, LocalRedeclChains);
  2585. ++Size;
  2586. }
  2587. }
  2588. LocalRedeclChains[Offset] = Size;
  2589. // Reverse the set of local redeclarations, so that we store them in
  2590. // order (since we found them in reverse order).
  2591. std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
  2592. // Add the mapping from the first ID to the set of local declarations.
  2593. LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
  2594. LocalRedeclsMap.push_back(Info);
  2595. assert(N == Redeclarations.size() &&
  2596. "Deserialized a declaration we shouldn't have");
  2597. }
  2598. if (LocalRedeclChains.empty())
  2599. return;
  2600. // Sort the local redeclarations map by the first declaration ID,
  2601. // since the reader will be performing binary searches on this information.
  2602. llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
  2603. // Emit the local redeclarations map.
  2604. using namespace llvm;
  2605. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2606. Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
  2607. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  2608. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2609. unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
  2610. RecordData Record;
  2611. Record.push_back(LOCAL_REDECLARATIONS_MAP);
  2612. Record.push_back(LocalRedeclsMap.size());
  2613. Stream.EmitRecordWithBlob(AbbrevID, Record,
  2614. reinterpret_cast<char*>(LocalRedeclsMap.data()),
  2615. LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
  2616. // Emit the redeclaration chains.
  2617. Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
  2618. }
  2619. void ASTWriter::WriteObjCCategories() {
  2620. llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
  2621. RecordData Categories;
  2622. for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
  2623. unsigned Size = 0;
  2624. unsigned StartIndex = Categories.size();
  2625. ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
  2626. // Allocate space for the size.
  2627. Categories.push_back(0);
  2628. // Add the categories.
  2629. for (ObjCCategoryDecl *Cat = Class->getCategoryList();
  2630. Cat; Cat = Cat->getNextClassCategory(), ++Size) {
  2631. assert(getDeclID(Cat) != 0 && "Bogus category");
  2632. AddDeclRef(Cat, Categories);
  2633. }
  2634. // Update the size.
  2635. Categories[StartIndex] = Size;
  2636. // Record this interface -> category map.
  2637. ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
  2638. CategoriesMap.push_back(CatInfo);
  2639. }
  2640. // Sort the categories map by the definition ID, since the reader will be
  2641. // performing binary searches on this information.
  2642. llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
  2643. // Emit the categories map.
  2644. using namespace llvm;
  2645. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2646. Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
  2647. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  2648. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2649. unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
  2650. RecordData Record;
  2651. Record.push_back(OBJC_CATEGORIES_MAP);
  2652. Record.push_back(CategoriesMap.size());
  2653. Stream.EmitRecordWithBlob(AbbrevID, Record,
  2654. reinterpret_cast<char*>(CategoriesMap.data()),
  2655. CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
  2656. // Emit the category lists.
  2657. Stream.EmitRecord(OBJC_CATEGORIES, Categories);
  2658. }
  2659. void ASTWriter::WriteMergedDecls() {
  2660. if (!Chain || Chain->MergedDecls.empty())
  2661. return;
  2662. RecordData Record;
  2663. for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
  2664. IEnd = Chain->MergedDecls.end();
  2665. I != IEnd; ++I) {
  2666. DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
  2667. : getDeclID(I->first);
  2668. assert(CanonID && "Merged declaration not known?");
  2669. Record.push_back(CanonID);
  2670. Record.push_back(I->second.size());
  2671. Record.append(I->second.begin(), I->second.end());
  2672. }
  2673. Stream.EmitRecord(MERGED_DECLARATIONS, Record);
  2674. }
  2675. //===----------------------------------------------------------------------===//
  2676. // General Serialization Routines
  2677. //===----------------------------------------------------------------------===//
  2678. /// \brief Write a record containing the given attributes.
  2679. void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
  2680. Record.push_back(Attrs.size());
  2681. for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
  2682. const Attr * A = *i;
  2683. Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
  2684. AddSourceRange(A->getRange(), Record);
  2685. #include "clang/Serialization/AttrPCHWrite.inc"
  2686. }
  2687. }
  2688. void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
  2689. Record.push_back(Str.size());
  2690. Record.insert(Record.end(), Str.begin(), Str.end());
  2691. }
  2692. void ASTWriter::AddVersionTuple(const VersionTuple &Version,
  2693. RecordDataImpl &Record) {
  2694. Record.push_back(Version.getMajor());
  2695. if (llvm::Optional<unsigned> Minor = Version.getMinor())
  2696. Record.push_back(*Minor + 1);
  2697. else
  2698. Record.push_back(0);
  2699. if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
  2700. Record.push_back(*Subminor + 1);
  2701. else
  2702. Record.push_back(0);
  2703. }
  2704. /// \brief Note that the identifier II occurs at the given offset
  2705. /// within the identifier table.
  2706. void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
  2707. IdentID ID = IdentifierIDs[II];
  2708. // Only store offsets new to this AST file. Other identifier names are looked
  2709. // up earlier in the chain and thus don't need an offset.
  2710. if (ID >= FirstIdentID)
  2711. IdentifierOffsets[ID - FirstIdentID] = Offset;
  2712. }
  2713. /// \brief Note that the selector Sel occurs at the given offset
  2714. /// within the method pool/selector table.
  2715. void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
  2716. unsigned ID = SelectorIDs[Sel];
  2717. assert(ID && "Unknown selector");
  2718. // Don't record offsets for selectors that are also available in a different
  2719. // file.
  2720. if (ID < FirstSelectorID)
  2721. return;
  2722. SelectorOffsets[ID - FirstSelectorID] = Offset;
  2723. }
  2724. ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
  2725. : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
  2726. WritingAST(false),
  2727. FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
  2728. FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
  2729. FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
  2730. FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
  2731. NextSubmoduleID(FirstSubmoduleID),
  2732. FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
  2733. CollectedStmts(&StmtsToEmit),
  2734. NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
  2735. NumVisibleDeclContexts(0),
  2736. NextCXXBaseSpecifiersID(1),
  2737. DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
  2738. DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
  2739. DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
  2740. DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
  2741. DeclTypedefAbbrev(0),
  2742. DeclVarAbbrev(0), DeclFieldAbbrev(0),
  2743. DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
  2744. {
  2745. }
  2746. ASTWriter::~ASTWriter() {
  2747. for (FileDeclIDsTy::iterator
  2748. I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
  2749. delete I->second;
  2750. }
  2751. void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
  2752. const std::string &OutputFile,
  2753. Module *WritingModule, StringRef isysroot) {
  2754. WritingAST = true;
  2755. // Emit the file header.
  2756. Stream.Emit((unsigned)'C', 8);
  2757. Stream.Emit((unsigned)'P', 8);
  2758. Stream.Emit((unsigned)'C', 8);
  2759. Stream.Emit((unsigned)'H', 8);
  2760. WriteBlockInfoBlock();
  2761. Context = &SemaRef.Context;
  2762. PP = &SemaRef.PP;
  2763. this->WritingModule = WritingModule;
  2764. WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule);
  2765. Context = 0;
  2766. PP = 0;
  2767. this->WritingModule = 0;
  2768. WritingAST = false;
  2769. }
  2770. template<typename Vector>
  2771. static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
  2772. ASTWriter::RecordData &Record) {
  2773. for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
  2774. I != E; ++I) {
  2775. Writer.AddDeclRef(*I, Record);
  2776. }
  2777. }
  2778. void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
  2779. StringRef isysroot,
  2780. const std::string &OutputFile,
  2781. Module *WritingModule) {
  2782. using namespace llvm;
  2783. // Make sure that the AST reader knows to finalize itself.
  2784. if (Chain)
  2785. Chain->finalizeForWriting();
  2786. ASTContext &Context = SemaRef.Context;
  2787. Preprocessor &PP = SemaRef.PP;
  2788. // Set up predefined declaration IDs.
  2789. DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
  2790. if (Context.ObjCIdDecl)
  2791. DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
  2792. if (Context.ObjCSelDecl)
  2793. DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
  2794. if (Context.ObjCClassDecl)
  2795. DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
  2796. if (Context.ObjCProtocolClassDecl)
  2797. DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
  2798. if (Context.Int128Decl)
  2799. DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
  2800. if (Context.UInt128Decl)
  2801. DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
  2802. if (Context.ObjCInstanceTypeDecl)
  2803. DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
  2804. if (!Chain) {
  2805. // Make sure that we emit IdentifierInfos (and any attached
  2806. // declarations) for builtins. We don't need to do this when we're
  2807. // emitting chained PCH files, because all of the builtins will be
  2808. // in the original PCH file.
  2809. // FIXME: Modules won't like this at all.
  2810. IdentifierTable &Table = PP.getIdentifierTable();
  2811. SmallVector<const char *, 32> BuiltinNames;
  2812. Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
  2813. Context.getLangOptions().NoBuiltin);
  2814. for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
  2815. getIdentifierRef(&Table.get(BuiltinNames[I]));
  2816. }
  2817. // If there are any out-of-date identifiers, bring them up to date.
  2818. if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
  2819. for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
  2820. IDEnd = PP.getIdentifierTable().end();
  2821. ID != IDEnd; ++ID)
  2822. if (ID->second->isOutOfDate())
  2823. ExtSource->updateOutOfDateIdentifier(*ID->second);
  2824. }
  2825. // Build a record containing all of the tentative definitions in this file, in
  2826. // TentativeDefinitions order. Generally, this record will be empty for
  2827. // headers.
  2828. RecordData TentativeDefinitions;
  2829. AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
  2830. // Build a record containing all of the file scoped decls in this file.
  2831. RecordData UnusedFileScopedDecls;
  2832. AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
  2833. UnusedFileScopedDecls);
  2834. // Build a record containing all of the delegating constructors we still need
  2835. // to resolve.
  2836. RecordData DelegatingCtorDecls;
  2837. AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
  2838. // Write the set of weak, undeclared identifiers. We always write the
  2839. // entire table, since later PCH files in a PCH chain are only interested in
  2840. // the results at the end of the chain.
  2841. RecordData WeakUndeclaredIdentifiers;
  2842. if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
  2843. for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
  2844. I = SemaRef.WeakUndeclaredIdentifiers.begin(),
  2845. E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
  2846. AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
  2847. AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
  2848. AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
  2849. WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
  2850. }
  2851. }
  2852. // Build a record containing all of the locally-scoped external
  2853. // declarations in this header file. Generally, this record will be
  2854. // empty.
  2855. RecordData LocallyScopedExternalDecls;
  2856. // FIXME: This is filling in the AST file in densemap order which is
  2857. // nondeterminstic!
  2858. for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  2859. TD = SemaRef.LocallyScopedExternalDecls.begin(),
  2860. TDEnd = SemaRef.LocallyScopedExternalDecls.end();
  2861. TD != TDEnd; ++TD) {
  2862. if (!TD->second->isFromASTFile())
  2863. AddDeclRef(TD->second, LocallyScopedExternalDecls);
  2864. }
  2865. // Build a record containing all of the ext_vector declarations.
  2866. RecordData ExtVectorDecls;
  2867. AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
  2868. // Build a record containing all of the VTable uses information.
  2869. RecordData VTableUses;
  2870. if (!SemaRef.VTableUses.empty()) {
  2871. for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
  2872. AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
  2873. AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
  2874. VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
  2875. }
  2876. }
  2877. // Build a record containing all of dynamic classes declarations.
  2878. RecordData DynamicClasses;
  2879. AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
  2880. // Build a record containing all of pending implicit instantiations.
  2881. RecordData PendingInstantiations;
  2882. for (std::deque<Sema::PendingImplicitInstantiation>::iterator
  2883. I = SemaRef.PendingInstantiations.begin(),
  2884. N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
  2885. AddDeclRef(I->first, PendingInstantiations);
  2886. AddSourceLocation(I->second, PendingInstantiations);
  2887. }
  2888. assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
  2889. "There are local ones at end of translation unit!");
  2890. // Build a record containing some declaration references.
  2891. RecordData SemaDeclRefs;
  2892. if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
  2893. AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
  2894. AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
  2895. }
  2896. RecordData CUDASpecialDeclRefs;
  2897. if (Context.getcudaConfigureCallDecl()) {
  2898. AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
  2899. }
  2900. // Build a record containing all of the known namespaces.
  2901. RecordData KnownNamespaces;
  2902. for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
  2903. I = SemaRef.KnownNamespaces.begin(),
  2904. IEnd = SemaRef.KnownNamespaces.end();
  2905. I != IEnd; ++I) {
  2906. if (!I->second)
  2907. AddDeclRef(I->first, KnownNamespaces);
  2908. }
  2909. // Write the remaining AST contents.
  2910. RecordData Record;
  2911. Stream.EnterSubblock(AST_BLOCK_ID, 5);
  2912. WriteMetadata(Context, isysroot, OutputFile);
  2913. WriteLanguageOptions(Context.getLangOptions());
  2914. if (StatCalls && isysroot.empty())
  2915. WriteStatCache(*StatCalls);
  2916. // Create a lexical update block containing all of the declarations in the
  2917. // translation unit that do not come from other AST files.
  2918. const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  2919. SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
  2920. for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
  2921. E = TU->noload_decls_end();
  2922. I != E; ++I) {
  2923. if (!(*I)->isFromASTFile())
  2924. NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
  2925. }
  2926. llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
  2927. Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
  2928. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  2929. unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
  2930. Record.clear();
  2931. Record.push_back(TU_UPDATE_LEXICAL);
  2932. Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
  2933. data(NewGlobalDecls));
  2934. // And a visible updates block for the translation unit.
  2935. Abv = new llvm::BitCodeAbbrev();
  2936. Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
  2937. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  2938. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
  2939. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  2940. UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
  2941. WriteDeclContextVisibleUpdate(TU);
  2942. // If the translation unit has an anonymous namespace, and we don't already
  2943. // have an update block for it, write it as an update block.
  2944. if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
  2945. ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
  2946. if (Record.empty()) {
  2947. Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
  2948. Record.push_back(reinterpret_cast<uint64_t>(NS));
  2949. }
  2950. }
  2951. // Resolve any declaration pointers within the declaration updates block.
  2952. ResolveDeclUpdatesBlocks();
  2953. // Form the record of special types.
  2954. RecordData SpecialTypes;
  2955. AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes);
  2956. AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
  2957. AddTypeRef(Context.getFILEType(), SpecialTypes);
  2958. AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
  2959. AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
  2960. AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
  2961. AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
  2962. AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
  2963. AddTypeRef(Context.getucontext_tType(), SpecialTypes);
  2964. // Keep writing types and declarations until all types and
  2965. // declarations have been written.
  2966. Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
  2967. WriteDeclsBlockAbbrevs();
  2968. for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
  2969. E = DeclsToRewrite.end();
  2970. I != E; ++I)
  2971. DeclTypesToEmit.push(const_cast<Decl*>(*I));
  2972. while (!DeclTypesToEmit.empty()) {
  2973. DeclOrType DOT = DeclTypesToEmit.front();
  2974. DeclTypesToEmit.pop();
  2975. if (DOT.isType())
  2976. WriteType(DOT.getType());
  2977. else
  2978. WriteDecl(Context, DOT.getDecl());
  2979. }
  2980. Stream.ExitBlock();
  2981. WriteFileDeclIDsMap();
  2982. WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
  2983. if (Chain) {
  2984. // Write the mapping information describing our module dependencies and how
  2985. // each of those modules were mapped into our own offset/ID space, so that
  2986. // the reader can build the appropriate mapping to its own offset/ID space.
  2987. // The map consists solely of a blob with the following format:
  2988. // *(module-name-len:i16 module-name:len*i8
  2989. // source-location-offset:i32
  2990. // identifier-id:i32
  2991. // preprocessed-entity-id:i32
  2992. // macro-definition-id:i32
  2993. // submodule-id:i32
  2994. // selector-id:i32
  2995. // declaration-id:i32
  2996. // c++-base-specifiers-id:i32
  2997. // type-id:i32)
  2998. //
  2999. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  3000. Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
  3001. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3002. unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
  3003. SmallString<2048> Buffer;
  3004. {
  3005. llvm::raw_svector_ostream Out(Buffer);
  3006. for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
  3007. MEnd = Chain->ModuleMgr.end();
  3008. M != MEnd; ++M) {
  3009. StringRef FileName = (*M)->FileName;
  3010. io::Emit16(Out, FileName.size());
  3011. Out.write(FileName.data(), FileName.size());
  3012. io::Emit32(Out, (*M)->SLocEntryBaseOffset);
  3013. io::Emit32(Out, (*M)->BaseIdentifierID);
  3014. io::Emit32(Out, (*M)->BasePreprocessedEntityID);
  3015. io::Emit32(Out, (*M)->BaseSubmoduleID);
  3016. io::Emit32(Out, (*M)->BaseSelectorID);
  3017. io::Emit32(Out, (*M)->BaseDeclID);
  3018. io::Emit32(Out, (*M)->BaseTypeIndex);
  3019. }
  3020. }
  3021. Record.clear();
  3022. Record.push_back(MODULE_OFFSET_MAP);
  3023. Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
  3024. Buffer.data(), Buffer.size());
  3025. }
  3026. WritePreprocessor(PP, WritingModule != 0);
  3027. WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
  3028. WriteSelectors(SemaRef);
  3029. WriteReferencedSelectorsPool(SemaRef);
  3030. WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0);
  3031. WriteFPPragmaOptions(SemaRef.getFPOptions());
  3032. WriteOpenCLExtensions(SemaRef);
  3033. WriteTypeDeclOffsets();
  3034. WritePragmaDiagnosticMappings(Context.getDiagnostics());
  3035. WriteCXXBaseSpecifiersOffsets();
  3036. // If we're emitting a module, write out the submodule information.
  3037. if (WritingModule)
  3038. WriteSubmodules(WritingModule);
  3039. Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
  3040. // Write the record containing external, unnamed definitions.
  3041. if (!ExternalDefinitions.empty())
  3042. Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
  3043. // Write the record containing tentative definitions.
  3044. if (!TentativeDefinitions.empty())
  3045. Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
  3046. // Write the record containing unused file scoped decls.
  3047. if (!UnusedFileScopedDecls.empty())
  3048. Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
  3049. // Write the record containing weak undeclared identifiers.
  3050. if (!WeakUndeclaredIdentifiers.empty())
  3051. Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
  3052. WeakUndeclaredIdentifiers);
  3053. // Write the record containing locally-scoped external definitions.
  3054. if (!LocallyScopedExternalDecls.empty())
  3055. Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
  3056. LocallyScopedExternalDecls);
  3057. // Write the record containing ext_vector type names.
  3058. if (!ExtVectorDecls.empty())
  3059. Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
  3060. // Write the record containing VTable uses information.
  3061. if (!VTableUses.empty())
  3062. Stream.EmitRecord(VTABLE_USES, VTableUses);
  3063. // Write the record containing dynamic classes declarations.
  3064. if (!DynamicClasses.empty())
  3065. Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
  3066. // Write the record containing pending implicit instantiations.
  3067. if (!PendingInstantiations.empty())
  3068. Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
  3069. // Write the record containing declaration references of Sema.
  3070. if (!SemaDeclRefs.empty())
  3071. Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
  3072. // Write the record containing CUDA-specific declaration references.
  3073. if (!CUDASpecialDeclRefs.empty())
  3074. Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
  3075. // Write the delegating constructors.
  3076. if (!DelegatingCtorDecls.empty())
  3077. Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
  3078. // Write the known namespaces.
  3079. if (!KnownNamespaces.empty())
  3080. Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
  3081. // Write the visible updates to DeclContexts.
  3082. for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
  3083. I = UpdatedDeclContexts.begin(),
  3084. E = UpdatedDeclContexts.end();
  3085. I != E; ++I)
  3086. WriteDeclContextVisibleUpdate(*I);
  3087. if (!WritingModule) {
  3088. // Write the submodules that were imported, if any.
  3089. RecordData ImportedModules;
  3090. for (ASTContext::import_iterator I = Context.local_import_begin(),
  3091. IEnd = Context.local_import_end();
  3092. I != IEnd; ++I) {
  3093. assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
  3094. ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
  3095. }
  3096. if (!ImportedModules.empty()) {
  3097. // Sort module IDs.
  3098. llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
  3099. // Unique module IDs.
  3100. ImportedModules.erase(std::unique(ImportedModules.begin(),
  3101. ImportedModules.end()),
  3102. ImportedModules.end());
  3103. Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
  3104. }
  3105. }
  3106. WriteDeclUpdatesBlocks();
  3107. WriteDeclReplacementsBlock();
  3108. WriteMergedDecls();
  3109. WriteRedeclarations();
  3110. WriteObjCCategories();
  3111. // Some simple statistics
  3112. Record.clear();
  3113. Record.push_back(NumStatements);
  3114. Record.push_back(NumMacros);
  3115. Record.push_back(NumLexicalDeclContexts);
  3116. Record.push_back(NumVisibleDeclContexts);
  3117. Stream.EmitRecord(STATISTICS, Record);
  3118. Stream.ExitBlock();
  3119. }
  3120. /// \brief Go through the declaration update blocks and resolve declaration
  3121. /// pointers into declaration IDs.
  3122. void ASTWriter::ResolveDeclUpdatesBlocks() {
  3123. for (DeclUpdateMap::iterator
  3124. I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
  3125. const Decl *D = I->first;
  3126. UpdateRecord &URec = I->second;
  3127. if (isRewritten(D))
  3128. continue; // The decl will be written completely
  3129. unsigned Idx = 0, N = URec.size();
  3130. while (Idx < N) {
  3131. switch ((DeclUpdateKind)URec[Idx++]) {
  3132. case UPD_CXX_ADDED_IMPLICIT_MEMBER:
  3133. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  3134. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
  3135. URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
  3136. ++Idx;
  3137. break;
  3138. case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
  3139. ++Idx;
  3140. break;
  3141. }
  3142. }
  3143. }
  3144. }
  3145. void ASTWriter::WriteDeclUpdatesBlocks() {
  3146. if (DeclUpdates.empty())
  3147. return;
  3148. RecordData OffsetsRecord;
  3149. Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
  3150. for (DeclUpdateMap::iterator
  3151. I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
  3152. const Decl *D = I->first;
  3153. UpdateRecord &URec = I->second;
  3154. if (isRewritten(D))
  3155. continue; // The decl will be written completely,no need to store updates.
  3156. uint64_t Offset = Stream.GetCurrentBitNo();
  3157. Stream.EmitRecord(DECL_UPDATES, URec);
  3158. OffsetsRecord.push_back(GetDeclRef(D));
  3159. OffsetsRecord.push_back(Offset);
  3160. }
  3161. Stream.ExitBlock();
  3162. Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
  3163. }
  3164. void ASTWriter::WriteDeclReplacementsBlock() {
  3165. if (ReplacedDecls.empty())
  3166. return;
  3167. RecordData Record;
  3168. for (SmallVector<ReplacedDeclInfo, 16>::iterator
  3169. I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
  3170. Record.push_back(I->ID);
  3171. Record.push_back(I->Offset);
  3172. Record.push_back(I->Loc);
  3173. }
  3174. Stream.EmitRecord(DECL_REPLACEMENTS, Record);
  3175. }
  3176. void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
  3177. Record.push_back(Loc.getRawEncoding());
  3178. }
  3179. void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
  3180. AddSourceLocation(Range.getBegin(), Record);
  3181. AddSourceLocation(Range.getEnd(), Record);
  3182. }
  3183. void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
  3184. Record.push_back(Value.getBitWidth());
  3185. const uint64_t *Words = Value.getRawData();
  3186. Record.append(Words, Words + Value.getNumWords());
  3187. }
  3188. void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
  3189. Record.push_back(Value.isUnsigned());
  3190. AddAPInt(Value, Record);
  3191. }
  3192. void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
  3193. AddAPInt(Value.bitcastToAPInt(), Record);
  3194. }
  3195. void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
  3196. Record.push_back(getIdentifierRef(II));
  3197. }
  3198. IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
  3199. if (II == 0)
  3200. return 0;
  3201. IdentID &ID = IdentifierIDs[II];
  3202. if (ID == 0)
  3203. ID = NextIdentID++;
  3204. return ID;
  3205. }
  3206. void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
  3207. Record.push_back(getSelectorRef(SelRef));
  3208. }
  3209. SelectorID ASTWriter::getSelectorRef(Selector Sel) {
  3210. if (Sel.getAsOpaquePtr() == 0) {
  3211. return 0;
  3212. }
  3213. SelectorID &SID = SelectorIDs[Sel];
  3214. if (SID == 0 && Chain) {
  3215. // This might trigger a ReadSelector callback, which will set the ID for
  3216. // this selector.
  3217. Chain->LoadSelector(Sel);
  3218. }
  3219. if (SID == 0) {
  3220. SID = NextSelectorID++;
  3221. }
  3222. return SID;
  3223. }
  3224. void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
  3225. AddDeclRef(Temp->getDestructor(), Record);
  3226. }
  3227. void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
  3228. CXXBaseSpecifier const *BasesEnd,
  3229. RecordDataImpl &Record) {
  3230. assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
  3231. CXXBaseSpecifiersToWrite.push_back(
  3232. QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
  3233. Bases, BasesEnd));
  3234. Record.push_back(NextCXXBaseSpecifiersID++);
  3235. }
  3236. void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
  3237. const TemplateArgumentLocInfo &Arg,
  3238. RecordDataImpl &Record) {
  3239. switch (Kind) {
  3240. case TemplateArgument::Expression:
  3241. AddStmt(Arg.getAsExpr());
  3242. break;
  3243. case TemplateArgument::Type:
  3244. AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
  3245. break;
  3246. case TemplateArgument::Template:
  3247. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
  3248. AddSourceLocation(Arg.getTemplateNameLoc(), Record);
  3249. break;
  3250. case TemplateArgument::TemplateExpansion:
  3251. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
  3252. AddSourceLocation(Arg.getTemplateNameLoc(), Record);
  3253. AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
  3254. break;
  3255. case TemplateArgument::Null:
  3256. case TemplateArgument::Integral:
  3257. case TemplateArgument::Declaration:
  3258. case TemplateArgument::Pack:
  3259. break;
  3260. }
  3261. }
  3262. void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
  3263. RecordDataImpl &Record) {
  3264. AddTemplateArgument(Arg.getArgument(), Record);
  3265. if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
  3266. bool InfoHasSameExpr
  3267. = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
  3268. Record.push_back(InfoHasSameExpr);
  3269. if (InfoHasSameExpr)
  3270. return; // Avoid storing the same expr twice.
  3271. }
  3272. AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
  3273. Record);
  3274. }
  3275. void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
  3276. RecordDataImpl &Record) {
  3277. if (TInfo == 0) {
  3278. AddTypeRef(QualType(), Record);
  3279. return;
  3280. }
  3281. AddTypeLoc(TInfo->getTypeLoc(), Record);
  3282. }
  3283. void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
  3284. AddTypeRef(TL.getType(), Record);
  3285. TypeLocWriter TLW(*this, Record);
  3286. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  3287. TLW.Visit(TL);
  3288. }
  3289. void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
  3290. Record.push_back(GetOrCreateTypeID(T));
  3291. }
  3292. TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
  3293. return MakeTypeID(*Context, T,
  3294. std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
  3295. }
  3296. TypeID ASTWriter::getTypeID(QualType T) const {
  3297. return MakeTypeID(*Context, T,
  3298. std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
  3299. }
  3300. TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
  3301. if (T.isNull())
  3302. return TypeIdx();
  3303. assert(!T.getLocalFastQualifiers());
  3304. TypeIdx &Idx = TypeIdxs[T];
  3305. if (Idx.getIndex() == 0) {
  3306. // We haven't seen this type before. Assign it a new ID and put it
  3307. // into the queue of types to emit.
  3308. Idx = TypeIdx(NextTypeID++);
  3309. DeclTypesToEmit.push(T);
  3310. }
  3311. return Idx;
  3312. }
  3313. TypeIdx ASTWriter::getTypeIdx(QualType T) const {
  3314. if (T.isNull())
  3315. return TypeIdx();
  3316. assert(!T.getLocalFastQualifiers());
  3317. TypeIdxMap::const_iterator I = TypeIdxs.find(T);
  3318. assert(I != TypeIdxs.end() && "Type not emitted!");
  3319. return I->second;
  3320. }
  3321. void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
  3322. Record.push_back(GetDeclRef(D));
  3323. }
  3324. DeclID ASTWriter::GetDeclRef(const Decl *D) {
  3325. assert(WritingAST && "Cannot request a declaration ID before AST writing");
  3326. if (D == 0) {
  3327. return 0;
  3328. }
  3329. // If D comes from an AST file, its declaration ID is already known and
  3330. // fixed.
  3331. if (D->isFromASTFile())
  3332. return D->getGlobalID();
  3333. assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
  3334. DeclID &ID = DeclIDs[D];
  3335. if (ID == 0) {
  3336. // We haven't seen this declaration before. Give it a new ID and
  3337. // enqueue it in the list of declarations to emit.
  3338. ID = NextDeclID++;
  3339. DeclTypesToEmit.push(const_cast<Decl *>(D));
  3340. }
  3341. return ID;
  3342. }
  3343. DeclID ASTWriter::getDeclID(const Decl *D) {
  3344. if (D == 0)
  3345. return 0;
  3346. // If D comes from an AST file, its declaration ID is already known and
  3347. // fixed.
  3348. if (D->isFromASTFile())
  3349. return D->getGlobalID();
  3350. assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
  3351. return DeclIDs[D];
  3352. }
  3353. static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
  3354. std::pair<unsigned, serialization::DeclID> R) {
  3355. return L.first < R.first;
  3356. }
  3357. void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
  3358. assert(ID);
  3359. assert(D);
  3360. SourceLocation Loc = D->getLocation();
  3361. if (Loc.isInvalid())
  3362. return;
  3363. // We only keep track of the file-level declarations of each file.
  3364. if (!D->getLexicalDeclContext()->isFileContext())
  3365. return;
  3366. SourceManager &SM = Context->getSourceManager();
  3367. SourceLocation FileLoc = SM.getFileLoc(Loc);
  3368. assert(SM.isLocalSourceLocation(FileLoc));
  3369. FileID FID;
  3370. unsigned Offset;
  3371. llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  3372. if (FID.isInvalid())
  3373. return;
  3374. const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID);
  3375. assert(Entry->isFile());
  3376. DeclIDInFileInfo *&Info = FileDeclIDs[Entry];
  3377. if (!Info)
  3378. Info = new DeclIDInFileInfo();
  3379. std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
  3380. LocDeclIDsTy &Decls = Info->DeclIDs;
  3381. if (Decls.empty() || Decls.back().first <= Offset) {
  3382. Decls.push_back(LocDecl);
  3383. return;
  3384. }
  3385. LocDeclIDsTy::iterator
  3386. I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
  3387. Decls.insert(I, LocDecl);
  3388. }
  3389. void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
  3390. // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
  3391. Record.push_back(Name.getNameKind());
  3392. switch (Name.getNameKind()) {
  3393. case DeclarationName::Identifier:
  3394. AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
  3395. break;
  3396. case DeclarationName::ObjCZeroArgSelector:
  3397. case DeclarationName::ObjCOneArgSelector:
  3398. case DeclarationName::ObjCMultiArgSelector:
  3399. AddSelectorRef(Name.getObjCSelector(), Record);
  3400. break;
  3401. case DeclarationName::CXXConstructorName:
  3402. case DeclarationName::CXXDestructorName:
  3403. case DeclarationName::CXXConversionFunctionName:
  3404. AddTypeRef(Name.getCXXNameType(), Record);
  3405. break;
  3406. case DeclarationName::CXXOperatorName:
  3407. Record.push_back(Name.getCXXOverloadedOperator());
  3408. break;
  3409. case DeclarationName::CXXLiteralOperatorName:
  3410. AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
  3411. break;
  3412. case DeclarationName::CXXUsingDirective:
  3413. // No extra data to emit
  3414. break;
  3415. }
  3416. }
  3417. void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
  3418. DeclarationName Name, RecordDataImpl &Record) {
  3419. switch (Name.getNameKind()) {
  3420. case DeclarationName::CXXConstructorName:
  3421. case DeclarationName::CXXDestructorName:
  3422. case DeclarationName::CXXConversionFunctionName:
  3423. AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
  3424. break;
  3425. case DeclarationName::CXXOperatorName:
  3426. AddSourceLocation(
  3427. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
  3428. Record);
  3429. AddSourceLocation(
  3430. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
  3431. Record);
  3432. break;
  3433. case DeclarationName::CXXLiteralOperatorName:
  3434. AddSourceLocation(
  3435. SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
  3436. Record);
  3437. break;
  3438. case DeclarationName::Identifier:
  3439. case DeclarationName::ObjCZeroArgSelector:
  3440. case DeclarationName::ObjCOneArgSelector:
  3441. case DeclarationName::ObjCMultiArgSelector:
  3442. case DeclarationName::CXXUsingDirective:
  3443. break;
  3444. }
  3445. }
  3446. void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  3447. RecordDataImpl &Record) {
  3448. AddDeclarationName(NameInfo.getName(), Record);
  3449. AddSourceLocation(NameInfo.getLoc(), Record);
  3450. AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
  3451. }
  3452. void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
  3453. RecordDataImpl &Record) {
  3454. AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
  3455. Record.push_back(Info.NumTemplParamLists);
  3456. for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
  3457. AddTemplateParameterList(Info.TemplParamLists[i], Record);
  3458. }
  3459. void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
  3460. RecordDataImpl &Record) {
  3461. // Nested name specifiers usually aren't too long. I think that 8 would
  3462. // typically accommodate the vast majority.
  3463. SmallVector<NestedNameSpecifier *, 8> NestedNames;
  3464. // Push each of the NNS's onto a stack for serialization in reverse order.
  3465. while (NNS) {
  3466. NestedNames.push_back(NNS);
  3467. NNS = NNS->getPrefix();
  3468. }
  3469. Record.push_back(NestedNames.size());
  3470. while(!NestedNames.empty()) {
  3471. NNS = NestedNames.pop_back_val();
  3472. NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
  3473. Record.push_back(Kind);
  3474. switch (Kind) {
  3475. case NestedNameSpecifier::Identifier:
  3476. AddIdentifierRef(NNS->getAsIdentifier(), Record);
  3477. break;
  3478. case NestedNameSpecifier::Namespace:
  3479. AddDeclRef(NNS->getAsNamespace(), Record);
  3480. break;
  3481. case NestedNameSpecifier::NamespaceAlias:
  3482. AddDeclRef(NNS->getAsNamespaceAlias(), Record);
  3483. break;
  3484. case NestedNameSpecifier::TypeSpec:
  3485. case NestedNameSpecifier::TypeSpecWithTemplate:
  3486. AddTypeRef(QualType(NNS->getAsType(), 0), Record);
  3487. Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  3488. break;
  3489. case NestedNameSpecifier::Global:
  3490. // Don't need to write an associated value.
  3491. break;
  3492. }
  3493. }
  3494. }
  3495. void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  3496. RecordDataImpl &Record) {
  3497. // Nested name specifiers usually aren't too long. I think that 8 would
  3498. // typically accommodate the vast majority.
  3499. SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
  3500. // Push each of the nested-name-specifiers's onto a stack for
  3501. // serialization in reverse order.
  3502. while (NNS) {
  3503. NestedNames.push_back(NNS);
  3504. NNS = NNS.getPrefix();
  3505. }
  3506. Record.push_back(NestedNames.size());
  3507. while(!NestedNames.empty()) {
  3508. NNS = NestedNames.pop_back_val();
  3509. NestedNameSpecifier::SpecifierKind Kind
  3510. = NNS.getNestedNameSpecifier()->getKind();
  3511. Record.push_back(Kind);
  3512. switch (Kind) {
  3513. case NestedNameSpecifier::Identifier:
  3514. AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
  3515. AddSourceRange(NNS.getLocalSourceRange(), Record);
  3516. break;
  3517. case NestedNameSpecifier::Namespace:
  3518. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
  3519. AddSourceRange(NNS.getLocalSourceRange(), Record);
  3520. break;
  3521. case NestedNameSpecifier::NamespaceAlias:
  3522. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
  3523. AddSourceRange(NNS.getLocalSourceRange(), Record);
  3524. break;
  3525. case NestedNameSpecifier::TypeSpec:
  3526. case NestedNameSpecifier::TypeSpecWithTemplate:
  3527. Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  3528. AddTypeLoc(NNS.getTypeLoc(), Record);
  3529. AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
  3530. break;
  3531. case NestedNameSpecifier::Global:
  3532. AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
  3533. break;
  3534. }
  3535. }
  3536. }
  3537. void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
  3538. TemplateName::NameKind Kind = Name.getKind();
  3539. Record.push_back(Kind);
  3540. switch (Kind) {
  3541. case TemplateName::Template:
  3542. AddDeclRef(Name.getAsTemplateDecl(), Record);
  3543. break;
  3544. case TemplateName::OverloadedTemplate: {
  3545. OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
  3546. Record.push_back(OvT->size());
  3547. for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
  3548. I != E; ++I)
  3549. AddDeclRef(*I, Record);
  3550. break;
  3551. }
  3552. case TemplateName::QualifiedTemplate: {
  3553. QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
  3554. AddNestedNameSpecifier(QualT->getQualifier(), Record);
  3555. Record.push_back(QualT->hasTemplateKeyword());
  3556. AddDeclRef(QualT->getTemplateDecl(), Record);
  3557. break;
  3558. }
  3559. case TemplateName::DependentTemplate: {
  3560. DependentTemplateName *DepT = Name.getAsDependentTemplateName();
  3561. AddNestedNameSpecifier(DepT->getQualifier(), Record);
  3562. Record.push_back(DepT->isIdentifier());
  3563. if (DepT->isIdentifier())
  3564. AddIdentifierRef(DepT->getIdentifier(), Record);
  3565. else
  3566. Record.push_back(DepT->getOperator());
  3567. break;
  3568. }
  3569. case TemplateName::SubstTemplateTemplateParm: {
  3570. SubstTemplateTemplateParmStorage *subst
  3571. = Name.getAsSubstTemplateTemplateParm();
  3572. AddDeclRef(subst->getParameter(), Record);
  3573. AddTemplateName(subst->getReplacement(), Record);
  3574. break;
  3575. }
  3576. case TemplateName::SubstTemplateTemplateParmPack: {
  3577. SubstTemplateTemplateParmPackStorage *SubstPack
  3578. = Name.getAsSubstTemplateTemplateParmPack();
  3579. AddDeclRef(SubstPack->getParameterPack(), Record);
  3580. AddTemplateArgument(SubstPack->getArgumentPack(), Record);
  3581. break;
  3582. }
  3583. }
  3584. }
  3585. void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
  3586. RecordDataImpl &Record) {
  3587. Record.push_back(Arg.getKind());
  3588. switch (Arg.getKind()) {
  3589. case TemplateArgument::Null:
  3590. break;
  3591. case TemplateArgument::Type:
  3592. AddTypeRef(Arg.getAsType(), Record);
  3593. break;
  3594. case TemplateArgument::Declaration:
  3595. AddDeclRef(Arg.getAsDecl(), Record);
  3596. break;
  3597. case TemplateArgument::Integral:
  3598. AddAPSInt(*Arg.getAsIntegral(), Record);
  3599. AddTypeRef(Arg.getIntegralType(), Record);
  3600. break;
  3601. case TemplateArgument::Template:
  3602. AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
  3603. break;
  3604. case TemplateArgument::TemplateExpansion:
  3605. AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
  3606. if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
  3607. Record.push_back(*NumExpansions + 1);
  3608. else
  3609. Record.push_back(0);
  3610. break;
  3611. case TemplateArgument::Expression:
  3612. AddStmt(Arg.getAsExpr());
  3613. break;
  3614. case TemplateArgument::Pack:
  3615. Record.push_back(Arg.pack_size());
  3616. for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
  3617. I != E; ++I)
  3618. AddTemplateArgument(*I, Record);
  3619. break;
  3620. }
  3621. }
  3622. void
  3623. ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
  3624. RecordDataImpl &Record) {
  3625. assert(TemplateParams && "No TemplateParams!");
  3626. AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
  3627. AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
  3628. AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
  3629. Record.push_back(TemplateParams->size());
  3630. for (TemplateParameterList::const_iterator
  3631. P = TemplateParams->begin(), PEnd = TemplateParams->end();
  3632. P != PEnd; ++P)
  3633. AddDeclRef(*P, Record);
  3634. }
  3635. /// \brief Emit a template argument list.
  3636. void
  3637. ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
  3638. RecordDataImpl &Record) {
  3639. assert(TemplateArgs && "No TemplateArgs!");
  3640. Record.push_back(TemplateArgs->size());
  3641. for (int i=0, e = TemplateArgs->size(); i != e; ++i)
  3642. AddTemplateArgument(TemplateArgs->get(i), Record);
  3643. }
  3644. void
  3645. ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
  3646. Record.push_back(Set.size());
  3647. for (UnresolvedSetImpl::const_iterator
  3648. I = Set.begin(), E = Set.end(); I != E; ++I) {
  3649. AddDeclRef(I.getDecl(), Record);
  3650. Record.push_back(I.getAccess());
  3651. }
  3652. }
  3653. void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
  3654. RecordDataImpl &Record) {
  3655. Record.push_back(Base.isVirtual());
  3656. Record.push_back(Base.isBaseOfClass());
  3657. Record.push_back(Base.getAccessSpecifierAsWritten());
  3658. Record.push_back(Base.getInheritConstructors());
  3659. AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
  3660. AddSourceRange(Base.getSourceRange(), Record);
  3661. AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
  3662. : SourceLocation(),
  3663. Record);
  3664. }
  3665. void ASTWriter::FlushCXXBaseSpecifiers() {
  3666. RecordData Record;
  3667. for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
  3668. Record.clear();
  3669. // Record the offset of this base-specifier set.
  3670. unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
  3671. if (Index == CXXBaseSpecifiersOffsets.size())
  3672. CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
  3673. else {
  3674. if (Index > CXXBaseSpecifiersOffsets.size())
  3675. CXXBaseSpecifiersOffsets.resize(Index + 1);
  3676. CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
  3677. }
  3678. const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
  3679. *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
  3680. Record.push_back(BEnd - B);
  3681. for (; B != BEnd; ++B)
  3682. AddCXXBaseSpecifier(*B, Record);
  3683. Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
  3684. // Flush any expressions that were written as part of the base specifiers.
  3685. FlushStmts();
  3686. }
  3687. CXXBaseSpecifiersToWrite.clear();
  3688. }
  3689. void ASTWriter::AddCXXCtorInitializers(
  3690. const CXXCtorInitializer * const *CtorInitializers,
  3691. unsigned NumCtorInitializers,
  3692. RecordDataImpl &Record) {
  3693. Record.push_back(NumCtorInitializers);
  3694. for (unsigned i=0; i != NumCtorInitializers; ++i) {
  3695. const CXXCtorInitializer *Init = CtorInitializers[i];
  3696. if (Init->isBaseInitializer()) {
  3697. Record.push_back(CTOR_INITIALIZER_BASE);
  3698. AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
  3699. Record.push_back(Init->isBaseVirtual());
  3700. } else if (Init->isDelegatingInitializer()) {
  3701. Record.push_back(CTOR_INITIALIZER_DELEGATING);
  3702. AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
  3703. } else if (Init->isMemberInitializer()){
  3704. Record.push_back(CTOR_INITIALIZER_MEMBER);
  3705. AddDeclRef(Init->getMember(), Record);
  3706. } else {
  3707. Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
  3708. AddDeclRef(Init->getIndirectMember(), Record);
  3709. }
  3710. AddSourceLocation(Init->getMemberLocation(), Record);
  3711. AddStmt(Init->getInit());
  3712. AddSourceLocation(Init->getLParenLoc(), Record);
  3713. AddSourceLocation(Init->getRParenLoc(), Record);
  3714. Record.push_back(Init->isWritten());
  3715. if (Init->isWritten()) {
  3716. Record.push_back(Init->getSourceOrder());
  3717. } else {
  3718. Record.push_back(Init->getNumArrayIndices());
  3719. for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
  3720. AddDeclRef(Init->getArrayIndex(i), Record);
  3721. }
  3722. }
  3723. }
  3724. void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
  3725. assert(D->DefinitionData);
  3726. struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
  3727. Record.push_back(Data.UserDeclaredConstructor);
  3728. Record.push_back(Data.UserDeclaredCopyConstructor);
  3729. Record.push_back(Data.UserDeclaredMoveConstructor);
  3730. Record.push_back(Data.UserDeclaredCopyAssignment);
  3731. Record.push_back(Data.UserDeclaredMoveAssignment);
  3732. Record.push_back(Data.UserDeclaredDestructor);
  3733. Record.push_back(Data.Aggregate);
  3734. Record.push_back(Data.PlainOldData);
  3735. Record.push_back(Data.Empty);
  3736. Record.push_back(Data.Polymorphic);
  3737. Record.push_back(Data.Abstract);
  3738. Record.push_back(Data.IsStandardLayout);
  3739. Record.push_back(Data.HasNoNonEmptyBases);
  3740. Record.push_back(Data.HasPrivateFields);
  3741. Record.push_back(Data.HasProtectedFields);
  3742. Record.push_back(Data.HasPublicFields);
  3743. Record.push_back(Data.HasMutableFields);
  3744. Record.push_back(Data.HasTrivialDefaultConstructor);
  3745. Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
  3746. Record.push_back(Data.HasTrivialCopyConstructor);
  3747. Record.push_back(Data.HasTrivialMoveConstructor);
  3748. Record.push_back(Data.HasTrivialCopyAssignment);
  3749. Record.push_back(Data.HasTrivialMoveAssignment);
  3750. Record.push_back(Data.HasTrivialDestructor);
  3751. Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
  3752. Record.push_back(Data.ComputedVisibleConversions);
  3753. Record.push_back(Data.UserProvidedDefaultConstructor);
  3754. Record.push_back(Data.DeclaredDefaultConstructor);
  3755. Record.push_back(Data.DeclaredCopyConstructor);
  3756. Record.push_back(Data.DeclaredMoveConstructor);
  3757. Record.push_back(Data.DeclaredCopyAssignment);
  3758. Record.push_back(Data.DeclaredMoveAssignment);
  3759. Record.push_back(Data.DeclaredDestructor);
  3760. Record.push_back(Data.FailedImplicitMoveConstructor);
  3761. Record.push_back(Data.FailedImplicitMoveAssignment);
  3762. Record.push_back(Data.NumBases);
  3763. if (Data.NumBases > 0)
  3764. AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
  3765. Record);
  3766. // FIXME: Make VBases lazily computed when needed to avoid storing them.
  3767. Record.push_back(Data.NumVBases);
  3768. if (Data.NumVBases > 0)
  3769. AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
  3770. Record);
  3771. AddUnresolvedSet(Data.Conversions, Record);
  3772. AddUnresolvedSet(Data.VisibleConversions, Record);
  3773. // Data.Definition is the owning decl, no need to write it.
  3774. AddDeclRef(Data.FirstFriend, Record);
  3775. }
  3776. void ASTWriter::ReaderInitialized(ASTReader *Reader) {
  3777. assert(Reader && "Cannot remove chain");
  3778. assert((!Chain || Chain == Reader) && "Cannot replace chain");
  3779. assert(FirstDeclID == NextDeclID &&
  3780. FirstTypeID == NextTypeID &&
  3781. FirstIdentID == NextIdentID &&
  3782. FirstSubmoduleID == NextSubmoduleID &&
  3783. FirstSelectorID == NextSelectorID &&
  3784. "Setting chain after writing has started.");
  3785. Chain = Reader;
  3786. FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
  3787. FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
  3788. FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
  3789. FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
  3790. FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
  3791. NextDeclID = FirstDeclID;
  3792. NextTypeID = FirstTypeID;
  3793. NextIdentID = FirstIdentID;
  3794. NextSelectorID = FirstSelectorID;
  3795. NextSubmoduleID = FirstSubmoduleID;
  3796. }
  3797. void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
  3798. IdentifierIDs[II] = ID;
  3799. if (II->hasMacroDefinition())
  3800. DeserializedMacroNames.push_back(II);
  3801. }
  3802. void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
  3803. // Always take the highest-numbered type index. This copes with an interesting
  3804. // case for chained AST writing where we schedule writing the type and then,
  3805. // later, deserialize the type from another AST. In this case, we want to
  3806. // keep the higher-numbered entry so that we can properly write it out to
  3807. // the AST file.
  3808. TypeIdx &StoredIdx = TypeIdxs[T];
  3809. if (Idx.getIndex() >= StoredIdx.getIndex())
  3810. StoredIdx = Idx;
  3811. }
  3812. void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
  3813. SelectorIDs[S] = ID;
  3814. }
  3815. void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
  3816. MacroDefinition *MD) {
  3817. assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
  3818. MacroDefinitions[MD] = ID;
  3819. }
  3820. void ASTWriter::MacroVisible(IdentifierInfo *II) {
  3821. DeserializedMacroNames.push_back(II);
  3822. }
  3823. void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
  3824. assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
  3825. SubmoduleIDs[Mod] = ID;
  3826. }
  3827. void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
  3828. assert(D->isCompleteDefinition());
  3829. assert(!WritingAST && "Already writing the AST!");
  3830. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  3831. // We are interested when a PCH decl is modified.
  3832. if (RD->isFromASTFile()) {
  3833. // A forward reference was mutated into a definition. Rewrite it.
  3834. // FIXME: This happens during template instantiation, should we
  3835. // have created a new definition decl instead ?
  3836. RewriteDecl(RD);
  3837. }
  3838. }
  3839. }
  3840. void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
  3841. assert(!WritingAST && "Already writing the AST!");
  3842. // TU and namespaces are handled elsewhere.
  3843. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
  3844. return;
  3845. if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
  3846. return; // Not a source decl added to a DeclContext from PCH.
  3847. AddUpdatedDeclContext(DC);
  3848. }
  3849. void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
  3850. assert(!WritingAST && "Already writing the AST!");
  3851. assert(D->isImplicit());
  3852. if (!(!D->isFromASTFile() && RD->isFromASTFile()))
  3853. return; // Not a source member added to a class from PCH.
  3854. if (!isa<CXXMethodDecl>(D))
  3855. return; // We are interested in lazily declared implicit methods.
  3856. // A decl coming from PCH was modified.
  3857. assert(RD->isCompleteDefinition());
  3858. UpdateRecord &Record = DeclUpdates[RD];
  3859. Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
  3860. Record.push_back(reinterpret_cast<uint64_t>(D));
  3861. }
  3862. void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
  3863. const ClassTemplateSpecializationDecl *D) {
  3864. // The specializations set is kept in the canonical template.
  3865. assert(!WritingAST && "Already writing the AST!");
  3866. TD = TD->getCanonicalDecl();
  3867. if (!(!D->isFromASTFile() && TD->isFromASTFile()))
  3868. return; // Not a source specialization added to a template from PCH.
  3869. UpdateRecord &Record = DeclUpdates[TD];
  3870. Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
  3871. Record.push_back(reinterpret_cast<uint64_t>(D));
  3872. }
  3873. void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
  3874. const FunctionDecl *D) {
  3875. // The specializations set is kept in the canonical template.
  3876. assert(!WritingAST && "Already writing the AST!");
  3877. TD = TD->getCanonicalDecl();
  3878. if (!(!D->isFromASTFile() && TD->isFromASTFile()))
  3879. return; // Not a source specialization added to a template from PCH.
  3880. UpdateRecord &Record = DeclUpdates[TD];
  3881. Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
  3882. Record.push_back(reinterpret_cast<uint64_t>(D));
  3883. }
  3884. void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
  3885. assert(!WritingAST && "Already writing the AST!");
  3886. if (!D->isFromASTFile())
  3887. return; // Declaration not imported from PCH.
  3888. // Implicit decl from a PCH was defined.
  3889. // FIXME: Should implicit definition be a separate FunctionDecl?
  3890. RewriteDecl(D);
  3891. }
  3892. void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
  3893. assert(!WritingAST && "Already writing the AST!");
  3894. if (!D->isFromASTFile())
  3895. return;
  3896. // Since the actual instantiation is delayed, this really means that we need
  3897. // to update the instantiation location.
  3898. UpdateRecord &Record = DeclUpdates[D];
  3899. Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
  3900. AddSourceLocation(
  3901. D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
  3902. }
  3903. void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
  3904. const ObjCInterfaceDecl *IFD) {
  3905. assert(!WritingAST && "Already writing the AST!");
  3906. if (!IFD->isFromASTFile())
  3907. return; // Declaration not imported from PCH.
  3908. assert(IFD->getDefinition() && "Category on a class without a definition?");
  3909. ObjCClassesWithCategories.insert(
  3910. const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
  3911. }
  3912. void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
  3913. const ObjCPropertyDecl *OrigProp,
  3914. const ObjCCategoryDecl *ClassExt) {
  3915. const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
  3916. if (!D)
  3917. return;
  3918. assert(!WritingAST && "Already writing the AST!");
  3919. if (!D->isFromASTFile())
  3920. return; // Declaration not imported from PCH.
  3921. RewriteDecl(D);
  3922. }