ASTWriter.cpp 175 KB

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