ASTWriter.cpp 162 KB

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