ASTWriter.cpp 165 KB

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