ASTWriter.cpp 197 KB

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