ASTReader.cpp 298 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473
  1. //===--- ASTReader.cpp - AST File Reader ----------------------------------===//
  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 ASTReader class, which reads AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTReader.h"
  14. #include "ASTCommon.h"
  15. #include "ASTReaderInternals.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/NestedNameSpecifier.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/AST/TypeLocVisitor.h"
  24. #include "clang/Basic/DiagnosticOptions.h"
  25. #include "clang/Basic/FileManager.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/SourceManagerInternals.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Basic/TargetOptions.h"
  30. #include "clang/Basic/Version.h"
  31. #include "clang/Basic/VersionTuple.h"
  32. #include "clang/Frontend/Utils.h"
  33. #include "clang/Lex/HeaderSearch.h"
  34. #include "clang/Lex/HeaderSearchOptions.h"
  35. #include "clang/Lex/MacroInfo.h"
  36. #include "clang/Lex/PreprocessingRecord.h"
  37. #include "clang/Lex/Preprocessor.h"
  38. #include "clang/Lex/PreprocessorOptions.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/Sema.h"
  41. #include "clang/Serialization/ASTDeserializationListener.h"
  42. #include "clang/Serialization/GlobalModuleIndex.h"
  43. #include "clang/Serialization/ModuleManager.h"
  44. #include "clang/Serialization/SerializationDiagnostic.h"
  45. #include "llvm/ADT/Hashing.h"
  46. #include "llvm/ADT/StringExtras.h"
  47. #include "llvm/Bitcode/BitstreamReader.h"
  48. #include "llvm/Support/ErrorHandling.h"
  49. #include "llvm/Support/FileSystem.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/Path.h"
  52. #include "llvm/Support/SaveAndRestore.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <algorithm>
  55. #include <cstdio>
  56. #include <iterator>
  57. #include <system_error>
  58. using namespace clang;
  59. using namespace clang::serialization;
  60. using namespace clang::serialization::reader;
  61. using llvm::BitstreamCursor;
  62. //===----------------------------------------------------------------------===//
  63. // ChainedASTReaderListener implementation
  64. //===----------------------------------------------------------------------===//
  65. bool
  66. ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
  67. return First->ReadFullVersionInformation(FullVersion) ||
  68. Second->ReadFullVersionInformation(FullVersion);
  69. }
  70. void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
  71. First->ReadModuleName(ModuleName);
  72. Second->ReadModuleName(ModuleName);
  73. }
  74. void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
  75. First->ReadModuleMapFile(ModuleMapPath);
  76. Second->ReadModuleMapFile(ModuleMapPath);
  77. }
  78. bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
  79. bool Complain) {
  80. return First->ReadLanguageOptions(LangOpts, Complain) ||
  81. Second->ReadLanguageOptions(LangOpts, Complain);
  82. }
  83. bool
  84. ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
  85. bool Complain) {
  86. return First->ReadTargetOptions(TargetOpts, Complain) ||
  87. Second->ReadTargetOptions(TargetOpts, Complain);
  88. }
  89. bool ChainedASTReaderListener::ReadDiagnosticOptions(
  90. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  91. return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
  92. Second->ReadDiagnosticOptions(DiagOpts, Complain);
  93. }
  94. bool
  95. ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  96. bool Complain) {
  97. return First->ReadFileSystemOptions(FSOpts, Complain) ||
  98. Second->ReadFileSystemOptions(FSOpts, Complain);
  99. }
  100. bool ChainedASTReaderListener::ReadHeaderSearchOptions(
  101. const HeaderSearchOptions &HSOpts, bool Complain) {
  102. return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
  103. Second->ReadHeaderSearchOptions(HSOpts, Complain);
  104. }
  105. bool ChainedASTReaderListener::ReadPreprocessorOptions(
  106. const PreprocessorOptions &PPOpts, bool Complain,
  107. std::string &SuggestedPredefines) {
  108. return First->ReadPreprocessorOptions(PPOpts, Complain,
  109. SuggestedPredefines) ||
  110. Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
  111. }
  112. void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
  113. unsigned Value) {
  114. First->ReadCounter(M, Value);
  115. Second->ReadCounter(M, Value);
  116. }
  117. bool ChainedASTReaderListener::needsInputFileVisitation() {
  118. return First->needsInputFileVisitation() ||
  119. Second->needsInputFileVisitation();
  120. }
  121. bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
  122. return First->needsSystemInputFileVisitation() ||
  123. Second->needsSystemInputFileVisitation();
  124. }
  125. void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
  126. First->visitModuleFile(Filename);
  127. Second->visitModuleFile(Filename);
  128. }
  129. bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
  130. bool isSystem,
  131. bool isOverridden) {
  132. bool Continue = false;
  133. if (First->needsInputFileVisitation() &&
  134. (!isSystem || First->needsSystemInputFileVisitation()))
  135. Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
  136. if (Second->needsInputFileVisitation() &&
  137. (!isSystem || Second->needsSystemInputFileVisitation()))
  138. Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
  139. return Continue;
  140. }
  141. //===----------------------------------------------------------------------===//
  142. // PCH validator implementation
  143. //===----------------------------------------------------------------------===//
  144. ASTReaderListener::~ASTReaderListener() {}
  145. /// \brief Compare the given set of language options against an existing set of
  146. /// language options.
  147. ///
  148. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  149. ///
  150. /// \returns true if the languagae options mis-match, false otherwise.
  151. static bool checkLanguageOptions(const LangOptions &LangOpts,
  152. const LangOptions &ExistingLangOpts,
  153. DiagnosticsEngine *Diags) {
  154. #define LANGOPT(Name, Bits, Default, Description) \
  155. if (ExistingLangOpts.Name != LangOpts.Name) { \
  156. if (Diags) \
  157. Diags->Report(diag::err_pch_langopt_mismatch) \
  158. << Description << LangOpts.Name << ExistingLangOpts.Name; \
  159. return true; \
  160. }
  161. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  162. if (ExistingLangOpts.Name != LangOpts.Name) { \
  163. if (Diags) \
  164. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  165. << Description; \
  166. return true; \
  167. }
  168. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  169. if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
  170. if (Diags) \
  171. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  172. << Description; \
  173. return true; \
  174. }
  175. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  176. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  177. #include "clang/Basic/LangOptions.def"
  178. if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
  179. if (Diags)
  180. Diags->Report(diag::err_pch_langopt_value_mismatch)
  181. << "target Objective-C runtime";
  182. return true;
  183. }
  184. if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
  185. LangOpts.CommentOpts.BlockCommandNames) {
  186. if (Diags)
  187. Diags->Report(diag::err_pch_langopt_value_mismatch)
  188. << "block command names";
  189. return true;
  190. }
  191. return false;
  192. }
  193. /// \brief Compare the given set of target options against an existing set of
  194. /// target options.
  195. ///
  196. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  197. ///
  198. /// \returns true if the target options mis-match, false otherwise.
  199. static bool checkTargetOptions(const TargetOptions &TargetOpts,
  200. const TargetOptions &ExistingTargetOpts,
  201. DiagnosticsEngine *Diags) {
  202. #define CHECK_TARGET_OPT(Field, Name) \
  203. if (TargetOpts.Field != ExistingTargetOpts.Field) { \
  204. if (Diags) \
  205. Diags->Report(diag::err_pch_targetopt_mismatch) \
  206. << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
  207. return true; \
  208. }
  209. CHECK_TARGET_OPT(Triple, "target");
  210. CHECK_TARGET_OPT(CPU, "target CPU");
  211. CHECK_TARGET_OPT(ABI, "target ABI");
  212. #undef CHECK_TARGET_OPT
  213. // Compare feature sets.
  214. SmallVector<StringRef, 4> ExistingFeatures(
  215. ExistingTargetOpts.FeaturesAsWritten.begin(),
  216. ExistingTargetOpts.FeaturesAsWritten.end());
  217. SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
  218. TargetOpts.FeaturesAsWritten.end());
  219. std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
  220. std::sort(ReadFeatures.begin(), ReadFeatures.end());
  221. unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
  222. unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
  223. while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
  224. if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
  225. ++ExistingIdx;
  226. ++ReadIdx;
  227. continue;
  228. }
  229. if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
  230. if (Diags)
  231. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  232. << false << ReadFeatures[ReadIdx];
  233. return true;
  234. }
  235. if (Diags)
  236. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  237. << true << ExistingFeatures[ExistingIdx];
  238. return true;
  239. }
  240. if (ExistingIdx < ExistingN) {
  241. if (Diags)
  242. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  243. << true << ExistingFeatures[ExistingIdx];
  244. return true;
  245. }
  246. if (ReadIdx < ReadN) {
  247. if (Diags)
  248. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  249. << false << ReadFeatures[ReadIdx];
  250. return true;
  251. }
  252. return false;
  253. }
  254. bool
  255. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
  256. bool Complain) {
  257. const LangOptions &ExistingLangOpts = PP.getLangOpts();
  258. return checkLanguageOptions(LangOpts, ExistingLangOpts,
  259. Complain? &Reader.Diags : nullptr);
  260. }
  261. bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
  262. bool Complain) {
  263. const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
  264. return checkTargetOptions(TargetOpts, ExistingTargetOpts,
  265. Complain? &Reader.Diags : nullptr);
  266. }
  267. namespace {
  268. typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
  269. MacroDefinitionsMap;
  270. typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
  271. DeclsMap;
  272. }
  273. static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
  274. DiagnosticsEngine &Diags,
  275. bool Complain) {
  276. typedef DiagnosticsEngine::Level Level;
  277. // Check current mappings for new -Werror mappings, and the stored mappings
  278. // for cases that were explicitly mapped to *not* be errors that are now
  279. // errors because of options like -Werror.
  280. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
  281. for (DiagnosticsEngine *MappingSource : MappingSources) {
  282. for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
  283. diag::kind DiagID = DiagIDMappingPair.first;
  284. Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
  285. if (CurLevel < DiagnosticsEngine::Error)
  286. continue; // not significant
  287. Level StoredLevel =
  288. StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
  289. if (StoredLevel < DiagnosticsEngine::Error) {
  290. if (Complain)
  291. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
  292. Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
  293. return true;
  294. }
  295. }
  296. }
  297. return false;
  298. }
  299. static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
  300. diag::Severity Ext = Diags.getExtensionHandlingBehavior();
  301. if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
  302. return true;
  303. return Ext >= diag::Severity::Error;
  304. }
  305. static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
  306. DiagnosticsEngine &Diags,
  307. bool IsSystem, bool Complain) {
  308. // Top-level options
  309. if (IsSystem) {
  310. if (Diags.getSuppressSystemWarnings())
  311. return false;
  312. // If -Wsystem-headers was not enabled before, be conservative
  313. if (StoredDiags.getSuppressSystemWarnings()) {
  314. if (Complain)
  315. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
  316. return true;
  317. }
  318. }
  319. if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
  320. if (Complain)
  321. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
  322. return true;
  323. }
  324. if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
  325. !StoredDiags.getEnableAllWarnings()) {
  326. if (Complain)
  327. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
  328. return true;
  329. }
  330. if (isExtHandlingFromDiagsError(Diags) &&
  331. !isExtHandlingFromDiagsError(StoredDiags)) {
  332. if (Complain)
  333. Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
  334. return true;
  335. }
  336. return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
  337. }
  338. bool PCHValidator::ReadDiagnosticOptions(
  339. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  340. DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
  341. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
  342. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  343. new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
  344. // This should never fail, because we would have processed these options
  345. // before writing them to an ASTFile.
  346. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
  347. ModuleManager &ModuleMgr = Reader.getModuleManager();
  348. assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
  349. // If the original import came from a file explicitly generated by the user,
  350. // don't check the diagnostic mappings.
  351. // FIXME: currently this is approximated by checking whether this is not a
  352. // module import.
  353. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
  354. // the transitive closure of its imports, since unrelated modules cannot be
  355. // imported until after this module finishes validation.
  356. ModuleFile *TopImport = *ModuleMgr.rbegin();
  357. while (!TopImport->ImportedBy.empty())
  358. TopImport = TopImport->ImportedBy[0];
  359. if (TopImport->Kind != MK_Module)
  360. return false;
  361. StringRef ModuleName = TopImport->ModuleName;
  362. assert(!ModuleName.empty() && "diagnostic options read before module name");
  363. Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
  364. assert(M && "missing module");
  365. // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
  366. // contains the union of their flags.
  367. return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
  368. }
  369. /// \brief Collect the macro definitions provided by the given preprocessor
  370. /// options.
  371. static void
  372. collectMacroDefinitions(const PreprocessorOptions &PPOpts,
  373. MacroDefinitionsMap &Macros,
  374. SmallVectorImpl<StringRef> *MacroNames = nullptr) {
  375. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  376. StringRef Macro = PPOpts.Macros[I].first;
  377. bool IsUndef = PPOpts.Macros[I].second;
  378. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  379. StringRef MacroName = MacroPair.first;
  380. StringRef MacroBody = MacroPair.second;
  381. // For an #undef'd macro, we only care about the name.
  382. if (IsUndef) {
  383. if (MacroNames && !Macros.count(MacroName))
  384. MacroNames->push_back(MacroName);
  385. Macros[MacroName] = std::make_pair("", true);
  386. continue;
  387. }
  388. // For a #define'd macro, figure out the actual definition.
  389. if (MacroName.size() == Macro.size())
  390. MacroBody = "1";
  391. else {
  392. // Note: GCC drops anything following an end-of-line character.
  393. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  394. MacroBody = MacroBody.substr(0, End);
  395. }
  396. if (MacroNames && !Macros.count(MacroName))
  397. MacroNames->push_back(MacroName);
  398. Macros[MacroName] = std::make_pair(MacroBody, false);
  399. }
  400. }
  401. /// \brief Check the preprocessor options deserialized from the control block
  402. /// against the preprocessor options in an existing preprocessor.
  403. ///
  404. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  405. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
  406. const PreprocessorOptions &ExistingPPOpts,
  407. DiagnosticsEngine *Diags,
  408. FileManager &FileMgr,
  409. std::string &SuggestedPredefines,
  410. const LangOptions &LangOpts) {
  411. // Check macro definitions.
  412. MacroDefinitionsMap ASTFileMacros;
  413. collectMacroDefinitions(PPOpts, ASTFileMacros);
  414. MacroDefinitionsMap ExistingMacros;
  415. SmallVector<StringRef, 4> ExistingMacroNames;
  416. collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
  417. for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
  418. // Dig out the macro definition in the existing preprocessor options.
  419. StringRef MacroName = ExistingMacroNames[I];
  420. std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
  421. // Check whether we know anything about this macro name or not.
  422. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
  423. = ASTFileMacros.find(MacroName);
  424. if (Known == ASTFileMacros.end()) {
  425. // FIXME: Check whether this identifier was referenced anywhere in the
  426. // AST file. If so, we should reject the AST file. Unfortunately, this
  427. // information isn't in the control block. What shall we do about it?
  428. if (Existing.second) {
  429. SuggestedPredefines += "#undef ";
  430. SuggestedPredefines += MacroName.str();
  431. SuggestedPredefines += '\n';
  432. } else {
  433. SuggestedPredefines += "#define ";
  434. SuggestedPredefines += MacroName.str();
  435. SuggestedPredefines += ' ';
  436. SuggestedPredefines += Existing.first.str();
  437. SuggestedPredefines += '\n';
  438. }
  439. continue;
  440. }
  441. // If the macro was defined in one but undef'd in the other, we have a
  442. // conflict.
  443. if (Existing.second != Known->second.second) {
  444. if (Diags) {
  445. Diags->Report(diag::err_pch_macro_def_undef)
  446. << MacroName << Known->second.second;
  447. }
  448. return true;
  449. }
  450. // If the macro was #undef'd in both, or if the macro bodies are identical,
  451. // it's fine.
  452. if (Existing.second || Existing.first == Known->second.first)
  453. continue;
  454. // The macro bodies differ; complain.
  455. if (Diags) {
  456. Diags->Report(diag::err_pch_macro_def_conflict)
  457. << MacroName << Known->second.first << Existing.first;
  458. }
  459. return true;
  460. }
  461. // Check whether we're using predefines.
  462. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
  463. if (Diags) {
  464. Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
  465. }
  466. return true;
  467. }
  468. // Detailed record is important since it is used for the module cache hash.
  469. if (LangOpts.Modules &&
  470. PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
  471. if (Diags) {
  472. Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
  473. }
  474. return true;
  475. }
  476. // Compute the #include and #include_macros lines we need.
  477. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
  478. StringRef File = ExistingPPOpts.Includes[I];
  479. if (File == ExistingPPOpts.ImplicitPCHInclude)
  480. continue;
  481. if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
  482. != PPOpts.Includes.end())
  483. continue;
  484. SuggestedPredefines += "#include \"";
  485. SuggestedPredefines += File;
  486. SuggestedPredefines += "\"\n";
  487. }
  488. for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
  489. StringRef File = ExistingPPOpts.MacroIncludes[I];
  490. if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
  491. File)
  492. != PPOpts.MacroIncludes.end())
  493. continue;
  494. SuggestedPredefines += "#__include_macros \"";
  495. SuggestedPredefines += File;
  496. SuggestedPredefines += "\"\n##\n";
  497. }
  498. return false;
  499. }
  500. bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  501. bool Complain,
  502. std::string &SuggestedPredefines) {
  503. const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
  504. return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
  505. Complain? &Reader.Diags : nullptr,
  506. PP.getFileManager(),
  507. SuggestedPredefines,
  508. PP.getLangOpts());
  509. }
  510. void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
  511. PP.setCounterValue(Value);
  512. }
  513. //===----------------------------------------------------------------------===//
  514. // AST reader implementation
  515. //===----------------------------------------------------------------------===//
  516. void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
  517. bool TakeOwnership) {
  518. DeserializationListener = Listener;
  519. OwnsDeserializationListener = TakeOwnership;
  520. }
  521. unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
  522. return serialization::ComputeHash(Sel);
  523. }
  524. std::pair<unsigned, unsigned>
  525. ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  526. using namespace llvm::support;
  527. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  528. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  529. return std::make_pair(KeyLen, DataLen);
  530. }
  531. ASTSelectorLookupTrait::internal_key_type
  532. ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  533. using namespace llvm::support;
  534. SelectorTable &SelTable = Reader.getContext().Selectors;
  535. unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
  536. IdentifierInfo *FirstII = Reader.getLocalIdentifier(
  537. F, endian::readNext<uint32_t, little, unaligned>(d));
  538. if (N == 0)
  539. return SelTable.getNullarySelector(FirstII);
  540. else if (N == 1)
  541. return SelTable.getUnarySelector(FirstII);
  542. SmallVector<IdentifierInfo *, 16> Args;
  543. Args.push_back(FirstII);
  544. for (unsigned I = 1; I != N; ++I)
  545. Args.push_back(Reader.getLocalIdentifier(
  546. F, endian::readNext<uint32_t, little, unaligned>(d)));
  547. return SelTable.getSelector(N, Args.data());
  548. }
  549. ASTSelectorLookupTrait::data_type
  550. ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
  551. unsigned DataLen) {
  552. using namespace llvm::support;
  553. data_type Result;
  554. Result.ID = Reader.getGlobalSelectorID(
  555. F, endian::readNext<uint32_t, little, unaligned>(d));
  556. unsigned NumInstanceMethodsAndBits =
  557. endian::readNext<uint16_t, little, unaligned>(d);
  558. unsigned NumFactoryMethodsAndBits =
  559. endian::readNext<uint16_t, little, unaligned>(d);
  560. Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
  561. Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
  562. unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
  563. unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
  564. // Load instance methods
  565. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  566. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  567. F, endian::readNext<uint32_t, little, unaligned>(d)))
  568. Result.Instance.push_back(Method);
  569. }
  570. // Load factory methods
  571. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  572. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  573. F, endian::readNext<uint32_t, little, unaligned>(d)))
  574. Result.Factory.push_back(Method);
  575. }
  576. return Result;
  577. }
  578. unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
  579. return llvm::HashString(a);
  580. }
  581. std::pair<unsigned, unsigned>
  582. ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
  583. using namespace llvm::support;
  584. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  585. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  586. return std::make_pair(KeyLen, DataLen);
  587. }
  588. ASTIdentifierLookupTraitBase::internal_key_type
  589. ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
  590. assert(n >= 2 && d[n-1] == '\0');
  591. return StringRef((const char*) d, n-1);
  592. }
  593. /// \brief Whether the given identifier is "interesting".
  594. static bool isInterestingIdentifier(IdentifierInfo &II) {
  595. return II.isPoisoned() ||
  596. II.isExtensionToken() ||
  597. II.getObjCOrBuiltinID() ||
  598. II.hasRevertedTokenIDToIdentifier() ||
  599. II.hadMacroDefinition() ||
  600. II.getFETokenInfo<void>();
  601. }
  602. IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
  603. const unsigned char* d,
  604. unsigned DataLen) {
  605. using namespace llvm::support;
  606. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  607. bool IsInteresting = RawID & 0x01;
  608. // Wipe out the "is interesting" bit.
  609. RawID = RawID >> 1;
  610. IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
  611. if (!IsInteresting) {
  612. // For uninteresting identifiers, just build the IdentifierInfo
  613. // and associate it with the persistent ID.
  614. IdentifierInfo *II = KnownII;
  615. if (!II) {
  616. II = &Reader.getIdentifierTable().getOwn(k);
  617. KnownII = II;
  618. }
  619. Reader.SetIdentifierInfo(ID, II);
  620. if (!II->isFromAST()) {
  621. bool WasInteresting = isInterestingIdentifier(*II);
  622. II->setIsFromAST();
  623. if (WasInteresting)
  624. II->setChangedSinceDeserialization();
  625. }
  626. Reader.markIdentifierUpToDate(II);
  627. return II;
  628. }
  629. unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
  630. unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
  631. bool CPlusPlusOperatorKeyword = Bits & 0x01;
  632. Bits >>= 1;
  633. bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
  634. Bits >>= 1;
  635. bool Poisoned = Bits & 0x01;
  636. Bits >>= 1;
  637. bool ExtensionToken = Bits & 0x01;
  638. Bits >>= 1;
  639. bool hasSubmoduleMacros = Bits & 0x01;
  640. Bits >>= 1;
  641. bool hadMacroDefinition = Bits & 0x01;
  642. Bits >>= 1;
  643. assert(Bits == 0 && "Extra bits in the identifier?");
  644. DataLen -= 8;
  645. // Build the IdentifierInfo itself and link the identifier ID with
  646. // the new IdentifierInfo.
  647. IdentifierInfo *II = KnownII;
  648. if (!II) {
  649. II = &Reader.getIdentifierTable().getOwn(StringRef(k));
  650. KnownII = II;
  651. }
  652. Reader.markIdentifierUpToDate(II);
  653. if (!II->isFromAST()) {
  654. bool WasInteresting = isInterestingIdentifier(*II);
  655. II->setIsFromAST();
  656. if (WasInteresting)
  657. II->setChangedSinceDeserialization();
  658. }
  659. // Set or check the various bits in the IdentifierInfo structure.
  660. // Token IDs are read-only.
  661. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
  662. II->RevertTokenIDToIdentifier();
  663. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  664. assert(II->isExtensionToken() == ExtensionToken &&
  665. "Incorrect extension token flag");
  666. (void)ExtensionToken;
  667. if (Poisoned)
  668. II->setIsPoisoned(true);
  669. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  670. "Incorrect C++ operator keyword flag");
  671. (void)CPlusPlusOperatorKeyword;
  672. // If this identifier is a macro, deserialize the macro
  673. // definition.
  674. if (hadMacroDefinition) {
  675. uint32_t MacroDirectivesOffset =
  676. endian::readNext<uint32_t, little, unaligned>(d);
  677. DataLen -= 4;
  678. SmallVector<uint32_t, 8> LocalMacroIDs;
  679. if (hasSubmoduleMacros) {
  680. while (true) {
  681. uint32_t LocalMacroID =
  682. endian::readNext<uint32_t, little, unaligned>(d);
  683. DataLen -= 4;
  684. if (LocalMacroID == 0xdeadbeef) break;
  685. LocalMacroIDs.push_back(LocalMacroID);
  686. }
  687. }
  688. if (F.Kind == MK_Module) {
  689. // Macro definitions are stored from newest to oldest, so reverse them
  690. // before registering them.
  691. llvm::SmallVector<unsigned, 8> MacroSizes;
  692. for (SmallVectorImpl<uint32_t>::iterator
  693. I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
  694. unsigned Size = 1;
  695. static const uint32_t HasOverridesFlag = 0x80000000U;
  696. if (I + 1 != E && (I[1] & HasOverridesFlag))
  697. Size += 1 + (I[1] & ~HasOverridesFlag);
  698. MacroSizes.push_back(Size);
  699. I += Size;
  700. }
  701. SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
  702. for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
  703. SE = MacroSizes.rend();
  704. SI != SE; ++SI) {
  705. I -= *SI;
  706. uint32_t LocalMacroID = *I;
  707. ArrayRef<uint32_t> Overrides;
  708. if (*SI != 1)
  709. Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
  710. Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
  711. }
  712. assert(I == LocalMacroIDs.begin());
  713. } else {
  714. Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
  715. }
  716. }
  717. Reader.SetIdentifierInfo(ID, II);
  718. // Read all of the declarations visible at global scope with this
  719. // name.
  720. if (DataLen > 0) {
  721. SmallVector<uint32_t, 4> DeclIDs;
  722. for (; DataLen > 0; DataLen -= 4)
  723. DeclIDs.push_back(Reader.getGlobalDeclID(
  724. F, endian::readNext<uint32_t, little, unaligned>(d)));
  725. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  726. }
  727. return II;
  728. }
  729. unsigned
  730. ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
  731. llvm::FoldingSetNodeID ID;
  732. ID.AddInteger(Key.Kind);
  733. switch (Key.Kind) {
  734. case DeclarationName::Identifier:
  735. case DeclarationName::CXXLiteralOperatorName:
  736. ID.AddString(((IdentifierInfo*)Key.Data)->getName());
  737. break;
  738. case DeclarationName::ObjCZeroArgSelector:
  739. case DeclarationName::ObjCOneArgSelector:
  740. case DeclarationName::ObjCMultiArgSelector:
  741. ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
  742. break;
  743. case DeclarationName::CXXOperatorName:
  744. ID.AddInteger((OverloadedOperatorKind)Key.Data);
  745. break;
  746. case DeclarationName::CXXConstructorName:
  747. case DeclarationName::CXXDestructorName:
  748. case DeclarationName::CXXConversionFunctionName:
  749. case DeclarationName::CXXUsingDirective:
  750. break;
  751. }
  752. return ID.ComputeHash();
  753. }
  754. ASTDeclContextNameLookupTrait::internal_key_type
  755. ASTDeclContextNameLookupTrait::GetInternalKey(
  756. const external_key_type& Name) const {
  757. DeclNameKey Key;
  758. Key.Kind = Name.getNameKind();
  759. switch (Name.getNameKind()) {
  760. case DeclarationName::Identifier:
  761. Key.Data = (uint64_t)Name.getAsIdentifierInfo();
  762. break;
  763. case DeclarationName::ObjCZeroArgSelector:
  764. case DeclarationName::ObjCOneArgSelector:
  765. case DeclarationName::ObjCMultiArgSelector:
  766. Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
  767. break;
  768. case DeclarationName::CXXOperatorName:
  769. Key.Data = Name.getCXXOverloadedOperator();
  770. break;
  771. case DeclarationName::CXXLiteralOperatorName:
  772. Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
  773. break;
  774. case DeclarationName::CXXConstructorName:
  775. case DeclarationName::CXXDestructorName:
  776. case DeclarationName::CXXConversionFunctionName:
  777. case DeclarationName::CXXUsingDirective:
  778. Key.Data = 0;
  779. break;
  780. }
  781. return Key;
  782. }
  783. std::pair<unsigned, unsigned>
  784. ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  785. using namespace llvm::support;
  786. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  787. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  788. return std::make_pair(KeyLen, DataLen);
  789. }
  790. ASTDeclContextNameLookupTrait::internal_key_type
  791. ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  792. using namespace llvm::support;
  793. DeclNameKey Key;
  794. Key.Kind = (DeclarationName::NameKind)*d++;
  795. switch (Key.Kind) {
  796. case DeclarationName::Identifier:
  797. Key.Data = (uint64_t)Reader.getLocalIdentifier(
  798. F, endian::readNext<uint32_t, little, unaligned>(d));
  799. break;
  800. case DeclarationName::ObjCZeroArgSelector:
  801. case DeclarationName::ObjCOneArgSelector:
  802. case DeclarationName::ObjCMultiArgSelector:
  803. Key.Data =
  804. (uint64_t)Reader.getLocalSelector(
  805. F, endian::readNext<uint32_t, little, unaligned>(
  806. d)).getAsOpaquePtr();
  807. break;
  808. case DeclarationName::CXXOperatorName:
  809. Key.Data = *d++; // OverloadedOperatorKind
  810. break;
  811. case DeclarationName::CXXLiteralOperatorName:
  812. Key.Data = (uint64_t)Reader.getLocalIdentifier(
  813. F, endian::readNext<uint32_t, little, unaligned>(d));
  814. break;
  815. case DeclarationName::CXXConstructorName:
  816. case DeclarationName::CXXDestructorName:
  817. case DeclarationName::CXXConversionFunctionName:
  818. case DeclarationName::CXXUsingDirective:
  819. Key.Data = 0;
  820. break;
  821. }
  822. return Key;
  823. }
  824. ASTDeclContextNameLookupTrait::data_type
  825. ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
  826. const unsigned char* d,
  827. unsigned DataLen) {
  828. using namespace llvm::support;
  829. unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
  830. LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
  831. const_cast<unsigned char *>(d));
  832. return std::make_pair(Start, Start + NumDecls);
  833. }
  834. bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
  835. BitstreamCursor &Cursor,
  836. const std::pair<uint64_t, uint64_t> &Offsets,
  837. DeclContextInfo &Info) {
  838. SavedStreamPosition SavedPosition(Cursor);
  839. // First the lexical decls.
  840. if (Offsets.first != 0) {
  841. Cursor.JumpToBit(Offsets.first);
  842. RecordData Record;
  843. StringRef Blob;
  844. unsigned Code = Cursor.ReadCode();
  845. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  846. if (RecCode != DECL_CONTEXT_LEXICAL) {
  847. Error("Expected lexical block");
  848. return true;
  849. }
  850. Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
  851. Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
  852. }
  853. // Now the lookup table.
  854. if (Offsets.second != 0) {
  855. Cursor.JumpToBit(Offsets.second);
  856. RecordData Record;
  857. StringRef Blob;
  858. unsigned Code = Cursor.ReadCode();
  859. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  860. if (RecCode != DECL_CONTEXT_VISIBLE) {
  861. Error("Expected visible lookup table block");
  862. return true;
  863. }
  864. Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
  865. (const unsigned char *)Blob.data() + Record[0],
  866. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  867. (const unsigned char *)Blob.data(),
  868. ASTDeclContextNameLookupTrait(*this, M));
  869. }
  870. return false;
  871. }
  872. void ASTReader::Error(StringRef Msg) {
  873. Error(diag::err_fe_pch_malformed, Msg);
  874. if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
  875. Diag(diag::note_module_cache_path)
  876. << PP.getHeaderSearchInfo().getModuleCachePath();
  877. }
  878. }
  879. void ASTReader::Error(unsigned DiagID,
  880. StringRef Arg1, StringRef Arg2) {
  881. if (Diags.isDiagnosticInFlight())
  882. Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
  883. else
  884. Diag(DiagID) << Arg1 << Arg2;
  885. }
  886. //===----------------------------------------------------------------------===//
  887. // Source Manager Deserialization
  888. //===----------------------------------------------------------------------===//
  889. /// \brief Read the line table in the source manager block.
  890. /// \returns true if there was an error.
  891. bool ASTReader::ParseLineTable(ModuleFile &F,
  892. SmallVectorImpl<uint64_t> &Record) {
  893. unsigned Idx = 0;
  894. LineTableInfo &LineTable = SourceMgr.getLineTable();
  895. // Parse the file names
  896. std::map<int, int> FileIDs;
  897. for (int I = 0, N = Record[Idx++]; I != N; ++I) {
  898. // Extract the file name
  899. unsigned FilenameLen = Record[Idx++];
  900. std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
  901. Idx += FilenameLen;
  902. MaybeAddSystemRootToFilename(F, Filename);
  903. FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
  904. }
  905. // Parse the line entries
  906. std::vector<LineEntry> Entries;
  907. while (Idx < Record.size()) {
  908. int FID = Record[Idx++];
  909. assert(FID >= 0 && "Serialized line entries for non-local file.");
  910. // Remap FileID from 1-based old view.
  911. FID += F.SLocEntryBaseID - 1;
  912. // Extract the line entries
  913. unsigned NumEntries = Record[Idx++];
  914. assert(NumEntries && "Numentries is 00000");
  915. Entries.clear();
  916. Entries.reserve(NumEntries);
  917. for (unsigned I = 0; I != NumEntries; ++I) {
  918. unsigned FileOffset = Record[Idx++];
  919. unsigned LineNo = Record[Idx++];
  920. int FilenameID = FileIDs[Record[Idx++]];
  921. SrcMgr::CharacteristicKind FileKind
  922. = (SrcMgr::CharacteristicKind)Record[Idx++];
  923. unsigned IncludeOffset = Record[Idx++];
  924. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  925. FileKind, IncludeOffset));
  926. }
  927. LineTable.AddEntry(FileID::get(FID), Entries);
  928. }
  929. return false;
  930. }
  931. /// \brief Read a source manager block
  932. bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
  933. using namespace SrcMgr;
  934. BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  935. // Set the source-location entry cursor to the current position in
  936. // the stream. This cursor will be used to read the contents of the
  937. // source manager block initially, and then lazily read
  938. // source-location entries as needed.
  939. SLocEntryCursor = F.Stream;
  940. // The stream itself is going to skip over the source manager block.
  941. if (F.Stream.SkipBlock()) {
  942. Error("malformed block record in AST file");
  943. return true;
  944. }
  945. // Enter the source manager block.
  946. if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
  947. Error("malformed source manager block record in AST file");
  948. return true;
  949. }
  950. RecordData Record;
  951. while (true) {
  952. llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
  953. switch (E.Kind) {
  954. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  955. case llvm::BitstreamEntry::Error:
  956. Error("malformed block record in AST file");
  957. return true;
  958. case llvm::BitstreamEntry::EndBlock:
  959. return false;
  960. case llvm::BitstreamEntry::Record:
  961. // The interesting case.
  962. break;
  963. }
  964. // Read a record.
  965. Record.clear();
  966. StringRef Blob;
  967. switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
  968. default: // Default behavior: ignore.
  969. break;
  970. case SM_SLOC_FILE_ENTRY:
  971. case SM_SLOC_BUFFER_ENTRY:
  972. case SM_SLOC_EXPANSION_ENTRY:
  973. // Once we hit one of the source location entries, we're done.
  974. return false;
  975. }
  976. }
  977. }
  978. /// \brief If a header file is not found at the path that we expect it to be
  979. /// and the PCH file was moved from its original location, try to resolve the
  980. /// file by assuming that header+PCH were moved together and the header is in
  981. /// the same place relative to the PCH.
  982. static std::string
  983. resolveFileRelativeToOriginalDir(const std::string &Filename,
  984. const std::string &OriginalDir,
  985. const std::string &CurrDir) {
  986. assert(OriginalDir != CurrDir &&
  987. "No point trying to resolve the file if the PCH dir didn't change");
  988. using namespace llvm::sys;
  989. SmallString<128> filePath(Filename);
  990. fs::make_absolute(filePath);
  991. assert(path::is_absolute(OriginalDir));
  992. SmallString<128> currPCHPath(CurrDir);
  993. path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
  994. fileDirE = path::end(path::parent_path(filePath));
  995. path::const_iterator origDirI = path::begin(OriginalDir),
  996. origDirE = path::end(OriginalDir);
  997. // Skip the common path components from filePath and OriginalDir.
  998. while (fileDirI != fileDirE && origDirI != origDirE &&
  999. *fileDirI == *origDirI) {
  1000. ++fileDirI;
  1001. ++origDirI;
  1002. }
  1003. for (; origDirI != origDirE; ++origDirI)
  1004. path::append(currPCHPath, "..");
  1005. path::append(currPCHPath, fileDirI, fileDirE);
  1006. path::append(currPCHPath, path::filename(Filename));
  1007. return currPCHPath.str();
  1008. }
  1009. bool ASTReader::ReadSLocEntry(int ID) {
  1010. if (ID == 0)
  1011. return false;
  1012. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1013. Error("source location entry ID out-of-range for AST file");
  1014. return true;
  1015. }
  1016. ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
  1017. F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
  1018. BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
  1019. unsigned BaseOffset = F->SLocEntryBaseOffset;
  1020. ++NumSLocEntriesRead;
  1021. llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
  1022. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1023. Error("incorrectly-formatted source location entry in AST file");
  1024. return true;
  1025. }
  1026. RecordData Record;
  1027. StringRef Blob;
  1028. switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
  1029. default:
  1030. Error("incorrectly-formatted source location entry in AST file");
  1031. return true;
  1032. case SM_SLOC_FILE_ENTRY: {
  1033. // We will detect whether a file changed and return 'Failure' for it, but
  1034. // we will also try to fail gracefully by setting up the SLocEntry.
  1035. unsigned InputID = Record[4];
  1036. InputFile IF = getInputFile(*F, InputID);
  1037. const FileEntry *File = IF.getFile();
  1038. bool OverriddenBuffer = IF.isOverridden();
  1039. // Note that we only check if a File was returned. If it was out-of-date
  1040. // we have complained but we will continue creating a FileID to recover
  1041. // gracefully.
  1042. if (!File)
  1043. return true;
  1044. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1045. if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
  1046. // This is the module's main file.
  1047. IncludeLoc = getImportLocation(F);
  1048. }
  1049. SrcMgr::CharacteristicKind
  1050. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1051. FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
  1052. ID, BaseOffset + Record[0]);
  1053. SrcMgr::FileInfo &FileInfo =
  1054. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
  1055. FileInfo.NumCreatedFIDs = Record[5];
  1056. if (Record[3])
  1057. FileInfo.setHasLineDirectives();
  1058. const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
  1059. unsigned NumFileDecls = Record[7];
  1060. if (NumFileDecls) {
  1061. assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
  1062. FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
  1063. NumFileDecls));
  1064. }
  1065. const SrcMgr::ContentCache *ContentCache
  1066. = SourceMgr.getOrCreateContentCache(File,
  1067. /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
  1068. if (OverriddenBuffer && !ContentCache->BufferOverridden &&
  1069. ContentCache->ContentsEntry == ContentCache->OrigEntry) {
  1070. unsigned Code = SLocEntryCursor.ReadCode();
  1071. Record.clear();
  1072. unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
  1073. if (RecCode != SM_SLOC_BUFFER_BLOB) {
  1074. Error("AST record has invalid code");
  1075. return true;
  1076. }
  1077. llvm::MemoryBuffer *Buffer
  1078. = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
  1079. SourceMgr.overrideFileContents(File, Buffer);
  1080. }
  1081. break;
  1082. }
  1083. case SM_SLOC_BUFFER_ENTRY: {
  1084. const char *Name = Blob.data();
  1085. unsigned Offset = Record[0];
  1086. SrcMgr::CharacteristicKind
  1087. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1088. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1089. if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
  1090. IncludeLoc = getImportLocation(F);
  1091. }
  1092. unsigned Code = SLocEntryCursor.ReadCode();
  1093. Record.clear();
  1094. unsigned RecCode
  1095. = SLocEntryCursor.readRecord(Code, Record, &Blob);
  1096. if (RecCode != SM_SLOC_BUFFER_BLOB) {
  1097. Error("AST record has invalid code");
  1098. return true;
  1099. }
  1100. llvm::MemoryBuffer *Buffer
  1101. = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
  1102. SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
  1103. IncludeLoc);
  1104. break;
  1105. }
  1106. case SM_SLOC_EXPANSION_ENTRY: {
  1107. SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
  1108. SourceMgr.createExpansionLoc(SpellingLoc,
  1109. ReadSourceLocation(*F, Record[2]),
  1110. ReadSourceLocation(*F, Record[3]),
  1111. Record[4],
  1112. ID,
  1113. BaseOffset + Record[0]);
  1114. break;
  1115. }
  1116. }
  1117. return false;
  1118. }
  1119. std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
  1120. if (ID == 0)
  1121. return std::make_pair(SourceLocation(), "");
  1122. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1123. Error("source location entry ID out-of-range for AST file");
  1124. return std::make_pair(SourceLocation(), "");
  1125. }
  1126. // Find which module file this entry lands in.
  1127. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
  1128. if (M->Kind != MK_Module)
  1129. return std::make_pair(SourceLocation(), "");
  1130. // FIXME: Can we map this down to a particular submodule? That would be
  1131. // ideal.
  1132. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
  1133. }
  1134. /// \brief Find the location where the module F is imported.
  1135. SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
  1136. if (F->ImportLoc.isValid())
  1137. return F->ImportLoc;
  1138. // Otherwise we have a PCH. It's considered to be "imported" at the first
  1139. // location of its includer.
  1140. if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
  1141. // Main file is the importer.
  1142. assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
  1143. return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1144. }
  1145. return F->ImportedBy[0]->FirstLoc;
  1146. }
  1147. /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
  1148. /// specified cursor. Read the abbreviations that are at the top of the block
  1149. /// and then leave the cursor pointing into the block.
  1150. bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
  1151. if (Cursor.EnterSubBlock(BlockID)) {
  1152. Error("malformed block record in AST file");
  1153. return Failure;
  1154. }
  1155. while (true) {
  1156. uint64_t Offset = Cursor.GetCurrentBitNo();
  1157. unsigned Code = Cursor.ReadCode();
  1158. // We expect all abbrevs to be at the start of the block.
  1159. if (Code != llvm::bitc::DEFINE_ABBREV) {
  1160. Cursor.JumpToBit(Offset);
  1161. return false;
  1162. }
  1163. Cursor.ReadAbbrevRecord();
  1164. }
  1165. }
  1166. Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
  1167. unsigned &Idx) {
  1168. Token Tok;
  1169. Tok.startToken();
  1170. Tok.setLocation(ReadSourceLocation(F, Record, Idx));
  1171. Tok.setLength(Record[Idx++]);
  1172. if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
  1173. Tok.setIdentifierInfo(II);
  1174. Tok.setKind((tok::TokenKind)Record[Idx++]);
  1175. Tok.setFlag((Token::TokenFlags)Record[Idx++]);
  1176. return Tok;
  1177. }
  1178. MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
  1179. BitstreamCursor &Stream = F.MacroCursor;
  1180. // Keep track of where we are in the stream, then jump back there
  1181. // after reading this macro.
  1182. SavedStreamPosition SavedPosition(Stream);
  1183. Stream.JumpToBit(Offset);
  1184. RecordData Record;
  1185. SmallVector<IdentifierInfo*, 16> MacroArgs;
  1186. MacroInfo *Macro = nullptr;
  1187. while (true) {
  1188. // Advance to the next record, but if we get to the end of the block, don't
  1189. // pop it (removing all the abbreviations from the cursor) since we want to
  1190. // be able to reseek within the block and read entries.
  1191. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
  1192. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
  1193. switch (Entry.Kind) {
  1194. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1195. case llvm::BitstreamEntry::Error:
  1196. Error("malformed block record in AST file");
  1197. return Macro;
  1198. case llvm::BitstreamEntry::EndBlock:
  1199. return Macro;
  1200. case llvm::BitstreamEntry::Record:
  1201. // The interesting case.
  1202. break;
  1203. }
  1204. // Read a record.
  1205. Record.clear();
  1206. PreprocessorRecordTypes RecType =
  1207. (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
  1208. switch (RecType) {
  1209. case PP_MACRO_DIRECTIVE_HISTORY:
  1210. return Macro;
  1211. case PP_MACRO_OBJECT_LIKE:
  1212. case PP_MACRO_FUNCTION_LIKE: {
  1213. // If we already have a macro, that means that we've hit the end
  1214. // of the definition of the macro we were looking for. We're
  1215. // done.
  1216. if (Macro)
  1217. return Macro;
  1218. unsigned NextIndex = 1; // Skip identifier ID.
  1219. SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
  1220. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
  1221. MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
  1222. MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
  1223. MI->setIsUsed(Record[NextIndex++]);
  1224. MI->setUsedForHeaderGuard(Record[NextIndex++]);
  1225. if (RecType == PP_MACRO_FUNCTION_LIKE) {
  1226. // Decode function-like macro info.
  1227. bool isC99VarArgs = Record[NextIndex++];
  1228. bool isGNUVarArgs = Record[NextIndex++];
  1229. bool hasCommaPasting = Record[NextIndex++];
  1230. MacroArgs.clear();
  1231. unsigned NumArgs = Record[NextIndex++];
  1232. for (unsigned i = 0; i != NumArgs; ++i)
  1233. MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
  1234. // Install function-like macro info.
  1235. MI->setIsFunctionLike();
  1236. if (isC99VarArgs) MI->setIsC99Varargs();
  1237. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1238. if (hasCommaPasting) MI->setHasCommaPasting();
  1239. MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
  1240. PP.getPreprocessorAllocator());
  1241. }
  1242. // Remember that we saw this macro last so that we add the tokens that
  1243. // form its body to it.
  1244. Macro = MI;
  1245. if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
  1246. Record[NextIndex]) {
  1247. // We have a macro definition. Register the association
  1248. PreprocessedEntityID
  1249. GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
  1250. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  1251. PreprocessingRecord::PPEntityID
  1252. PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
  1253. MacroDefinition *PPDef =
  1254. cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
  1255. if (PPDef)
  1256. PPRec.RegisterMacroDefinition(Macro, PPDef);
  1257. }
  1258. ++NumMacrosRead;
  1259. break;
  1260. }
  1261. case PP_TOKEN: {
  1262. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1263. // erroneous, just pretend we didn't see this.
  1264. if (!Macro) break;
  1265. unsigned Idx = 0;
  1266. Token Tok = ReadToken(F, Record, Idx);
  1267. Macro->AddTokenToBody(Tok);
  1268. break;
  1269. }
  1270. }
  1271. }
  1272. }
  1273. PreprocessedEntityID
  1274. ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
  1275. ContinuousRangeMap<uint32_t, int, 2>::const_iterator
  1276. I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
  1277. assert(I != M.PreprocessedEntityRemap.end()
  1278. && "Invalid index into preprocessed entity index remap");
  1279. return LocalID + I->second;
  1280. }
  1281. unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
  1282. return llvm::hash_combine(ikey.Size, ikey.ModTime);
  1283. }
  1284. HeaderFileInfoTrait::internal_key_type
  1285. HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
  1286. internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
  1287. FE->getName() };
  1288. return ikey;
  1289. }
  1290. bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
  1291. if (a.Size != b.Size || a.ModTime != b.ModTime)
  1292. return false;
  1293. if (strcmp(a.Filename, b.Filename) == 0)
  1294. return true;
  1295. // Determine whether the actual files are equivalent.
  1296. FileManager &FileMgr = Reader.getFileManager();
  1297. const FileEntry *FEA = FileMgr.getFile(a.Filename);
  1298. const FileEntry *FEB = FileMgr.getFile(b.Filename);
  1299. return (FEA && FEA == FEB);
  1300. }
  1301. std::pair<unsigned, unsigned>
  1302. HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
  1303. using namespace llvm::support;
  1304. unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
  1305. unsigned DataLen = (unsigned) *d++;
  1306. return std::make_pair(KeyLen, DataLen);
  1307. }
  1308. HeaderFileInfoTrait::internal_key_type
  1309. HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
  1310. using namespace llvm::support;
  1311. internal_key_type ikey;
  1312. ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
  1313. ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
  1314. ikey.Filename = (const char *)d;
  1315. return ikey;
  1316. }
  1317. HeaderFileInfoTrait::data_type
  1318. HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
  1319. unsigned DataLen) {
  1320. const unsigned char *End = d + DataLen;
  1321. using namespace llvm::support;
  1322. HeaderFileInfo HFI;
  1323. unsigned Flags = *d++;
  1324. HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
  1325. ((Flags >> 6) & 0x03);
  1326. HFI.isImport = (Flags >> 5) & 0x01;
  1327. HFI.isPragmaOnce = (Flags >> 4) & 0x01;
  1328. HFI.DirInfo = (Flags >> 2) & 0x03;
  1329. HFI.Resolved = (Flags >> 1) & 0x01;
  1330. HFI.IndexHeaderMapHeader = Flags & 0x01;
  1331. HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
  1332. HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
  1333. M, endian::readNext<uint32_t, little, unaligned>(d));
  1334. if (unsigned FrameworkOffset =
  1335. endian::readNext<uint32_t, little, unaligned>(d)) {
  1336. // The framework offset is 1 greater than the actual offset,
  1337. // since 0 is used as an indicator for "no framework name".
  1338. StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
  1339. HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
  1340. }
  1341. if (d != End) {
  1342. uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
  1343. if (LocalSMID) {
  1344. // This header is part of a module. Associate it with the module to enable
  1345. // implicit module import.
  1346. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
  1347. Module *Mod = Reader.getSubmodule(GlobalSMID);
  1348. HFI.isModuleHeader = true;
  1349. FileManager &FileMgr = Reader.getFileManager();
  1350. ModuleMap &ModMap =
  1351. Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1352. ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
  1353. }
  1354. }
  1355. assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
  1356. (void)End;
  1357. // This HeaderFileInfo was externally loaded.
  1358. HFI.External = true;
  1359. return HFI;
  1360. }
  1361. void
  1362. ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
  1363. GlobalMacroID GMacID,
  1364. ArrayRef<SubmoduleID> Overrides) {
  1365. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1366. SubmoduleID *OverrideData = nullptr;
  1367. if (!Overrides.empty()) {
  1368. OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
  1369. OverrideData[0] = Overrides.size();
  1370. for (unsigned I = 0; I != Overrides.size(); ++I)
  1371. OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
  1372. }
  1373. PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
  1374. }
  1375. void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
  1376. ModuleFile *M,
  1377. uint64_t MacroDirectivesOffset) {
  1378. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1379. PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
  1380. }
  1381. void ASTReader::ReadDefinedMacros() {
  1382. // Note that we are loading defined macros.
  1383. Deserializing Macros(this);
  1384. for (ModuleReverseIterator I = ModuleMgr.rbegin(),
  1385. E = ModuleMgr.rend(); I != E; ++I) {
  1386. BitstreamCursor &MacroCursor = (*I)->MacroCursor;
  1387. // If there was no preprocessor block, skip this file.
  1388. if (!MacroCursor.getBitStreamReader())
  1389. continue;
  1390. BitstreamCursor Cursor = MacroCursor;
  1391. Cursor.JumpToBit((*I)->MacroStartOffset);
  1392. RecordData Record;
  1393. while (true) {
  1394. llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
  1395. switch (E.Kind) {
  1396. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1397. case llvm::BitstreamEntry::Error:
  1398. Error("malformed block record in AST file");
  1399. return;
  1400. case llvm::BitstreamEntry::EndBlock:
  1401. goto NextCursor;
  1402. case llvm::BitstreamEntry::Record:
  1403. Record.clear();
  1404. switch (Cursor.readRecord(E.ID, Record)) {
  1405. default: // Default behavior: ignore.
  1406. break;
  1407. case PP_MACRO_OBJECT_LIKE:
  1408. case PP_MACRO_FUNCTION_LIKE:
  1409. getLocalIdentifier(**I, Record[0]);
  1410. break;
  1411. case PP_TOKEN:
  1412. // Ignore tokens.
  1413. break;
  1414. }
  1415. break;
  1416. }
  1417. }
  1418. NextCursor: ;
  1419. }
  1420. }
  1421. namespace {
  1422. /// \brief Visitor class used to look up identifirs in an AST file.
  1423. class IdentifierLookupVisitor {
  1424. StringRef Name;
  1425. unsigned PriorGeneration;
  1426. unsigned &NumIdentifierLookups;
  1427. unsigned &NumIdentifierLookupHits;
  1428. IdentifierInfo *Found;
  1429. public:
  1430. IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
  1431. unsigned &NumIdentifierLookups,
  1432. unsigned &NumIdentifierLookupHits)
  1433. : Name(Name), PriorGeneration(PriorGeneration),
  1434. NumIdentifierLookups(NumIdentifierLookups),
  1435. NumIdentifierLookupHits(NumIdentifierLookupHits),
  1436. Found()
  1437. {
  1438. }
  1439. static bool visit(ModuleFile &M, void *UserData) {
  1440. IdentifierLookupVisitor *This
  1441. = static_cast<IdentifierLookupVisitor *>(UserData);
  1442. // If we've already searched this module file, skip it now.
  1443. if (M.Generation <= This->PriorGeneration)
  1444. return true;
  1445. ASTIdentifierLookupTable *IdTable
  1446. = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
  1447. if (!IdTable)
  1448. return false;
  1449. ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
  1450. M, This->Found);
  1451. ++This->NumIdentifierLookups;
  1452. ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
  1453. if (Pos == IdTable->end())
  1454. return false;
  1455. // Dereferencing the iterator has the effect of building the
  1456. // IdentifierInfo node and populating it with the various
  1457. // declarations it needs.
  1458. ++This->NumIdentifierLookupHits;
  1459. This->Found = *Pos;
  1460. return true;
  1461. }
  1462. // \brief Retrieve the identifier info found within the module
  1463. // files.
  1464. IdentifierInfo *getIdentifierInfo() const { return Found; }
  1465. };
  1466. }
  1467. void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
  1468. // Note that we are loading an identifier.
  1469. Deserializing AnIdentifier(this);
  1470. unsigned PriorGeneration = 0;
  1471. if (getContext().getLangOpts().Modules)
  1472. PriorGeneration = IdentifierGeneration[&II];
  1473. // If there is a global index, look there first to determine which modules
  1474. // provably do not have any results for this identifier.
  1475. GlobalModuleIndex::HitSet Hits;
  1476. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  1477. if (!loadGlobalIndex()) {
  1478. if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
  1479. HitsPtr = &Hits;
  1480. }
  1481. }
  1482. IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
  1483. NumIdentifierLookups,
  1484. NumIdentifierLookupHits);
  1485. ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
  1486. markIdentifierUpToDate(&II);
  1487. }
  1488. void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
  1489. if (!II)
  1490. return;
  1491. II->setOutOfDate(false);
  1492. // Update the generation for this identifier.
  1493. if (getContext().getLangOpts().Modules)
  1494. IdentifierGeneration[II] = getGeneration();
  1495. }
  1496. struct ASTReader::ModuleMacroInfo {
  1497. SubmoduleID SubModID;
  1498. MacroInfo *MI;
  1499. SubmoduleID *Overrides;
  1500. // FIXME: Remove this.
  1501. ModuleFile *F;
  1502. bool isDefine() const { return MI; }
  1503. SubmoduleID getSubmoduleID() const { return SubModID; }
  1504. ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
  1505. if (!Overrides)
  1506. return None;
  1507. return llvm::makeArrayRef(Overrides + 1, *Overrides);
  1508. }
  1509. MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
  1510. if (!MI)
  1511. return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
  1512. getOverriddenSubmodules());
  1513. return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
  1514. getOverriddenSubmodules());
  1515. }
  1516. };
  1517. ASTReader::ModuleMacroInfo *
  1518. ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
  1519. ModuleMacroInfo Info;
  1520. uint32_t ID = PMInfo.ModuleMacroData.MacID;
  1521. if (ID & 1) {
  1522. // Macro undefinition.
  1523. Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
  1524. Info.MI = nullptr;
  1525. } else {
  1526. // Macro definition.
  1527. GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
  1528. assert(GMacID);
  1529. // If this macro has already been loaded, don't do so again.
  1530. // FIXME: This is highly dubious. Multiple macro definitions can have the
  1531. // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
  1532. if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
  1533. return nullptr;
  1534. Info.MI = getMacro(GMacID);
  1535. Info.SubModID = Info.MI->getOwningModuleID();
  1536. }
  1537. Info.Overrides = PMInfo.ModuleMacroData.Overrides;
  1538. Info.F = PMInfo.M;
  1539. return new (Context) ModuleMacroInfo(Info);
  1540. }
  1541. void ASTReader::resolvePendingMacro(IdentifierInfo *II,
  1542. const PendingMacroInfo &PMInfo) {
  1543. assert(II);
  1544. if (PMInfo.M->Kind != MK_Module) {
  1545. installPCHMacroDirectives(II, *PMInfo.M,
  1546. PMInfo.PCHMacroData.MacroDirectivesOffset);
  1547. return;
  1548. }
  1549. // Module Macro.
  1550. ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
  1551. if (!MMI)
  1552. return;
  1553. Module *Owner = getSubmodule(MMI->getSubmoduleID());
  1554. if (Owner && Owner->NameVisibility == Module::Hidden) {
  1555. // Macros in the owning module are hidden. Just remember this macro to
  1556. // install if we make this module visible.
  1557. HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
  1558. } else {
  1559. installImportedMacro(II, MMI, Owner);
  1560. }
  1561. }
  1562. void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
  1563. ModuleFile &M, uint64_t Offset) {
  1564. assert(M.Kind != MK_Module);
  1565. BitstreamCursor &Cursor = M.MacroCursor;
  1566. SavedStreamPosition SavedPosition(Cursor);
  1567. Cursor.JumpToBit(Offset);
  1568. llvm::BitstreamEntry Entry =
  1569. Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  1570. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1571. Error("malformed block record in AST file");
  1572. return;
  1573. }
  1574. RecordData Record;
  1575. PreprocessorRecordTypes RecType =
  1576. (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
  1577. if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
  1578. Error("malformed block record in AST file");
  1579. return;
  1580. }
  1581. // Deserialize the macro directives history in reverse source-order.
  1582. MacroDirective *Latest = nullptr, *Earliest = nullptr;
  1583. unsigned Idx = 0, N = Record.size();
  1584. while (Idx < N) {
  1585. MacroDirective *MD = nullptr;
  1586. SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
  1587. MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
  1588. switch (K) {
  1589. case MacroDirective::MD_Define: {
  1590. GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
  1591. MacroInfo *MI = getMacro(GMacID);
  1592. SubmoduleID ImportedFrom = Record[Idx++];
  1593. bool IsAmbiguous = Record[Idx++];
  1594. llvm::SmallVector<unsigned, 4> Overrides;
  1595. if (ImportedFrom) {
  1596. Overrides.insert(Overrides.end(),
  1597. &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
  1598. Idx += Overrides.size() + 1;
  1599. }
  1600. DefMacroDirective *DefMD =
  1601. PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
  1602. DefMD->setAmbiguous(IsAmbiguous);
  1603. MD = DefMD;
  1604. break;
  1605. }
  1606. case MacroDirective::MD_Undefine: {
  1607. SubmoduleID ImportedFrom = Record[Idx++];
  1608. llvm::SmallVector<unsigned, 4> Overrides;
  1609. if (ImportedFrom) {
  1610. Overrides.insert(Overrides.end(),
  1611. &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
  1612. Idx += Overrides.size() + 1;
  1613. }
  1614. MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
  1615. break;
  1616. }
  1617. case MacroDirective::MD_Visibility:
  1618. bool isPublic = Record[Idx++];
  1619. MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
  1620. break;
  1621. }
  1622. if (!Latest)
  1623. Latest = MD;
  1624. if (Earliest)
  1625. Earliest->setPrevious(MD);
  1626. Earliest = MD;
  1627. }
  1628. PP.setLoadedMacroDirective(II, Latest);
  1629. }
  1630. /// \brief For the given macro definitions, check if they are both in system
  1631. /// modules.
  1632. static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
  1633. Module *NewOwner, ASTReader &Reader) {
  1634. assert(PrevMI && NewMI);
  1635. Module *PrevOwner = nullptr;
  1636. if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
  1637. PrevOwner = Reader.getSubmodule(PrevModID);
  1638. SourceManager &SrcMgr = Reader.getSourceManager();
  1639. bool PrevInSystem
  1640. = PrevOwner? PrevOwner->IsSystem
  1641. : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
  1642. bool NewInSystem
  1643. = NewOwner? NewOwner->IsSystem
  1644. : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
  1645. if (PrevOwner && PrevOwner == NewOwner)
  1646. return false;
  1647. return PrevInSystem && NewInSystem;
  1648. }
  1649. void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
  1650. SourceLocation ImportLoc,
  1651. AmbiguousMacros &Ambig,
  1652. ArrayRef<SubmoduleID> Overrides) {
  1653. for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
  1654. SubmoduleID OwnerID = Overrides[OI];
  1655. // If this macro is not yet visible, remove it from the hidden names list.
  1656. // It won't be there if we're in the middle of making the owner visible.
  1657. Module *Owner = getSubmodule(OwnerID);
  1658. auto HiddenIt = HiddenNamesMap.find(Owner);
  1659. if (HiddenIt != HiddenNamesMap.end()) {
  1660. HiddenNames &Hidden = HiddenIt->second;
  1661. HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
  1662. if (HI != Hidden.HiddenMacros.end()) {
  1663. // Register the macro now so we don't lose it when we re-export.
  1664. PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
  1665. auto SubOverrides = HI->second->getOverriddenSubmodules();
  1666. Hidden.HiddenMacros.erase(HI);
  1667. removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
  1668. }
  1669. }
  1670. // If this macro is already in our list of conflicts, remove it from there.
  1671. Ambig.erase(
  1672. std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
  1673. return MD->getInfo()->getOwningModuleID() == OwnerID;
  1674. }),
  1675. Ambig.end());
  1676. }
  1677. }
  1678. ASTReader::AmbiguousMacros *
  1679. ASTReader::removeOverriddenMacros(IdentifierInfo *II,
  1680. SourceLocation ImportLoc,
  1681. ArrayRef<SubmoduleID> Overrides) {
  1682. MacroDirective *Prev = PP.getMacroDirective(II);
  1683. if (!Prev && Overrides.empty())
  1684. return nullptr;
  1685. DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
  1686. : nullptr;
  1687. if (PrevDef && PrevDef->isAmbiguous()) {
  1688. // We had a prior ambiguity. Check whether we resolve it (or make it worse).
  1689. AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
  1690. Ambig.push_back(PrevDef);
  1691. removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
  1692. if (!Ambig.empty())
  1693. return &Ambig;
  1694. AmbiguousMacroDefs.erase(II);
  1695. } else {
  1696. // There's no ambiguity yet. Maybe we're introducing one.
  1697. AmbiguousMacros Ambig;
  1698. if (PrevDef)
  1699. Ambig.push_back(PrevDef);
  1700. removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
  1701. if (!Ambig.empty()) {
  1702. AmbiguousMacros &Result = AmbiguousMacroDefs[II];
  1703. std::swap(Result, Ambig);
  1704. return &Result;
  1705. }
  1706. }
  1707. // We ended up with no ambiguity.
  1708. return nullptr;
  1709. }
  1710. void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
  1711. Module *Owner) {
  1712. assert(II && Owner);
  1713. SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
  1714. if (ImportLoc.isInvalid()) {
  1715. // FIXME: If we made macros from this module visible but didn't provide a
  1716. // source location for the import, we don't have a location for the macro.
  1717. // Use the location at which the containing module file was first imported
  1718. // for now.
  1719. ImportLoc = MMI->F->DirectImportLoc;
  1720. assert(ImportLoc.isValid() && "no import location for a visible macro?");
  1721. }
  1722. AmbiguousMacros *Prev =
  1723. removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
  1724. // Create a synthetic macro definition corresponding to the import (or null
  1725. // if this was an undefinition of the macro).
  1726. MacroDirective *Imported = MMI->import(PP, ImportLoc);
  1727. DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
  1728. // If there's no ambiguity, just install the macro.
  1729. if (!Prev) {
  1730. PP.appendMacroDirective(II, Imported);
  1731. return;
  1732. }
  1733. assert(!Prev->empty());
  1734. if (!MD) {
  1735. // We imported a #undef that didn't remove all prior definitions. The most
  1736. // recent prior definition remains, and we install it in the place of the
  1737. // imported directive, as if by a local #pragma pop_macro.
  1738. MacroInfo *NewMI = Prev->back()->getInfo();
  1739. Prev->pop_back();
  1740. MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
  1741. // Install our #undef first so that we don't lose track of it. We'll replace
  1742. // this with whichever macro definition ends up winning.
  1743. PP.appendMacroDirective(II, Imported);
  1744. }
  1745. // We're introducing a macro definition that creates or adds to an ambiguity.
  1746. // We can resolve that ambiguity if this macro is token-for-token identical to
  1747. // all of the existing definitions.
  1748. MacroInfo *NewMI = MD->getInfo();
  1749. assert(NewMI && "macro definition with no MacroInfo?");
  1750. while (!Prev->empty()) {
  1751. MacroInfo *PrevMI = Prev->back()->getInfo();
  1752. assert(PrevMI && "macro definition with no MacroInfo?");
  1753. // Before marking the macros as ambiguous, check if this is a case where
  1754. // both macros are in system headers. If so, we trust that the system
  1755. // did not get it wrong. This also handles cases where Clang's own
  1756. // headers have a different spelling of certain system macros:
  1757. // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
  1758. // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
  1759. //
  1760. // FIXME: Remove the defined-in-system-headers check. clang's limits.h
  1761. // overrides the system limits.h's macros, so there's no conflict here.
  1762. if (NewMI != PrevMI &&
  1763. !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
  1764. !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
  1765. break;
  1766. // The previous definition is the same as this one (or both are defined in
  1767. // system modules so we can assume they're equivalent); we don't need to
  1768. // track it any more.
  1769. Prev->pop_back();
  1770. }
  1771. if (!Prev->empty())
  1772. MD->setAmbiguous(true);
  1773. PP.appendMacroDirective(II, MD);
  1774. }
  1775. ASTReader::InputFileInfo
  1776. ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
  1777. // Go find this input file.
  1778. BitstreamCursor &Cursor = F.InputFilesCursor;
  1779. SavedStreamPosition SavedPosition(Cursor);
  1780. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1781. unsigned Code = Cursor.ReadCode();
  1782. RecordData Record;
  1783. StringRef Blob;
  1784. unsigned Result = Cursor.readRecord(Code, Record, &Blob);
  1785. assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
  1786. "invalid record type for input file");
  1787. (void)Result;
  1788. std::string Filename;
  1789. off_t StoredSize;
  1790. time_t StoredTime;
  1791. bool Overridden;
  1792. assert(Record[0] == ID && "Bogus stored ID or offset");
  1793. StoredSize = static_cast<off_t>(Record[1]);
  1794. StoredTime = static_cast<time_t>(Record[2]);
  1795. Overridden = static_cast<bool>(Record[3]);
  1796. Filename = Blob;
  1797. MaybeAddSystemRootToFilename(F, Filename);
  1798. InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
  1799. return R;
  1800. }
  1801. std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
  1802. return readInputFileInfo(F, ID).Filename;
  1803. }
  1804. InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
  1805. // If this ID is bogus, just return an empty input file.
  1806. if (ID == 0 || ID > F.InputFilesLoaded.size())
  1807. return InputFile();
  1808. // If we've already loaded this input file, return it.
  1809. if (F.InputFilesLoaded[ID-1].getFile())
  1810. return F.InputFilesLoaded[ID-1];
  1811. if (F.InputFilesLoaded[ID-1].isNotFound())
  1812. return InputFile();
  1813. // Go find this input file.
  1814. BitstreamCursor &Cursor = F.InputFilesCursor;
  1815. SavedStreamPosition SavedPosition(Cursor);
  1816. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1817. InputFileInfo FI = readInputFileInfo(F, ID);
  1818. off_t StoredSize = FI.StoredSize;
  1819. time_t StoredTime = FI.StoredTime;
  1820. bool Overridden = FI.Overridden;
  1821. StringRef Filename = FI.Filename;
  1822. const FileEntry *File
  1823. = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
  1824. : FileMgr.getFile(Filename, /*OpenFile=*/false);
  1825. // If we didn't find the file, resolve it relative to the
  1826. // original directory from which this AST file was created.
  1827. if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
  1828. F.OriginalDir != CurrentDir) {
  1829. std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
  1830. F.OriginalDir,
  1831. CurrentDir);
  1832. if (!Resolved.empty())
  1833. File = FileMgr.getFile(Resolved);
  1834. }
  1835. // For an overridden file, create a virtual file with the stored
  1836. // size/timestamp.
  1837. if (Overridden && File == nullptr) {
  1838. File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
  1839. }
  1840. if (File == nullptr) {
  1841. if (Complain) {
  1842. std::string ErrorStr = "could not find file '";
  1843. ErrorStr += Filename;
  1844. ErrorStr += "' referenced by AST file";
  1845. Error(ErrorStr.c_str());
  1846. }
  1847. // Record that we didn't find the file.
  1848. F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
  1849. return InputFile();
  1850. }
  1851. // Check if there was a request to override the contents of the file
  1852. // that was part of the precompiled header. Overridding such a file
  1853. // can lead to problems when lexing using the source locations from the
  1854. // PCH.
  1855. SourceManager &SM = getSourceManager();
  1856. if (!Overridden && SM.isFileOverridden(File)) {
  1857. if (Complain)
  1858. Error(diag::err_fe_pch_file_overridden, Filename);
  1859. // After emitting the diagnostic, recover by disabling the override so
  1860. // that the original file will be used.
  1861. SM.disableFileContentsOverride(File);
  1862. // The FileEntry is a virtual file entry with the size of the contents
  1863. // that would override the original contents. Set it to the original's
  1864. // size/time.
  1865. FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
  1866. StoredSize, StoredTime);
  1867. }
  1868. bool IsOutOfDate = false;
  1869. // For an overridden file, there is nothing to validate.
  1870. if (!Overridden && (StoredSize != File->getSize()
  1871. #if !defined(LLVM_ON_WIN32)
  1872. // In our regression testing, the Windows file system seems to
  1873. // have inconsistent modification times that sometimes
  1874. // erroneously trigger this error-handling path.
  1875. || StoredTime != File->getModificationTime()
  1876. #endif
  1877. )) {
  1878. if (Complain) {
  1879. // Build a list of the PCH imports that got us here (in reverse).
  1880. SmallVector<ModuleFile *, 4> ImportStack(1, &F);
  1881. while (ImportStack.back()->ImportedBy.size() > 0)
  1882. ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
  1883. // The top-level PCH is stale.
  1884. StringRef TopLevelPCHName(ImportStack.back()->FileName);
  1885. Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
  1886. // Print the import stack.
  1887. if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
  1888. Diag(diag::note_pch_required_by)
  1889. << Filename << ImportStack[0]->FileName;
  1890. for (unsigned I = 1; I < ImportStack.size(); ++I)
  1891. Diag(diag::note_pch_required_by)
  1892. << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
  1893. }
  1894. if (!Diags.isDiagnosticInFlight())
  1895. Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
  1896. }
  1897. IsOutOfDate = true;
  1898. }
  1899. InputFile IF = InputFile(File, Overridden, IsOutOfDate);
  1900. // Note that we've loaded this input file.
  1901. F.InputFilesLoaded[ID-1] = IF;
  1902. return IF;
  1903. }
  1904. const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
  1905. ModuleFile &M = ModuleMgr.getPrimaryModule();
  1906. std::string Filename = filenameStrRef;
  1907. MaybeAddSystemRootToFilename(M, Filename);
  1908. const FileEntry *File = FileMgr.getFile(Filename);
  1909. if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
  1910. M.OriginalDir != CurrentDir) {
  1911. std::string resolved = resolveFileRelativeToOriginalDir(Filename,
  1912. M.OriginalDir,
  1913. CurrentDir);
  1914. if (!resolved.empty())
  1915. File = FileMgr.getFile(resolved);
  1916. }
  1917. return File;
  1918. }
  1919. /// \brief If we are loading a relocatable PCH file, and the filename is
  1920. /// not an absolute path, add the system root to the beginning of the file
  1921. /// name.
  1922. void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
  1923. std::string &Filename) {
  1924. // If this is not a relocatable PCH file, there's nothing to do.
  1925. if (!M.RelocatablePCH)
  1926. return;
  1927. if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
  1928. return;
  1929. if (isysroot.empty()) {
  1930. // If no system root was given, default to '/'
  1931. Filename.insert(Filename.begin(), '/');
  1932. return;
  1933. }
  1934. unsigned Length = isysroot.size();
  1935. if (isysroot[Length - 1] != '/')
  1936. Filename.insert(Filename.begin(), '/');
  1937. Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
  1938. }
  1939. ASTReader::ASTReadResult
  1940. ASTReader::ReadControlBlock(ModuleFile &F,
  1941. SmallVectorImpl<ImportedModule> &Loaded,
  1942. const ModuleFile *ImportedBy,
  1943. unsigned ClientLoadCapabilities) {
  1944. BitstreamCursor &Stream = F.Stream;
  1945. if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
  1946. Error("malformed block record in AST file");
  1947. return Failure;
  1948. }
  1949. // Read all of the records and blocks in the control block.
  1950. RecordData Record;
  1951. while (1) {
  1952. llvm::BitstreamEntry Entry = Stream.advance();
  1953. switch (Entry.Kind) {
  1954. case llvm::BitstreamEntry::Error:
  1955. Error("malformed block record in AST file");
  1956. return Failure;
  1957. case llvm::BitstreamEntry::EndBlock: {
  1958. // Validate input files.
  1959. const HeaderSearchOptions &HSOpts =
  1960. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  1961. // All user input files reside at the index range [0, Record[1]), and
  1962. // system input files reside at [Record[1], Record[0]).
  1963. // Record is the one from INPUT_FILE_OFFSETS.
  1964. unsigned NumInputs = Record[0];
  1965. unsigned NumUserInputs = Record[1];
  1966. if (!DisableValidation &&
  1967. (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
  1968. F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
  1969. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  1970. // If we are reading a module, we will create a verification timestamp,
  1971. // so we verify all input files. Otherwise, verify only user input
  1972. // files.
  1973. unsigned N = NumUserInputs;
  1974. if (ValidateSystemInputs ||
  1975. (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
  1976. N = NumInputs;
  1977. for (unsigned I = 0; I < N; ++I) {
  1978. InputFile IF = getInputFile(F, I+1, Complain);
  1979. if (!IF.getFile() || IF.isOutOfDate())
  1980. return OutOfDate;
  1981. }
  1982. }
  1983. if (Listener)
  1984. Listener->visitModuleFile(F.FileName);
  1985. if (Listener && Listener->needsInputFileVisitation()) {
  1986. unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
  1987. : NumUserInputs;
  1988. for (unsigned I = 0; I < N; ++I) {
  1989. bool IsSystem = I >= NumUserInputs;
  1990. InputFileInfo FI = readInputFileInfo(F, I+1);
  1991. Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
  1992. }
  1993. }
  1994. return Success;
  1995. }
  1996. case llvm::BitstreamEntry::SubBlock:
  1997. switch (Entry.ID) {
  1998. case INPUT_FILES_BLOCK_ID:
  1999. F.InputFilesCursor = Stream;
  2000. if (Stream.SkipBlock() || // Skip with the main cursor
  2001. // Read the abbreviations
  2002. ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
  2003. Error("malformed block record in AST file");
  2004. return Failure;
  2005. }
  2006. continue;
  2007. default:
  2008. if (Stream.SkipBlock()) {
  2009. Error("malformed block record in AST file");
  2010. return Failure;
  2011. }
  2012. continue;
  2013. }
  2014. case llvm::BitstreamEntry::Record:
  2015. // The interesting case.
  2016. break;
  2017. }
  2018. // Read and process a record.
  2019. Record.clear();
  2020. StringRef Blob;
  2021. switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
  2022. case METADATA: {
  2023. if (Record[0] != VERSION_MAJOR && !DisableValidation) {
  2024. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2025. Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
  2026. : diag::err_pch_version_too_new);
  2027. return VersionMismatch;
  2028. }
  2029. bool hasErrors = Record[5];
  2030. if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
  2031. Diag(diag::err_pch_with_compiler_errors);
  2032. return HadErrors;
  2033. }
  2034. F.RelocatablePCH = Record[4];
  2035. const std::string &CurBranch = getClangFullRepositoryVersion();
  2036. StringRef ASTBranch = Blob;
  2037. if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
  2038. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2039. Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
  2040. return VersionMismatch;
  2041. }
  2042. break;
  2043. }
  2044. case IMPORTS: {
  2045. // Load each of the imported PCH files.
  2046. unsigned Idx = 0, N = Record.size();
  2047. while (Idx < N) {
  2048. // Read information about the AST file.
  2049. ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
  2050. // The import location will be the local one for now; we will adjust
  2051. // all import locations of module imports after the global source
  2052. // location info are setup.
  2053. SourceLocation ImportLoc =
  2054. SourceLocation::getFromRawEncoding(Record[Idx++]);
  2055. off_t StoredSize = (off_t)Record[Idx++];
  2056. time_t StoredModTime = (time_t)Record[Idx++];
  2057. unsigned Length = Record[Idx++];
  2058. SmallString<128> ImportedFile(Record.begin() + Idx,
  2059. Record.begin() + Idx + Length);
  2060. Idx += Length;
  2061. // Load the AST file.
  2062. switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
  2063. StoredSize, StoredModTime,
  2064. ClientLoadCapabilities)) {
  2065. case Failure: return Failure;
  2066. // If we have to ignore the dependency, we'll have to ignore this too.
  2067. case Missing:
  2068. case OutOfDate: return OutOfDate;
  2069. case VersionMismatch: return VersionMismatch;
  2070. case ConfigurationMismatch: return ConfigurationMismatch;
  2071. case HadErrors: return HadErrors;
  2072. case Success: break;
  2073. }
  2074. }
  2075. break;
  2076. }
  2077. case LANGUAGE_OPTIONS: {
  2078. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2079. if (Listener && &F == *ModuleMgr.begin() &&
  2080. ParseLanguageOptions(Record, Complain, *Listener) &&
  2081. !DisableValidation && !AllowConfigurationMismatch)
  2082. return ConfigurationMismatch;
  2083. break;
  2084. }
  2085. case TARGET_OPTIONS: {
  2086. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  2087. if (Listener && &F == *ModuleMgr.begin() &&
  2088. ParseTargetOptions(Record, Complain, *Listener) &&
  2089. !DisableValidation && !AllowConfigurationMismatch)
  2090. return ConfigurationMismatch;
  2091. break;
  2092. }
  2093. case DIAGNOSTIC_OPTIONS: {
  2094. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
  2095. if (Listener && &F == *ModuleMgr.begin() &&
  2096. ParseDiagnosticOptions(Record, Complain, *Listener) &&
  2097. !DisableValidation)
  2098. return OutOfDate;
  2099. break;
  2100. }
  2101. case FILE_SYSTEM_OPTIONS: {
  2102. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  2103. if (Listener && &F == *ModuleMgr.begin() &&
  2104. ParseFileSystemOptions(Record, Complain, *Listener) &&
  2105. !DisableValidation && !AllowConfigurationMismatch)
  2106. return ConfigurationMismatch;
  2107. break;
  2108. }
  2109. case HEADER_SEARCH_OPTIONS: {
  2110. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  2111. if (Listener && &F == *ModuleMgr.begin() &&
  2112. ParseHeaderSearchOptions(Record, Complain, *Listener) &&
  2113. !DisableValidation && !AllowConfigurationMismatch)
  2114. return ConfigurationMismatch;
  2115. break;
  2116. }
  2117. case PREPROCESSOR_OPTIONS: {
  2118. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  2119. if (Listener && &F == *ModuleMgr.begin() &&
  2120. ParsePreprocessorOptions(Record, Complain, *Listener,
  2121. SuggestedPredefines) &&
  2122. !DisableValidation && !AllowConfigurationMismatch)
  2123. return ConfigurationMismatch;
  2124. break;
  2125. }
  2126. case ORIGINAL_FILE:
  2127. F.OriginalSourceFileID = FileID::get(Record[0]);
  2128. F.ActualOriginalSourceFileName = Blob;
  2129. F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
  2130. MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
  2131. break;
  2132. case ORIGINAL_FILE_ID:
  2133. F.OriginalSourceFileID = FileID::get(Record[0]);
  2134. break;
  2135. case ORIGINAL_PCH_DIR:
  2136. F.OriginalDir = Blob;
  2137. break;
  2138. case MODULE_NAME:
  2139. F.ModuleName = Blob;
  2140. if (Listener)
  2141. Listener->ReadModuleName(F.ModuleName);
  2142. break;
  2143. case MODULE_MAP_FILE:
  2144. if (ASTReadResult Result =
  2145. ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
  2146. return Result;
  2147. case INPUT_FILE_OFFSETS:
  2148. F.InputFileOffsets = (const uint32_t *)Blob.data();
  2149. F.InputFilesLoaded.resize(Record[0]);
  2150. break;
  2151. }
  2152. }
  2153. }
  2154. ASTReader::ASTReadResult
  2155. ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  2156. BitstreamCursor &Stream = F.Stream;
  2157. if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
  2158. Error("malformed block record in AST file");
  2159. return Failure;
  2160. }
  2161. // Read all of the records and blocks for the AST file.
  2162. RecordData Record;
  2163. while (1) {
  2164. llvm::BitstreamEntry Entry = Stream.advance();
  2165. switch (Entry.Kind) {
  2166. case llvm::BitstreamEntry::Error:
  2167. Error("error at end of module block in AST file");
  2168. return Failure;
  2169. case llvm::BitstreamEntry::EndBlock: {
  2170. // Outside of C++, we do not store a lookup map for the translation unit.
  2171. // Instead, mark it as needing a lookup map to be built if this module
  2172. // contains any declarations lexically within it (which it always does!).
  2173. // This usually has no cost, since we very rarely need the lookup map for
  2174. // the translation unit outside C++.
  2175. DeclContext *DC = Context.getTranslationUnitDecl();
  2176. if (DC->hasExternalLexicalStorage() &&
  2177. !getContext().getLangOpts().CPlusPlus)
  2178. DC->setMustBuildLookupTable();
  2179. return Success;
  2180. }
  2181. case llvm::BitstreamEntry::SubBlock:
  2182. switch (Entry.ID) {
  2183. case DECLTYPES_BLOCK_ID:
  2184. // We lazily load the decls block, but we want to set up the
  2185. // DeclsCursor cursor to point into it. Clone our current bitcode
  2186. // cursor to it, enter the block and read the abbrevs in that block.
  2187. // With the main cursor, we just skip over it.
  2188. F.DeclsCursor = Stream;
  2189. if (Stream.SkipBlock() || // Skip with the main cursor.
  2190. // Read the abbrevs.
  2191. ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
  2192. Error("malformed block record in AST file");
  2193. return Failure;
  2194. }
  2195. break;
  2196. case PREPROCESSOR_BLOCK_ID:
  2197. F.MacroCursor = Stream;
  2198. if (!PP.getExternalSource())
  2199. PP.setExternalSource(this);
  2200. if (Stream.SkipBlock() ||
  2201. ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
  2202. Error("malformed block record in AST file");
  2203. return Failure;
  2204. }
  2205. F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
  2206. break;
  2207. case PREPROCESSOR_DETAIL_BLOCK_ID:
  2208. F.PreprocessorDetailCursor = Stream;
  2209. if (Stream.SkipBlock() ||
  2210. ReadBlockAbbrevs(F.PreprocessorDetailCursor,
  2211. PREPROCESSOR_DETAIL_BLOCK_ID)) {
  2212. Error("malformed preprocessor detail record in AST file");
  2213. return Failure;
  2214. }
  2215. F.PreprocessorDetailStartOffset
  2216. = F.PreprocessorDetailCursor.GetCurrentBitNo();
  2217. if (!PP.getPreprocessingRecord())
  2218. PP.createPreprocessingRecord();
  2219. if (!PP.getPreprocessingRecord()->getExternalSource())
  2220. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2221. break;
  2222. case SOURCE_MANAGER_BLOCK_ID:
  2223. if (ReadSourceManagerBlock(F))
  2224. return Failure;
  2225. break;
  2226. case SUBMODULE_BLOCK_ID:
  2227. if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
  2228. return Result;
  2229. break;
  2230. case COMMENTS_BLOCK_ID: {
  2231. BitstreamCursor C = Stream;
  2232. if (Stream.SkipBlock() ||
  2233. ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
  2234. Error("malformed comments block in AST file");
  2235. return Failure;
  2236. }
  2237. CommentsCursors.push_back(std::make_pair(C, &F));
  2238. break;
  2239. }
  2240. default:
  2241. if (Stream.SkipBlock()) {
  2242. Error("malformed block record in AST file");
  2243. return Failure;
  2244. }
  2245. break;
  2246. }
  2247. continue;
  2248. case llvm::BitstreamEntry::Record:
  2249. // The interesting case.
  2250. break;
  2251. }
  2252. // Read and process a record.
  2253. Record.clear();
  2254. StringRef Blob;
  2255. switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
  2256. default: // Default behavior: ignore.
  2257. break;
  2258. case TYPE_OFFSET: {
  2259. if (F.LocalNumTypes != 0) {
  2260. Error("duplicate TYPE_OFFSET record in AST file");
  2261. return Failure;
  2262. }
  2263. F.TypeOffsets = (const uint32_t *)Blob.data();
  2264. F.LocalNumTypes = Record[0];
  2265. unsigned LocalBaseTypeIndex = Record[1];
  2266. F.BaseTypeIndex = getTotalNumTypes();
  2267. if (F.LocalNumTypes > 0) {
  2268. // Introduce the global -> local mapping for types within this module.
  2269. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
  2270. // Introduce the local -> global mapping for types within this module.
  2271. F.TypeRemap.insertOrReplace(
  2272. std::make_pair(LocalBaseTypeIndex,
  2273. F.BaseTypeIndex - LocalBaseTypeIndex));
  2274. }
  2275. // Increase size by >= 1 so we get a unique base index in the next module.
  2276. TypesLoaded.resize(TypesLoaded.size() + std::max(F.LocalNumTypes, 1U));
  2277. break;
  2278. }
  2279. case DECL_OFFSET: {
  2280. if (F.LocalNumDecls != 0) {
  2281. Error("duplicate DECL_OFFSET record in AST file");
  2282. return Failure;
  2283. }
  2284. F.DeclOffsets = (const DeclOffset *)Blob.data();
  2285. F.LocalNumDecls = Record[0];
  2286. unsigned LocalBaseDeclID = Record[1];
  2287. F.BaseDeclID = getTotalNumDecls();
  2288. if (F.LocalNumDecls > 0) {
  2289. // Introduce the global -> local mapping for declarations within this
  2290. // module.
  2291. GlobalDeclMap.insert(
  2292. std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
  2293. // Introduce the local -> global mapping for declarations within this
  2294. // module.
  2295. F.DeclRemap.insertOrReplace(
  2296. std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
  2297. // Introduce the global -> local mapping for declarations within this
  2298. // module.
  2299. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
  2300. }
  2301. // Increase size by >= 1 so we get a unique base index in the next module.
  2302. DeclsLoaded.resize(DeclsLoaded.size() + std::max(F.LocalNumDecls, 1U));
  2303. break;
  2304. }
  2305. case TU_UPDATE_LEXICAL: {
  2306. DeclContext *TU = Context.getTranslationUnitDecl();
  2307. DeclContextInfo &Info = F.DeclContextInfos[TU];
  2308. Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
  2309. Info.NumLexicalDecls
  2310. = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
  2311. TU->setHasExternalLexicalStorage(true);
  2312. break;
  2313. }
  2314. case UPDATE_VISIBLE: {
  2315. unsigned Idx = 0;
  2316. serialization::DeclID ID = ReadDeclID(F, Record, Idx);
  2317. ASTDeclContextNameLookupTable *Table =
  2318. ASTDeclContextNameLookupTable::Create(
  2319. (const unsigned char *)Blob.data() + Record[Idx++],
  2320. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  2321. (const unsigned char *)Blob.data(),
  2322. ASTDeclContextNameLookupTrait(*this, F));
  2323. if (Decl *D = GetExistingDecl(ID)) {
  2324. auto *DC = cast<DeclContext>(D);
  2325. DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
  2326. auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
  2327. delete LookupTable;
  2328. LookupTable = Table;
  2329. } else
  2330. PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
  2331. break;
  2332. }
  2333. case IDENTIFIER_TABLE:
  2334. F.IdentifierTableData = Blob.data();
  2335. if (Record[0]) {
  2336. F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
  2337. (const unsigned char *)F.IdentifierTableData + Record[0],
  2338. (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
  2339. (const unsigned char *)F.IdentifierTableData,
  2340. ASTIdentifierLookupTrait(*this, F));
  2341. PP.getIdentifierTable().setExternalIdentifierLookup(this);
  2342. }
  2343. break;
  2344. case IDENTIFIER_OFFSET: {
  2345. if (F.LocalNumIdentifiers != 0) {
  2346. Error("duplicate IDENTIFIER_OFFSET record in AST file");
  2347. return Failure;
  2348. }
  2349. F.IdentifierOffsets = (const uint32_t *)Blob.data();
  2350. F.LocalNumIdentifiers = Record[0];
  2351. unsigned LocalBaseIdentifierID = Record[1];
  2352. F.BaseIdentifierID = getTotalNumIdentifiers();
  2353. if (F.LocalNumIdentifiers > 0) {
  2354. // Introduce the global -> local mapping for identifiers within this
  2355. // module.
  2356. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
  2357. &F));
  2358. // Introduce the local -> global mapping for identifiers within this
  2359. // module.
  2360. F.IdentifierRemap.insertOrReplace(
  2361. std::make_pair(LocalBaseIdentifierID,
  2362. F.BaseIdentifierID - LocalBaseIdentifierID));
  2363. }
  2364. // Increase size by >= 1 so we get a unique base index in the next module.
  2365. IdentifiersLoaded.resize(IdentifiersLoaded.size() +
  2366. std::max(F.LocalNumIdentifiers, 1U));
  2367. break;
  2368. }
  2369. case EAGERLY_DESERIALIZED_DECLS:
  2370. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2371. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2372. break;
  2373. case SPECIAL_TYPES:
  2374. if (SpecialTypes.empty()) {
  2375. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2376. SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
  2377. break;
  2378. }
  2379. if (SpecialTypes.size() != Record.size()) {
  2380. Error("invalid special-types record");
  2381. return Failure;
  2382. }
  2383. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  2384. serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
  2385. if (!SpecialTypes[I])
  2386. SpecialTypes[I] = ID;
  2387. // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
  2388. // merge step?
  2389. }
  2390. break;
  2391. case STATISTICS:
  2392. TotalNumStatements += Record[0];
  2393. TotalNumMacros += Record[1];
  2394. TotalLexicalDeclContexts += Record[2];
  2395. TotalVisibleDeclContexts += Record[3];
  2396. break;
  2397. case UNUSED_FILESCOPED_DECLS:
  2398. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2399. UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2400. break;
  2401. case DELEGATING_CTORS:
  2402. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2403. DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2404. break;
  2405. case WEAK_UNDECLARED_IDENTIFIERS:
  2406. if (Record.size() % 4 != 0) {
  2407. Error("invalid weak identifiers record");
  2408. return Failure;
  2409. }
  2410. // FIXME: Ignore weak undeclared identifiers from non-original PCH
  2411. // files. This isn't the way to do it :)
  2412. WeakUndeclaredIdentifiers.clear();
  2413. // Translate the weak, undeclared identifiers into global IDs.
  2414. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
  2415. WeakUndeclaredIdentifiers.push_back(
  2416. getGlobalIdentifierID(F, Record[I++]));
  2417. WeakUndeclaredIdentifiers.push_back(
  2418. getGlobalIdentifierID(F, Record[I++]));
  2419. WeakUndeclaredIdentifiers.push_back(
  2420. ReadSourceLocation(F, Record, I).getRawEncoding());
  2421. WeakUndeclaredIdentifiers.push_back(Record[I++]);
  2422. }
  2423. break;
  2424. case LOCALLY_SCOPED_EXTERN_C_DECLS:
  2425. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2426. LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
  2427. break;
  2428. case SELECTOR_OFFSETS: {
  2429. F.SelectorOffsets = (const uint32_t *)Blob.data();
  2430. F.LocalNumSelectors = Record[0];
  2431. unsigned LocalBaseSelectorID = Record[1];
  2432. F.BaseSelectorID = getTotalNumSelectors();
  2433. if (F.LocalNumSelectors > 0) {
  2434. // Introduce the global -> local mapping for selectors within this
  2435. // module.
  2436. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
  2437. // Introduce the local -> global mapping for selectors within this
  2438. // module.
  2439. F.SelectorRemap.insertOrReplace(
  2440. std::make_pair(LocalBaseSelectorID,
  2441. F.BaseSelectorID - LocalBaseSelectorID));
  2442. }
  2443. // Increase size by >= 1 so we get a unique base index in the next module.
  2444. SelectorsLoaded.resize(SelectorsLoaded.size() +
  2445. std::max(F.LocalNumSelectors, 1U));
  2446. break;
  2447. }
  2448. case METHOD_POOL:
  2449. F.SelectorLookupTableData = (const unsigned char *)Blob.data();
  2450. if (Record[0])
  2451. F.SelectorLookupTable
  2452. = ASTSelectorLookupTable::Create(
  2453. F.SelectorLookupTableData + Record[0],
  2454. F.SelectorLookupTableData,
  2455. ASTSelectorLookupTrait(*this, F));
  2456. TotalNumMethodPoolEntries += Record[1];
  2457. break;
  2458. case REFERENCED_SELECTOR_POOL:
  2459. if (!Record.empty()) {
  2460. for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
  2461. ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
  2462. Record[Idx++]));
  2463. ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
  2464. getRawEncoding());
  2465. }
  2466. }
  2467. break;
  2468. case PP_COUNTER_VALUE:
  2469. if (!Record.empty() && Listener)
  2470. Listener->ReadCounter(F, Record[0]);
  2471. break;
  2472. case FILE_SORTED_DECLS:
  2473. F.FileSortedDecls = (const DeclID *)Blob.data();
  2474. F.NumFileSortedDecls = Record[0];
  2475. break;
  2476. case SOURCE_LOCATION_OFFSETS: {
  2477. F.SLocEntryOffsets = (const uint32_t *)Blob.data();
  2478. F.LocalNumSLocEntries = Record[0];
  2479. unsigned SLocSpaceSize = Record[1];
  2480. // Increase size by >= 1 so we get a unique base index in the next module.
  2481. std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
  2482. SourceMgr.AllocateLoadedSLocEntries(std::max(F.LocalNumSLocEntries, 1U),
  2483. SLocSpaceSize);
  2484. // Make our entry in the range map. BaseID is negative and growing, so
  2485. // we invert it. Because we invert it, though, we need the other end of
  2486. // the range.
  2487. unsigned RangeStart =
  2488. unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
  2489. GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
  2490. F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
  2491. // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
  2492. assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
  2493. GlobalSLocOffsetMap.insert(
  2494. std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
  2495. - SLocSpaceSize,&F));
  2496. // Initialize the remapping table.
  2497. // Invalid stays invalid.
  2498. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
  2499. // This module. Base was 2 when being compiled.
  2500. F.SLocRemap.insertOrReplace(std::make_pair(2U,
  2501. static_cast<int>(F.SLocEntryBaseOffset - 2)));
  2502. TotalNumSLocEntries += F.LocalNumSLocEntries;
  2503. break;
  2504. }
  2505. case MODULE_OFFSET_MAP: {
  2506. // Additional remapping information.
  2507. const unsigned char *Data = (const unsigned char*)Blob.data();
  2508. const unsigned char *DataEnd = Data + Blob.size();
  2509. // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
  2510. if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
  2511. F.SLocRemap.insert(std::make_pair(0U, 0));
  2512. F.SLocRemap.insert(std::make_pair(2U, 1));
  2513. }
  2514. // Continuous range maps we may be updating in our module.
  2515. ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
  2516. ContinuousRangeMap<uint32_t, int, 2>::Builder
  2517. IdentifierRemap(F.IdentifierRemap);
  2518. ContinuousRangeMap<uint32_t, int, 2>::Builder
  2519. MacroRemap(F.MacroRemap);
  2520. ContinuousRangeMap<uint32_t, int, 2>::Builder
  2521. PreprocessedEntityRemap(F.PreprocessedEntityRemap);
  2522. ContinuousRangeMap<uint32_t, int, 2>::Builder
  2523. SubmoduleRemap(F.SubmoduleRemap);
  2524. ContinuousRangeMap<uint32_t, int, 2>::Builder
  2525. SelectorRemap(F.SelectorRemap);
  2526. ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
  2527. ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
  2528. while(Data < DataEnd) {
  2529. using namespace llvm::support;
  2530. uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
  2531. StringRef Name = StringRef((const char*)Data, Len);
  2532. Data += Len;
  2533. ModuleFile *OM = ModuleMgr.lookup(Name);
  2534. if (!OM) {
  2535. Error("SourceLocation remap refers to unknown module");
  2536. return Failure;
  2537. }
  2538. uint32_t SLocOffset =
  2539. endian::readNext<uint32_t, little, unaligned>(Data);
  2540. uint32_t IdentifierIDOffset =
  2541. endian::readNext<uint32_t, little, unaligned>(Data);
  2542. uint32_t MacroIDOffset =
  2543. endian::readNext<uint32_t, little, unaligned>(Data);
  2544. uint32_t PreprocessedEntityIDOffset =
  2545. endian::readNext<uint32_t, little, unaligned>(Data);
  2546. uint32_t SubmoduleIDOffset =
  2547. endian::readNext<uint32_t, little, unaligned>(Data);
  2548. uint32_t SelectorIDOffset =
  2549. endian::readNext<uint32_t, little, unaligned>(Data);
  2550. uint32_t DeclIDOffset =
  2551. endian::readNext<uint32_t, little, unaligned>(Data);
  2552. uint32_t TypeIndexOffset =
  2553. endian::readNext<uint32_t, little, unaligned>(Data);
  2554. // Source location offset is mapped to OM->SLocEntryBaseOffset.
  2555. SLocRemap.insert(std::make_pair(SLocOffset,
  2556. static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
  2557. IdentifierRemap.insert(
  2558. std::make_pair(IdentifierIDOffset,
  2559. OM->BaseIdentifierID - IdentifierIDOffset));
  2560. MacroRemap.insert(std::make_pair(MacroIDOffset,
  2561. OM->BaseMacroID - MacroIDOffset));
  2562. PreprocessedEntityRemap.insert(
  2563. std::make_pair(PreprocessedEntityIDOffset,
  2564. OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
  2565. SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
  2566. OM->BaseSubmoduleID - SubmoduleIDOffset));
  2567. SelectorRemap.insert(std::make_pair(SelectorIDOffset,
  2568. OM->BaseSelectorID - SelectorIDOffset));
  2569. DeclRemap.insert(std::make_pair(DeclIDOffset,
  2570. OM->BaseDeclID - DeclIDOffset));
  2571. TypeRemap.insert(std::make_pair(TypeIndexOffset,
  2572. OM->BaseTypeIndex - TypeIndexOffset));
  2573. // Global -> local mappings.
  2574. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
  2575. }
  2576. break;
  2577. }
  2578. case SOURCE_MANAGER_LINE_TABLE:
  2579. if (ParseLineTable(F, Record))
  2580. return Failure;
  2581. break;
  2582. case SOURCE_LOCATION_PRELOADS: {
  2583. // Need to transform from the local view (1-based IDs) to the global view,
  2584. // which is based off F.SLocEntryBaseID.
  2585. if (!F.PreloadSLocEntries.empty()) {
  2586. Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
  2587. return Failure;
  2588. }
  2589. F.PreloadSLocEntries.swap(Record);
  2590. break;
  2591. }
  2592. case EXT_VECTOR_DECLS:
  2593. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2594. ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2595. break;
  2596. case VTABLE_USES:
  2597. if (Record.size() % 3 != 0) {
  2598. Error("Invalid VTABLE_USES record");
  2599. return Failure;
  2600. }
  2601. // Later tables overwrite earlier ones.
  2602. // FIXME: Modules will have some trouble with this. This is clearly not
  2603. // the right way to do this.
  2604. VTableUses.clear();
  2605. for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
  2606. VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
  2607. VTableUses.push_back(
  2608. ReadSourceLocation(F, Record, Idx).getRawEncoding());
  2609. VTableUses.push_back(Record[Idx++]);
  2610. }
  2611. break;
  2612. case DYNAMIC_CLASSES:
  2613. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2614. DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
  2615. break;
  2616. case PENDING_IMPLICIT_INSTANTIATIONS:
  2617. if (PendingInstantiations.size() % 2 != 0) {
  2618. Error("Invalid existing PendingInstantiations");
  2619. return Failure;
  2620. }
  2621. if (Record.size() % 2 != 0) {
  2622. Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
  2623. return Failure;
  2624. }
  2625. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2626. PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
  2627. PendingInstantiations.push_back(
  2628. ReadSourceLocation(F, Record, I).getRawEncoding());
  2629. }
  2630. break;
  2631. case SEMA_DECL_REFS:
  2632. if (Record.size() != 2) {
  2633. Error("Invalid SEMA_DECL_REFS block");
  2634. return Failure;
  2635. }
  2636. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2637. SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2638. break;
  2639. case PPD_ENTITIES_OFFSETS: {
  2640. F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
  2641. assert(Blob.size() % sizeof(PPEntityOffset) == 0);
  2642. F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
  2643. unsigned LocalBasePreprocessedEntityID = Record[0];
  2644. unsigned StartingID;
  2645. if (!PP.getPreprocessingRecord())
  2646. PP.createPreprocessingRecord();
  2647. if (!PP.getPreprocessingRecord()->getExternalSource())
  2648. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2649. // Increase size by >= 1 so we get a unique base index in the next module.
  2650. StartingID
  2651. = PP.getPreprocessingRecord()
  2652. ->allocateLoadedEntities(std::max(F.NumPreprocessedEntities, 1U));
  2653. F.BasePreprocessedEntityID = StartingID;
  2654. if (F.NumPreprocessedEntities > 0) {
  2655. // Introduce the global -> local mapping for preprocessed entities in
  2656. // this module.
  2657. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
  2658. // Introduce the local -> global mapping for preprocessed entities in
  2659. // this module.
  2660. F.PreprocessedEntityRemap.insertOrReplace(
  2661. std::make_pair(LocalBasePreprocessedEntityID,
  2662. F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
  2663. }
  2664. break;
  2665. }
  2666. case DECL_UPDATE_OFFSETS: {
  2667. if (Record.size() % 2 != 0) {
  2668. Error("invalid DECL_UPDATE_OFFSETS block in AST file");
  2669. return Failure;
  2670. }
  2671. for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
  2672. GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
  2673. DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
  2674. // If we've already loaded the decl, perform the updates when we finish
  2675. // loading this block.
  2676. if (Decl *D = GetExistingDecl(ID))
  2677. PendingUpdateRecords.push_back(std::make_pair(ID, D));
  2678. }
  2679. break;
  2680. }
  2681. case DECL_REPLACEMENTS: {
  2682. if (Record.size() % 3 != 0) {
  2683. Error("invalid DECL_REPLACEMENTS block in AST file");
  2684. return Failure;
  2685. }
  2686. for (unsigned I = 0, N = Record.size(); I != N; I += 3)
  2687. ReplacedDecls[getGlobalDeclID(F, Record[I])]
  2688. = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
  2689. break;
  2690. }
  2691. case OBJC_CATEGORIES_MAP: {
  2692. if (F.LocalNumObjCCategoriesInMap != 0) {
  2693. Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
  2694. return Failure;
  2695. }
  2696. F.LocalNumObjCCategoriesInMap = Record[0];
  2697. F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
  2698. break;
  2699. }
  2700. case OBJC_CATEGORIES:
  2701. F.ObjCCategories.swap(Record);
  2702. break;
  2703. case CXX_BASE_SPECIFIER_OFFSETS: {
  2704. if (F.LocalNumCXXBaseSpecifiers != 0) {
  2705. Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
  2706. return Failure;
  2707. }
  2708. F.LocalNumCXXBaseSpecifiers = Record[0];
  2709. F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
  2710. NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
  2711. break;
  2712. }
  2713. case DIAG_PRAGMA_MAPPINGS:
  2714. if (F.PragmaDiagMappings.empty())
  2715. F.PragmaDiagMappings.swap(Record);
  2716. else
  2717. F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
  2718. Record.begin(), Record.end());
  2719. break;
  2720. case CUDA_SPECIAL_DECL_REFS:
  2721. // Later tables overwrite earlier ones.
  2722. // FIXME: Modules will have trouble with this.
  2723. CUDASpecialDeclRefs.clear();
  2724. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2725. CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2726. break;
  2727. case HEADER_SEARCH_TABLE: {
  2728. F.HeaderFileInfoTableData = Blob.data();
  2729. F.LocalNumHeaderFileInfos = Record[1];
  2730. if (Record[0]) {
  2731. F.HeaderFileInfoTable
  2732. = HeaderFileInfoLookupTable::Create(
  2733. (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
  2734. (const unsigned char *)F.HeaderFileInfoTableData,
  2735. HeaderFileInfoTrait(*this, F,
  2736. &PP.getHeaderSearchInfo(),
  2737. Blob.data() + Record[2]));
  2738. PP.getHeaderSearchInfo().SetExternalSource(this);
  2739. if (!PP.getHeaderSearchInfo().getExternalLookup())
  2740. PP.getHeaderSearchInfo().SetExternalLookup(this);
  2741. }
  2742. break;
  2743. }
  2744. case FP_PRAGMA_OPTIONS:
  2745. // Later tables overwrite earlier ones.
  2746. FPPragmaOptions.swap(Record);
  2747. break;
  2748. case OPENCL_EXTENSIONS:
  2749. // Later tables overwrite earlier ones.
  2750. OpenCLExtensions.swap(Record);
  2751. break;
  2752. case TENTATIVE_DEFINITIONS:
  2753. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2754. TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
  2755. break;
  2756. case KNOWN_NAMESPACES:
  2757. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2758. KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
  2759. break;
  2760. case UNDEFINED_BUT_USED:
  2761. if (UndefinedButUsed.size() % 2 != 0) {
  2762. Error("Invalid existing UndefinedButUsed");
  2763. return Failure;
  2764. }
  2765. if (Record.size() % 2 != 0) {
  2766. Error("invalid undefined-but-used record");
  2767. return Failure;
  2768. }
  2769. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2770. UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
  2771. UndefinedButUsed.push_back(
  2772. ReadSourceLocation(F, Record, I).getRawEncoding());
  2773. }
  2774. break;
  2775. case IMPORTED_MODULES: {
  2776. if (F.Kind != MK_Module) {
  2777. // If we aren't loading a module (which has its own exports), make
  2778. // all of the imported modules visible.
  2779. // FIXME: Deal with macros-only imports.
  2780. for (unsigned I = 0, N = Record.size(); I != N; /**/) {
  2781. unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
  2782. SourceLocation Loc = ReadSourceLocation(F, Record, I);
  2783. if (GlobalID)
  2784. ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
  2785. }
  2786. }
  2787. break;
  2788. }
  2789. case LOCAL_REDECLARATIONS: {
  2790. F.RedeclarationChains.swap(Record);
  2791. break;
  2792. }
  2793. case LOCAL_REDECLARATIONS_MAP: {
  2794. if (F.LocalNumRedeclarationsInMap != 0) {
  2795. Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
  2796. return Failure;
  2797. }
  2798. F.LocalNumRedeclarationsInMap = Record[0];
  2799. F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
  2800. break;
  2801. }
  2802. case MERGED_DECLARATIONS: {
  2803. for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
  2804. GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
  2805. SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
  2806. for (unsigned N = Record[Idx++]; N > 0; --N)
  2807. Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
  2808. }
  2809. break;
  2810. }
  2811. case MACRO_OFFSET: {
  2812. if (F.LocalNumMacros != 0) {
  2813. Error("duplicate MACRO_OFFSET record in AST file");
  2814. return Failure;
  2815. }
  2816. F.MacroOffsets = (const uint32_t *)Blob.data();
  2817. F.LocalNumMacros = Record[0];
  2818. unsigned LocalBaseMacroID = Record[1];
  2819. F.BaseMacroID = getTotalNumMacros();
  2820. if (F.LocalNumMacros > 0) {
  2821. // Introduce the global -> local mapping for macros within this module.
  2822. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
  2823. // Introduce the local -> global mapping for macros within this module.
  2824. F.MacroRemap.insertOrReplace(
  2825. std::make_pair(LocalBaseMacroID,
  2826. F.BaseMacroID - LocalBaseMacroID));
  2827. }
  2828. // Increase size by >= 1 so we get a unique base index in the next module.
  2829. MacrosLoaded.resize(MacrosLoaded.size() + std::max(F.LocalNumMacros, 1U));
  2830. break;
  2831. }
  2832. case MACRO_TABLE: {
  2833. // FIXME: Not used yet.
  2834. break;
  2835. }
  2836. case LATE_PARSED_TEMPLATE: {
  2837. LateParsedTemplates.append(Record.begin(), Record.end());
  2838. break;
  2839. }
  2840. case OPTIMIZE_PRAGMA_OPTIONS:
  2841. if (Record.size() != 1) {
  2842. Error("invalid pragma optimize record");
  2843. return Failure;
  2844. }
  2845. OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
  2846. break;
  2847. }
  2848. }
  2849. }
  2850. ASTReader::ASTReadResult
  2851. ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  2852. const ModuleFile *ImportedBy,
  2853. unsigned ClientLoadCapabilities) {
  2854. unsigned Idx = 0;
  2855. F.ModuleMapPath = ReadString(Record, Idx);
  2856. // Try to resolve ModuleName in the current header search context and
  2857. // verify that it is found in the same module map file as we saved. If the
  2858. // top-level AST file is a main file, skip this check because there is no
  2859. // usable header search context.
  2860. assert(!F.ModuleName.empty() &&
  2861. "MODULE_NAME should come before MOUDLE_MAP_FILE");
  2862. if (F.Kind == MK_Module && (*ModuleMgr.begin())->Kind != MK_MainFile) {
  2863. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
  2864. if (!M) {
  2865. assert(ImportedBy && "top-level import should be verified");
  2866. if ((ClientLoadCapabilities & ARR_Missing) == 0)
  2867. Diag(diag::err_imported_module_not_found)
  2868. << F.ModuleName << ImportedBy->FileName;
  2869. return Missing;
  2870. }
  2871. // Check the primary module map file.
  2872. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  2873. const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
  2874. const FileEntry *ModMap = Map.getModuleMapFileForUniquing(M);
  2875. if (StoredModMap == nullptr || StoredModMap != ModMap) {
  2876. assert(ModMap && "found module is missing module map file");
  2877. assert(M->Name == F.ModuleName && "found module with different name");
  2878. assert(ImportedBy && "top-level import should be verified");
  2879. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2880. Diag(diag::err_imported_module_modmap_changed)
  2881. << F.ModuleName << ImportedBy->FileName
  2882. << ModMap->getName() << F.ModuleMapPath;
  2883. return OutOfDate;
  2884. }
  2885. llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
  2886. for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
  2887. // FIXME: we should use input files rather than storing names.
  2888. std::string Filename = ReadString(Record, Idx);
  2889. const FileEntry *F =
  2890. FileMgr.getFile(Filename, false, false);
  2891. if (F == nullptr) {
  2892. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2893. Error("could not find file '" + Filename +"' referenced by AST file");
  2894. return OutOfDate;
  2895. }
  2896. AdditionalStoredMaps.insert(F);
  2897. }
  2898. // Check any additional module map files (e.g. module.private.modulemap)
  2899. // that are not in the pcm.
  2900. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
  2901. for (const FileEntry *ModMap : *AdditionalModuleMaps) {
  2902. // Remove files that match
  2903. // Note: SmallPtrSet::erase is really remove
  2904. if (!AdditionalStoredMaps.erase(ModMap)) {
  2905. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2906. Diag(diag::err_module_different_modmap)
  2907. << F.ModuleName << /*new*/0 << ModMap->getName();
  2908. return OutOfDate;
  2909. }
  2910. }
  2911. }
  2912. // Check any additional module map files that are in the pcm, but not
  2913. // found in header search. Cases that match are already removed.
  2914. for (const FileEntry *ModMap : AdditionalStoredMaps) {
  2915. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2916. Diag(diag::err_module_different_modmap)
  2917. << F.ModuleName << /*not new*/1 << ModMap->getName();
  2918. return OutOfDate;
  2919. }
  2920. }
  2921. if (Listener)
  2922. Listener->ReadModuleMapFile(F.ModuleMapPath);
  2923. return Success;
  2924. }
  2925. /// \brief Move the given method to the back of the global list of methods.
  2926. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
  2927. // Find the entry for this selector in the method pool.
  2928. Sema::GlobalMethodPool::iterator Known
  2929. = S.MethodPool.find(Method->getSelector());
  2930. if (Known == S.MethodPool.end())
  2931. return;
  2932. // Retrieve the appropriate method list.
  2933. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
  2934. : Known->second.second;
  2935. bool Found = false;
  2936. for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
  2937. if (!Found) {
  2938. if (List->Method == Method) {
  2939. Found = true;
  2940. } else {
  2941. // Keep searching.
  2942. continue;
  2943. }
  2944. }
  2945. if (List->getNext())
  2946. List->Method = List->getNext()->Method;
  2947. else
  2948. List->Method = Method;
  2949. }
  2950. }
  2951. void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
  2952. bool FromFinalization) {
  2953. // FIXME: Only do this if Owner->NameVisibility == AllVisible.
  2954. for (Decl *D : Names.HiddenDecls) {
  2955. bool wasHidden = D->Hidden;
  2956. D->Hidden = false;
  2957. if (wasHidden && SemaObj) {
  2958. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
  2959. moveMethodToBackOfGlobalList(*SemaObj, Method);
  2960. }
  2961. }
  2962. }
  2963. assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
  2964. "nothing to make visible?");
  2965. for (const auto &Macro : Names.HiddenMacros) {
  2966. if (FromFinalization)
  2967. PP.appendMacroDirective(Macro.first,
  2968. Macro.second->import(PP, SourceLocation()));
  2969. else
  2970. installImportedMacro(Macro.first, Macro.second, Owner);
  2971. }
  2972. }
  2973. void ASTReader::makeModuleVisible(Module *Mod,
  2974. Module::NameVisibilityKind NameVisibility,
  2975. SourceLocation ImportLoc,
  2976. bool Complain) {
  2977. llvm::SmallPtrSet<Module *, 4> Visited;
  2978. SmallVector<Module *, 4> Stack;
  2979. Stack.push_back(Mod);
  2980. while (!Stack.empty()) {
  2981. Mod = Stack.pop_back_val();
  2982. if (NameVisibility <= Mod->NameVisibility) {
  2983. // This module already has this level of visibility (or greater), so
  2984. // there is nothing more to do.
  2985. continue;
  2986. }
  2987. if (!Mod->isAvailable()) {
  2988. // Modules that aren't available cannot be made visible.
  2989. continue;
  2990. }
  2991. // Update the module's name visibility.
  2992. if (NameVisibility >= Module::MacrosVisible &&
  2993. Mod->NameVisibility < Module::MacrosVisible)
  2994. Mod->MacroVisibilityLoc = ImportLoc;
  2995. Mod->NameVisibility = NameVisibility;
  2996. // If we've already deserialized any names from this module,
  2997. // mark them as visible.
  2998. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
  2999. if (Hidden != HiddenNamesMap.end()) {
  3000. auto HiddenNames = std::move(*Hidden);
  3001. HiddenNamesMap.erase(Hidden);
  3002. makeNamesVisible(HiddenNames.second, HiddenNames.first,
  3003. /*FromFinalization*/false);
  3004. assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
  3005. "making names visible added hidden names");
  3006. }
  3007. // Push any exported modules onto the stack to be marked as visible.
  3008. SmallVector<Module *, 16> Exports;
  3009. Mod->getExportedModules(Exports);
  3010. for (SmallVectorImpl<Module *>::iterator
  3011. I = Exports.begin(), E = Exports.end(); I != E; ++I) {
  3012. Module *Exported = *I;
  3013. if (Visited.insert(Exported))
  3014. Stack.push_back(Exported);
  3015. }
  3016. // Detect any conflicts.
  3017. if (Complain) {
  3018. assert(ImportLoc.isValid() && "Missing import location");
  3019. for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
  3020. if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
  3021. Diag(ImportLoc, diag::warn_module_conflict)
  3022. << Mod->getFullModuleName()
  3023. << Mod->Conflicts[I].Other->getFullModuleName()
  3024. << Mod->Conflicts[I].Message;
  3025. // FIXME: Need note where the other module was imported.
  3026. }
  3027. }
  3028. }
  3029. }
  3030. }
  3031. bool ASTReader::loadGlobalIndex() {
  3032. if (GlobalIndex)
  3033. return false;
  3034. if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
  3035. !Context.getLangOpts().Modules)
  3036. return true;
  3037. // Try to load the global index.
  3038. TriedLoadingGlobalIndex = true;
  3039. StringRef ModuleCachePath
  3040. = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  3041. std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
  3042. = GlobalModuleIndex::readIndex(ModuleCachePath);
  3043. if (!Result.first)
  3044. return true;
  3045. GlobalIndex.reset(Result.first);
  3046. ModuleMgr.setGlobalIndex(GlobalIndex.get());
  3047. return false;
  3048. }
  3049. bool ASTReader::isGlobalIndexUnavailable() const {
  3050. return Context.getLangOpts().Modules && UseGlobalIndex &&
  3051. !hasGlobalIndex() && TriedLoadingGlobalIndex;
  3052. }
  3053. static void updateModuleTimestamp(ModuleFile &MF) {
  3054. // Overwrite the timestamp file contents so that file's mtime changes.
  3055. std::string TimestampFilename = MF.getTimestampFilename();
  3056. std::error_code EC;
  3057. llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
  3058. if (EC)
  3059. return;
  3060. OS << "Timestamp file\n";
  3061. }
  3062. ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
  3063. ModuleKind Type,
  3064. SourceLocation ImportLoc,
  3065. unsigned ClientLoadCapabilities) {
  3066. llvm::SaveAndRestore<SourceLocation>
  3067. SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
  3068. // Defer any pending actions until we get to the end of reading the AST file.
  3069. Deserializing AnASTFile(this);
  3070. // Bump the generation number.
  3071. unsigned PreviousGeneration = incrementGeneration(Context);
  3072. unsigned NumModules = ModuleMgr.size();
  3073. SmallVector<ImportedModule, 4> Loaded;
  3074. switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
  3075. /*ImportedBy=*/nullptr, Loaded,
  3076. 0, 0,
  3077. ClientLoadCapabilities)) {
  3078. case Failure:
  3079. case Missing:
  3080. case OutOfDate:
  3081. case VersionMismatch:
  3082. case ConfigurationMismatch:
  3083. case HadErrors: {
  3084. llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
  3085. for (const ImportedModule &IM : Loaded)
  3086. LoadedSet.insert(IM.Mod);
  3087. ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
  3088. LoadedSet,
  3089. Context.getLangOpts().Modules
  3090. ? &PP.getHeaderSearchInfo().getModuleMap()
  3091. : nullptr);
  3092. // If we find that any modules are unusable, the global index is going
  3093. // to be out-of-date. Just remove it.
  3094. GlobalIndex.reset();
  3095. ModuleMgr.setGlobalIndex(nullptr);
  3096. return ReadResult;
  3097. }
  3098. case Success:
  3099. break;
  3100. }
  3101. // Here comes stuff that we only do once the entire chain is loaded.
  3102. // Load the AST blocks of all of the modules that we loaded.
  3103. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  3104. MEnd = Loaded.end();
  3105. M != MEnd; ++M) {
  3106. ModuleFile &F = *M->Mod;
  3107. // Read the AST block.
  3108. if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
  3109. return Result;
  3110. // Once read, set the ModuleFile bit base offset and update the size in
  3111. // bits of all files we've seen.
  3112. F.GlobalBitOffset = TotalModulesSizeInBits;
  3113. TotalModulesSizeInBits += F.SizeInBits;
  3114. GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
  3115. // Preload SLocEntries.
  3116. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
  3117. int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
  3118. // Load it through the SourceManager and don't call ReadSLocEntry()
  3119. // directly because the entry may have already been loaded in which case
  3120. // calling ReadSLocEntry() directly would trigger an assertion in
  3121. // SourceManager.
  3122. SourceMgr.getLoadedSLocEntryByID(Index);
  3123. }
  3124. }
  3125. // Setup the import locations and notify the module manager that we've
  3126. // committed to these module files.
  3127. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  3128. MEnd = Loaded.end();
  3129. M != MEnd; ++M) {
  3130. ModuleFile &F = *M->Mod;
  3131. ModuleMgr.moduleFileAccepted(&F);
  3132. // Set the import location.
  3133. F.DirectImportLoc = ImportLoc;
  3134. if (!M->ImportedBy)
  3135. F.ImportLoc = M->ImportLoc;
  3136. else
  3137. F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
  3138. M->ImportLoc.getRawEncoding());
  3139. }
  3140. // Mark all of the identifiers in the identifier table as being out of date,
  3141. // so that various accessors know to check the loaded modules when the
  3142. // identifier is used.
  3143. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
  3144. IdEnd = PP.getIdentifierTable().end();
  3145. Id != IdEnd; ++Id)
  3146. Id->second->setOutOfDate(true);
  3147. // Resolve any unresolved module exports.
  3148. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
  3149. UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
  3150. SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
  3151. Module *ResolvedMod = getSubmodule(GlobalID);
  3152. switch (Unresolved.Kind) {
  3153. case UnresolvedModuleRef::Conflict:
  3154. if (ResolvedMod) {
  3155. Module::Conflict Conflict;
  3156. Conflict.Other = ResolvedMod;
  3157. Conflict.Message = Unresolved.String.str();
  3158. Unresolved.Mod->Conflicts.push_back(Conflict);
  3159. }
  3160. continue;
  3161. case UnresolvedModuleRef::Import:
  3162. if (ResolvedMod)
  3163. Unresolved.Mod->Imports.push_back(ResolvedMod);
  3164. continue;
  3165. case UnresolvedModuleRef::Export:
  3166. if (ResolvedMod || Unresolved.IsWildcard)
  3167. Unresolved.Mod->Exports.push_back(
  3168. Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
  3169. continue;
  3170. }
  3171. }
  3172. UnresolvedModuleRefs.clear();
  3173. // FIXME: How do we load the 'use'd modules? They may not be submodules.
  3174. // Might be unnecessary as use declarations are only used to build the
  3175. // module itself.
  3176. InitializeContext();
  3177. if (SemaObj)
  3178. UpdateSema();
  3179. if (DeserializationListener)
  3180. DeserializationListener->ReaderInitialized(this);
  3181. ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
  3182. if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
  3183. PrimaryModule.OriginalSourceFileID
  3184. = FileID::get(PrimaryModule.SLocEntryBaseID
  3185. + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
  3186. // If this AST file is a precompiled preamble, then set the
  3187. // preamble file ID of the source manager to the file source file
  3188. // from which the preamble was built.
  3189. if (Type == MK_Preamble) {
  3190. SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
  3191. } else if (Type == MK_MainFile) {
  3192. SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
  3193. }
  3194. }
  3195. // For any Objective-C class definitions we have already loaded, make sure
  3196. // that we load any additional categories.
  3197. for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
  3198. loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
  3199. ObjCClassesLoaded[I],
  3200. PreviousGeneration);
  3201. }
  3202. if (PP.getHeaderSearchInfo()
  3203. .getHeaderSearchOpts()
  3204. .ModulesValidateOncePerBuildSession) {
  3205. // Now we are certain that the module and all modules it depends on are
  3206. // up to date. Create or update timestamp files for modules that are
  3207. // located in the module cache (not for PCH files that could be anywhere
  3208. // in the filesystem).
  3209. for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
  3210. ImportedModule &M = Loaded[I];
  3211. if (M.Mod->Kind == MK_Module) {
  3212. updateModuleTimestamp(*M.Mod);
  3213. }
  3214. }
  3215. }
  3216. return Success;
  3217. }
  3218. ASTReader::ASTReadResult
  3219. ASTReader::ReadASTCore(StringRef FileName,
  3220. ModuleKind Type,
  3221. SourceLocation ImportLoc,
  3222. ModuleFile *ImportedBy,
  3223. SmallVectorImpl<ImportedModule> &Loaded,
  3224. off_t ExpectedSize, time_t ExpectedModTime,
  3225. unsigned ClientLoadCapabilities) {
  3226. ModuleFile *M;
  3227. std::string ErrorStr;
  3228. ModuleManager::AddModuleResult AddResult
  3229. = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
  3230. getGeneration(), ExpectedSize, ExpectedModTime,
  3231. M, ErrorStr);
  3232. switch (AddResult) {
  3233. case ModuleManager::AlreadyLoaded:
  3234. return Success;
  3235. case ModuleManager::NewlyLoaded:
  3236. // Load module file below.
  3237. break;
  3238. case ModuleManager::Missing:
  3239. // The module file was missing; if the client handle handle, that, return
  3240. // it.
  3241. if (ClientLoadCapabilities & ARR_Missing)
  3242. return Missing;
  3243. // Otherwise, return an error.
  3244. {
  3245. std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
  3246. + ErrorStr;
  3247. Error(Msg);
  3248. }
  3249. return Failure;
  3250. case ModuleManager::OutOfDate:
  3251. // We couldn't load the module file because it is out-of-date. If the
  3252. // client can handle out-of-date, return it.
  3253. if (ClientLoadCapabilities & ARR_OutOfDate)
  3254. return OutOfDate;
  3255. // Otherwise, return an error.
  3256. {
  3257. std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
  3258. + ErrorStr;
  3259. Error(Msg);
  3260. }
  3261. return Failure;
  3262. }
  3263. assert(M && "Missing module file");
  3264. // FIXME: This seems rather a hack. Should CurrentDir be part of the
  3265. // module?
  3266. if (FileName != "-") {
  3267. CurrentDir = llvm::sys::path::parent_path(FileName);
  3268. if (CurrentDir.empty()) CurrentDir = ".";
  3269. }
  3270. ModuleFile &F = *M;
  3271. BitstreamCursor &Stream = F.Stream;
  3272. Stream.init(F.StreamFile);
  3273. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  3274. // Sniff for the signature.
  3275. if (Stream.Read(8) != 'C' ||
  3276. Stream.Read(8) != 'P' ||
  3277. Stream.Read(8) != 'C' ||
  3278. Stream.Read(8) != 'H') {
  3279. Diag(diag::err_not_a_pch_file) << FileName;
  3280. return Failure;
  3281. }
  3282. // This is used for compatibility with older PCH formats.
  3283. bool HaveReadControlBlock = false;
  3284. while (1) {
  3285. llvm::BitstreamEntry Entry = Stream.advance();
  3286. switch (Entry.Kind) {
  3287. case llvm::BitstreamEntry::Error:
  3288. case llvm::BitstreamEntry::EndBlock:
  3289. case llvm::BitstreamEntry::Record:
  3290. Error("invalid record at top-level of AST file");
  3291. return Failure;
  3292. case llvm::BitstreamEntry::SubBlock:
  3293. break;
  3294. }
  3295. // We only know the control subblock ID.
  3296. switch (Entry.ID) {
  3297. case llvm::bitc::BLOCKINFO_BLOCK_ID:
  3298. if (Stream.ReadBlockInfoBlock()) {
  3299. Error("malformed BlockInfoBlock in AST file");
  3300. return Failure;
  3301. }
  3302. break;
  3303. case CONTROL_BLOCK_ID:
  3304. HaveReadControlBlock = true;
  3305. switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
  3306. case Success:
  3307. break;
  3308. case Failure: return Failure;
  3309. case Missing: return Missing;
  3310. case OutOfDate: return OutOfDate;
  3311. case VersionMismatch: return VersionMismatch;
  3312. case ConfigurationMismatch: return ConfigurationMismatch;
  3313. case HadErrors: return HadErrors;
  3314. }
  3315. break;
  3316. case AST_BLOCK_ID:
  3317. if (!HaveReadControlBlock) {
  3318. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  3319. Diag(diag::err_pch_version_too_old);
  3320. return VersionMismatch;
  3321. }
  3322. // Record that we've loaded this module.
  3323. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
  3324. return Success;
  3325. default:
  3326. if (Stream.SkipBlock()) {
  3327. Error("malformed block record in AST file");
  3328. return Failure;
  3329. }
  3330. break;
  3331. }
  3332. }
  3333. return Success;
  3334. }
  3335. void ASTReader::InitializeContext() {
  3336. // If there's a listener, notify them that we "read" the translation unit.
  3337. if (DeserializationListener)
  3338. DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
  3339. Context.getTranslationUnitDecl());
  3340. // FIXME: Find a better way to deal with collisions between these
  3341. // built-in types. Right now, we just ignore the problem.
  3342. // Load the special types.
  3343. if (SpecialTypes.size() >= NumSpecialTypeIDs) {
  3344. if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
  3345. if (!Context.CFConstantStringTypeDecl)
  3346. Context.setCFConstantStringType(GetType(String));
  3347. }
  3348. if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
  3349. QualType FileType = GetType(File);
  3350. if (FileType.isNull()) {
  3351. Error("FILE type is NULL");
  3352. return;
  3353. }
  3354. if (!Context.FILEDecl) {
  3355. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  3356. Context.setFILEDecl(Typedef->getDecl());
  3357. else {
  3358. const TagType *Tag = FileType->getAs<TagType>();
  3359. if (!Tag) {
  3360. Error("Invalid FILE type in AST file");
  3361. return;
  3362. }
  3363. Context.setFILEDecl(Tag->getDecl());
  3364. }
  3365. }
  3366. }
  3367. if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
  3368. QualType Jmp_bufType = GetType(Jmp_buf);
  3369. if (Jmp_bufType.isNull()) {
  3370. Error("jmp_buf type is NULL");
  3371. return;
  3372. }
  3373. if (!Context.jmp_bufDecl) {
  3374. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  3375. Context.setjmp_bufDecl(Typedef->getDecl());
  3376. else {
  3377. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  3378. if (!Tag) {
  3379. Error("Invalid jmp_buf type in AST file");
  3380. return;
  3381. }
  3382. Context.setjmp_bufDecl(Tag->getDecl());
  3383. }
  3384. }
  3385. }
  3386. if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
  3387. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  3388. if (Sigjmp_bufType.isNull()) {
  3389. Error("sigjmp_buf type is NULL");
  3390. return;
  3391. }
  3392. if (!Context.sigjmp_bufDecl) {
  3393. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  3394. Context.setsigjmp_bufDecl(Typedef->getDecl());
  3395. else {
  3396. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  3397. assert(Tag && "Invalid sigjmp_buf type in AST file");
  3398. Context.setsigjmp_bufDecl(Tag->getDecl());
  3399. }
  3400. }
  3401. }
  3402. if (unsigned ObjCIdRedef
  3403. = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
  3404. if (Context.ObjCIdRedefinitionType.isNull())
  3405. Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  3406. }
  3407. if (unsigned ObjCClassRedef
  3408. = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
  3409. if (Context.ObjCClassRedefinitionType.isNull())
  3410. Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  3411. }
  3412. if (unsigned ObjCSelRedef
  3413. = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
  3414. if (Context.ObjCSelRedefinitionType.isNull())
  3415. Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  3416. }
  3417. if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
  3418. QualType Ucontext_tType = GetType(Ucontext_t);
  3419. if (Ucontext_tType.isNull()) {
  3420. Error("ucontext_t type is NULL");
  3421. return;
  3422. }
  3423. if (!Context.ucontext_tDecl) {
  3424. if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
  3425. Context.setucontext_tDecl(Typedef->getDecl());
  3426. else {
  3427. const TagType *Tag = Ucontext_tType->getAs<TagType>();
  3428. assert(Tag && "Invalid ucontext_t type in AST file");
  3429. Context.setucontext_tDecl(Tag->getDecl());
  3430. }
  3431. }
  3432. }
  3433. }
  3434. ReadPragmaDiagnosticMappings(Context.getDiagnostics());
  3435. // If there were any CUDA special declarations, deserialize them.
  3436. if (!CUDASpecialDeclRefs.empty()) {
  3437. assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
  3438. Context.setcudaConfigureCallDecl(
  3439. cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
  3440. }
  3441. // Re-export any modules that were imported by a non-module AST file.
  3442. // FIXME: This does not make macro-only imports visible again. It also doesn't
  3443. // make #includes mapped to module imports visible.
  3444. for (auto &Import : ImportedModules) {
  3445. if (Module *Imported = getSubmodule(Import.ID))
  3446. makeModuleVisible(Imported, Module::AllVisible,
  3447. /*ImportLoc=*/Import.ImportLoc,
  3448. /*Complain=*/false);
  3449. }
  3450. ImportedModules.clear();
  3451. }
  3452. void ASTReader::finalizeForWriting() {
  3453. while (!HiddenNamesMap.empty()) {
  3454. auto HiddenNames = std::move(*HiddenNamesMap.begin());
  3455. HiddenNamesMap.erase(HiddenNamesMap.begin());
  3456. makeNamesVisible(HiddenNames.second, HiddenNames.first,
  3457. /*FromFinalization*/true);
  3458. }
  3459. }
  3460. /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
  3461. /// cursor into the start of the given block ID, returning false on success and
  3462. /// true on failure.
  3463. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
  3464. while (1) {
  3465. llvm::BitstreamEntry Entry = Cursor.advance();
  3466. switch (Entry.Kind) {
  3467. case llvm::BitstreamEntry::Error:
  3468. case llvm::BitstreamEntry::EndBlock:
  3469. return true;
  3470. case llvm::BitstreamEntry::Record:
  3471. // Ignore top-level records.
  3472. Cursor.skipRecord(Entry.ID);
  3473. break;
  3474. case llvm::BitstreamEntry::SubBlock:
  3475. if (Entry.ID == BlockID) {
  3476. if (Cursor.EnterSubBlock(BlockID))
  3477. return true;
  3478. // Found it!
  3479. return false;
  3480. }
  3481. if (Cursor.SkipBlock())
  3482. return true;
  3483. }
  3484. }
  3485. }
  3486. /// \brief Retrieve the name of the original source file name
  3487. /// directly from the AST file, without actually loading the AST
  3488. /// file.
  3489. std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
  3490. FileManager &FileMgr,
  3491. DiagnosticsEngine &Diags) {
  3492. // Open the AST file.
  3493. std::string ErrStr;
  3494. std::unique_ptr<llvm::MemoryBuffer> Buffer;
  3495. Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
  3496. if (!Buffer) {
  3497. Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
  3498. return std::string();
  3499. }
  3500. // Initialize the stream
  3501. llvm::BitstreamReader StreamFile;
  3502. BitstreamCursor Stream;
  3503. StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
  3504. (const unsigned char *)Buffer->getBufferEnd());
  3505. Stream.init(StreamFile);
  3506. // Sniff for the signature.
  3507. if (Stream.Read(8) != 'C' ||
  3508. Stream.Read(8) != 'P' ||
  3509. Stream.Read(8) != 'C' ||
  3510. Stream.Read(8) != 'H') {
  3511. Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
  3512. return std::string();
  3513. }
  3514. // Scan for the CONTROL_BLOCK_ID block.
  3515. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
  3516. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  3517. return std::string();
  3518. }
  3519. // Scan for ORIGINAL_FILE inside the control block.
  3520. RecordData Record;
  3521. while (1) {
  3522. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3523. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  3524. return std::string();
  3525. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  3526. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  3527. return std::string();
  3528. }
  3529. Record.clear();
  3530. StringRef Blob;
  3531. if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
  3532. return Blob.str();
  3533. }
  3534. }
  3535. namespace {
  3536. class SimplePCHValidator : public ASTReaderListener {
  3537. const LangOptions &ExistingLangOpts;
  3538. const TargetOptions &ExistingTargetOpts;
  3539. const PreprocessorOptions &ExistingPPOpts;
  3540. FileManager &FileMgr;
  3541. public:
  3542. SimplePCHValidator(const LangOptions &ExistingLangOpts,
  3543. const TargetOptions &ExistingTargetOpts,
  3544. const PreprocessorOptions &ExistingPPOpts,
  3545. FileManager &FileMgr)
  3546. : ExistingLangOpts(ExistingLangOpts),
  3547. ExistingTargetOpts(ExistingTargetOpts),
  3548. ExistingPPOpts(ExistingPPOpts),
  3549. FileMgr(FileMgr)
  3550. {
  3551. }
  3552. bool ReadLanguageOptions(const LangOptions &LangOpts,
  3553. bool Complain) override {
  3554. return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
  3555. }
  3556. bool ReadTargetOptions(const TargetOptions &TargetOpts,
  3557. bool Complain) override {
  3558. return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
  3559. }
  3560. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  3561. bool Complain,
  3562. std::string &SuggestedPredefines) override {
  3563. return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
  3564. SuggestedPredefines, ExistingLangOpts);
  3565. }
  3566. };
  3567. }
  3568. bool ASTReader::readASTFileControlBlock(StringRef Filename,
  3569. FileManager &FileMgr,
  3570. ASTReaderListener &Listener) {
  3571. // Open the AST file.
  3572. std::string ErrStr;
  3573. std::unique_ptr<llvm::MemoryBuffer> Buffer;
  3574. Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
  3575. if (!Buffer) {
  3576. return true;
  3577. }
  3578. // Initialize the stream
  3579. llvm::BitstreamReader StreamFile;
  3580. BitstreamCursor Stream;
  3581. StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
  3582. (const unsigned char *)Buffer->getBufferEnd());
  3583. Stream.init(StreamFile);
  3584. // Sniff for the signature.
  3585. if (Stream.Read(8) != 'C' ||
  3586. Stream.Read(8) != 'P' ||
  3587. Stream.Read(8) != 'C' ||
  3588. Stream.Read(8) != 'H') {
  3589. return true;
  3590. }
  3591. // Scan for the CONTROL_BLOCK_ID block.
  3592. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  3593. return true;
  3594. bool NeedsInputFiles = Listener.needsInputFileVisitation();
  3595. bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
  3596. BitstreamCursor InputFilesCursor;
  3597. if (NeedsInputFiles) {
  3598. InputFilesCursor = Stream;
  3599. if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
  3600. return true;
  3601. // Read the abbreviations
  3602. while (true) {
  3603. uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
  3604. unsigned Code = InputFilesCursor.ReadCode();
  3605. // We expect all abbrevs to be at the start of the block.
  3606. if (Code != llvm::bitc::DEFINE_ABBREV) {
  3607. InputFilesCursor.JumpToBit(Offset);
  3608. break;
  3609. }
  3610. InputFilesCursor.ReadAbbrevRecord();
  3611. }
  3612. }
  3613. // Scan for ORIGINAL_FILE inside the control block.
  3614. RecordData Record;
  3615. while (1) {
  3616. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3617. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  3618. return false;
  3619. if (Entry.Kind != llvm::BitstreamEntry::Record)
  3620. return true;
  3621. Record.clear();
  3622. StringRef Blob;
  3623. unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
  3624. switch ((ControlRecordTypes)RecCode) {
  3625. case METADATA: {
  3626. if (Record[0] != VERSION_MAJOR)
  3627. return true;
  3628. if (Listener.ReadFullVersionInformation(Blob))
  3629. return true;
  3630. break;
  3631. }
  3632. case MODULE_NAME:
  3633. Listener.ReadModuleName(Blob);
  3634. break;
  3635. case MODULE_MAP_FILE: {
  3636. unsigned Idx = 0;
  3637. Listener.ReadModuleMapFile(ReadString(Record, Idx));
  3638. break;
  3639. }
  3640. case LANGUAGE_OPTIONS:
  3641. if (ParseLanguageOptions(Record, false, Listener))
  3642. return true;
  3643. break;
  3644. case TARGET_OPTIONS:
  3645. if (ParseTargetOptions(Record, false, Listener))
  3646. return true;
  3647. break;
  3648. case DIAGNOSTIC_OPTIONS:
  3649. if (ParseDiagnosticOptions(Record, false, Listener))
  3650. return true;
  3651. break;
  3652. case FILE_SYSTEM_OPTIONS:
  3653. if (ParseFileSystemOptions(Record, false, Listener))
  3654. return true;
  3655. break;
  3656. case HEADER_SEARCH_OPTIONS:
  3657. if (ParseHeaderSearchOptions(Record, false, Listener))
  3658. return true;
  3659. break;
  3660. case PREPROCESSOR_OPTIONS: {
  3661. std::string IgnoredSuggestedPredefines;
  3662. if (ParsePreprocessorOptions(Record, false, Listener,
  3663. IgnoredSuggestedPredefines))
  3664. return true;
  3665. break;
  3666. }
  3667. case INPUT_FILE_OFFSETS: {
  3668. if (!NeedsInputFiles)
  3669. break;
  3670. unsigned NumInputFiles = Record[0];
  3671. unsigned NumUserFiles = Record[1];
  3672. const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
  3673. for (unsigned I = 0; I != NumInputFiles; ++I) {
  3674. // Go find this input file.
  3675. bool isSystemFile = I >= NumUserFiles;
  3676. if (isSystemFile && !NeedsSystemInputFiles)
  3677. break; // the rest are system input files
  3678. BitstreamCursor &Cursor = InputFilesCursor;
  3679. SavedStreamPosition SavedPosition(Cursor);
  3680. Cursor.JumpToBit(InputFileOffs[I]);
  3681. unsigned Code = Cursor.ReadCode();
  3682. RecordData Record;
  3683. StringRef Blob;
  3684. bool shouldContinue = false;
  3685. switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
  3686. case INPUT_FILE:
  3687. bool Overridden = static_cast<bool>(Record[3]);
  3688. shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
  3689. break;
  3690. }
  3691. if (!shouldContinue)
  3692. break;
  3693. }
  3694. break;
  3695. }
  3696. default:
  3697. // No other validation to perform.
  3698. break;
  3699. }
  3700. }
  3701. }
  3702. bool ASTReader::isAcceptableASTFile(StringRef Filename,
  3703. FileManager &FileMgr,
  3704. const LangOptions &LangOpts,
  3705. const TargetOptions &TargetOpts,
  3706. const PreprocessorOptions &PPOpts) {
  3707. SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
  3708. return !readASTFileControlBlock(Filename, FileMgr, validator);
  3709. }
  3710. ASTReader::ASTReadResult
  3711. ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  3712. // Enter the submodule block.
  3713. if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
  3714. Error("malformed submodule block record in AST file");
  3715. return Failure;
  3716. }
  3717. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  3718. bool First = true;
  3719. Module *CurrentModule = nullptr;
  3720. RecordData Record;
  3721. while (true) {
  3722. llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
  3723. switch (Entry.Kind) {
  3724. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  3725. case llvm::BitstreamEntry::Error:
  3726. Error("malformed block record in AST file");
  3727. return Failure;
  3728. case llvm::BitstreamEntry::EndBlock:
  3729. return Success;
  3730. case llvm::BitstreamEntry::Record:
  3731. // The interesting case.
  3732. break;
  3733. }
  3734. // Read a record.
  3735. StringRef Blob;
  3736. Record.clear();
  3737. switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
  3738. default: // Default behavior: ignore.
  3739. break;
  3740. case SUBMODULE_DEFINITION: {
  3741. if (First) {
  3742. Error("missing submodule metadata record at beginning of block");
  3743. return Failure;
  3744. }
  3745. if (Record.size() < 8) {
  3746. Error("malformed module definition");
  3747. return Failure;
  3748. }
  3749. StringRef Name = Blob;
  3750. unsigned Idx = 0;
  3751. SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
  3752. SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
  3753. bool IsFramework = Record[Idx++];
  3754. bool IsExplicit = Record[Idx++];
  3755. bool IsSystem = Record[Idx++];
  3756. bool IsExternC = Record[Idx++];
  3757. bool InferSubmodules = Record[Idx++];
  3758. bool InferExplicitSubmodules = Record[Idx++];
  3759. bool InferExportWildcard = Record[Idx++];
  3760. bool ConfigMacrosExhaustive = Record[Idx++];
  3761. Module *ParentModule = nullptr;
  3762. if (Parent)
  3763. ParentModule = getSubmodule(Parent);
  3764. // Retrieve this (sub)module from the module map, creating it if
  3765. // necessary.
  3766. CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
  3767. IsExplicit).first;
  3768. // FIXME: set the definition loc for CurrentModule, or call
  3769. // ModMap.setInferredModuleAllowedBy()
  3770. SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
  3771. if (GlobalIndex >= SubmodulesLoaded.size() ||
  3772. SubmodulesLoaded[GlobalIndex]) {
  3773. Error("too many submodules");
  3774. return Failure;
  3775. }
  3776. if (!ParentModule) {
  3777. if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
  3778. if (CurFile != F.File) {
  3779. if (!Diags.isDiagnosticInFlight()) {
  3780. Diag(diag::err_module_file_conflict)
  3781. << CurrentModule->getTopLevelModuleName()
  3782. << CurFile->getName()
  3783. << F.File->getName();
  3784. }
  3785. return Failure;
  3786. }
  3787. }
  3788. CurrentModule->setASTFile(F.File);
  3789. }
  3790. CurrentModule->IsFromModuleFile = true;
  3791. CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
  3792. CurrentModule->IsExternC = IsExternC;
  3793. CurrentModule->InferSubmodules = InferSubmodules;
  3794. CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
  3795. CurrentModule->InferExportWildcard = InferExportWildcard;
  3796. CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
  3797. if (DeserializationListener)
  3798. DeserializationListener->ModuleRead(GlobalID, CurrentModule);
  3799. SubmodulesLoaded[GlobalIndex] = CurrentModule;
  3800. // Clear out data that will be replaced by what is the module file.
  3801. CurrentModule->LinkLibraries.clear();
  3802. CurrentModule->ConfigMacros.clear();
  3803. CurrentModule->UnresolvedConflicts.clear();
  3804. CurrentModule->Conflicts.clear();
  3805. break;
  3806. }
  3807. case SUBMODULE_UMBRELLA_HEADER: {
  3808. if (First) {
  3809. Error("missing submodule metadata record at beginning of block");
  3810. return Failure;
  3811. }
  3812. if (!CurrentModule)
  3813. break;
  3814. if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
  3815. if (!CurrentModule->getUmbrellaHeader())
  3816. ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
  3817. else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
  3818. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3819. Error("mismatched umbrella headers in submodule");
  3820. return OutOfDate;
  3821. }
  3822. }
  3823. break;
  3824. }
  3825. case SUBMODULE_HEADER: {
  3826. if (First) {
  3827. Error("missing submodule metadata record at beginning of block");
  3828. return Failure;
  3829. }
  3830. if (!CurrentModule)
  3831. break;
  3832. // We lazily associate headers with their modules via the HeaderInfoTable.
  3833. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  3834. // of complete filenames or remove it entirely.
  3835. break;
  3836. }
  3837. case SUBMODULE_EXCLUDED_HEADER: {
  3838. if (First) {
  3839. Error("missing submodule metadata record at beginning of block");
  3840. return Failure;
  3841. }
  3842. if (!CurrentModule)
  3843. break;
  3844. // We lazily associate headers with their modules via the HeaderInfoTable.
  3845. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  3846. // of complete filenames or remove it entirely.
  3847. break;
  3848. }
  3849. case SUBMODULE_PRIVATE_HEADER: {
  3850. if (First) {
  3851. Error("missing submodule metadata record at beginning of block");
  3852. return Failure;
  3853. }
  3854. if (!CurrentModule)
  3855. break;
  3856. // We lazily associate headers with their modules via the HeaderInfoTable.
  3857. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  3858. // of complete filenames or remove it entirely.
  3859. break;
  3860. }
  3861. case SUBMODULE_TOPHEADER: {
  3862. if (First) {
  3863. Error("missing submodule metadata record at beginning of block");
  3864. return Failure;
  3865. }
  3866. if (!CurrentModule)
  3867. break;
  3868. CurrentModule->addTopHeaderFilename(Blob);
  3869. break;
  3870. }
  3871. case SUBMODULE_UMBRELLA_DIR: {
  3872. if (First) {
  3873. Error("missing submodule metadata record at beginning of block");
  3874. return Failure;
  3875. }
  3876. if (!CurrentModule)
  3877. break;
  3878. if (const DirectoryEntry *Umbrella
  3879. = PP.getFileManager().getDirectory(Blob)) {
  3880. if (!CurrentModule->getUmbrellaDir())
  3881. ModMap.setUmbrellaDir(CurrentModule, Umbrella);
  3882. else if (CurrentModule->getUmbrellaDir() != Umbrella) {
  3883. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3884. Error("mismatched umbrella directories in submodule");
  3885. return OutOfDate;
  3886. }
  3887. }
  3888. break;
  3889. }
  3890. case SUBMODULE_METADATA: {
  3891. if (!First) {
  3892. Error("submodule metadata record not at beginning of block");
  3893. return Failure;
  3894. }
  3895. First = false;
  3896. F.BaseSubmoduleID = getTotalNumSubmodules();
  3897. F.LocalNumSubmodules = Record[0];
  3898. unsigned LocalBaseSubmoduleID = Record[1];
  3899. if (F.LocalNumSubmodules > 0) {
  3900. // Introduce the global -> local mapping for submodules within this
  3901. // module.
  3902. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
  3903. // Introduce the local -> global mapping for submodules within this
  3904. // module.
  3905. F.SubmoduleRemap.insertOrReplace(
  3906. std::make_pair(LocalBaseSubmoduleID,
  3907. F.BaseSubmoduleID - LocalBaseSubmoduleID));
  3908. }
  3909. // Increase size by >= 1 so we get a unique base index in the next module.
  3910. SubmodulesLoaded.resize(SubmodulesLoaded.size() +
  3911. std::max(F.LocalNumSubmodules, 1U));
  3912. break;
  3913. }
  3914. case SUBMODULE_IMPORTS: {
  3915. if (First) {
  3916. Error("missing submodule metadata record at beginning of block");
  3917. return Failure;
  3918. }
  3919. if (!CurrentModule)
  3920. break;
  3921. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  3922. UnresolvedModuleRef Unresolved;
  3923. Unresolved.File = &F;
  3924. Unresolved.Mod = CurrentModule;
  3925. Unresolved.ID = Record[Idx];
  3926. Unresolved.Kind = UnresolvedModuleRef::Import;
  3927. Unresolved.IsWildcard = false;
  3928. UnresolvedModuleRefs.push_back(Unresolved);
  3929. }
  3930. break;
  3931. }
  3932. case SUBMODULE_EXPORTS: {
  3933. if (First) {
  3934. Error("missing submodule metadata record at beginning of block");
  3935. return Failure;
  3936. }
  3937. if (!CurrentModule)
  3938. break;
  3939. for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
  3940. UnresolvedModuleRef Unresolved;
  3941. Unresolved.File = &F;
  3942. Unresolved.Mod = CurrentModule;
  3943. Unresolved.ID = Record[Idx];
  3944. Unresolved.Kind = UnresolvedModuleRef::Export;
  3945. Unresolved.IsWildcard = Record[Idx + 1];
  3946. UnresolvedModuleRefs.push_back(Unresolved);
  3947. }
  3948. // Once we've loaded the set of exports, there's no reason to keep
  3949. // the parsed, unresolved exports around.
  3950. CurrentModule->UnresolvedExports.clear();
  3951. break;
  3952. }
  3953. case SUBMODULE_REQUIRES: {
  3954. if (First) {
  3955. Error("missing submodule metadata record at beginning of block");
  3956. return Failure;
  3957. }
  3958. if (!CurrentModule)
  3959. break;
  3960. CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
  3961. Context.getTargetInfo());
  3962. break;
  3963. }
  3964. case SUBMODULE_LINK_LIBRARY:
  3965. if (First) {
  3966. Error("missing submodule metadata record at beginning of block");
  3967. return Failure;
  3968. }
  3969. if (!CurrentModule)
  3970. break;
  3971. CurrentModule->LinkLibraries.push_back(
  3972. Module::LinkLibrary(Blob, Record[0]));
  3973. break;
  3974. case SUBMODULE_CONFIG_MACRO:
  3975. if (First) {
  3976. Error("missing submodule metadata record at beginning of block");
  3977. return Failure;
  3978. }
  3979. if (!CurrentModule)
  3980. break;
  3981. CurrentModule->ConfigMacros.push_back(Blob.str());
  3982. break;
  3983. case SUBMODULE_CONFLICT: {
  3984. if (First) {
  3985. Error("missing submodule metadata record at beginning of block");
  3986. return Failure;
  3987. }
  3988. if (!CurrentModule)
  3989. break;
  3990. UnresolvedModuleRef Unresolved;
  3991. Unresolved.File = &F;
  3992. Unresolved.Mod = CurrentModule;
  3993. Unresolved.ID = Record[0];
  3994. Unresolved.Kind = UnresolvedModuleRef::Conflict;
  3995. Unresolved.IsWildcard = false;
  3996. Unresolved.String = Blob;
  3997. UnresolvedModuleRefs.push_back(Unresolved);
  3998. break;
  3999. }
  4000. }
  4001. }
  4002. }
  4003. /// \brief Parse the record that corresponds to a LangOptions data
  4004. /// structure.
  4005. ///
  4006. /// This routine parses the language options from the AST file and then gives
  4007. /// them to the AST listener if one is set.
  4008. ///
  4009. /// \returns true if the listener deems the file unacceptable, false otherwise.
  4010. bool ASTReader::ParseLanguageOptions(const RecordData &Record,
  4011. bool Complain,
  4012. ASTReaderListener &Listener) {
  4013. LangOptions LangOpts;
  4014. unsigned Idx = 0;
  4015. #define LANGOPT(Name, Bits, Default, Description) \
  4016. LangOpts.Name = Record[Idx++];
  4017. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  4018. LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
  4019. #include "clang/Basic/LangOptions.def"
  4020. #define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
  4021. #include "clang/Basic/Sanitizers.def"
  4022. ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
  4023. VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
  4024. LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
  4025. unsigned Length = Record[Idx++];
  4026. LangOpts.CurrentModule.assign(Record.begin() + Idx,
  4027. Record.begin() + Idx + Length);
  4028. Idx += Length;
  4029. // Comment options.
  4030. for (unsigned N = Record[Idx++]; N; --N) {
  4031. LangOpts.CommentOpts.BlockCommandNames.push_back(
  4032. ReadString(Record, Idx));
  4033. }
  4034. LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
  4035. return Listener.ReadLanguageOptions(LangOpts, Complain);
  4036. }
  4037. bool ASTReader::ParseTargetOptions(const RecordData &Record,
  4038. bool Complain,
  4039. ASTReaderListener &Listener) {
  4040. unsigned Idx = 0;
  4041. TargetOptions TargetOpts;
  4042. TargetOpts.Triple = ReadString(Record, Idx);
  4043. TargetOpts.CPU = ReadString(Record, Idx);
  4044. TargetOpts.ABI = ReadString(Record, Idx);
  4045. for (unsigned N = Record[Idx++]; N; --N) {
  4046. TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
  4047. }
  4048. for (unsigned N = Record[Idx++]; N; --N) {
  4049. TargetOpts.Features.push_back(ReadString(Record, Idx));
  4050. }
  4051. return Listener.ReadTargetOptions(TargetOpts, Complain);
  4052. }
  4053. bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  4054. ASTReaderListener &Listener) {
  4055. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
  4056. unsigned Idx = 0;
  4057. #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
  4058. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  4059. DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
  4060. #include "clang/Basic/DiagnosticOptions.def"
  4061. for (unsigned N = Record[Idx++]; N; --N)
  4062. DiagOpts->Warnings.push_back(ReadString(Record, Idx));
  4063. for (unsigned N = Record[Idx++]; N; --N)
  4064. DiagOpts->Remarks.push_back(ReadString(Record, Idx));
  4065. return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
  4066. }
  4067. bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
  4068. ASTReaderListener &Listener) {
  4069. FileSystemOptions FSOpts;
  4070. unsigned Idx = 0;
  4071. FSOpts.WorkingDir = ReadString(Record, Idx);
  4072. return Listener.ReadFileSystemOptions(FSOpts, Complain);
  4073. }
  4074. bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
  4075. bool Complain,
  4076. ASTReaderListener &Listener) {
  4077. HeaderSearchOptions HSOpts;
  4078. unsigned Idx = 0;
  4079. HSOpts.Sysroot = ReadString(Record, Idx);
  4080. // Include entries.
  4081. for (unsigned N = Record[Idx++]; N; --N) {
  4082. std::string Path = ReadString(Record, Idx);
  4083. frontend::IncludeDirGroup Group
  4084. = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
  4085. bool IsFramework = Record[Idx++];
  4086. bool IgnoreSysRoot = Record[Idx++];
  4087. HSOpts.UserEntries.push_back(
  4088. HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
  4089. }
  4090. // System header prefixes.
  4091. for (unsigned N = Record[Idx++]; N; --N) {
  4092. std::string Prefix = ReadString(Record, Idx);
  4093. bool IsSystemHeader = Record[Idx++];
  4094. HSOpts.SystemHeaderPrefixes.push_back(
  4095. HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
  4096. }
  4097. HSOpts.ResourceDir = ReadString(Record, Idx);
  4098. HSOpts.ModuleCachePath = ReadString(Record, Idx);
  4099. HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
  4100. HSOpts.DisableModuleHash = Record[Idx++];
  4101. HSOpts.UseBuiltinIncludes = Record[Idx++];
  4102. HSOpts.UseStandardSystemIncludes = Record[Idx++];
  4103. HSOpts.UseStandardCXXIncludes = Record[Idx++];
  4104. HSOpts.UseLibcxx = Record[Idx++];
  4105. return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
  4106. }
  4107. bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
  4108. bool Complain,
  4109. ASTReaderListener &Listener,
  4110. std::string &SuggestedPredefines) {
  4111. PreprocessorOptions PPOpts;
  4112. unsigned Idx = 0;
  4113. // Macro definitions/undefs
  4114. for (unsigned N = Record[Idx++]; N; --N) {
  4115. std::string Macro = ReadString(Record, Idx);
  4116. bool IsUndef = Record[Idx++];
  4117. PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
  4118. }
  4119. // Includes
  4120. for (unsigned N = Record[Idx++]; N; --N) {
  4121. PPOpts.Includes.push_back(ReadString(Record, Idx));
  4122. }
  4123. // Macro Includes
  4124. for (unsigned N = Record[Idx++]; N; --N) {
  4125. PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
  4126. }
  4127. PPOpts.UsePredefines = Record[Idx++];
  4128. PPOpts.DetailedRecord = Record[Idx++];
  4129. PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
  4130. PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
  4131. PPOpts.ObjCXXARCStandardLibrary =
  4132. static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
  4133. SuggestedPredefines.clear();
  4134. return Listener.ReadPreprocessorOptions(PPOpts, Complain,
  4135. SuggestedPredefines);
  4136. }
  4137. std::pair<ModuleFile *, unsigned>
  4138. ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
  4139. GlobalPreprocessedEntityMapType::iterator
  4140. I = GlobalPreprocessedEntityMap.find(GlobalIndex);
  4141. assert(I != GlobalPreprocessedEntityMap.end() &&
  4142. "Corrupted global preprocessed entity map");
  4143. ModuleFile *M = I->second;
  4144. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
  4145. return std::make_pair(M, LocalIndex);
  4146. }
  4147. std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
  4148. ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
  4149. if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
  4150. return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
  4151. Mod.NumPreprocessedEntities);
  4152. return std::make_pair(PreprocessingRecord::iterator(),
  4153. PreprocessingRecord::iterator());
  4154. }
  4155. std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
  4156. ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
  4157. return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
  4158. ModuleDeclIterator(this, &Mod,
  4159. Mod.FileSortedDecls + Mod.NumFileSortedDecls));
  4160. }
  4161. PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
  4162. PreprocessedEntityID PPID = Index+1;
  4163. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4164. ModuleFile &M = *PPInfo.first;
  4165. unsigned LocalIndex = PPInfo.second;
  4166. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4167. if (!PP.getPreprocessingRecord()) {
  4168. Error("no preprocessing record");
  4169. return nullptr;
  4170. }
  4171. SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
  4172. M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
  4173. llvm::BitstreamEntry Entry =
  4174. M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  4175. if (Entry.Kind != llvm::BitstreamEntry::Record)
  4176. return nullptr;
  4177. // Read the record.
  4178. SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
  4179. ReadSourceLocation(M, PPOffs.End));
  4180. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  4181. StringRef Blob;
  4182. RecordData Record;
  4183. PreprocessorDetailRecordTypes RecType =
  4184. (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
  4185. Entry.ID, Record, &Blob);
  4186. switch (RecType) {
  4187. case PPD_MACRO_EXPANSION: {
  4188. bool isBuiltin = Record[0];
  4189. IdentifierInfo *Name = nullptr;
  4190. MacroDefinition *Def = nullptr;
  4191. if (isBuiltin)
  4192. Name = getLocalIdentifier(M, Record[1]);
  4193. else {
  4194. PreprocessedEntityID
  4195. GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
  4196. Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
  4197. }
  4198. MacroExpansion *ME;
  4199. if (isBuiltin)
  4200. ME = new (PPRec) MacroExpansion(Name, Range);
  4201. else
  4202. ME = new (PPRec) MacroExpansion(Def, Range);
  4203. return ME;
  4204. }
  4205. case PPD_MACRO_DEFINITION: {
  4206. // Decode the identifier info and then check again; if the macro is
  4207. // still defined and associated with the identifier,
  4208. IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
  4209. MacroDefinition *MD
  4210. = new (PPRec) MacroDefinition(II, Range);
  4211. if (DeserializationListener)
  4212. DeserializationListener->MacroDefinitionRead(PPID, MD);
  4213. return MD;
  4214. }
  4215. case PPD_INCLUSION_DIRECTIVE: {
  4216. const char *FullFileNameStart = Blob.data() + Record[0];
  4217. StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
  4218. const FileEntry *File = nullptr;
  4219. if (!FullFileName.empty())
  4220. File = PP.getFileManager().getFile(FullFileName);
  4221. // FIXME: Stable encoding
  4222. InclusionDirective::InclusionKind Kind
  4223. = static_cast<InclusionDirective::InclusionKind>(Record[2]);
  4224. InclusionDirective *ID
  4225. = new (PPRec) InclusionDirective(PPRec, Kind,
  4226. StringRef(Blob.data(), Record[0]),
  4227. Record[1], Record[3],
  4228. File,
  4229. Range);
  4230. return ID;
  4231. }
  4232. }
  4233. llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
  4234. }
  4235. /// \brief \arg SLocMapI points at a chunk of a module that contains no
  4236. /// preprocessed entities or the entities it contains are not the ones we are
  4237. /// looking for. Find the next module that contains entities and return the ID
  4238. /// of the first entry.
  4239. PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
  4240. GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
  4241. ++SLocMapI;
  4242. for (GlobalSLocOffsetMapType::const_iterator
  4243. EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
  4244. ModuleFile &M = *SLocMapI->second;
  4245. if (M.NumPreprocessedEntities)
  4246. return M.BasePreprocessedEntityID;
  4247. }
  4248. return getTotalNumPreprocessedEntities();
  4249. }
  4250. namespace {
  4251. template <unsigned PPEntityOffset::*PPLoc>
  4252. struct PPEntityComp {
  4253. const ASTReader &Reader;
  4254. ModuleFile &M;
  4255. PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
  4256. bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
  4257. SourceLocation LHS = getLoc(L);
  4258. SourceLocation RHS = getLoc(R);
  4259. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4260. }
  4261. bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
  4262. SourceLocation LHS = getLoc(L);
  4263. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4264. }
  4265. bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
  4266. SourceLocation RHS = getLoc(R);
  4267. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4268. }
  4269. SourceLocation getLoc(const PPEntityOffset &PPE) const {
  4270. return Reader.ReadSourceLocation(M, PPE.*PPLoc);
  4271. }
  4272. };
  4273. }
  4274. PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
  4275. bool EndsAfter) const {
  4276. if (SourceMgr.isLocalSourceLocation(Loc))
  4277. return getTotalNumPreprocessedEntities();
  4278. GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
  4279. SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
  4280. assert(SLocMapI != GlobalSLocOffsetMap.end() &&
  4281. "Corrupted global sloc offset map");
  4282. if (SLocMapI->second->NumPreprocessedEntities == 0)
  4283. return findNextPreprocessedEntity(SLocMapI);
  4284. ModuleFile &M = *SLocMapI->second;
  4285. typedef const PPEntityOffset *pp_iterator;
  4286. pp_iterator pp_begin = M.PreprocessedEntityOffsets;
  4287. pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
  4288. size_t Count = M.NumPreprocessedEntities;
  4289. size_t Half;
  4290. pp_iterator First = pp_begin;
  4291. pp_iterator PPI;
  4292. if (EndsAfter) {
  4293. PPI = std::upper_bound(pp_begin, pp_end, Loc,
  4294. PPEntityComp<&PPEntityOffset::Begin>(*this, M));
  4295. } else {
  4296. // Do a binary search manually instead of using std::lower_bound because
  4297. // The end locations of entities may be unordered (when a macro expansion
  4298. // is inside another macro argument), but for this case it is not important
  4299. // whether we get the first macro expansion or its containing macro.
  4300. while (Count > 0) {
  4301. Half = Count / 2;
  4302. PPI = First;
  4303. std::advance(PPI, Half);
  4304. if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
  4305. Loc)) {
  4306. First = PPI;
  4307. ++First;
  4308. Count = Count - Half - 1;
  4309. } else
  4310. Count = Half;
  4311. }
  4312. }
  4313. if (PPI == pp_end)
  4314. return findNextPreprocessedEntity(SLocMapI);
  4315. return M.BasePreprocessedEntityID + (PPI - pp_begin);
  4316. }
  4317. /// \brief Returns a pair of [Begin, End) indices of preallocated
  4318. /// preprocessed entities that \arg Range encompasses.
  4319. std::pair<unsigned, unsigned>
  4320. ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
  4321. if (Range.isInvalid())
  4322. return std::make_pair(0,0);
  4323. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  4324. PreprocessedEntityID BeginID =
  4325. findPreprocessedEntity(Range.getBegin(), false);
  4326. PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
  4327. return std::make_pair(BeginID, EndID);
  4328. }
  4329. /// \brief Optionally returns true or false if the preallocated preprocessed
  4330. /// entity with index \arg Index came from file \arg FID.
  4331. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
  4332. FileID FID) {
  4333. if (FID.isInvalid())
  4334. return false;
  4335. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4336. ModuleFile &M = *PPInfo.first;
  4337. unsigned LocalIndex = PPInfo.second;
  4338. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4339. SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
  4340. if (Loc.isInvalid())
  4341. return false;
  4342. if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
  4343. return true;
  4344. else
  4345. return false;
  4346. }
  4347. namespace {
  4348. /// \brief Visitor used to search for information about a header file.
  4349. class HeaderFileInfoVisitor {
  4350. const FileEntry *FE;
  4351. Optional<HeaderFileInfo> HFI;
  4352. public:
  4353. explicit HeaderFileInfoVisitor(const FileEntry *FE)
  4354. : FE(FE) { }
  4355. static bool visit(ModuleFile &M, void *UserData) {
  4356. HeaderFileInfoVisitor *This
  4357. = static_cast<HeaderFileInfoVisitor *>(UserData);
  4358. HeaderFileInfoLookupTable *Table
  4359. = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
  4360. if (!Table)
  4361. return false;
  4362. // Look in the on-disk hash table for an entry for this file name.
  4363. HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
  4364. if (Pos == Table->end())
  4365. return false;
  4366. This->HFI = *Pos;
  4367. return true;
  4368. }
  4369. Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
  4370. };
  4371. }
  4372. HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
  4373. HeaderFileInfoVisitor Visitor(FE);
  4374. ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
  4375. if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
  4376. return *HFI;
  4377. return HeaderFileInfo();
  4378. }
  4379. void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
  4380. // FIXME: Make it work properly with modules.
  4381. SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
  4382. for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
  4383. ModuleFile &F = *(*I);
  4384. unsigned Idx = 0;
  4385. DiagStates.clear();
  4386. assert(!Diag.DiagStates.empty());
  4387. DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
  4388. while (Idx < F.PragmaDiagMappings.size()) {
  4389. SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
  4390. unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
  4391. if (DiagStateID != 0) {
  4392. Diag.DiagStatePoints.push_back(
  4393. DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
  4394. FullSourceLoc(Loc, SourceMgr)));
  4395. continue;
  4396. }
  4397. assert(DiagStateID == 0);
  4398. // A new DiagState was created here.
  4399. Diag.DiagStates.push_back(*Diag.GetCurDiagState());
  4400. DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
  4401. DiagStates.push_back(NewState);
  4402. Diag.DiagStatePoints.push_back(
  4403. DiagnosticsEngine::DiagStatePoint(NewState,
  4404. FullSourceLoc(Loc, SourceMgr)));
  4405. while (1) {
  4406. assert(Idx < F.PragmaDiagMappings.size() &&
  4407. "Invalid data, didn't find '-1' marking end of diag/map pairs");
  4408. if (Idx >= F.PragmaDiagMappings.size()) {
  4409. break; // Something is messed up but at least avoid infinite loop in
  4410. // release build.
  4411. }
  4412. unsigned DiagID = F.PragmaDiagMappings[Idx++];
  4413. if (DiagID == (unsigned)-1) {
  4414. break; // no more diag/map pairs for this location.
  4415. }
  4416. diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
  4417. DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
  4418. Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
  4419. }
  4420. }
  4421. }
  4422. }
  4423. /// \brief Get the correct cursor and offset for loading a type.
  4424. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
  4425. GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
  4426. assert(I != GlobalTypeMap.end() && "Corrupted global type map");
  4427. ModuleFile *M = I->second;
  4428. return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
  4429. }
  4430. /// \brief Read and return the type with the given index..
  4431. ///
  4432. /// The index is the type ID, shifted and minus the number of predefs. This
  4433. /// routine actually reads the record corresponding to the type at the given
  4434. /// location. It is a helper routine for GetType, which deals with reading type
  4435. /// IDs.
  4436. QualType ASTReader::readTypeRecord(unsigned Index) {
  4437. RecordLocation Loc = TypeCursorForIndex(Index);
  4438. BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  4439. // Keep track of where we are in the stream, then jump back there
  4440. // after reading this type.
  4441. SavedStreamPosition SavedPosition(DeclsCursor);
  4442. ReadingKindTracker ReadingKind(Read_Type, *this);
  4443. // Note that we are loading a type record.
  4444. Deserializing AType(this);
  4445. unsigned Idx = 0;
  4446. DeclsCursor.JumpToBit(Loc.Offset);
  4447. RecordData Record;
  4448. unsigned Code = DeclsCursor.ReadCode();
  4449. switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
  4450. case TYPE_EXT_QUAL: {
  4451. if (Record.size() != 2) {
  4452. Error("Incorrect encoding of extended qualifier type");
  4453. return QualType();
  4454. }
  4455. QualType Base = readType(*Loc.F, Record, Idx);
  4456. Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
  4457. return Context.getQualifiedType(Base, Quals);
  4458. }
  4459. case TYPE_COMPLEX: {
  4460. if (Record.size() != 1) {
  4461. Error("Incorrect encoding of complex type");
  4462. return QualType();
  4463. }
  4464. QualType ElemType = readType(*Loc.F, Record, Idx);
  4465. return Context.getComplexType(ElemType);
  4466. }
  4467. case TYPE_POINTER: {
  4468. if (Record.size() != 1) {
  4469. Error("Incorrect encoding of pointer type");
  4470. return QualType();
  4471. }
  4472. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4473. return Context.getPointerType(PointeeType);
  4474. }
  4475. case TYPE_DECAYED: {
  4476. if (Record.size() != 1) {
  4477. Error("Incorrect encoding of decayed type");
  4478. return QualType();
  4479. }
  4480. QualType OriginalType = readType(*Loc.F, Record, Idx);
  4481. QualType DT = Context.getAdjustedParameterType(OriginalType);
  4482. if (!isa<DecayedType>(DT))
  4483. Error("Decayed type does not decay");
  4484. return DT;
  4485. }
  4486. case TYPE_ADJUSTED: {
  4487. if (Record.size() != 2) {
  4488. Error("Incorrect encoding of adjusted type");
  4489. return QualType();
  4490. }
  4491. QualType OriginalTy = readType(*Loc.F, Record, Idx);
  4492. QualType AdjustedTy = readType(*Loc.F, Record, Idx);
  4493. return Context.getAdjustedType(OriginalTy, AdjustedTy);
  4494. }
  4495. case TYPE_BLOCK_POINTER: {
  4496. if (Record.size() != 1) {
  4497. Error("Incorrect encoding of block pointer type");
  4498. return QualType();
  4499. }
  4500. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4501. return Context.getBlockPointerType(PointeeType);
  4502. }
  4503. case TYPE_LVALUE_REFERENCE: {
  4504. if (Record.size() != 2) {
  4505. Error("Incorrect encoding of lvalue reference type");
  4506. return QualType();
  4507. }
  4508. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4509. return Context.getLValueReferenceType(PointeeType, Record[1]);
  4510. }
  4511. case TYPE_RVALUE_REFERENCE: {
  4512. if (Record.size() != 1) {
  4513. Error("Incorrect encoding of rvalue reference type");
  4514. return QualType();
  4515. }
  4516. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4517. return Context.getRValueReferenceType(PointeeType);
  4518. }
  4519. case TYPE_MEMBER_POINTER: {
  4520. if (Record.size() != 2) {
  4521. Error("Incorrect encoding of member pointer type");
  4522. return QualType();
  4523. }
  4524. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4525. QualType ClassType = readType(*Loc.F, Record, Idx);
  4526. if (PointeeType.isNull() || ClassType.isNull())
  4527. return QualType();
  4528. return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
  4529. }
  4530. case TYPE_CONSTANT_ARRAY: {
  4531. QualType ElementType = readType(*Loc.F, Record, Idx);
  4532. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4533. unsigned IndexTypeQuals = Record[2];
  4534. unsigned Idx = 3;
  4535. llvm::APInt Size = ReadAPInt(Record, Idx);
  4536. return Context.getConstantArrayType(ElementType, Size,
  4537. ASM, IndexTypeQuals);
  4538. }
  4539. case TYPE_INCOMPLETE_ARRAY: {
  4540. QualType ElementType = readType(*Loc.F, Record, Idx);
  4541. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4542. unsigned IndexTypeQuals = Record[2];
  4543. return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
  4544. }
  4545. case TYPE_VARIABLE_ARRAY: {
  4546. QualType ElementType = readType(*Loc.F, Record, Idx);
  4547. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4548. unsigned IndexTypeQuals = Record[2];
  4549. SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
  4550. SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
  4551. return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
  4552. ASM, IndexTypeQuals,
  4553. SourceRange(LBLoc, RBLoc));
  4554. }
  4555. case TYPE_VECTOR: {
  4556. if (Record.size() != 3) {
  4557. Error("incorrect encoding of vector type in AST file");
  4558. return QualType();
  4559. }
  4560. QualType ElementType = readType(*Loc.F, Record, Idx);
  4561. unsigned NumElements = Record[1];
  4562. unsigned VecKind = Record[2];
  4563. return Context.getVectorType(ElementType, NumElements,
  4564. (VectorType::VectorKind)VecKind);
  4565. }
  4566. case TYPE_EXT_VECTOR: {
  4567. if (Record.size() != 3) {
  4568. Error("incorrect encoding of extended vector type in AST file");
  4569. return QualType();
  4570. }
  4571. QualType ElementType = readType(*Loc.F, Record, Idx);
  4572. unsigned NumElements = Record[1];
  4573. return Context.getExtVectorType(ElementType, NumElements);
  4574. }
  4575. case TYPE_FUNCTION_NO_PROTO: {
  4576. if (Record.size() != 6) {
  4577. Error("incorrect encoding of no-proto function type");
  4578. return QualType();
  4579. }
  4580. QualType ResultType = readType(*Loc.F, Record, Idx);
  4581. FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
  4582. (CallingConv)Record[4], Record[5]);
  4583. return Context.getFunctionNoProtoType(ResultType, Info);
  4584. }
  4585. case TYPE_FUNCTION_PROTO: {
  4586. QualType ResultType = readType(*Loc.F, Record, Idx);
  4587. FunctionProtoType::ExtProtoInfo EPI;
  4588. EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
  4589. /*hasregparm*/ Record[2],
  4590. /*regparm*/ Record[3],
  4591. static_cast<CallingConv>(Record[4]),
  4592. /*produces*/ Record[5]);
  4593. unsigned Idx = 6;
  4594. EPI.Variadic = Record[Idx++];
  4595. EPI.HasTrailingReturn = Record[Idx++];
  4596. EPI.TypeQuals = Record[Idx++];
  4597. EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
  4598. SmallVector<QualType, 8> ExceptionStorage;
  4599. readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
  4600. unsigned NumParams = Record[Idx++];
  4601. SmallVector<QualType, 16> ParamTypes;
  4602. for (unsigned I = 0; I != NumParams; ++I)
  4603. ParamTypes.push_back(readType(*Loc.F, Record, Idx));
  4604. return Context.getFunctionType(ResultType, ParamTypes, EPI);
  4605. }
  4606. case TYPE_UNRESOLVED_USING: {
  4607. unsigned Idx = 0;
  4608. return Context.getTypeDeclType(
  4609. ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
  4610. }
  4611. case TYPE_TYPEDEF: {
  4612. if (Record.size() != 2) {
  4613. Error("incorrect encoding of typedef type");
  4614. return QualType();
  4615. }
  4616. unsigned Idx = 0;
  4617. TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
  4618. QualType Canonical = readType(*Loc.F, Record, Idx);
  4619. if (!Canonical.isNull())
  4620. Canonical = Context.getCanonicalType(Canonical);
  4621. return Context.getTypedefType(Decl, Canonical);
  4622. }
  4623. case TYPE_TYPEOF_EXPR:
  4624. return Context.getTypeOfExprType(ReadExpr(*Loc.F));
  4625. case TYPE_TYPEOF: {
  4626. if (Record.size() != 1) {
  4627. Error("incorrect encoding of typeof(type) in AST file");
  4628. return QualType();
  4629. }
  4630. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4631. return Context.getTypeOfType(UnderlyingType);
  4632. }
  4633. case TYPE_DECLTYPE: {
  4634. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4635. return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
  4636. }
  4637. case TYPE_UNARY_TRANSFORM: {
  4638. QualType BaseType = readType(*Loc.F, Record, Idx);
  4639. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4640. UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
  4641. return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
  4642. }
  4643. case TYPE_AUTO: {
  4644. QualType Deduced = readType(*Loc.F, Record, Idx);
  4645. bool IsDecltypeAuto = Record[Idx++];
  4646. bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
  4647. return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
  4648. }
  4649. case TYPE_RECORD: {
  4650. if (Record.size() != 2) {
  4651. Error("incorrect encoding of record type");
  4652. return QualType();
  4653. }
  4654. unsigned Idx = 0;
  4655. bool IsDependent = Record[Idx++];
  4656. RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
  4657. RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
  4658. QualType T = Context.getRecordType(RD);
  4659. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4660. return T;
  4661. }
  4662. case TYPE_ENUM: {
  4663. if (Record.size() != 2) {
  4664. Error("incorrect encoding of enum type");
  4665. return QualType();
  4666. }
  4667. unsigned Idx = 0;
  4668. bool IsDependent = Record[Idx++];
  4669. QualType T
  4670. = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
  4671. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4672. return T;
  4673. }
  4674. case TYPE_ATTRIBUTED: {
  4675. if (Record.size() != 3) {
  4676. Error("incorrect encoding of attributed type");
  4677. return QualType();
  4678. }
  4679. QualType modifiedType = readType(*Loc.F, Record, Idx);
  4680. QualType equivalentType = readType(*Loc.F, Record, Idx);
  4681. AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
  4682. return Context.getAttributedType(kind, modifiedType, equivalentType);
  4683. }
  4684. case TYPE_PAREN: {
  4685. if (Record.size() != 1) {
  4686. Error("incorrect encoding of paren type");
  4687. return QualType();
  4688. }
  4689. QualType InnerType = readType(*Loc.F, Record, Idx);
  4690. return Context.getParenType(InnerType);
  4691. }
  4692. case TYPE_PACK_EXPANSION: {
  4693. if (Record.size() != 2) {
  4694. Error("incorrect encoding of pack expansion type");
  4695. return QualType();
  4696. }
  4697. QualType Pattern = readType(*Loc.F, Record, Idx);
  4698. if (Pattern.isNull())
  4699. return QualType();
  4700. Optional<unsigned> NumExpansions;
  4701. if (Record[1])
  4702. NumExpansions = Record[1] - 1;
  4703. return Context.getPackExpansionType(Pattern, NumExpansions);
  4704. }
  4705. case TYPE_ELABORATED: {
  4706. unsigned Idx = 0;
  4707. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4708. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4709. QualType NamedType = readType(*Loc.F, Record, Idx);
  4710. return Context.getElaboratedType(Keyword, NNS, NamedType);
  4711. }
  4712. case TYPE_OBJC_INTERFACE: {
  4713. unsigned Idx = 0;
  4714. ObjCInterfaceDecl *ItfD
  4715. = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
  4716. return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
  4717. }
  4718. case TYPE_OBJC_OBJECT: {
  4719. unsigned Idx = 0;
  4720. QualType Base = readType(*Loc.F, Record, Idx);
  4721. unsigned NumProtos = Record[Idx++];
  4722. SmallVector<ObjCProtocolDecl*, 4> Protos;
  4723. for (unsigned I = 0; I != NumProtos; ++I)
  4724. Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
  4725. return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
  4726. }
  4727. case TYPE_OBJC_OBJECT_POINTER: {
  4728. unsigned Idx = 0;
  4729. QualType Pointee = readType(*Loc.F, Record, Idx);
  4730. return Context.getObjCObjectPointerType(Pointee);
  4731. }
  4732. case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
  4733. unsigned Idx = 0;
  4734. QualType Parm = readType(*Loc.F, Record, Idx);
  4735. QualType Replacement = readType(*Loc.F, Record, Idx);
  4736. return Context.getSubstTemplateTypeParmType(
  4737. cast<TemplateTypeParmType>(Parm),
  4738. Context.getCanonicalType(Replacement));
  4739. }
  4740. case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
  4741. unsigned Idx = 0;
  4742. QualType Parm = readType(*Loc.F, Record, Idx);
  4743. TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
  4744. return Context.getSubstTemplateTypeParmPackType(
  4745. cast<TemplateTypeParmType>(Parm),
  4746. ArgPack);
  4747. }
  4748. case TYPE_INJECTED_CLASS_NAME: {
  4749. CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
  4750. QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
  4751. // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
  4752. // for AST reading, too much interdependencies.
  4753. const Type *T;
  4754. if (const Type *Existing = D->getTypeForDecl())
  4755. T = Existing;
  4756. else if (auto *Prev = D->getPreviousDecl())
  4757. T = Prev->getTypeForDecl();
  4758. else
  4759. T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
  4760. return QualType(T, 0);
  4761. }
  4762. case TYPE_TEMPLATE_TYPE_PARM: {
  4763. unsigned Idx = 0;
  4764. unsigned Depth = Record[Idx++];
  4765. unsigned Index = Record[Idx++];
  4766. bool Pack = Record[Idx++];
  4767. TemplateTypeParmDecl *D
  4768. = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
  4769. return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
  4770. }
  4771. case TYPE_DEPENDENT_NAME: {
  4772. unsigned Idx = 0;
  4773. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4774. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4775. const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
  4776. QualType Canon = readType(*Loc.F, Record, Idx);
  4777. if (!Canon.isNull())
  4778. Canon = Context.getCanonicalType(Canon);
  4779. return Context.getDependentNameType(Keyword, NNS, Name, Canon);
  4780. }
  4781. case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
  4782. unsigned Idx = 0;
  4783. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4784. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4785. const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
  4786. unsigned NumArgs = Record[Idx++];
  4787. SmallVector<TemplateArgument, 8> Args;
  4788. Args.reserve(NumArgs);
  4789. while (NumArgs--)
  4790. Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
  4791. return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
  4792. Args.size(), Args.data());
  4793. }
  4794. case TYPE_DEPENDENT_SIZED_ARRAY: {
  4795. unsigned Idx = 0;
  4796. // ArrayType
  4797. QualType ElementType = readType(*Loc.F, Record, Idx);
  4798. ArrayType::ArraySizeModifier ASM
  4799. = (ArrayType::ArraySizeModifier)Record[Idx++];
  4800. unsigned IndexTypeQuals = Record[Idx++];
  4801. // DependentSizedArrayType
  4802. Expr *NumElts = ReadExpr(*Loc.F);
  4803. SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
  4804. return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
  4805. IndexTypeQuals, Brackets);
  4806. }
  4807. case TYPE_TEMPLATE_SPECIALIZATION: {
  4808. unsigned Idx = 0;
  4809. bool IsDependent = Record[Idx++];
  4810. TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
  4811. SmallVector<TemplateArgument, 8> Args;
  4812. ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
  4813. QualType Underlying = readType(*Loc.F, Record, Idx);
  4814. QualType T;
  4815. if (Underlying.isNull())
  4816. T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
  4817. Args.size());
  4818. else
  4819. T = Context.getTemplateSpecializationType(Name, Args.data(),
  4820. Args.size(), Underlying);
  4821. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4822. return T;
  4823. }
  4824. case TYPE_ATOMIC: {
  4825. if (Record.size() != 1) {
  4826. Error("Incorrect encoding of atomic type");
  4827. return QualType();
  4828. }
  4829. QualType ValueType = readType(*Loc.F, Record, Idx);
  4830. return Context.getAtomicType(ValueType);
  4831. }
  4832. }
  4833. llvm_unreachable("Invalid TypeCode!");
  4834. }
  4835. void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
  4836. SmallVectorImpl<QualType> &Exceptions,
  4837. FunctionProtoType::ExceptionSpecInfo &ESI,
  4838. const RecordData &Record, unsigned &Idx) {
  4839. ExceptionSpecificationType EST =
  4840. static_cast<ExceptionSpecificationType>(Record[Idx++]);
  4841. ESI.Type = EST;
  4842. if (EST == EST_Dynamic) {
  4843. for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
  4844. Exceptions.push_back(readType(ModuleFile, Record, Idx));
  4845. ESI.Exceptions = Exceptions;
  4846. } else if (EST == EST_ComputedNoexcept) {
  4847. ESI.NoexceptExpr = ReadExpr(ModuleFile);
  4848. } else if (EST == EST_Uninstantiated) {
  4849. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4850. ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4851. } else if (EST == EST_Unevaluated) {
  4852. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4853. }
  4854. }
  4855. class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  4856. ASTReader &Reader;
  4857. ModuleFile &F;
  4858. const ASTReader::RecordData &Record;
  4859. unsigned &Idx;
  4860. SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
  4861. unsigned &I) {
  4862. return Reader.ReadSourceLocation(F, R, I);
  4863. }
  4864. template<typename T>
  4865. T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
  4866. return Reader.ReadDeclAs<T>(F, Record, Idx);
  4867. }
  4868. public:
  4869. TypeLocReader(ASTReader &Reader, ModuleFile &F,
  4870. const ASTReader::RecordData &Record, unsigned &Idx)
  4871. : Reader(Reader), F(F), Record(Record), Idx(Idx)
  4872. { }
  4873. // We want compile-time assurance that we've enumerated all of
  4874. // these, so unfortunately we have to declare them first, then
  4875. // define them out-of-line.
  4876. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4877. #define TYPELOC(CLASS, PARENT) \
  4878. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  4879. #include "clang/AST/TypeLocNodes.def"
  4880. void VisitFunctionTypeLoc(FunctionTypeLoc);
  4881. void VisitArrayTypeLoc(ArrayTypeLoc);
  4882. };
  4883. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4884. // nothing to do
  4885. }
  4886. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  4887. TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
  4888. if (TL.needsExtraLocalData()) {
  4889. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
  4890. TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
  4891. TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
  4892. TL.setModeAttr(Record[Idx++]);
  4893. }
  4894. }
  4895. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  4896. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4897. }
  4898. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  4899. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  4900. }
  4901. void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  4902. // nothing to do
  4903. }
  4904. void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  4905. // nothing to do
  4906. }
  4907. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  4908. TL.setCaretLoc(ReadSourceLocation(Record, Idx));
  4909. }
  4910. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  4911. TL.setAmpLoc(ReadSourceLocation(Record, Idx));
  4912. }
  4913. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  4914. TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
  4915. }
  4916. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  4917. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  4918. TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4919. }
  4920. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  4921. TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
  4922. TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
  4923. if (Record[Idx++])
  4924. TL.setSizeExpr(Reader.ReadExpr(F));
  4925. else
  4926. TL.setSizeExpr(nullptr);
  4927. }
  4928. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  4929. VisitArrayTypeLoc(TL);
  4930. }
  4931. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  4932. VisitArrayTypeLoc(TL);
  4933. }
  4934. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  4935. VisitArrayTypeLoc(TL);
  4936. }
  4937. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  4938. DependentSizedArrayTypeLoc TL) {
  4939. VisitArrayTypeLoc(TL);
  4940. }
  4941. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  4942. DependentSizedExtVectorTypeLoc TL) {
  4943. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4944. }
  4945. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  4946. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4947. }
  4948. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  4949. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4950. }
  4951. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  4952. TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
  4953. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4954. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4955. TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
  4956. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
  4957. TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
  4958. }
  4959. }
  4960. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  4961. VisitFunctionTypeLoc(TL);
  4962. }
  4963. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  4964. VisitFunctionTypeLoc(TL);
  4965. }
  4966. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  4967. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4968. }
  4969. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  4970. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4971. }
  4972. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  4973. TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
  4974. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4975. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4976. }
  4977. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  4978. TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
  4979. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4980. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4981. TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4982. }
  4983. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  4984. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4985. }
  4986. void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  4987. TL.setKWLoc(ReadSourceLocation(Record, Idx));
  4988. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4989. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4990. TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4991. }
  4992. void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
  4993. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4994. }
  4995. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  4996. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4997. }
  4998. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  4999. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5000. }
  5001. void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  5002. TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
  5003. if (TL.hasAttrOperand()) {
  5004. SourceRange range;
  5005. range.setBegin(ReadSourceLocation(Record, Idx));
  5006. range.setEnd(ReadSourceLocation(Record, Idx));
  5007. TL.setAttrOperandParensRange(range);
  5008. }
  5009. if (TL.hasAttrExprOperand()) {
  5010. if (Record[Idx++])
  5011. TL.setAttrExprOperand(Reader.ReadExpr(F));
  5012. else
  5013. TL.setAttrExprOperand(nullptr);
  5014. } else if (TL.hasAttrEnumOperand())
  5015. TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
  5016. }
  5017. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  5018. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5019. }
  5020. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  5021. SubstTemplateTypeParmTypeLoc TL) {
  5022. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5023. }
  5024. void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
  5025. SubstTemplateTypeParmPackTypeLoc TL) {
  5026. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5027. }
  5028. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  5029. TemplateSpecializationTypeLoc TL) {
  5030. TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
  5031. TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
  5032. TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
  5033. TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
  5034. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5035. TL.setArgLocInfo(i,
  5036. Reader.GetTemplateArgumentLocInfo(F,
  5037. TL.getTypePtr()->getArg(i).getKind(),
  5038. Record, Idx));
  5039. }
  5040. void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
  5041. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  5042. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  5043. }
  5044. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  5045. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  5046. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  5047. }
  5048. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  5049. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5050. }
  5051. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  5052. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  5053. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  5054. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5055. }
  5056. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  5057. DependentTemplateSpecializationTypeLoc TL) {
  5058. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  5059. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  5060. TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
  5061. TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
  5062. TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
  5063. TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
  5064. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  5065. TL.setArgLocInfo(I,
  5066. Reader.GetTemplateArgumentLocInfo(F,
  5067. TL.getTypePtr()->getArg(I).getKind(),
  5068. Record, Idx));
  5069. }
  5070. void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  5071. TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
  5072. }
  5073. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  5074. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  5075. }
  5076. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  5077. TL.setHasBaseTypeAsWritten(Record[Idx++]);
  5078. TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
  5079. TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
  5080. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5081. TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
  5082. }
  5083. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  5084. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  5085. }
  5086. void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  5087. TL.setKWLoc(ReadSourceLocation(Record, Idx));
  5088. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  5089. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  5090. }
  5091. TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
  5092. const RecordData &Record,
  5093. unsigned &Idx) {
  5094. QualType InfoTy = readType(F, Record, Idx);
  5095. if (InfoTy.isNull())
  5096. return nullptr;
  5097. TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
  5098. TypeLocReader TLR(*this, F, Record, Idx);
  5099. for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
  5100. TLR.Visit(TL);
  5101. return TInfo;
  5102. }
  5103. QualType ASTReader::GetType(TypeID ID) {
  5104. unsigned FastQuals = ID & Qualifiers::FastMask;
  5105. unsigned Index = ID >> Qualifiers::FastWidth;
  5106. if (Index < NUM_PREDEF_TYPE_IDS) {
  5107. QualType T;
  5108. switch ((PredefinedTypeIDs)Index) {
  5109. case PREDEF_TYPE_NULL_ID: return QualType();
  5110. case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
  5111. case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
  5112. case PREDEF_TYPE_CHAR_U_ID:
  5113. case PREDEF_TYPE_CHAR_S_ID:
  5114. // FIXME: Check that the signedness of CharTy is correct!
  5115. T = Context.CharTy;
  5116. break;
  5117. case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
  5118. case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
  5119. case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
  5120. case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
  5121. case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
  5122. case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
  5123. case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
  5124. case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
  5125. case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
  5126. case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
  5127. case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
  5128. case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
  5129. case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
  5130. case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
  5131. case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
  5132. case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
  5133. case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
  5134. case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
  5135. case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
  5136. case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
  5137. case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
  5138. case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
  5139. case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
  5140. case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
  5141. case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
  5142. case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
  5143. case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
  5144. case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
  5145. case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
  5146. case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
  5147. case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
  5148. case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
  5149. case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
  5150. case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
  5151. case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
  5152. case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
  5153. case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
  5154. case PREDEF_TYPE_AUTO_RREF_DEDUCT:
  5155. T = Context.getAutoRRefDeductType();
  5156. break;
  5157. case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
  5158. T = Context.ARCUnbridgedCastTy;
  5159. break;
  5160. case PREDEF_TYPE_VA_LIST_TAG:
  5161. T = Context.getVaListTagType();
  5162. break;
  5163. case PREDEF_TYPE_BUILTIN_FN:
  5164. T = Context.BuiltinFnTy;
  5165. break;
  5166. }
  5167. assert(!T.isNull() && "Unknown predefined type");
  5168. return T.withFastQualifiers(FastQuals);
  5169. }
  5170. Index -= NUM_PREDEF_TYPE_IDS;
  5171. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  5172. if (TypesLoaded[Index].isNull()) {
  5173. TypesLoaded[Index] = readTypeRecord(Index);
  5174. if (TypesLoaded[Index].isNull())
  5175. return QualType();
  5176. TypesLoaded[Index]->setFromAST();
  5177. if (DeserializationListener)
  5178. DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
  5179. TypesLoaded[Index]);
  5180. }
  5181. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  5182. }
  5183. QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
  5184. return GetType(getGlobalTypeID(F, LocalID));
  5185. }
  5186. serialization::TypeID
  5187. ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
  5188. unsigned FastQuals = LocalID & Qualifiers::FastMask;
  5189. unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
  5190. if (LocalIndex < NUM_PREDEF_TYPE_IDS)
  5191. return LocalID;
  5192. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  5193. = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
  5194. assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
  5195. unsigned GlobalIndex = LocalIndex + I->second;
  5196. return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
  5197. }
  5198. TemplateArgumentLocInfo
  5199. ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
  5200. TemplateArgument::ArgKind Kind,
  5201. const RecordData &Record,
  5202. unsigned &Index) {
  5203. switch (Kind) {
  5204. case TemplateArgument::Expression:
  5205. return ReadExpr(F);
  5206. case TemplateArgument::Type:
  5207. return GetTypeSourceInfo(F, Record, Index);
  5208. case TemplateArgument::Template: {
  5209. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5210. Index);
  5211. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5212. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5213. SourceLocation());
  5214. }
  5215. case TemplateArgument::TemplateExpansion: {
  5216. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5217. Index);
  5218. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5219. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
  5220. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5221. EllipsisLoc);
  5222. }
  5223. case TemplateArgument::Null:
  5224. case TemplateArgument::Integral:
  5225. case TemplateArgument::Declaration:
  5226. case TemplateArgument::NullPtr:
  5227. case TemplateArgument::Pack:
  5228. // FIXME: Is this right?
  5229. return TemplateArgumentLocInfo();
  5230. }
  5231. llvm_unreachable("unexpected template argument loc");
  5232. }
  5233. TemplateArgumentLoc
  5234. ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
  5235. const RecordData &Record, unsigned &Index) {
  5236. TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
  5237. if (Arg.getKind() == TemplateArgument::Expression) {
  5238. if (Record[Index++]) // bool InfoHasSameExpr.
  5239. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  5240. }
  5241. return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
  5242. Record, Index));
  5243. }
  5244. const ASTTemplateArgumentListInfo*
  5245. ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
  5246. const RecordData &Record,
  5247. unsigned &Index) {
  5248. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
  5249. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
  5250. unsigned NumArgsAsWritten = Record[Index++];
  5251. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  5252. for (unsigned i = 0; i != NumArgsAsWritten; ++i)
  5253. TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
  5254. return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
  5255. }
  5256. Decl *ASTReader::GetExternalDecl(uint32_t ID) {
  5257. return GetDecl(ID);
  5258. }
  5259. void ASTReader::CompleteRedeclChain(const Decl *D) {
  5260. if (NumCurrentElementsDeserializing) {
  5261. // We arrange to not care about the complete redeclaration chain while we're
  5262. // deserializing. Just remember that the AST has marked this one as complete
  5263. // but that it's not actually complete yet, so we know we still need to
  5264. // complete it later.
  5265. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
  5266. return;
  5267. }
  5268. const DeclContext *DC = D->getDeclContext()->getRedeclContext();
  5269. // If this is a named declaration, complete it by looking it up
  5270. // within its context.
  5271. //
  5272. // FIXME: We don't currently handle the cases where we can't do this;
  5273. // merging a class definition that contains unnamed entities should merge
  5274. // those entities. Likewise, merging a function definition should merge
  5275. // all mergeable entities within it.
  5276. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
  5277. isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
  5278. if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
  5279. auto *II = Name.getAsIdentifierInfo();
  5280. if (isa<TranslationUnitDecl>(DC) && II) {
  5281. // Outside of C++, we don't have a lookup table for the TU, so update
  5282. // the identifier instead. In C++, either way should work fine.
  5283. if (II->isOutOfDate())
  5284. updateOutOfDateIdentifier(*II);
  5285. } else
  5286. DC->lookup(Name);
  5287. }
  5288. }
  5289. }
  5290. uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
  5291. const RecordData &Record,
  5292. unsigned &Idx) {
  5293. if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
  5294. Error("malformed AST file: missing C++ base specifier");
  5295. return 0;
  5296. }
  5297. unsigned LocalID = Record[Idx++];
  5298. return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
  5299. }
  5300. CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  5301. RecordLocation Loc = getLocalBitOffset(Offset);
  5302. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  5303. SavedStreamPosition SavedPosition(Cursor);
  5304. Cursor.JumpToBit(Loc.Offset);
  5305. ReadingKindTracker ReadingKind(Read_Decl, *this);
  5306. RecordData Record;
  5307. unsigned Code = Cursor.ReadCode();
  5308. unsigned RecCode = Cursor.readRecord(Code, Record);
  5309. if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
  5310. Error("malformed AST file: missing C++ base specifiers");
  5311. return nullptr;
  5312. }
  5313. unsigned Idx = 0;
  5314. unsigned NumBases = Record[Idx++];
  5315. void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
  5316. CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
  5317. for (unsigned I = 0; I != NumBases; ++I)
  5318. Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
  5319. return Bases;
  5320. }
  5321. serialization::DeclID
  5322. ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
  5323. if (LocalID < NUM_PREDEF_DECL_IDS)
  5324. return LocalID;
  5325. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  5326. = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
  5327. assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
  5328. return LocalID + I->second;
  5329. }
  5330. bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
  5331. ModuleFile &M) const {
  5332. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
  5333. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  5334. return &M == I->second;
  5335. }
  5336. ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
  5337. if (!D->isFromASTFile())
  5338. return nullptr;
  5339. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
  5340. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  5341. return I->second;
  5342. }
  5343. SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
  5344. if (ID < NUM_PREDEF_DECL_IDS)
  5345. return SourceLocation();
  5346. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5347. if (Index > DeclsLoaded.size()) {
  5348. Error("declaration ID out-of-range for AST file");
  5349. return SourceLocation();
  5350. }
  5351. if (Decl *D = DeclsLoaded[Index])
  5352. return D->getLocation();
  5353. unsigned RawLocation = 0;
  5354. RecordLocation Rec = DeclCursorForID(ID, RawLocation);
  5355. return ReadSourceLocation(*Rec.F, RawLocation);
  5356. }
  5357. Decl *ASTReader::GetExistingDecl(DeclID ID) {
  5358. if (ID < NUM_PREDEF_DECL_IDS) {
  5359. switch ((PredefinedDeclIDs)ID) {
  5360. case PREDEF_DECL_NULL_ID:
  5361. return nullptr;
  5362. case PREDEF_DECL_TRANSLATION_UNIT_ID:
  5363. return Context.getTranslationUnitDecl();
  5364. case PREDEF_DECL_OBJC_ID_ID:
  5365. return Context.getObjCIdDecl();
  5366. case PREDEF_DECL_OBJC_SEL_ID:
  5367. return Context.getObjCSelDecl();
  5368. case PREDEF_DECL_OBJC_CLASS_ID:
  5369. return Context.getObjCClassDecl();
  5370. case PREDEF_DECL_OBJC_PROTOCOL_ID:
  5371. return Context.getObjCProtocolDecl();
  5372. case PREDEF_DECL_INT_128_ID:
  5373. return Context.getInt128Decl();
  5374. case PREDEF_DECL_UNSIGNED_INT_128_ID:
  5375. return Context.getUInt128Decl();
  5376. case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
  5377. return Context.getObjCInstanceTypeDecl();
  5378. case PREDEF_DECL_BUILTIN_VA_LIST_ID:
  5379. return Context.getBuiltinVaListDecl();
  5380. }
  5381. }
  5382. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5383. if (Index >= DeclsLoaded.size()) {
  5384. assert(0 && "declaration ID out-of-range for AST file");
  5385. Error("declaration ID out-of-range for AST file");
  5386. return nullptr;
  5387. }
  5388. return DeclsLoaded[Index];
  5389. }
  5390. Decl *ASTReader::GetDecl(DeclID ID) {
  5391. if (ID < NUM_PREDEF_DECL_IDS)
  5392. return GetExistingDecl(ID);
  5393. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5394. if (Index >= DeclsLoaded.size()) {
  5395. assert(0 && "declaration ID out-of-range for AST file");
  5396. Error("declaration ID out-of-range for AST file");
  5397. return nullptr;
  5398. }
  5399. if (!DeclsLoaded[Index]) {
  5400. ReadDeclRecord(ID);
  5401. if (DeserializationListener)
  5402. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  5403. }
  5404. return DeclsLoaded[Index];
  5405. }
  5406. DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  5407. DeclID GlobalID) {
  5408. if (GlobalID < NUM_PREDEF_DECL_IDS)
  5409. return GlobalID;
  5410. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
  5411. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  5412. ModuleFile *Owner = I->second;
  5413. llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
  5414. = M.GlobalToLocalDeclIDs.find(Owner);
  5415. if (Pos == M.GlobalToLocalDeclIDs.end())
  5416. return 0;
  5417. return GlobalID - Owner->BaseDeclID + Pos->second;
  5418. }
  5419. serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
  5420. const RecordData &Record,
  5421. unsigned &Idx) {
  5422. if (Idx >= Record.size()) {
  5423. Error("Corrupted AST file");
  5424. return 0;
  5425. }
  5426. return getGlobalDeclID(F, Record[Idx++]);
  5427. }
  5428. /// \brief Resolve the offset of a statement into a statement.
  5429. ///
  5430. /// This operation will read a new statement from the external
  5431. /// source each time it is called, and is meant to be used via a
  5432. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  5433. Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
  5434. // Switch case IDs are per Decl.
  5435. ClearSwitchCaseIDs();
  5436. // Offset here is a global offset across the entire chain.
  5437. RecordLocation Loc = getLocalBitOffset(Offset);
  5438. Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
  5439. return ReadStmtFromStream(*Loc.F);
  5440. }
  5441. namespace {
  5442. class FindExternalLexicalDeclsVisitor {
  5443. ASTReader &Reader;
  5444. const DeclContext *DC;
  5445. bool (*isKindWeWant)(Decl::Kind);
  5446. SmallVectorImpl<Decl*> &Decls;
  5447. bool PredefsVisited[NUM_PREDEF_DECL_IDS];
  5448. public:
  5449. FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
  5450. bool (*isKindWeWant)(Decl::Kind),
  5451. SmallVectorImpl<Decl*> &Decls)
  5452. : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
  5453. {
  5454. for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
  5455. PredefsVisited[I] = false;
  5456. }
  5457. static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
  5458. if (Preorder)
  5459. return false;
  5460. FindExternalLexicalDeclsVisitor *This
  5461. = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
  5462. ModuleFile::DeclContextInfosMap::iterator Info
  5463. = M.DeclContextInfos.find(This->DC);
  5464. if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
  5465. return false;
  5466. // Load all of the declaration IDs
  5467. for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
  5468. *IDE = ID + Info->second.NumLexicalDecls;
  5469. ID != IDE; ++ID) {
  5470. if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
  5471. continue;
  5472. // Don't add predefined declarations to the lexical context more
  5473. // than once.
  5474. if (ID->second < NUM_PREDEF_DECL_IDS) {
  5475. if (This->PredefsVisited[ID->second])
  5476. continue;
  5477. This->PredefsVisited[ID->second] = true;
  5478. }
  5479. if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
  5480. if (!This->DC->isDeclInLexicalTraversal(D))
  5481. This->Decls.push_back(D);
  5482. }
  5483. }
  5484. return false;
  5485. }
  5486. };
  5487. }
  5488. ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
  5489. bool (*isKindWeWant)(Decl::Kind),
  5490. SmallVectorImpl<Decl*> &Decls) {
  5491. // There might be lexical decls in multiple modules, for the TU at
  5492. // least. Walk all of the modules in the order they were loaded.
  5493. FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
  5494. ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
  5495. ++NumLexicalDeclContextsRead;
  5496. return ELR_Success;
  5497. }
  5498. namespace {
  5499. class DeclIDComp {
  5500. ASTReader &Reader;
  5501. ModuleFile &Mod;
  5502. public:
  5503. DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
  5504. bool operator()(LocalDeclID L, LocalDeclID R) const {
  5505. SourceLocation LHS = getLocation(L);
  5506. SourceLocation RHS = getLocation(R);
  5507. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5508. }
  5509. bool operator()(SourceLocation LHS, LocalDeclID R) const {
  5510. SourceLocation RHS = getLocation(R);
  5511. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5512. }
  5513. bool operator()(LocalDeclID L, SourceLocation RHS) const {
  5514. SourceLocation LHS = getLocation(L);
  5515. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5516. }
  5517. SourceLocation getLocation(LocalDeclID ID) const {
  5518. return Reader.getSourceManager().getFileLoc(
  5519. Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
  5520. }
  5521. };
  5522. }
  5523. void ASTReader::FindFileRegionDecls(FileID File,
  5524. unsigned Offset, unsigned Length,
  5525. SmallVectorImpl<Decl *> &Decls) {
  5526. SourceManager &SM = getSourceManager();
  5527. llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
  5528. if (I == FileDeclIDs.end())
  5529. return;
  5530. FileDeclsInfo &DInfo = I->second;
  5531. if (DInfo.Decls.empty())
  5532. return;
  5533. SourceLocation
  5534. BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
  5535. SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
  5536. DeclIDComp DIDComp(*this, *DInfo.Mod);
  5537. ArrayRef<serialization::LocalDeclID>::iterator
  5538. BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  5539. BeginLoc, DIDComp);
  5540. if (BeginIt != DInfo.Decls.begin())
  5541. --BeginIt;
  5542. // If we are pointing at a top-level decl inside an objc container, we need
  5543. // to backtrack until we find it otherwise we will fail to report that the
  5544. // region overlaps with an objc container.
  5545. while (BeginIt != DInfo.Decls.begin() &&
  5546. GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
  5547. ->isTopLevelDeclInObjCContainer())
  5548. --BeginIt;
  5549. ArrayRef<serialization::LocalDeclID>::iterator
  5550. EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  5551. EndLoc, DIDComp);
  5552. if (EndIt != DInfo.Decls.end())
  5553. ++EndIt;
  5554. for (ArrayRef<serialization::LocalDeclID>::iterator
  5555. DIt = BeginIt; DIt != EndIt; ++DIt)
  5556. Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
  5557. }
  5558. namespace {
  5559. /// \brief ModuleFile visitor used to perform name lookup into a
  5560. /// declaration context.
  5561. class DeclContextNameLookupVisitor {
  5562. ASTReader &Reader;
  5563. ArrayRef<const DeclContext *> Contexts;
  5564. DeclarationName Name;
  5565. SmallVectorImpl<NamedDecl *> &Decls;
  5566. public:
  5567. DeclContextNameLookupVisitor(ASTReader &Reader,
  5568. ArrayRef<const DeclContext *> Contexts,
  5569. DeclarationName Name,
  5570. SmallVectorImpl<NamedDecl *> &Decls)
  5571. : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
  5572. static bool visit(ModuleFile &M, void *UserData) {
  5573. DeclContextNameLookupVisitor *This
  5574. = static_cast<DeclContextNameLookupVisitor *>(UserData);
  5575. // Check whether we have any visible declaration information for
  5576. // this context in this module.
  5577. ModuleFile::DeclContextInfosMap::iterator Info;
  5578. bool FoundInfo = false;
  5579. for (auto *DC : This->Contexts) {
  5580. Info = M.DeclContextInfos.find(DC);
  5581. if (Info != M.DeclContextInfos.end() &&
  5582. Info->second.NameLookupTableData) {
  5583. FoundInfo = true;
  5584. break;
  5585. }
  5586. }
  5587. if (!FoundInfo)
  5588. return false;
  5589. // Look for this name within this module.
  5590. ASTDeclContextNameLookupTable *LookupTable =
  5591. Info->second.NameLookupTableData;
  5592. ASTDeclContextNameLookupTable::iterator Pos
  5593. = LookupTable->find(This->Name);
  5594. if (Pos == LookupTable->end())
  5595. return false;
  5596. bool FoundAnything = false;
  5597. ASTDeclContextNameLookupTrait::data_type Data = *Pos;
  5598. for (; Data.first != Data.second; ++Data.first) {
  5599. NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
  5600. if (!ND)
  5601. continue;
  5602. if (ND->getDeclName() != This->Name) {
  5603. // A name might be null because the decl's redeclarable part is
  5604. // currently read before reading its name. The lookup is triggered by
  5605. // building that decl (likely indirectly), and so it is later in the
  5606. // sense of "already existing" and can be ignored here.
  5607. // FIXME: This should not happen; deserializing declarations should
  5608. // not perform lookups since that can lead to deserialization cycles.
  5609. continue;
  5610. }
  5611. // Record this declaration.
  5612. FoundAnything = true;
  5613. This->Decls.push_back(ND);
  5614. }
  5615. return FoundAnything;
  5616. }
  5617. };
  5618. }
  5619. /// \brief Retrieve the "definitive" module file for the definition of the
  5620. /// given declaration context, if there is one.
  5621. ///
  5622. /// The "definitive" module file is the only place where we need to look to
  5623. /// find information about the declarations within the given declaration
  5624. /// context. For example, C++ and Objective-C classes, C structs/unions, and
  5625. /// Objective-C protocols, categories, and extensions are all defined in a
  5626. /// single place in the source code, so they have definitive module files
  5627. /// associated with them. C++ namespaces, on the other hand, can have
  5628. /// definitions in multiple different module files.
  5629. ///
  5630. /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
  5631. /// NDEBUG checking.
  5632. static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
  5633. ASTReader &Reader) {
  5634. if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
  5635. return Reader.getOwningModuleFile(cast<Decl>(DefDC));
  5636. return nullptr;
  5637. }
  5638. bool
  5639. ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  5640. DeclarationName Name) {
  5641. assert(DC->hasExternalVisibleStorage() &&
  5642. "DeclContext has no visible decls in storage");
  5643. if (!Name)
  5644. return false;
  5645. Deserializing LookupResults(this);
  5646. SmallVector<NamedDecl *, 64> Decls;
  5647. // Compute the declaration contexts we need to look into. Multiple such
  5648. // declaration contexts occur when two declaration contexts from disjoint
  5649. // modules get merged, e.g., when two namespaces with the same name are
  5650. // independently defined in separate modules.
  5651. SmallVector<const DeclContext *, 2> Contexts;
  5652. Contexts.push_back(DC);
  5653. if (DC->isNamespace()) {
  5654. auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
  5655. if (Merged != MergedDecls.end()) {
  5656. for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
  5657. Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
  5658. }
  5659. }
  5660. auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
  5661. DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
  5662. // If we can definitively determine which module file to look into,
  5663. // only look there. Otherwise, look in all module files.
  5664. ModuleFile *Definitive;
  5665. if (Contexts.size() == 1 &&
  5666. (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
  5667. DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
  5668. } else {
  5669. ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
  5670. }
  5671. };
  5672. LookUpInContexts(Contexts);
  5673. // If this might be an implicit special member function, then also search
  5674. // all merged definitions of the surrounding class. We need to search them
  5675. // individually, because finding an entity in one of them doesn't imply that
  5676. // we can't find a different entity in another one.
  5677. if (isa<CXXRecordDecl>(DC)) {
  5678. auto Kind = Name.getNameKind();
  5679. if (Kind == DeclarationName::CXXConstructorName ||
  5680. Kind == DeclarationName::CXXDestructorName ||
  5681. (Kind == DeclarationName::CXXOperatorName &&
  5682. Name.getCXXOverloadedOperator() == OO_Equal)) {
  5683. auto Merged = MergedLookups.find(DC);
  5684. if (Merged != MergedLookups.end())
  5685. for (auto *MergedDC : Merged->second)
  5686. LookUpInContexts(MergedDC);
  5687. }
  5688. }
  5689. ++NumVisibleDeclContextsRead;
  5690. SetExternalVisibleDeclsForName(DC, Name, Decls);
  5691. return !Decls.empty();
  5692. }
  5693. namespace {
  5694. /// \brief ModuleFile visitor used to retrieve all visible names in a
  5695. /// declaration context.
  5696. class DeclContextAllNamesVisitor {
  5697. ASTReader &Reader;
  5698. SmallVectorImpl<const DeclContext *> &Contexts;
  5699. DeclsMap &Decls;
  5700. bool VisitAll;
  5701. public:
  5702. DeclContextAllNamesVisitor(ASTReader &Reader,
  5703. SmallVectorImpl<const DeclContext *> &Contexts,
  5704. DeclsMap &Decls, bool VisitAll)
  5705. : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
  5706. static bool visit(ModuleFile &M, void *UserData) {
  5707. DeclContextAllNamesVisitor *This
  5708. = static_cast<DeclContextAllNamesVisitor *>(UserData);
  5709. // Check whether we have any visible declaration information for
  5710. // this context in this module.
  5711. ModuleFile::DeclContextInfosMap::iterator Info;
  5712. bool FoundInfo = false;
  5713. for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
  5714. Info = M.DeclContextInfos.find(This->Contexts[I]);
  5715. if (Info != M.DeclContextInfos.end() &&
  5716. Info->second.NameLookupTableData) {
  5717. FoundInfo = true;
  5718. break;
  5719. }
  5720. }
  5721. if (!FoundInfo)
  5722. return false;
  5723. ASTDeclContextNameLookupTable *LookupTable =
  5724. Info->second.NameLookupTableData;
  5725. bool FoundAnything = false;
  5726. for (ASTDeclContextNameLookupTable::data_iterator
  5727. I = LookupTable->data_begin(), E = LookupTable->data_end();
  5728. I != E;
  5729. ++I) {
  5730. ASTDeclContextNameLookupTrait::data_type Data = *I;
  5731. for (; Data.first != Data.second; ++Data.first) {
  5732. NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
  5733. *Data.first);
  5734. if (!ND)
  5735. continue;
  5736. // Record this declaration.
  5737. FoundAnything = true;
  5738. This->Decls[ND->getDeclName()].push_back(ND);
  5739. }
  5740. }
  5741. return FoundAnything && !This->VisitAll;
  5742. }
  5743. };
  5744. }
  5745. void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
  5746. if (!DC->hasExternalVisibleStorage())
  5747. return;
  5748. DeclsMap Decls;
  5749. // Compute the declaration contexts we need to look into. Multiple such
  5750. // declaration contexts occur when two declaration contexts from disjoint
  5751. // modules get merged, e.g., when two namespaces with the same name are
  5752. // independently defined in separate modules.
  5753. SmallVector<const DeclContext *, 2> Contexts;
  5754. Contexts.push_back(DC);
  5755. if (DC->isNamespace()) {
  5756. MergedDeclsMap::iterator Merged
  5757. = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
  5758. if (Merged != MergedDecls.end()) {
  5759. for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
  5760. Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
  5761. }
  5762. }
  5763. DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
  5764. /*VisitAll=*/DC->isFileContext());
  5765. ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
  5766. ++NumVisibleDeclContextsRead;
  5767. for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  5768. SetExternalVisibleDeclsForName(DC, I->first, I->second);
  5769. }
  5770. const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
  5771. }
  5772. /// \brief Under non-PCH compilation the consumer receives the objc methods
  5773. /// before receiving the implementation, and codegen depends on this.
  5774. /// We simulate this by deserializing and passing to consumer the methods of the
  5775. /// implementation before passing the deserialized implementation decl.
  5776. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
  5777. ASTConsumer *Consumer) {
  5778. assert(ImplD && Consumer);
  5779. for (auto *I : ImplD->methods())
  5780. Consumer->HandleInterestingDecl(DeclGroupRef(I));
  5781. Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
  5782. }
  5783. void ASTReader::PassInterestingDeclsToConsumer() {
  5784. assert(Consumer);
  5785. if (PassingDeclsToConsumer)
  5786. return;
  5787. // Guard variable to avoid recursively redoing the process of passing
  5788. // decls to consumer.
  5789. SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
  5790. true);
  5791. while (!InterestingDecls.empty()) {
  5792. Decl *D = InterestingDecls.front();
  5793. InterestingDecls.pop_front();
  5794. PassInterestingDeclToConsumer(D);
  5795. }
  5796. }
  5797. void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
  5798. if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  5799. PassObjCImplDeclToConsumer(ImplD, Consumer);
  5800. else
  5801. Consumer->HandleInterestingDecl(DeclGroupRef(D));
  5802. }
  5803. void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
  5804. this->Consumer = Consumer;
  5805. if (!Consumer)
  5806. return;
  5807. for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
  5808. // Force deserialization of this decl, which will cause it to be queued for
  5809. // passing to the consumer.
  5810. GetDecl(EagerlyDeserializedDecls[I]);
  5811. }
  5812. EagerlyDeserializedDecls.clear();
  5813. PassInterestingDeclsToConsumer();
  5814. }
  5815. void ASTReader::PrintStats() {
  5816. std::fprintf(stderr, "*** AST File Statistics:\n");
  5817. unsigned NumTypesLoaded
  5818. = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
  5819. QualType());
  5820. unsigned NumDeclsLoaded
  5821. = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
  5822. (Decl *)nullptr);
  5823. unsigned NumIdentifiersLoaded
  5824. = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
  5825. IdentifiersLoaded.end(),
  5826. (IdentifierInfo *)nullptr);
  5827. unsigned NumMacrosLoaded
  5828. = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
  5829. MacrosLoaded.end(),
  5830. (MacroInfo *)nullptr);
  5831. unsigned NumSelectorsLoaded
  5832. = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
  5833. SelectorsLoaded.end(),
  5834. Selector());
  5835. if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
  5836. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  5837. NumSLocEntriesRead, TotalNumSLocEntries,
  5838. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  5839. if (!TypesLoaded.empty())
  5840. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  5841. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  5842. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  5843. if (!DeclsLoaded.empty())
  5844. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  5845. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  5846. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  5847. if (!IdentifiersLoaded.empty())
  5848. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  5849. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  5850. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  5851. if (!MacrosLoaded.empty())
  5852. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  5853. NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
  5854. ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
  5855. if (!SelectorsLoaded.empty())
  5856. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  5857. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  5858. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  5859. if (TotalNumStatements)
  5860. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  5861. NumStatementsRead, TotalNumStatements,
  5862. ((float)NumStatementsRead/TotalNumStatements * 100));
  5863. if (TotalNumMacros)
  5864. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  5865. NumMacrosRead, TotalNumMacros,
  5866. ((float)NumMacrosRead/TotalNumMacros * 100));
  5867. if (TotalLexicalDeclContexts)
  5868. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  5869. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  5870. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  5871. * 100));
  5872. if (TotalVisibleDeclContexts)
  5873. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  5874. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  5875. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  5876. * 100));
  5877. if (TotalNumMethodPoolEntries) {
  5878. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  5879. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  5880. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  5881. * 100));
  5882. }
  5883. if (NumMethodPoolLookups) {
  5884. std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
  5885. NumMethodPoolHits, NumMethodPoolLookups,
  5886. ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
  5887. }
  5888. if (NumMethodPoolTableLookups) {
  5889. std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
  5890. NumMethodPoolTableHits, NumMethodPoolTableLookups,
  5891. ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
  5892. * 100.0));
  5893. }
  5894. if (NumIdentifierLookupHits) {
  5895. std::fprintf(stderr,
  5896. " %u / %u identifier table lookups succeeded (%f%%)\n",
  5897. NumIdentifierLookupHits, NumIdentifierLookups,
  5898. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  5899. }
  5900. if (GlobalIndex) {
  5901. std::fprintf(stderr, "\n");
  5902. GlobalIndex->printStats();
  5903. }
  5904. std::fprintf(stderr, "\n");
  5905. dump();
  5906. std::fprintf(stderr, "\n");
  5907. }
  5908. template<typename Key, typename ModuleFile, unsigned InitialCapacity>
  5909. static void
  5910. dumpModuleIDMap(StringRef Name,
  5911. const ContinuousRangeMap<Key, ModuleFile *,
  5912. InitialCapacity> &Map) {
  5913. if (Map.begin() == Map.end())
  5914. return;
  5915. typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
  5916. llvm::errs() << Name << ":\n";
  5917. for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
  5918. I != IEnd; ++I) {
  5919. llvm::errs() << " " << I->first << " -> " << I->second->FileName
  5920. << "\n";
  5921. }
  5922. }
  5923. void ASTReader::dump() {
  5924. llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
  5925. dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
  5926. dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
  5927. dumpModuleIDMap("Global type map", GlobalTypeMap);
  5928. dumpModuleIDMap("Global declaration map", GlobalDeclMap);
  5929. dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
  5930. dumpModuleIDMap("Global macro map", GlobalMacroMap);
  5931. dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
  5932. dumpModuleIDMap("Global selector map", GlobalSelectorMap);
  5933. dumpModuleIDMap("Global preprocessed entity map",
  5934. GlobalPreprocessedEntityMap);
  5935. llvm::errs() << "\n*** PCH/Modules Loaded:";
  5936. for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
  5937. MEnd = ModuleMgr.end();
  5938. M != MEnd; ++M)
  5939. (*M)->dump();
  5940. }
  5941. /// Return the amount of memory used by memory buffers, breaking down
  5942. /// by heap-backed versus mmap'ed memory.
  5943. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
  5944. for (ModuleConstIterator I = ModuleMgr.begin(),
  5945. E = ModuleMgr.end(); I != E; ++I) {
  5946. if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
  5947. size_t bytes = buf->getBufferSize();
  5948. switch (buf->getBufferKind()) {
  5949. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  5950. sizes.malloc_bytes += bytes;
  5951. break;
  5952. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  5953. sizes.mmap_bytes += bytes;
  5954. break;
  5955. }
  5956. }
  5957. }
  5958. }
  5959. void ASTReader::InitializeSema(Sema &S) {
  5960. SemaObj = &S;
  5961. S.addExternalSource(this);
  5962. // Makes sure any declarations that were deserialized "too early"
  5963. // still get added to the identifier's declaration chains.
  5964. for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
  5965. pushExternalDeclIntoScope(PreloadedDecls[I],
  5966. PreloadedDecls[I]->getDeclName());
  5967. }
  5968. PreloadedDecls.clear();
  5969. // FIXME: What happens if these are changed by a module import?
  5970. if (!FPPragmaOptions.empty()) {
  5971. assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
  5972. SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
  5973. }
  5974. // FIXME: What happens if these are changed by a module import?
  5975. if (!OpenCLExtensions.empty()) {
  5976. unsigned I = 0;
  5977. #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
  5978. #include "clang/Basic/OpenCLExtensions.def"
  5979. assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
  5980. }
  5981. UpdateSema();
  5982. }
  5983. void ASTReader::UpdateSema() {
  5984. assert(SemaObj && "no Sema to update");
  5985. // Load the offsets of the declarations that Sema references.
  5986. // They will be lazily deserialized when needed.
  5987. if (!SemaDeclRefs.empty()) {
  5988. assert(SemaDeclRefs.size() % 2 == 0);
  5989. for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
  5990. if (!SemaObj->StdNamespace)
  5991. SemaObj->StdNamespace = SemaDeclRefs[I];
  5992. if (!SemaObj->StdBadAlloc)
  5993. SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
  5994. }
  5995. SemaDeclRefs.clear();
  5996. }
  5997. // Update the state of 'pragma clang optimize'. Use the same API as if we had
  5998. // encountered the pragma in the source.
  5999. if(OptimizeOffPragmaLocation.isValid())
  6000. SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
  6001. }
  6002. IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
  6003. // Note that we are loading an identifier.
  6004. Deserializing AnIdentifier(this);
  6005. StringRef Name(NameStart, NameEnd - NameStart);
  6006. // If there is a global index, look there first to determine which modules
  6007. // provably do not have any results for this identifier.
  6008. GlobalModuleIndex::HitSet Hits;
  6009. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  6010. if (!loadGlobalIndex()) {
  6011. if (GlobalIndex->lookupIdentifier(Name, Hits)) {
  6012. HitsPtr = &Hits;
  6013. }
  6014. }
  6015. IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
  6016. NumIdentifierLookups,
  6017. NumIdentifierLookupHits);
  6018. ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
  6019. IdentifierInfo *II = Visitor.getIdentifierInfo();
  6020. markIdentifierUpToDate(II);
  6021. return II;
  6022. }
  6023. namespace clang {
  6024. /// \brief An identifier-lookup iterator that enumerates all of the
  6025. /// identifiers stored within a set of AST files.
  6026. class ASTIdentifierIterator : public IdentifierIterator {
  6027. /// \brief The AST reader whose identifiers are being enumerated.
  6028. const ASTReader &Reader;
  6029. /// \brief The current index into the chain of AST files stored in
  6030. /// the AST reader.
  6031. unsigned Index;
  6032. /// \brief The current position within the identifier lookup table
  6033. /// of the current AST file.
  6034. ASTIdentifierLookupTable::key_iterator Current;
  6035. /// \brief The end position within the identifier lookup table of
  6036. /// the current AST file.
  6037. ASTIdentifierLookupTable::key_iterator End;
  6038. public:
  6039. explicit ASTIdentifierIterator(const ASTReader &Reader);
  6040. StringRef Next() override;
  6041. };
  6042. }
  6043. ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
  6044. : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
  6045. ASTIdentifierLookupTable *IdTable
  6046. = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
  6047. Current = IdTable->key_begin();
  6048. End = IdTable->key_end();
  6049. }
  6050. StringRef ASTIdentifierIterator::Next() {
  6051. while (Current == End) {
  6052. // If we have exhausted all of our AST files, we're done.
  6053. if (Index == 0)
  6054. return StringRef();
  6055. --Index;
  6056. ASTIdentifierLookupTable *IdTable
  6057. = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
  6058. IdentifierLookupTable;
  6059. Current = IdTable->key_begin();
  6060. End = IdTable->key_end();
  6061. }
  6062. // We have any identifiers remaining in the current AST file; return
  6063. // the next one.
  6064. StringRef Result = *Current;
  6065. ++Current;
  6066. return Result;
  6067. }
  6068. IdentifierIterator *ASTReader::getIdentifiers() {
  6069. if (!loadGlobalIndex())
  6070. return GlobalIndex->createIdentifierIterator();
  6071. return new ASTIdentifierIterator(*this);
  6072. }
  6073. namespace clang { namespace serialization {
  6074. class ReadMethodPoolVisitor {
  6075. ASTReader &Reader;
  6076. Selector Sel;
  6077. unsigned PriorGeneration;
  6078. unsigned InstanceBits;
  6079. unsigned FactoryBits;
  6080. SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
  6081. SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
  6082. public:
  6083. ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
  6084. unsigned PriorGeneration)
  6085. : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
  6086. InstanceBits(0), FactoryBits(0) { }
  6087. static bool visit(ModuleFile &M, void *UserData) {
  6088. ReadMethodPoolVisitor *This
  6089. = static_cast<ReadMethodPoolVisitor *>(UserData);
  6090. if (!M.SelectorLookupTable)
  6091. return false;
  6092. // If we've already searched this module file, skip it now.
  6093. if (M.Generation <= This->PriorGeneration)
  6094. return true;
  6095. ++This->Reader.NumMethodPoolTableLookups;
  6096. ASTSelectorLookupTable *PoolTable
  6097. = (ASTSelectorLookupTable*)M.SelectorLookupTable;
  6098. ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
  6099. if (Pos == PoolTable->end())
  6100. return false;
  6101. ++This->Reader.NumMethodPoolTableHits;
  6102. ++This->Reader.NumSelectorsRead;
  6103. // FIXME: Not quite happy with the statistics here. We probably should
  6104. // disable this tracking when called via LoadSelector.
  6105. // Also, should entries without methods count as misses?
  6106. ++This->Reader.NumMethodPoolEntriesRead;
  6107. ASTSelectorLookupTrait::data_type Data = *Pos;
  6108. if (This->Reader.DeserializationListener)
  6109. This->Reader.DeserializationListener->SelectorRead(Data.ID,
  6110. This->Sel);
  6111. This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
  6112. This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
  6113. This->InstanceBits = Data.InstanceBits;
  6114. This->FactoryBits = Data.FactoryBits;
  6115. return true;
  6116. }
  6117. /// \brief Retrieve the instance methods found by this visitor.
  6118. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
  6119. return InstanceMethods;
  6120. }
  6121. /// \brief Retrieve the instance methods found by this visitor.
  6122. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
  6123. return FactoryMethods;
  6124. }
  6125. unsigned getInstanceBits() const { return InstanceBits; }
  6126. unsigned getFactoryBits() const { return FactoryBits; }
  6127. };
  6128. } } // end namespace clang::serialization
  6129. /// \brief Add the given set of methods to the method list.
  6130. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
  6131. ObjCMethodList &List) {
  6132. for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
  6133. S.addMethodToGlobalList(&List, Methods[I]);
  6134. }
  6135. }
  6136. void ASTReader::ReadMethodPool(Selector Sel) {
  6137. // Get the selector generation and update it to the current generation.
  6138. unsigned &Generation = SelectorGeneration[Sel];
  6139. unsigned PriorGeneration = Generation;
  6140. Generation = getGeneration();
  6141. // Search for methods defined with this selector.
  6142. ++NumMethodPoolLookups;
  6143. ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
  6144. ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
  6145. if (Visitor.getInstanceMethods().empty() &&
  6146. Visitor.getFactoryMethods().empty())
  6147. return;
  6148. ++NumMethodPoolHits;
  6149. if (!getSema())
  6150. return;
  6151. Sema &S = *getSema();
  6152. Sema::GlobalMethodPool::iterator Pos
  6153. = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
  6154. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
  6155. addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
  6156. Pos->second.first.setBits(Visitor.getInstanceBits());
  6157. Pos->second.second.setBits(Visitor.getFactoryBits());
  6158. }
  6159. void ASTReader::ReadKnownNamespaces(
  6160. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  6161. Namespaces.clear();
  6162. for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
  6163. if (NamespaceDecl *Namespace
  6164. = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
  6165. Namespaces.push_back(Namespace);
  6166. }
  6167. }
  6168. void ASTReader::ReadUndefinedButUsed(
  6169. llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
  6170. for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
  6171. NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
  6172. SourceLocation Loc =
  6173. SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
  6174. Undefined.insert(std::make_pair(D, Loc));
  6175. }
  6176. }
  6177. void ASTReader::ReadTentativeDefinitions(
  6178. SmallVectorImpl<VarDecl *> &TentativeDefs) {
  6179. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  6180. VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
  6181. if (Var)
  6182. TentativeDefs.push_back(Var);
  6183. }
  6184. TentativeDefinitions.clear();
  6185. }
  6186. void ASTReader::ReadUnusedFileScopedDecls(
  6187. SmallVectorImpl<const DeclaratorDecl *> &Decls) {
  6188. for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
  6189. DeclaratorDecl *D
  6190. = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
  6191. if (D)
  6192. Decls.push_back(D);
  6193. }
  6194. UnusedFileScopedDecls.clear();
  6195. }
  6196. void ASTReader::ReadDelegatingConstructors(
  6197. SmallVectorImpl<CXXConstructorDecl *> &Decls) {
  6198. for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
  6199. CXXConstructorDecl *D
  6200. = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
  6201. if (D)
  6202. Decls.push_back(D);
  6203. }
  6204. DelegatingCtorDecls.clear();
  6205. }
  6206. void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
  6207. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
  6208. TypedefNameDecl *D
  6209. = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
  6210. if (D)
  6211. Decls.push_back(D);
  6212. }
  6213. ExtVectorDecls.clear();
  6214. }
  6215. void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
  6216. for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
  6217. CXXRecordDecl *D
  6218. = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
  6219. if (D)
  6220. Decls.push_back(D);
  6221. }
  6222. DynamicClasses.clear();
  6223. }
  6224. void
  6225. ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
  6226. for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
  6227. NamedDecl *D
  6228. = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
  6229. if (D)
  6230. Decls.push_back(D);
  6231. }
  6232. LocallyScopedExternCDecls.clear();
  6233. }
  6234. void ASTReader::ReadReferencedSelectors(
  6235. SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
  6236. if (ReferencedSelectorsData.empty())
  6237. return;
  6238. // If there are @selector references added them to its pool. This is for
  6239. // implementation of -Wselector.
  6240. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  6241. unsigned I = 0;
  6242. while (I < DataSize) {
  6243. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  6244. SourceLocation SelLoc
  6245. = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  6246. Sels.push_back(std::make_pair(Sel, SelLoc));
  6247. }
  6248. ReferencedSelectorsData.clear();
  6249. }
  6250. void ASTReader::ReadWeakUndeclaredIdentifiers(
  6251. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
  6252. if (WeakUndeclaredIdentifiers.empty())
  6253. return;
  6254. for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
  6255. IdentifierInfo *WeakId
  6256. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6257. IdentifierInfo *AliasId
  6258. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6259. SourceLocation Loc
  6260. = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
  6261. bool Used = WeakUndeclaredIdentifiers[I++];
  6262. WeakInfo WI(AliasId, Loc);
  6263. WI.setUsed(Used);
  6264. WeakIDs.push_back(std::make_pair(WeakId, WI));
  6265. }
  6266. WeakUndeclaredIdentifiers.clear();
  6267. }
  6268. void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
  6269. for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
  6270. ExternalVTableUse VT;
  6271. VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  6272. VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
  6273. VT.DefinitionRequired = VTableUses[Idx++];
  6274. VTables.push_back(VT);
  6275. }
  6276. VTableUses.clear();
  6277. }
  6278. void ASTReader::ReadPendingInstantiations(
  6279. SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
  6280. for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
  6281. ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
  6282. SourceLocation Loc
  6283. = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
  6284. Pending.push_back(std::make_pair(D, Loc));
  6285. }
  6286. PendingInstantiations.clear();
  6287. }
  6288. void ASTReader::ReadLateParsedTemplates(
  6289. llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
  6290. for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
  6291. /* In loop */) {
  6292. FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
  6293. LateParsedTemplate *LT = new LateParsedTemplate;
  6294. LT->D = GetDecl(LateParsedTemplates[Idx++]);
  6295. ModuleFile *F = getOwningModuleFile(LT->D);
  6296. assert(F && "No module");
  6297. unsigned TokN = LateParsedTemplates[Idx++];
  6298. LT->Toks.reserve(TokN);
  6299. for (unsigned T = 0; T < TokN; ++T)
  6300. LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
  6301. LPTMap[FD] = LT;
  6302. }
  6303. LateParsedTemplates.clear();
  6304. }
  6305. void ASTReader::LoadSelector(Selector Sel) {
  6306. // It would be complicated to avoid reading the methods anyway. So don't.
  6307. ReadMethodPool(Sel);
  6308. }
  6309. void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
  6310. assert(ID && "Non-zero identifier ID required");
  6311. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  6312. IdentifiersLoaded[ID - 1] = II;
  6313. if (DeserializationListener)
  6314. DeserializationListener->IdentifierRead(ID, II);
  6315. }
  6316. /// \brief Set the globally-visible declarations associated with the given
  6317. /// identifier.
  6318. ///
  6319. /// If the AST reader is currently in a state where the given declaration IDs
  6320. /// cannot safely be resolved, they are queued until it is safe to resolve
  6321. /// them.
  6322. ///
  6323. /// \param II an IdentifierInfo that refers to one or more globally-visible
  6324. /// declarations.
  6325. ///
  6326. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  6327. /// visible at global scope.
  6328. ///
  6329. /// \param Decls if non-null, this vector will be populated with the set of
  6330. /// deserialized declarations. These declarations will not be pushed into
  6331. /// scope.
  6332. void
  6333. ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  6334. const SmallVectorImpl<uint32_t> &DeclIDs,
  6335. SmallVectorImpl<Decl *> *Decls) {
  6336. if (NumCurrentElementsDeserializing && !Decls) {
  6337. PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
  6338. return;
  6339. }
  6340. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  6341. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  6342. if (SemaObj) {
  6343. // If we're simply supposed to record the declarations, do so now.
  6344. if (Decls) {
  6345. Decls->push_back(D);
  6346. continue;
  6347. }
  6348. // Introduce this declaration into the translation-unit scope
  6349. // and add it to the declaration chain for this identifier, so
  6350. // that (unqualified) name lookup will find it.
  6351. pushExternalDeclIntoScope(D, II);
  6352. } else {
  6353. // Queue this declaration so that it will be added to the
  6354. // translation unit scope and identifier's declaration chain
  6355. // once a Sema object is known.
  6356. PreloadedDecls.push_back(D);
  6357. }
  6358. }
  6359. }
  6360. IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
  6361. if (ID == 0)
  6362. return nullptr;
  6363. if (IdentifiersLoaded.empty()) {
  6364. Error("no identifier table in AST file");
  6365. return nullptr;
  6366. }
  6367. ID -= 1;
  6368. if (!IdentifiersLoaded[ID]) {
  6369. GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
  6370. assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
  6371. ModuleFile *M = I->second;
  6372. unsigned Index = ID - M->BaseIdentifierID;
  6373. const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
  6374. // All of the strings in the AST file are preceded by a 16-bit length.
  6375. // Extract that 16-bit length to avoid having to execute strlen().
  6376. // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
  6377. // unsigned integers. This is important to avoid integer overflow when
  6378. // we cast them to 'unsigned'.
  6379. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
  6380. unsigned StrLen = (((unsigned) StrLenPtr[0])
  6381. | (((unsigned) StrLenPtr[1]) << 8)) - 1;
  6382. IdentifiersLoaded[ID]
  6383. = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
  6384. if (DeserializationListener)
  6385. DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
  6386. }
  6387. return IdentifiersLoaded[ID];
  6388. }
  6389. IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
  6390. return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
  6391. }
  6392. IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
  6393. if (LocalID < NUM_PREDEF_IDENT_IDS)
  6394. return LocalID;
  6395. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6396. = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
  6397. assert(I != M.IdentifierRemap.end()
  6398. && "Invalid index into identifier index remap");
  6399. return LocalID + I->second;
  6400. }
  6401. MacroInfo *ASTReader::getMacro(MacroID ID) {
  6402. if (ID == 0)
  6403. return nullptr;
  6404. if (MacrosLoaded.empty()) {
  6405. Error("no macro table in AST file");
  6406. return nullptr;
  6407. }
  6408. ID -= NUM_PREDEF_MACRO_IDS;
  6409. if (!MacrosLoaded[ID]) {
  6410. GlobalMacroMapType::iterator I
  6411. = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
  6412. assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
  6413. ModuleFile *M = I->second;
  6414. unsigned Index = ID - M->BaseMacroID;
  6415. MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
  6416. if (DeserializationListener)
  6417. DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
  6418. MacrosLoaded[ID]);
  6419. }
  6420. return MacrosLoaded[ID];
  6421. }
  6422. MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
  6423. if (LocalID < NUM_PREDEF_MACRO_IDS)
  6424. return LocalID;
  6425. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6426. = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
  6427. assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
  6428. return LocalID + I->second;
  6429. }
  6430. serialization::SubmoduleID
  6431. ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
  6432. if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
  6433. return LocalID;
  6434. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6435. = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
  6436. assert(I != M.SubmoduleRemap.end()
  6437. && "Invalid index into submodule index remap");
  6438. return LocalID + I->second;
  6439. }
  6440. Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
  6441. if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
  6442. assert(GlobalID == 0 && "Unhandled global submodule ID");
  6443. return nullptr;
  6444. }
  6445. if (GlobalID > SubmodulesLoaded.size()) {
  6446. Error("submodule ID out of range in AST file");
  6447. return nullptr;
  6448. }
  6449. return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
  6450. }
  6451. Module *ASTReader::getModule(unsigned ID) {
  6452. return getSubmodule(ID);
  6453. }
  6454. Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
  6455. return DecodeSelector(getGlobalSelectorID(M, LocalID));
  6456. }
  6457. Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
  6458. if (ID == 0)
  6459. return Selector();
  6460. if (ID > SelectorsLoaded.size()) {
  6461. Error("selector ID out of range in AST file");
  6462. return Selector();
  6463. }
  6464. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
  6465. // Load this selector from the selector table.
  6466. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
  6467. assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
  6468. ModuleFile &M = *I->second;
  6469. ASTSelectorLookupTrait Trait(*this, M);
  6470. unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
  6471. SelectorsLoaded[ID - 1] =
  6472. Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
  6473. if (DeserializationListener)
  6474. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  6475. }
  6476. return SelectorsLoaded[ID - 1];
  6477. }
  6478. Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
  6479. return DecodeSelector(ID);
  6480. }
  6481. uint32_t ASTReader::GetNumExternalSelectors() {
  6482. // ID 0 (the null selector) is considered an external selector.
  6483. return getTotalNumSelectors() + 1;
  6484. }
  6485. serialization::SelectorID
  6486. ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
  6487. if (LocalID < NUM_PREDEF_SELECTOR_IDS)
  6488. return LocalID;
  6489. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6490. = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
  6491. assert(I != M.SelectorRemap.end()
  6492. && "Invalid index into selector index remap");
  6493. return LocalID + I->second;
  6494. }
  6495. DeclarationName
  6496. ASTReader::ReadDeclarationName(ModuleFile &F,
  6497. const RecordData &Record, unsigned &Idx) {
  6498. DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
  6499. switch (Kind) {
  6500. case DeclarationName::Identifier:
  6501. return DeclarationName(GetIdentifierInfo(F, Record, Idx));
  6502. case DeclarationName::ObjCZeroArgSelector:
  6503. case DeclarationName::ObjCOneArgSelector:
  6504. case DeclarationName::ObjCMultiArgSelector:
  6505. return DeclarationName(ReadSelector(F, Record, Idx));
  6506. case DeclarationName::CXXConstructorName:
  6507. return Context.DeclarationNames.getCXXConstructorName(
  6508. Context.getCanonicalType(readType(F, Record, Idx)));
  6509. case DeclarationName::CXXDestructorName:
  6510. return Context.DeclarationNames.getCXXDestructorName(
  6511. Context.getCanonicalType(readType(F, Record, Idx)));
  6512. case DeclarationName::CXXConversionFunctionName:
  6513. return Context.DeclarationNames.getCXXConversionFunctionName(
  6514. Context.getCanonicalType(readType(F, Record, Idx)));
  6515. case DeclarationName::CXXOperatorName:
  6516. return Context.DeclarationNames.getCXXOperatorName(
  6517. (OverloadedOperatorKind)Record[Idx++]);
  6518. case DeclarationName::CXXLiteralOperatorName:
  6519. return Context.DeclarationNames.getCXXLiteralOperatorName(
  6520. GetIdentifierInfo(F, Record, Idx));
  6521. case DeclarationName::CXXUsingDirective:
  6522. return DeclarationName::getUsingDirectiveName();
  6523. }
  6524. llvm_unreachable("Invalid NameKind!");
  6525. }
  6526. void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
  6527. DeclarationNameLoc &DNLoc,
  6528. DeclarationName Name,
  6529. const RecordData &Record, unsigned &Idx) {
  6530. switch (Name.getNameKind()) {
  6531. case DeclarationName::CXXConstructorName:
  6532. case DeclarationName::CXXDestructorName:
  6533. case DeclarationName::CXXConversionFunctionName:
  6534. DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
  6535. break;
  6536. case DeclarationName::CXXOperatorName:
  6537. DNLoc.CXXOperatorName.BeginOpNameLoc
  6538. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6539. DNLoc.CXXOperatorName.EndOpNameLoc
  6540. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6541. break;
  6542. case DeclarationName::CXXLiteralOperatorName:
  6543. DNLoc.CXXLiteralOperatorName.OpNameLoc
  6544. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6545. break;
  6546. case DeclarationName::Identifier:
  6547. case DeclarationName::ObjCZeroArgSelector:
  6548. case DeclarationName::ObjCOneArgSelector:
  6549. case DeclarationName::ObjCMultiArgSelector:
  6550. case DeclarationName::CXXUsingDirective:
  6551. break;
  6552. }
  6553. }
  6554. void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
  6555. DeclarationNameInfo &NameInfo,
  6556. const RecordData &Record, unsigned &Idx) {
  6557. NameInfo.setName(ReadDeclarationName(F, Record, Idx));
  6558. NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
  6559. DeclarationNameLoc DNLoc;
  6560. ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
  6561. NameInfo.setInfo(DNLoc);
  6562. }
  6563. void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
  6564. const RecordData &Record, unsigned &Idx) {
  6565. Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
  6566. unsigned NumTPLists = Record[Idx++];
  6567. Info.NumTemplParamLists = NumTPLists;
  6568. if (NumTPLists) {
  6569. Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
  6570. for (unsigned i=0; i != NumTPLists; ++i)
  6571. Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
  6572. }
  6573. }
  6574. TemplateName
  6575. ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
  6576. unsigned &Idx) {
  6577. TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
  6578. switch (Kind) {
  6579. case TemplateName::Template:
  6580. return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
  6581. case TemplateName::OverloadedTemplate: {
  6582. unsigned size = Record[Idx++];
  6583. UnresolvedSet<8> Decls;
  6584. while (size--)
  6585. Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
  6586. return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
  6587. }
  6588. case TemplateName::QualifiedTemplate: {
  6589. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  6590. bool hasTemplKeyword = Record[Idx++];
  6591. TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
  6592. return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
  6593. }
  6594. case TemplateName::DependentTemplate: {
  6595. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  6596. if (Record[Idx++]) // isIdentifier
  6597. return Context.getDependentTemplateName(NNS,
  6598. GetIdentifierInfo(F, Record,
  6599. Idx));
  6600. return Context.getDependentTemplateName(NNS,
  6601. (OverloadedOperatorKind)Record[Idx++]);
  6602. }
  6603. case TemplateName::SubstTemplateTemplateParm: {
  6604. TemplateTemplateParmDecl *param
  6605. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  6606. if (!param) return TemplateName();
  6607. TemplateName replacement = ReadTemplateName(F, Record, Idx);
  6608. return Context.getSubstTemplateTemplateParm(param, replacement);
  6609. }
  6610. case TemplateName::SubstTemplateTemplateParmPack: {
  6611. TemplateTemplateParmDecl *Param
  6612. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  6613. if (!Param)
  6614. return TemplateName();
  6615. TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
  6616. if (ArgPack.getKind() != TemplateArgument::Pack)
  6617. return TemplateName();
  6618. return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
  6619. }
  6620. }
  6621. llvm_unreachable("Unhandled template name kind!");
  6622. }
  6623. TemplateArgument
  6624. ASTReader::ReadTemplateArgument(ModuleFile &F,
  6625. const RecordData &Record, unsigned &Idx) {
  6626. TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
  6627. switch (Kind) {
  6628. case TemplateArgument::Null:
  6629. return TemplateArgument();
  6630. case TemplateArgument::Type:
  6631. return TemplateArgument(readType(F, Record, Idx));
  6632. case TemplateArgument::Declaration: {
  6633. ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
  6634. bool ForReferenceParam = Record[Idx++];
  6635. return TemplateArgument(D, ForReferenceParam);
  6636. }
  6637. case TemplateArgument::NullPtr:
  6638. return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
  6639. case TemplateArgument::Integral: {
  6640. llvm::APSInt Value = ReadAPSInt(Record, Idx);
  6641. QualType T = readType(F, Record, Idx);
  6642. return TemplateArgument(Context, Value, T);
  6643. }
  6644. case TemplateArgument::Template:
  6645. return TemplateArgument(ReadTemplateName(F, Record, Idx));
  6646. case TemplateArgument::TemplateExpansion: {
  6647. TemplateName Name = ReadTemplateName(F, Record, Idx);
  6648. Optional<unsigned> NumTemplateExpansions;
  6649. if (unsigned NumExpansions = Record[Idx++])
  6650. NumTemplateExpansions = NumExpansions - 1;
  6651. return TemplateArgument(Name, NumTemplateExpansions);
  6652. }
  6653. case TemplateArgument::Expression:
  6654. return TemplateArgument(ReadExpr(F));
  6655. case TemplateArgument::Pack: {
  6656. unsigned NumArgs = Record[Idx++];
  6657. TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
  6658. for (unsigned I = 0; I != NumArgs; ++I)
  6659. Args[I] = ReadTemplateArgument(F, Record, Idx);
  6660. return TemplateArgument(Args, NumArgs);
  6661. }
  6662. }
  6663. llvm_unreachable("Unhandled template argument kind!");
  6664. }
  6665. TemplateParameterList *
  6666. ASTReader::ReadTemplateParameterList(ModuleFile &F,
  6667. const RecordData &Record, unsigned &Idx) {
  6668. SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
  6669. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
  6670. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
  6671. unsigned NumParams = Record[Idx++];
  6672. SmallVector<NamedDecl *, 16> Params;
  6673. Params.reserve(NumParams);
  6674. while (NumParams--)
  6675. Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
  6676. TemplateParameterList* TemplateParams =
  6677. TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
  6678. Params.data(), Params.size(), RAngleLoc);
  6679. return TemplateParams;
  6680. }
  6681. void
  6682. ASTReader::
  6683. ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
  6684. ModuleFile &F, const RecordData &Record,
  6685. unsigned &Idx) {
  6686. unsigned NumTemplateArgs = Record[Idx++];
  6687. TemplArgs.reserve(NumTemplateArgs);
  6688. while (NumTemplateArgs--)
  6689. TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
  6690. }
  6691. /// \brief Read a UnresolvedSet structure.
  6692. void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
  6693. const RecordData &Record, unsigned &Idx) {
  6694. unsigned NumDecls = Record[Idx++];
  6695. Set.reserve(Context, NumDecls);
  6696. while (NumDecls--) {
  6697. DeclID ID = ReadDeclID(F, Record, Idx);
  6698. AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
  6699. Set.addLazyDecl(Context, ID, AS);
  6700. }
  6701. }
  6702. CXXBaseSpecifier
  6703. ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
  6704. const RecordData &Record, unsigned &Idx) {
  6705. bool isVirtual = static_cast<bool>(Record[Idx++]);
  6706. bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
  6707. AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
  6708. bool inheritConstructors = static_cast<bool>(Record[Idx++]);
  6709. TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
  6710. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6711. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
  6712. CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
  6713. EllipsisLoc);
  6714. Result.setInheritConstructors(inheritConstructors);
  6715. return Result;
  6716. }
  6717. std::pair<CXXCtorInitializer **, unsigned>
  6718. ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
  6719. unsigned &Idx) {
  6720. CXXCtorInitializer **CtorInitializers = nullptr;
  6721. unsigned NumInitializers = Record[Idx++];
  6722. if (NumInitializers) {
  6723. CtorInitializers
  6724. = new (Context) CXXCtorInitializer*[NumInitializers];
  6725. for (unsigned i=0; i != NumInitializers; ++i) {
  6726. TypeSourceInfo *TInfo = nullptr;
  6727. bool IsBaseVirtual = false;
  6728. FieldDecl *Member = nullptr;
  6729. IndirectFieldDecl *IndirectMember = nullptr;
  6730. CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
  6731. switch (Type) {
  6732. case CTOR_INITIALIZER_BASE:
  6733. TInfo = GetTypeSourceInfo(F, Record, Idx);
  6734. IsBaseVirtual = Record[Idx++];
  6735. break;
  6736. case CTOR_INITIALIZER_DELEGATING:
  6737. TInfo = GetTypeSourceInfo(F, Record, Idx);
  6738. break;
  6739. case CTOR_INITIALIZER_MEMBER:
  6740. Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
  6741. break;
  6742. case CTOR_INITIALIZER_INDIRECT_MEMBER:
  6743. IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
  6744. break;
  6745. }
  6746. SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
  6747. Expr *Init = ReadExpr(F);
  6748. SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
  6749. SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
  6750. bool IsWritten = Record[Idx++];
  6751. unsigned SourceOrderOrNumArrayIndices;
  6752. SmallVector<VarDecl *, 8> Indices;
  6753. if (IsWritten) {
  6754. SourceOrderOrNumArrayIndices = Record[Idx++];
  6755. } else {
  6756. SourceOrderOrNumArrayIndices = Record[Idx++];
  6757. Indices.reserve(SourceOrderOrNumArrayIndices);
  6758. for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
  6759. Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
  6760. }
  6761. CXXCtorInitializer *BOMInit;
  6762. if (Type == CTOR_INITIALIZER_BASE) {
  6763. BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
  6764. LParenLoc, Init, RParenLoc,
  6765. MemberOrEllipsisLoc);
  6766. } else if (Type == CTOR_INITIALIZER_DELEGATING) {
  6767. BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
  6768. Init, RParenLoc);
  6769. } else if (IsWritten) {
  6770. if (Member)
  6771. BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
  6772. LParenLoc, Init, RParenLoc);
  6773. else
  6774. BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
  6775. MemberOrEllipsisLoc, LParenLoc,
  6776. Init, RParenLoc);
  6777. } else {
  6778. if (IndirectMember) {
  6779. assert(Indices.empty() && "Indirect field improperly initialized");
  6780. BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
  6781. MemberOrEllipsisLoc, LParenLoc,
  6782. Init, RParenLoc);
  6783. } else {
  6784. BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
  6785. LParenLoc, Init, RParenLoc,
  6786. Indices.data(), Indices.size());
  6787. }
  6788. }
  6789. if (IsWritten)
  6790. BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
  6791. CtorInitializers[i] = BOMInit;
  6792. }
  6793. }
  6794. return std::make_pair(CtorInitializers, NumInitializers);
  6795. }
  6796. NestedNameSpecifier *
  6797. ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
  6798. const RecordData &Record, unsigned &Idx) {
  6799. unsigned N = Record[Idx++];
  6800. NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
  6801. for (unsigned I = 0; I != N; ++I) {
  6802. NestedNameSpecifier::SpecifierKind Kind
  6803. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  6804. switch (Kind) {
  6805. case NestedNameSpecifier::Identifier: {
  6806. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  6807. NNS = NestedNameSpecifier::Create(Context, Prev, II);
  6808. break;
  6809. }
  6810. case NestedNameSpecifier::Namespace: {
  6811. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  6812. NNS = NestedNameSpecifier::Create(Context, Prev, NS);
  6813. break;
  6814. }
  6815. case NestedNameSpecifier::NamespaceAlias: {
  6816. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  6817. NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
  6818. break;
  6819. }
  6820. case NestedNameSpecifier::TypeSpec:
  6821. case NestedNameSpecifier::TypeSpecWithTemplate: {
  6822. const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
  6823. if (!T)
  6824. return nullptr;
  6825. bool Template = Record[Idx++];
  6826. NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
  6827. break;
  6828. }
  6829. case NestedNameSpecifier::Global: {
  6830. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  6831. // No associated value, and there can't be a prefix.
  6832. break;
  6833. }
  6834. }
  6835. Prev = NNS;
  6836. }
  6837. return NNS;
  6838. }
  6839. NestedNameSpecifierLoc
  6840. ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
  6841. unsigned &Idx) {
  6842. unsigned N = Record[Idx++];
  6843. NestedNameSpecifierLocBuilder Builder;
  6844. for (unsigned I = 0; I != N; ++I) {
  6845. NestedNameSpecifier::SpecifierKind Kind
  6846. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  6847. switch (Kind) {
  6848. case NestedNameSpecifier::Identifier: {
  6849. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  6850. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6851. Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
  6852. break;
  6853. }
  6854. case NestedNameSpecifier::Namespace: {
  6855. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  6856. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6857. Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
  6858. break;
  6859. }
  6860. case NestedNameSpecifier::NamespaceAlias: {
  6861. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  6862. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6863. Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
  6864. break;
  6865. }
  6866. case NestedNameSpecifier::TypeSpec:
  6867. case NestedNameSpecifier::TypeSpecWithTemplate: {
  6868. bool Template = Record[Idx++];
  6869. TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
  6870. if (!T)
  6871. return NestedNameSpecifierLoc();
  6872. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  6873. // FIXME: 'template' keyword location not saved anywhere, so we fake it.
  6874. Builder.Extend(Context,
  6875. Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
  6876. T->getTypeLoc(), ColonColonLoc);
  6877. break;
  6878. }
  6879. case NestedNameSpecifier::Global: {
  6880. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  6881. Builder.MakeGlobal(Context, ColonColonLoc);
  6882. break;
  6883. }
  6884. }
  6885. }
  6886. return Builder.getWithLocInContext(Context);
  6887. }
  6888. SourceRange
  6889. ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
  6890. unsigned &Idx) {
  6891. SourceLocation beg = ReadSourceLocation(F, Record, Idx);
  6892. SourceLocation end = ReadSourceLocation(F, Record, Idx);
  6893. return SourceRange(beg, end);
  6894. }
  6895. /// \brief Read an integral value
  6896. llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
  6897. unsigned BitWidth = Record[Idx++];
  6898. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  6899. llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
  6900. Idx += NumWords;
  6901. return Result;
  6902. }
  6903. /// \brief Read a signed integral value
  6904. llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
  6905. bool isUnsigned = Record[Idx++];
  6906. return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
  6907. }
  6908. /// \brief Read a floating-point value
  6909. llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
  6910. const llvm::fltSemantics &Sem,
  6911. unsigned &Idx) {
  6912. return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
  6913. }
  6914. // \brief Read a string
  6915. std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
  6916. unsigned Len = Record[Idx++];
  6917. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  6918. Idx += Len;
  6919. return Result;
  6920. }
  6921. VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
  6922. unsigned &Idx) {
  6923. unsigned Major = Record[Idx++];
  6924. unsigned Minor = Record[Idx++];
  6925. unsigned Subminor = Record[Idx++];
  6926. if (Minor == 0)
  6927. return VersionTuple(Major);
  6928. if (Subminor == 0)
  6929. return VersionTuple(Major, Minor - 1);
  6930. return VersionTuple(Major, Minor - 1, Subminor - 1);
  6931. }
  6932. CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
  6933. const RecordData &Record,
  6934. unsigned &Idx) {
  6935. CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
  6936. return CXXTemporary::Create(Context, Decl);
  6937. }
  6938. DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
  6939. return Diag(CurrentImportLoc, DiagID);
  6940. }
  6941. DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
  6942. return Diags.Report(Loc, DiagID);
  6943. }
  6944. /// \brief Retrieve the identifier table associated with the
  6945. /// preprocessor.
  6946. IdentifierTable &ASTReader::getIdentifierTable() {
  6947. return PP.getIdentifierTable();
  6948. }
  6949. /// \brief Record that the given ID maps to the given switch-case
  6950. /// statement.
  6951. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  6952. assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
  6953. "Already have a SwitchCase with this ID");
  6954. (*CurrSwitchCaseStmts)[ID] = SC;
  6955. }
  6956. /// \brief Retrieve the switch-case statement with the given ID.
  6957. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
  6958. assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
  6959. return (*CurrSwitchCaseStmts)[ID];
  6960. }
  6961. void ASTReader::ClearSwitchCaseIDs() {
  6962. CurrSwitchCaseStmts->clear();
  6963. }
  6964. void ASTReader::ReadComments() {
  6965. std::vector<RawComment *> Comments;
  6966. for (SmallVectorImpl<std::pair<BitstreamCursor,
  6967. serialization::ModuleFile *> >::iterator
  6968. I = CommentsCursors.begin(),
  6969. E = CommentsCursors.end();
  6970. I != E; ++I) {
  6971. Comments.clear();
  6972. BitstreamCursor &Cursor = I->first;
  6973. serialization::ModuleFile &F = *I->second;
  6974. SavedStreamPosition SavedPosition(Cursor);
  6975. RecordData Record;
  6976. while (true) {
  6977. llvm::BitstreamEntry Entry =
  6978. Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
  6979. switch (Entry.Kind) {
  6980. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  6981. case llvm::BitstreamEntry::Error:
  6982. Error("malformed block record in AST file");
  6983. return;
  6984. case llvm::BitstreamEntry::EndBlock:
  6985. goto NextCursor;
  6986. case llvm::BitstreamEntry::Record:
  6987. // The interesting case.
  6988. break;
  6989. }
  6990. // Read a record.
  6991. Record.clear();
  6992. switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
  6993. case COMMENTS_RAW_COMMENT: {
  6994. unsigned Idx = 0;
  6995. SourceRange SR = ReadSourceRange(F, Record, Idx);
  6996. RawComment::CommentKind Kind =
  6997. (RawComment::CommentKind) Record[Idx++];
  6998. bool IsTrailingComment = Record[Idx++];
  6999. bool IsAlmostTrailingComment = Record[Idx++];
  7000. Comments.push_back(new (Context) RawComment(
  7001. SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
  7002. Context.getLangOpts().CommentOpts.ParseAllComments));
  7003. break;
  7004. }
  7005. }
  7006. }
  7007. NextCursor:
  7008. Context.Comments.addDeserializedComments(Comments);
  7009. }
  7010. }
  7011. std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
  7012. // If we know the owning module, use it.
  7013. if (Module *M = D->getOwningModule())
  7014. return M->getFullModuleName();
  7015. // Otherwise, use the name of the top-level module the decl is within.
  7016. if (ModuleFile *M = getOwningModuleFile(D))
  7017. return M->ModuleName;
  7018. // Not from a module.
  7019. return "";
  7020. }
  7021. void ASTReader::finishPendingActions() {
  7022. while (!PendingIdentifierInfos.empty() ||
  7023. !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
  7024. !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
  7025. !PendingUpdateRecords.empty()) {
  7026. // If any identifiers with corresponding top-level declarations have
  7027. // been loaded, load those declarations now.
  7028. typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
  7029. TopLevelDeclsMap;
  7030. TopLevelDeclsMap TopLevelDecls;
  7031. while (!PendingIdentifierInfos.empty()) {
  7032. IdentifierInfo *II = PendingIdentifierInfos.back().first;
  7033. SmallVector<uint32_t, 4> DeclIDs =
  7034. std::move(PendingIdentifierInfos.back().second);
  7035. PendingIdentifierInfos.pop_back();
  7036. SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
  7037. }
  7038. // For each decl chain that we wanted to complete while deserializing, mark
  7039. // it as "still needs to be completed".
  7040. for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
  7041. markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
  7042. }
  7043. PendingIncompleteDeclChains.clear();
  7044. // Load pending declaration chains.
  7045. for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
  7046. loadPendingDeclChain(PendingDeclChains[I]);
  7047. PendingDeclChainsKnown.erase(PendingDeclChains[I]);
  7048. }
  7049. PendingDeclChains.clear();
  7050. // Make the most recent of the top-level declarations visible.
  7051. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
  7052. TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
  7053. IdentifierInfo *II = TLD->first;
  7054. for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
  7055. pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
  7056. }
  7057. }
  7058. // Load any pending macro definitions.
  7059. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
  7060. IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
  7061. SmallVector<PendingMacroInfo, 2> GlobalIDs;
  7062. GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
  7063. // Initialize the macro history from chained-PCHs ahead of module imports.
  7064. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7065. ++IDIdx) {
  7066. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7067. if (Info.M->Kind != MK_Module)
  7068. resolvePendingMacro(II, Info);
  7069. }
  7070. // Handle module imports.
  7071. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7072. ++IDIdx) {
  7073. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7074. if (Info.M->Kind == MK_Module)
  7075. resolvePendingMacro(II, Info);
  7076. }
  7077. }
  7078. PendingMacroIDs.clear();
  7079. // Wire up the DeclContexts for Decls that we delayed setting until
  7080. // recursive loading is completed.
  7081. while (!PendingDeclContextInfos.empty()) {
  7082. PendingDeclContextInfo Info = PendingDeclContextInfos.front();
  7083. PendingDeclContextInfos.pop_front();
  7084. DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
  7085. DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
  7086. Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
  7087. }
  7088. // Perform any pending declaration updates.
  7089. while (!PendingUpdateRecords.empty()) {
  7090. auto Update = PendingUpdateRecords.pop_back_val();
  7091. ReadingKindTracker ReadingKind(Read_Decl, *this);
  7092. loadDeclUpdateRecords(Update.first, Update.second);
  7093. }
  7094. }
  7095. // If we deserialized any C++ or Objective-C class definitions, any
  7096. // Objective-C protocol definitions, or any redeclarable templates, make sure
  7097. // that all redeclarations point to the definitions. Note that this can only
  7098. // happen now, after the redeclaration chains have been fully wired.
  7099. for (Decl *D : PendingDefinitions) {
  7100. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7101. if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
  7102. // Make sure that the TagType points at the definition.
  7103. const_cast<TagType*>(TagT)->decl = TD;
  7104. }
  7105. if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
  7106. for (auto R : RD->redecls())
  7107. cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
  7108. }
  7109. continue;
  7110. }
  7111. if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  7112. // Make sure that the ObjCInterfaceType points at the definition.
  7113. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
  7114. ->Decl = ID;
  7115. for (auto R : ID->redecls())
  7116. R->Data = ID->Data;
  7117. continue;
  7118. }
  7119. if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
  7120. for (auto R : PD->redecls())
  7121. R->Data = PD->Data;
  7122. continue;
  7123. }
  7124. auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
  7125. for (auto R : RTD->redecls())
  7126. R->Common = RTD->Common;
  7127. }
  7128. PendingDefinitions.clear();
  7129. // Load the bodies of any functions or methods we've encountered. We do
  7130. // this now (delayed) so that we can be sure that the declaration chains
  7131. // have been fully wired up.
  7132. for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
  7133. PBEnd = PendingBodies.end();
  7134. PB != PBEnd; ++PB) {
  7135. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
  7136. // FIXME: Check for =delete/=default?
  7137. // FIXME: Complain about ODR violations here?
  7138. if (!getContext().getLangOpts().Modules || !FD->hasBody())
  7139. FD->setLazyBody(PB->second);
  7140. continue;
  7141. }
  7142. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
  7143. if (!getContext().getLangOpts().Modules || !MD->hasBody())
  7144. MD->setLazyBody(PB->second);
  7145. }
  7146. PendingBodies.clear();
  7147. }
  7148. void ASTReader::diagnoseOdrViolations() {
  7149. if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
  7150. return;
  7151. // Trigger the import of the full definition of each class that had any
  7152. // odr-merging problems, so we can produce better diagnostics for them.
  7153. // These updates may in turn find and diagnose some ODR failures, so take
  7154. // ownership of the set first.
  7155. auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
  7156. PendingOdrMergeFailures.clear();
  7157. for (auto &Merge : OdrMergeFailures) {
  7158. Merge.first->buildLookup();
  7159. Merge.first->decls_begin();
  7160. Merge.first->bases_begin();
  7161. Merge.first->vbases_begin();
  7162. for (auto *RD : Merge.second) {
  7163. RD->decls_begin();
  7164. RD->bases_begin();
  7165. RD->vbases_begin();
  7166. }
  7167. }
  7168. // For each declaration from a merged context, check that the canonical
  7169. // definition of that context also contains a declaration of the same
  7170. // entity.
  7171. //
  7172. // Caution: this loop does things that might invalidate iterators into
  7173. // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
  7174. while (!PendingOdrMergeChecks.empty()) {
  7175. NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
  7176. // FIXME: Skip over implicit declarations for now. This matters for things
  7177. // like implicitly-declared special member functions. This isn't entirely
  7178. // correct; we can end up with multiple unmerged declarations of the same
  7179. // implicit entity.
  7180. if (D->isImplicit())
  7181. continue;
  7182. DeclContext *CanonDef = D->getDeclContext();
  7183. DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
  7184. bool Found = false;
  7185. const Decl *DCanon = D->getCanonicalDecl();
  7186. llvm::SmallVector<const NamedDecl*, 4> Candidates;
  7187. for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
  7188. !Found && I != E; ++I) {
  7189. for (auto RI : (*I)->redecls()) {
  7190. if (RI->getLexicalDeclContext() == CanonDef) {
  7191. // This declaration is present in the canonical definition. If it's
  7192. // in the same redecl chain, it's the one we're looking for.
  7193. if (RI->getCanonicalDecl() == DCanon)
  7194. Found = true;
  7195. else
  7196. Candidates.push_back(cast<NamedDecl>(RI));
  7197. break;
  7198. }
  7199. }
  7200. }
  7201. if (!Found) {
  7202. D->setInvalidDecl();
  7203. std::string CanonDefModule =
  7204. getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
  7205. Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
  7206. << D << getOwningModuleNameForDiagnostic(D)
  7207. << CanonDef << CanonDefModule.empty() << CanonDefModule;
  7208. if (Candidates.empty())
  7209. Diag(cast<Decl>(CanonDef)->getLocation(),
  7210. diag::note_module_odr_violation_no_possible_decls) << D;
  7211. else {
  7212. for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
  7213. Diag(Candidates[I]->getLocation(),
  7214. diag::note_module_odr_violation_possible_decl)
  7215. << Candidates[I];
  7216. }
  7217. DiagnosedOdrMergeFailures.insert(CanonDef);
  7218. }
  7219. }
  7220. // Issue any pending ODR-failure diagnostics.
  7221. for (auto &Merge : OdrMergeFailures) {
  7222. // If we've already pointed out a specific problem with this class, don't
  7223. // bother issuing a general "something's different" diagnostic.
  7224. if (!DiagnosedOdrMergeFailures.insert(Merge.first))
  7225. continue;
  7226. bool Diagnosed = false;
  7227. for (auto *RD : Merge.second) {
  7228. // Multiple different declarations got merged together; tell the user
  7229. // where they came from.
  7230. if (Merge.first != RD) {
  7231. // FIXME: Walk the definition, figure out what's different,
  7232. // and diagnose that.
  7233. if (!Diagnosed) {
  7234. std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
  7235. Diag(Merge.first->getLocation(),
  7236. diag::err_module_odr_violation_different_definitions)
  7237. << Merge.first << Module.empty() << Module;
  7238. Diagnosed = true;
  7239. }
  7240. Diag(RD->getLocation(),
  7241. diag::note_module_odr_violation_different_definitions)
  7242. << getOwningModuleNameForDiagnostic(RD);
  7243. }
  7244. }
  7245. if (!Diagnosed) {
  7246. // All definitions are updates to the same declaration. This happens if a
  7247. // module instantiates the declaration of a class template specialization
  7248. // and two or more other modules instantiate its definition.
  7249. //
  7250. // FIXME: Indicate which modules had instantiations of this definition.
  7251. // FIXME: How can this even happen?
  7252. Diag(Merge.first->getLocation(),
  7253. diag::err_module_odr_violation_different_instantiations)
  7254. << Merge.first;
  7255. }
  7256. }
  7257. }
  7258. void ASTReader::FinishedDeserializing() {
  7259. assert(NumCurrentElementsDeserializing &&
  7260. "FinishedDeserializing not paired with StartedDeserializing");
  7261. if (NumCurrentElementsDeserializing == 1) {
  7262. // We decrease NumCurrentElementsDeserializing only after pending actions
  7263. // are finished, to avoid recursively re-calling finishPendingActions().
  7264. finishPendingActions();
  7265. }
  7266. --NumCurrentElementsDeserializing;
  7267. if (NumCurrentElementsDeserializing == 0) {
  7268. diagnoseOdrViolations();
  7269. // We are not in recursive loading, so it's safe to pass the "interesting"
  7270. // decls to the consumer.
  7271. if (Consumer)
  7272. PassInterestingDeclsToConsumer();
  7273. }
  7274. }
  7275. void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  7276. D = D->getMostRecentDecl();
  7277. if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
  7278. SemaObj->TUScope->AddDecl(D);
  7279. } else if (SemaObj->TUScope) {
  7280. // Adding the decl to IdResolver may have failed because it was already in
  7281. // (even though it was not added in scope). If it is already in, make sure
  7282. // it gets in the scope as well.
  7283. if (std::find(SemaObj->IdResolver.begin(Name),
  7284. SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
  7285. SemaObj->TUScope->AddDecl(D);
  7286. }
  7287. }
  7288. ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
  7289. bool DisableValidation, bool AllowASTWithCompilerErrors,
  7290. bool AllowConfigurationMismatch, bool ValidateSystemInputs,
  7291. bool UseGlobalIndex)
  7292. : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
  7293. OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
  7294. FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
  7295. SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
  7296. ModuleMgr(PP.getFileManager()), isysroot(isysroot),
  7297. DisableValidation(DisableValidation),
  7298. AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
  7299. AllowConfigurationMismatch(AllowConfigurationMismatch),
  7300. ValidateSystemInputs(ValidateSystemInputs),
  7301. UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
  7302. CurrSwitchCaseStmts(&SwitchCaseStmts),
  7303. NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
  7304. TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
  7305. NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
  7306. NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
  7307. NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
  7308. NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
  7309. NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
  7310. NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
  7311. TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
  7312. PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
  7313. ReadingKind(Read_None) {
  7314. SourceMgr.setExternalSLocEntrySource(this);
  7315. }
  7316. ASTReader::~ASTReader() {
  7317. if (OwnsDeserializationListener)
  7318. delete DeserializationListener;
  7319. for (DeclContextVisibleUpdatesPending::iterator
  7320. I = PendingVisibleUpdates.begin(),
  7321. E = PendingVisibleUpdates.end();
  7322. I != E; ++I) {
  7323. for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
  7324. F = I->second.end();
  7325. J != F; ++J)
  7326. delete J->first;
  7327. }
  7328. }