ASTImporter.cpp 367 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070
  1. //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ASTImporter class which imports AST nodes from one
  10. // context into another context.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTImporter.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/ASTImporterSharedState.h"
  17. #include "clang/AST/ASTStructuralEquivalence.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclAccessPair.h"
  21. #include "clang/AST/DeclBase.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclFriend.h"
  24. #include "clang/AST/DeclGroup.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/DeclVisitor.h"
  28. #include "clang/AST/DeclarationName.h"
  29. #include "clang/AST/Expr.h"
  30. #include "clang/AST/ExprCXX.h"
  31. #include "clang/AST/ExprObjC.h"
  32. #include "clang/AST/ExternalASTSource.h"
  33. #include "clang/AST/LambdaCapture.h"
  34. #include "clang/AST/NestedNameSpecifier.h"
  35. #include "clang/AST/OperationKinds.h"
  36. #include "clang/AST/Stmt.h"
  37. #include "clang/AST/StmtCXX.h"
  38. #include "clang/AST/StmtObjC.h"
  39. #include "clang/AST/StmtVisitor.h"
  40. #include "clang/AST/TemplateBase.h"
  41. #include "clang/AST/TemplateName.h"
  42. #include "clang/AST/Type.h"
  43. #include "clang/AST/TypeLoc.h"
  44. #include "clang/AST/TypeVisitor.h"
  45. #include "clang/AST/UnresolvedSet.h"
  46. #include "clang/Basic/Builtins.h"
  47. #include "clang/Basic/ExceptionSpecificationType.h"
  48. #include "clang/Basic/FileManager.h"
  49. #include "clang/Basic/IdentifierTable.h"
  50. #include "clang/Basic/LLVM.h"
  51. #include "clang/Basic/LangOptions.h"
  52. #include "clang/Basic/SourceLocation.h"
  53. #include "clang/Basic/SourceManager.h"
  54. #include "clang/Basic/Specifiers.h"
  55. #include "llvm/ADT/APSInt.h"
  56. #include "llvm/ADT/ArrayRef.h"
  57. #include "llvm/ADT/DenseMap.h"
  58. #include "llvm/ADT/STLExtras.h"
  59. #include "llvm/ADT/ScopeExit.h"
  60. #include "llvm/ADT/SmallVector.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/MemoryBuffer.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cstddef>
  67. #include <memory>
  68. #include <optional>
  69. #include <type_traits>
  70. #include <utility>
  71. namespace clang {
  72. using llvm::make_error;
  73. using llvm::Error;
  74. using llvm::Expected;
  75. using ExpectedTypePtr = llvm::Expected<const Type *>;
  76. using ExpectedType = llvm::Expected<QualType>;
  77. using ExpectedStmt = llvm::Expected<Stmt *>;
  78. using ExpectedExpr = llvm::Expected<Expr *>;
  79. using ExpectedDecl = llvm::Expected<Decl *>;
  80. using ExpectedSLoc = llvm::Expected<SourceLocation>;
  81. using ExpectedName = llvm::Expected<DeclarationName>;
  82. std::string ASTImportError::toString() const {
  83. // FIXME: Improve error texts.
  84. switch (Error) {
  85. case NameConflict:
  86. return "NameConflict";
  87. case UnsupportedConstruct:
  88. return "UnsupportedConstruct";
  89. case Unknown:
  90. return "Unknown error";
  91. }
  92. llvm_unreachable("Invalid error code.");
  93. return "Invalid error code.";
  94. }
  95. void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
  96. std::error_code ASTImportError::convertToErrorCode() const {
  97. llvm_unreachable("Function not implemented.");
  98. }
  99. char ASTImportError::ID;
  100. template <class T>
  101. SmallVector<Decl *, 2>
  102. getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
  103. SmallVector<Decl *, 2> Redecls;
  104. for (auto *R : D->getFirstDecl()->redecls()) {
  105. if (R != D->getFirstDecl())
  106. Redecls.push_back(R);
  107. }
  108. Redecls.push_back(D->getFirstDecl());
  109. std::reverse(Redecls.begin(), Redecls.end());
  110. return Redecls;
  111. }
  112. SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
  113. if (auto *FD = dyn_cast<FunctionDecl>(D))
  114. return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
  115. if (auto *VD = dyn_cast<VarDecl>(D))
  116. return getCanonicalForwardRedeclChain<VarDecl>(VD);
  117. if (auto *TD = dyn_cast<TagDecl>(D))
  118. return getCanonicalForwardRedeclChain<TagDecl>(TD);
  119. llvm_unreachable("Bad declaration kind");
  120. }
  121. void updateFlags(const Decl *From, Decl *To) {
  122. // Check if some flags or attrs are new in 'From' and copy into 'To'.
  123. // FIXME: Other flags or attrs?
  124. if (From->isUsed(false) && !To->isUsed(false))
  125. To->setIsUsed();
  126. }
  127. /// How to handle import errors that occur when import of a child declaration
  128. /// of a DeclContext fails.
  129. class ChildErrorHandlingStrategy {
  130. /// This context is imported (in the 'from' domain).
  131. /// It is nullptr if a non-DeclContext is imported.
  132. const DeclContext *const FromDC;
  133. /// Ignore import errors of the children.
  134. /// If true, the context can be imported successfully if a child
  135. /// of it failed to import. Otherwise the import errors of the child nodes
  136. /// are accumulated (joined) into the import error object of the parent.
  137. /// (Import of a parent can fail in other ways.)
  138. bool const IgnoreChildErrors;
  139. public:
  140. ChildErrorHandlingStrategy(const DeclContext *FromDC)
  141. : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {}
  142. ChildErrorHandlingStrategy(const Decl *FromD)
  143. : FromDC(dyn_cast<DeclContext>(FromD)),
  144. IgnoreChildErrors(!isa<TagDecl>(FromD)) {}
  145. /// Process the import result of a child (of the current declaration).
  146. /// \param ResultErr The import error that can be used as result of
  147. /// importing the parent. This may be changed by the function.
  148. /// \param ChildErr Result of importing a child. Can be success or error.
  149. void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
  150. if (ChildErr && !IgnoreChildErrors)
  151. ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
  152. else
  153. consumeError(std::move(ChildErr));
  154. }
  155. /// Determine if import failure of a child does not cause import failure of
  156. /// its parent.
  157. bool ignoreChildErrorOnParent(Decl *FromChildD) const {
  158. if (!IgnoreChildErrors || !FromDC)
  159. return false;
  160. return FromDC->containsDecl(FromChildD);
  161. }
  162. };
  163. class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
  164. public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
  165. public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
  166. ASTImporter &Importer;
  167. // Use this instead of Importer.importInto .
  168. template <typename ImportT>
  169. [[nodiscard]] Error importInto(ImportT &To, const ImportT &From) {
  170. return Importer.importInto(To, From);
  171. }
  172. // Use this to import pointers of specific type.
  173. template <typename ImportT>
  174. [[nodiscard]] Error importInto(ImportT *&To, ImportT *From) {
  175. auto ToOrErr = Importer.Import(From);
  176. if (ToOrErr)
  177. To = cast_or_null<ImportT>(*ToOrErr);
  178. return ToOrErr.takeError();
  179. }
  180. // Call the import function of ASTImporter for a baseclass of type `T` and
  181. // cast the return value to `T`.
  182. template <typename T>
  183. auto import(T *From)
  184. -> std::conditional_t<std::is_base_of_v<Type, T>, Expected<const T *>,
  185. Expected<T *>> {
  186. auto ToOrErr = Importer.Import(From);
  187. if (!ToOrErr)
  188. return ToOrErr.takeError();
  189. return cast_or_null<T>(*ToOrErr);
  190. }
  191. template <typename T>
  192. auto import(const T *From) {
  193. return import(const_cast<T *>(From));
  194. }
  195. // Call the import function of ASTImporter for type `T`.
  196. template <typename T>
  197. Expected<T> import(const T &From) {
  198. return Importer.Import(From);
  199. }
  200. // Import an std::optional<T> by importing the contained T, if any.
  201. template <typename T>
  202. Expected<std::optional<T>> import(std::optional<T> From) {
  203. if (!From)
  204. return std::nullopt;
  205. return import(*From);
  206. }
  207. ExplicitSpecifier importExplicitSpecifier(Error &Err,
  208. ExplicitSpecifier ESpec);
  209. // Wrapper for an overload set.
  210. template <typename ToDeclT> struct CallOverloadedCreateFun {
  211. template <typename... Args> decltype(auto) operator()(Args &&... args) {
  212. return ToDeclT::Create(std::forward<Args>(args)...);
  213. }
  214. };
  215. // Always use these functions to create a Decl during import. There are
  216. // certain tasks which must be done after the Decl was created, e.g. we
  217. // must immediately register that as an imported Decl. The parameter `ToD`
  218. // will be set to the newly created Decl or if had been imported before
  219. // then to the already imported Decl. Returns a bool value set to true if
  220. // the `FromD` had been imported before.
  221. template <typename ToDeclT, typename FromDeclT, typename... Args>
  222. [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
  223. Args &&...args) {
  224. // There may be several overloads of ToDeclT::Create. We must make sure
  225. // to call the one which would be chosen by the arguments, thus we use a
  226. // wrapper for the overload set.
  227. CallOverloadedCreateFun<ToDeclT> OC;
  228. return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
  229. std::forward<Args>(args)...);
  230. }
  231. // Use this overload if a special Type is needed to be created. E.g if we
  232. // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
  233. // then:
  234. // TypedefNameDecl *ToTypedef;
  235. // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
  236. template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
  237. typename... Args>
  238. [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
  239. Args &&...args) {
  240. CallOverloadedCreateFun<NewDeclT> OC;
  241. return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
  242. std::forward<Args>(args)...);
  243. }
  244. // Use this version if a special create function must be
  245. // used, e.g. CXXRecordDecl::CreateLambda .
  246. template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
  247. typename... Args>
  248. [[nodiscard]] bool
  249. GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
  250. FromDeclT *FromD, Args &&...args) {
  251. if (Importer.getImportDeclErrorIfAny(FromD)) {
  252. ToD = nullptr;
  253. return true; // Already imported but with error.
  254. }
  255. ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
  256. if (ToD)
  257. return true; // Already imported.
  258. ToD = CreateFun(std::forward<Args>(args)...);
  259. // Keep track of imported Decls.
  260. Importer.RegisterImportedDecl(FromD, ToD);
  261. Importer.SharedState->markAsNewDecl(ToD);
  262. InitializeImportedDecl(FromD, ToD);
  263. return false; // A new Decl is created.
  264. }
  265. void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
  266. ToD->IdentifierNamespace = FromD->IdentifierNamespace;
  267. if (FromD->isUsed())
  268. ToD->setIsUsed();
  269. if (FromD->isImplicit())
  270. ToD->setImplicit();
  271. }
  272. // Check if we have found an existing definition. Returns with that
  273. // definition if yes, otherwise returns null.
  274. Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
  275. const FunctionDecl *Definition = nullptr;
  276. if (D->doesThisDeclarationHaveABody() &&
  277. FoundFunction->hasBody(Definition))
  278. return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
  279. return nullptr;
  280. }
  281. void addDeclToContexts(Decl *FromD, Decl *ToD) {
  282. if (Importer.isMinimalImport()) {
  283. // In minimal import case the decl must be added even if it is not
  284. // contained in original context, for LLDB compatibility.
  285. // FIXME: Check if a better solution is possible.
  286. if (!FromD->getDescribedTemplate() &&
  287. FromD->getFriendObjectKind() == Decl::FOK_None)
  288. ToD->getLexicalDeclContext()->addDeclInternal(ToD);
  289. return;
  290. }
  291. DeclContext *FromDC = FromD->getDeclContext();
  292. DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
  293. DeclContext *ToDC = ToD->getDeclContext();
  294. DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
  295. bool Visible = false;
  296. if (FromDC->containsDeclAndLoad(FromD)) {
  297. ToDC->addDeclInternal(ToD);
  298. Visible = true;
  299. }
  300. if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
  301. ToLexicalDC->addDeclInternal(ToD);
  302. Visible = true;
  303. }
  304. // If the Decl was added to any context, it was made already visible.
  305. // Otherwise it is still possible that it should be visible.
  306. if (!Visible) {
  307. if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
  308. auto *ToNamed = cast<NamedDecl>(ToD);
  309. DeclContextLookupResult FromLookup =
  310. FromDC->lookup(FromNamed->getDeclName());
  311. if (llvm::is_contained(FromLookup, FromNamed))
  312. ToDC->makeDeclVisibleInContext(ToNamed);
  313. }
  314. }
  315. }
  316. void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
  317. DeclContext *OldDC) {
  318. ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
  319. if (!LT)
  320. return;
  321. for (NamedDecl *TP : Params)
  322. LT->update(TP, OldDC);
  323. }
  324. void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
  325. updateLookupTableForTemplateParameters(
  326. Params, Importer.getToContext().getTranslationUnitDecl());
  327. }
  328. public:
  329. explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
  330. using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
  331. using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
  332. using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
  333. // Importing types
  334. ExpectedType VisitType(const Type *T);
  335. ExpectedType VisitAtomicType(const AtomicType *T);
  336. ExpectedType VisitBuiltinType(const BuiltinType *T);
  337. ExpectedType VisitDecayedType(const DecayedType *T);
  338. ExpectedType VisitComplexType(const ComplexType *T);
  339. ExpectedType VisitPointerType(const PointerType *T);
  340. ExpectedType VisitBlockPointerType(const BlockPointerType *T);
  341. ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
  342. ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
  343. ExpectedType VisitMemberPointerType(const MemberPointerType *T);
  344. ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
  345. ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
  346. ExpectedType VisitVariableArrayType(const VariableArrayType *T);
  347. ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
  348. // FIXME: DependentSizedExtVectorType
  349. ExpectedType VisitVectorType(const VectorType *T);
  350. ExpectedType VisitExtVectorType(const ExtVectorType *T);
  351. ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
  352. ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
  353. ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
  354. ExpectedType VisitParenType(const ParenType *T);
  355. ExpectedType VisitTypedefType(const TypedefType *T);
  356. ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
  357. // FIXME: DependentTypeOfExprType
  358. ExpectedType VisitTypeOfType(const TypeOfType *T);
  359. ExpectedType VisitUsingType(const UsingType *T);
  360. ExpectedType VisitDecltypeType(const DecltypeType *T);
  361. ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
  362. ExpectedType VisitAutoType(const AutoType *T);
  363. ExpectedType VisitDeducedTemplateSpecializationType(
  364. const DeducedTemplateSpecializationType *T);
  365. ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
  366. // FIXME: DependentDecltypeType
  367. ExpectedType VisitRecordType(const RecordType *T);
  368. ExpectedType VisitEnumType(const EnumType *T);
  369. ExpectedType VisitAttributedType(const AttributedType *T);
  370. ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
  371. ExpectedType VisitSubstTemplateTypeParmType(
  372. const SubstTemplateTypeParmType *T);
  373. ExpectedType
  374. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T);
  375. ExpectedType VisitTemplateSpecializationType(
  376. const TemplateSpecializationType *T);
  377. ExpectedType VisitElaboratedType(const ElaboratedType *T);
  378. ExpectedType VisitDependentNameType(const DependentNameType *T);
  379. ExpectedType VisitPackExpansionType(const PackExpansionType *T);
  380. ExpectedType VisitDependentTemplateSpecializationType(
  381. const DependentTemplateSpecializationType *T);
  382. ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
  383. ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
  384. ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
  385. // Importing declarations
  386. Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
  387. SourceLocation &Loc);
  388. Error ImportDeclParts(
  389. NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
  390. DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
  391. Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
  392. Error ImportDeclarationNameLoc(
  393. const DeclarationNameInfo &From, DeclarationNameInfo &To);
  394. Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
  395. Error ImportDeclContext(
  396. Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
  397. Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
  398. Expected<CXXCastPath> ImportCastPath(CastExpr *E);
  399. Expected<APValue> ImportAPValue(const APValue &FromValue);
  400. using Designator = DesignatedInitExpr::Designator;
  401. /// What we should import from the definition.
  402. enum ImportDefinitionKind {
  403. /// Import the default subset of the definition, which might be
  404. /// nothing (if minimal import is set) or might be everything (if minimal
  405. /// import is not set).
  406. IDK_Default,
  407. /// Import everything.
  408. IDK_Everything,
  409. /// Import only the bare bones needed to establish a valid
  410. /// DeclContext.
  411. IDK_Basic
  412. };
  413. bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
  414. return IDK == IDK_Everything ||
  415. (IDK == IDK_Default && !Importer.isMinimalImport());
  416. }
  417. Error ImportInitializer(VarDecl *From, VarDecl *To);
  418. Error ImportDefinition(
  419. RecordDecl *From, RecordDecl *To,
  420. ImportDefinitionKind Kind = IDK_Default);
  421. Error ImportDefinition(
  422. EnumDecl *From, EnumDecl *To,
  423. ImportDefinitionKind Kind = IDK_Default);
  424. Error ImportDefinition(
  425. ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
  426. ImportDefinitionKind Kind = IDK_Default);
  427. Error ImportDefinition(
  428. ObjCProtocolDecl *From, ObjCProtocolDecl *To,
  429. ImportDefinitionKind Kind = IDK_Default);
  430. Error ImportTemplateArguments(ArrayRef<TemplateArgument> FromArgs,
  431. SmallVectorImpl<TemplateArgument> &ToArgs);
  432. Expected<TemplateArgument>
  433. ImportTemplateArgument(const TemplateArgument &From);
  434. template <typename InContainerTy>
  435. Error ImportTemplateArgumentListInfo(
  436. const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
  437. template<typename InContainerTy>
  438. Error ImportTemplateArgumentListInfo(
  439. SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
  440. const InContainerTy &Container, TemplateArgumentListInfo &Result);
  441. using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
  442. using FunctionTemplateAndArgsTy =
  443. std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
  444. Expected<FunctionTemplateAndArgsTy>
  445. ImportFunctionTemplateWithTemplateArgsFromSpecialization(
  446. FunctionDecl *FromFD);
  447. Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
  448. DeclaratorDecl *ToD);
  449. Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
  450. Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
  451. Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
  452. ParmVarDecl *ToParam);
  453. Expected<InheritedConstructor>
  454. ImportInheritedConstructor(const InheritedConstructor &From);
  455. template <typename T>
  456. bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
  457. bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true);
  458. ExpectedDecl VisitDecl(Decl *D);
  459. ExpectedDecl VisitImportDecl(ImportDecl *D);
  460. ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
  461. ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
  462. ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
  463. ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
  464. ExpectedDecl VisitBindingDecl(BindingDecl *D);
  465. ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
  466. ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
  467. ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
  468. ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
  469. ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
  470. ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
  471. ExpectedDecl VisitLabelDecl(LabelDecl *D);
  472. ExpectedDecl VisitEnumDecl(EnumDecl *D);
  473. ExpectedDecl VisitRecordDecl(RecordDecl *D);
  474. ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
  475. ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
  476. ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
  477. ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
  478. ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
  479. ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
  480. ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
  481. ExpectedDecl VisitFieldDecl(FieldDecl *D);
  482. ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
  483. ExpectedDecl VisitFriendDecl(FriendDecl *D);
  484. ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
  485. ExpectedDecl VisitVarDecl(VarDecl *D);
  486. ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
  487. ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
  488. ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
  489. ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
  490. ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
  491. ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
  492. ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
  493. ExpectedDecl VisitUsingDecl(UsingDecl *D);
  494. ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
  495. ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
  496. ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D);
  497. ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
  498. ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
  499. ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
  500. ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
  501. ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
  502. ExpectedDecl
  503. VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
  504. Expected<ObjCTypeParamList *>
  505. ImportObjCTypeParamList(ObjCTypeParamList *list);
  506. ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
  507. ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
  508. ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
  509. ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
  510. ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
  511. ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
  512. ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
  513. ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
  514. ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
  515. ExpectedDecl VisitClassTemplateSpecializationDecl(
  516. ClassTemplateSpecializationDecl *D);
  517. ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
  518. ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
  519. ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
  520. // Importing statements
  521. ExpectedStmt VisitStmt(Stmt *S);
  522. ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
  523. ExpectedStmt VisitDeclStmt(DeclStmt *S);
  524. ExpectedStmt VisitNullStmt(NullStmt *S);
  525. ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
  526. ExpectedStmt VisitCaseStmt(CaseStmt *S);
  527. ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
  528. ExpectedStmt VisitLabelStmt(LabelStmt *S);
  529. ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
  530. ExpectedStmt VisitIfStmt(IfStmt *S);
  531. ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
  532. ExpectedStmt VisitWhileStmt(WhileStmt *S);
  533. ExpectedStmt VisitDoStmt(DoStmt *S);
  534. ExpectedStmt VisitForStmt(ForStmt *S);
  535. ExpectedStmt VisitGotoStmt(GotoStmt *S);
  536. ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
  537. ExpectedStmt VisitContinueStmt(ContinueStmt *S);
  538. ExpectedStmt VisitBreakStmt(BreakStmt *S);
  539. ExpectedStmt VisitReturnStmt(ReturnStmt *S);
  540. // FIXME: MSAsmStmt
  541. // FIXME: SEHExceptStmt
  542. // FIXME: SEHFinallyStmt
  543. // FIXME: SEHTryStmt
  544. // FIXME: SEHLeaveStmt
  545. // FIXME: CapturedStmt
  546. ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
  547. ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
  548. ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
  549. // FIXME: MSDependentExistsStmt
  550. ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
  551. ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
  552. ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
  553. ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
  554. ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  555. ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
  556. ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  557. // Importing expressions
  558. ExpectedStmt VisitExpr(Expr *E);
  559. ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E);
  560. ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
  561. ExpectedStmt VisitChooseExpr(ChooseExpr *E);
  562. ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E);
  563. ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
  564. ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
  565. ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
  566. ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
  567. ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
  568. ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
  569. ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
  570. ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
  571. ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
  572. ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
  573. ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
  574. ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
  575. ExpectedStmt VisitStringLiteral(StringLiteral *E);
  576. ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
  577. ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
  578. ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
  579. ExpectedStmt VisitConstantExpr(ConstantExpr *E);
  580. ExpectedStmt VisitParenExpr(ParenExpr *E);
  581. ExpectedStmt VisitParenListExpr(ParenListExpr *E);
  582. ExpectedStmt VisitStmtExpr(StmtExpr *E);
  583. ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
  584. ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
  585. ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
  586. ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
  587. ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
  588. ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
  589. ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
  590. ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
  591. ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
  592. ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
  593. ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
  594. ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
  595. ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
  596. ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
  597. ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
  598. ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
  599. ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
  600. ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
  601. ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
  602. ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
  603. ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
  604. ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
  605. ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
  606. ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
  607. ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
  608. ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
  609. ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
  610. ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
  611. ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
  612. ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
  613. ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
  614. ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
  615. ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
  616. ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
  617. ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
  618. ExpectedStmt VisitMemberExpr(MemberExpr *E);
  619. ExpectedStmt VisitCallExpr(CallExpr *E);
  620. ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
  621. ExpectedStmt VisitInitListExpr(InitListExpr *E);
  622. ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
  623. ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
  624. ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
  625. ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
  626. ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
  627. ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
  628. ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
  629. ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
  630. ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
  631. ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
  632. // Helper for chaining together multiple imports. If an error is detected,
  633. // subsequent imports will return default constructed nodes, so that failure
  634. // can be detected with a single conditional branch after a sequence of
  635. // imports.
  636. template <typename T> T importChecked(Error &Err, const T &From) {
  637. // Don't attempt to import nodes if we hit an error earlier.
  638. if (Err)
  639. return T{};
  640. Expected<T> MaybeVal = import(From);
  641. if (!MaybeVal) {
  642. Err = MaybeVal.takeError();
  643. return T{};
  644. }
  645. return *MaybeVal;
  646. }
  647. template<typename IIter, typename OIter>
  648. Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
  649. using ItemT = std::remove_reference_t<decltype(*Obegin)>;
  650. for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
  651. Expected<ItemT> ToOrErr = import(*Ibegin);
  652. if (!ToOrErr)
  653. return ToOrErr.takeError();
  654. *Obegin = *ToOrErr;
  655. }
  656. return Error::success();
  657. }
  658. // Import every item from a container structure into an output container.
  659. // If error occurs, stops at first error and returns the error.
  660. // The output container should have space for all needed elements (it is not
  661. // expanded, new items are put into from the beginning).
  662. template<typename InContainerTy, typename OutContainerTy>
  663. Error ImportContainerChecked(
  664. const InContainerTy &InContainer, OutContainerTy &OutContainer) {
  665. return ImportArrayChecked(
  666. InContainer.begin(), InContainer.end(), OutContainer.begin());
  667. }
  668. template<typename InContainerTy, typename OIter>
  669. Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
  670. return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
  671. }
  672. Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
  673. CXXMethodDecl *FromMethod);
  674. Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
  675. FunctionDecl *FromFD);
  676. // Returns true if the given function has a placeholder return type and
  677. // that type is declared inside the body of the function.
  678. // E.g. auto f() { struct X{}; return X(); }
  679. bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
  680. };
  681. template <typename InContainerTy>
  682. Error ASTNodeImporter::ImportTemplateArgumentListInfo(
  683. SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
  684. const InContainerTy &Container, TemplateArgumentListInfo &Result) {
  685. auto ToLAngleLocOrErr = import(FromLAngleLoc);
  686. if (!ToLAngleLocOrErr)
  687. return ToLAngleLocOrErr.takeError();
  688. auto ToRAngleLocOrErr = import(FromRAngleLoc);
  689. if (!ToRAngleLocOrErr)
  690. return ToRAngleLocOrErr.takeError();
  691. TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
  692. if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
  693. return Err;
  694. Result = ToTAInfo;
  695. return Error::success();
  696. }
  697. template <>
  698. Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
  699. const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
  700. return ImportTemplateArgumentListInfo(
  701. From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
  702. }
  703. template <>
  704. Error ASTNodeImporter::ImportTemplateArgumentListInfo<
  705. ASTTemplateArgumentListInfo>(
  706. const ASTTemplateArgumentListInfo &From,
  707. TemplateArgumentListInfo &Result) {
  708. return ImportTemplateArgumentListInfo(
  709. From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
  710. }
  711. Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
  712. ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
  713. FunctionDecl *FromFD) {
  714. assert(FromFD->getTemplatedKind() ==
  715. FunctionDecl::TK_FunctionTemplateSpecialization);
  716. FunctionTemplateAndArgsTy Result;
  717. auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
  718. if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
  719. return std::move(Err);
  720. // Import template arguments.
  721. if (Error Err = ImportTemplateArguments(FTSInfo->TemplateArguments->asArray(),
  722. std::get<1>(Result)))
  723. return std::move(Err);
  724. return Result;
  725. }
  726. template <>
  727. Expected<TemplateParameterList *>
  728. ASTNodeImporter::import(TemplateParameterList *From) {
  729. SmallVector<NamedDecl *, 4> To(From->size());
  730. if (Error Err = ImportContainerChecked(*From, To))
  731. return std::move(Err);
  732. ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
  733. if (!ToRequiresClause)
  734. return ToRequiresClause.takeError();
  735. auto ToTemplateLocOrErr = import(From->getTemplateLoc());
  736. if (!ToTemplateLocOrErr)
  737. return ToTemplateLocOrErr.takeError();
  738. auto ToLAngleLocOrErr = import(From->getLAngleLoc());
  739. if (!ToLAngleLocOrErr)
  740. return ToLAngleLocOrErr.takeError();
  741. auto ToRAngleLocOrErr = import(From->getRAngleLoc());
  742. if (!ToRAngleLocOrErr)
  743. return ToRAngleLocOrErr.takeError();
  744. return TemplateParameterList::Create(
  745. Importer.getToContext(),
  746. *ToTemplateLocOrErr,
  747. *ToLAngleLocOrErr,
  748. To,
  749. *ToRAngleLocOrErr,
  750. *ToRequiresClause);
  751. }
  752. template <>
  753. Expected<TemplateArgument>
  754. ASTNodeImporter::import(const TemplateArgument &From) {
  755. switch (From.getKind()) {
  756. case TemplateArgument::Null:
  757. return TemplateArgument();
  758. case TemplateArgument::Type: {
  759. ExpectedType ToTypeOrErr = import(From.getAsType());
  760. if (!ToTypeOrErr)
  761. return ToTypeOrErr.takeError();
  762. return TemplateArgument(*ToTypeOrErr);
  763. }
  764. case TemplateArgument::Integral: {
  765. ExpectedType ToTypeOrErr = import(From.getIntegralType());
  766. if (!ToTypeOrErr)
  767. return ToTypeOrErr.takeError();
  768. return TemplateArgument(From, *ToTypeOrErr);
  769. }
  770. case TemplateArgument::Declaration: {
  771. Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
  772. if (!ToOrErr)
  773. return ToOrErr.takeError();
  774. ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
  775. if (!ToTypeOrErr)
  776. return ToTypeOrErr.takeError();
  777. return TemplateArgument(*ToOrErr, *ToTypeOrErr);
  778. }
  779. case TemplateArgument::NullPtr: {
  780. ExpectedType ToTypeOrErr = import(From.getNullPtrType());
  781. if (!ToTypeOrErr)
  782. return ToTypeOrErr.takeError();
  783. return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
  784. }
  785. case TemplateArgument::Template: {
  786. Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
  787. if (!ToTemplateOrErr)
  788. return ToTemplateOrErr.takeError();
  789. return TemplateArgument(*ToTemplateOrErr);
  790. }
  791. case TemplateArgument::TemplateExpansion: {
  792. Expected<TemplateName> ToTemplateOrErr =
  793. import(From.getAsTemplateOrTemplatePattern());
  794. if (!ToTemplateOrErr)
  795. return ToTemplateOrErr.takeError();
  796. return TemplateArgument(
  797. *ToTemplateOrErr, From.getNumTemplateExpansions());
  798. }
  799. case TemplateArgument::Expression:
  800. if (ExpectedExpr ToExpr = import(From.getAsExpr()))
  801. return TemplateArgument(*ToExpr);
  802. else
  803. return ToExpr.takeError();
  804. case TemplateArgument::Pack: {
  805. SmallVector<TemplateArgument, 2> ToPack;
  806. ToPack.reserve(From.pack_size());
  807. if (Error Err = ImportTemplateArguments(From.pack_elements(), ToPack))
  808. return std::move(Err);
  809. return TemplateArgument(
  810. llvm::ArrayRef(ToPack).copy(Importer.getToContext()));
  811. }
  812. }
  813. llvm_unreachable("Invalid template argument kind");
  814. }
  815. template <>
  816. Expected<TemplateArgumentLoc>
  817. ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
  818. Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
  819. if (!ArgOrErr)
  820. return ArgOrErr.takeError();
  821. TemplateArgument Arg = *ArgOrErr;
  822. TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
  823. TemplateArgumentLocInfo ToInfo;
  824. if (Arg.getKind() == TemplateArgument::Expression) {
  825. ExpectedExpr E = import(FromInfo.getAsExpr());
  826. if (!E)
  827. return E.takeError();
  828. ToInfo = TemplateArgumentLocInfo(*E);
  829. } else if (Arg.getKind() == TemplateArgument::Type) {
  830. if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
  831. ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
  832. else
  833. return TSIOrErr.takeError();
  834. } else {
  835. auto ToTemplateQualifierLocOrErr =
  836. import(FromInfo.getTemplateQualifierLoc());
  837. if (!ToTemplateQualifierLocOrErr)
  838. return ToTemplateQualifierLocOrErr.takeError();
  839. auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
  840. if (!ToTemplateNameLocOrErr)
  841. return ToTemplateNameLocOrErr.takeError();
  842. auto ToTemplateEllipsisLocOrErr =
  843. import(FromInfo.getTemplateEllipsisLoc());
  844. if (!ToTemplateEllipsisLocOrErr)
  845. return ToTemplateEllipsisLocOrErr.takeError();
  846. ToInfo = TemplateArgumentLocInfo(
  847. Importer.getToContext(), *ToTemplateQualifierLocOrErr,
  848. *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
  849. }
  850. return TemplateArgumentLoc(Arg, ToInfo);
  851. }
  852. template <>
  853. Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
  854. if (DG.isNull())
  855. return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
  856. size_t NumDecls = DG.end() - DG.begin();
  857. SmallVector<Decl *, 1> ToDecls;
  858. ToDecls.reserve(NumDecls);
  859. for (Decl *FromD : DG) {
  860. if (auto ToDOrErr = import(FromD))
  861. ToDecls.push_back(*ToDOrErr);
  862. else
  863. return ToDOrErr.takeError();
  864. }
  865. return DeclGroupRef::Create(Importer.getToContext(),
  866. ToDecls.begin(),
  867. NumDecls);
  868. }
  869. template <>
  870. Expected<ASTNodeImporter::Designator>
  871. ASTNodeImporter::import(const Designator &D) {
  872. if (D.isFieldDesignator()) {
  873. IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
  874. ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
  875. if (!ToDotLocOrErr)
  876. return ToDotLocOrErr.takeError();
  877. ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
  878. if (!ToFieldLocOrErr)
  879. return ToFieldLocOrErr.takeError();
  880. return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
  881. }
  882. ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
  883. if (!ToLBracketLocOrErr)
  884. return ToLBracketLocOrErr.takeError();
  885. ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
  886. if (!ToRBracketLocOrErr)
  887. return ToRBracketLocOrErr.takeError();
  888. if (D.isArrayDesignator())
  889. return Designator(D.getFirstExprIndex(),
  890. *ToLBracketLocOrErr, *ToRBracketLocOrErr);
  891. ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
  892. if (!ToEllipsisLocOrErr)
  893. return ToEllipsisLocOrErr.takeError();
  894. assert(D.isArrayRangeDesignator());
  895. return Designator(
  896. D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
  897. *ToRBracketLocOrErr);
  898. }
  899. template <>
  900. Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
  901. ValueDecl *Var = nullptr;
  902. if (From.capturesVariable()) {
  903. if (auto VarOrErr = import(From.getCapturedVar()))
  904. Var = *VarOrErr;
  905. else
  906. return VarOrErr.takeError();
  907. }
  908. auto LocationOrErr = import(From.getLocation());
  909. if (!LocationOrErr)
  910. return LocationOrErr.takeError();
  911. SourceLocation EllipsisLoc;
  912. if (From.isPackExpansion())
  913. if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
  914. return std::move(Err);
  915. return LambdaCapture(
  916. *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
  917. EllipsisLoc);
  918. }
  919. template <typename T>
  920. bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
  921. if (Found->getLinkageInternal() != From->getLinkageInternal())
  922. return false;
  923. if (From->hasExternalFormalLinkage())
  924. return Found->hasExternalFormalLinkage();
  925. if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
  926. return false;
  927. if (From->isInAnonymousNamespace())
  928. return Found->isInAnonymousNamespace();
  929. else
  930. return !Found->isInAnonymousNamespace() &&
  931. !Found->hasExternalFormalLinkage();
  932. }
  933. template <>
  934. bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
  935. TypedefNameDecl *From) {
  936. if (Found->getLinkageInternal() != From->getLinkageInternal())
  937. return false;
  938. if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
  939. return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
  940. return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
  941. }
  942. } // namespace clang
  943. //----------------------------------------------------------------------------
  944. // Import Types
  945. //----------------------------------------------------------------------------
  946. using namespace clang;
  947. ExpectedType ASTNodeImporter::VisitType(const Type *T) {
  948. Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
  949. << T->getTypeClassName();
  950. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  951. }
  952. ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
  953. ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
  954. if (!UnderlyingTypeOrErr)
  955. return UnderlyingTypeOrErr.takeError();
  956. return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
  957. }
  958. ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
  959. switch (T->getKind()) {
  960. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  961. case BuiltinType::Id: \
  962. return Importer.getToContext().SingletonId;
  963. #include "clang/Basic/OpenCLImageTypes.def"
  964. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  965. case BuiltinType::Id: \
  966. return Importer.getToContext().Id##Ty;
  967. #include "clang/Basic/OpenCLExtensionTypes.def"
  968. #define SVE_TYPE(Name, Id, SingletonId) \
  969. case BuiltinType::Id: \
  970. return Importer.getToContext().SingletonId;
  971. #include "clang/Basic/AArch64SVEACLETypes.def"
  972. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  973. case BuiltinType::Id: \
  974. return Importer.getToContext().Id##Ty;
  975. #include "clang/Basic/PPCTypes.def"
  976. #define RVV_TYPE(Name, Id, SingletonId) \
  977. case BuiltinType::Id: \
  978. return Importer.getToContext().SingletonId;
  979. #include "clang/Basic/RISCVVTypes.def"
  980. #define SHARED_SINGLETON_TYPE(Expansion)
  981. #define BUILTIN_TYPE(Id, SingletonId) \
  982. case BuiltinType::Id: return Importer.getToContext().SingletonId;
  983. #include "clang/AST/BuiltinTypes.def"
  984. // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
  985. // context supports C++.
  986. // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
  987. // context supports ObjC.
  988. case BuiltinType::Char_U:
  989. // The context we're importing from has an unsigned 'char'. If we're
  990. // importing into a context with a signed 'char', translate to
  991. // 'unsigned char' instead.
  992. if (Importer.getToContext().getLangOpts().CharIsSigned)
  993. return Importer.getToContext().UnsignedCharTy;
  994. return Importer.getToContext().CharTy;
  995. case BuiltinType::Char_S:
  996. // The context we're importing from has an unsigned 'char'. If we're
  997. // importing into a context with a signed 'char', translate to
  998. // 'unsigned char' instead.
  999. if (!Importer.getToContext().getLangOpts().CharIsSigned)
  1000. return Importer.getToContext().SignedCharTy;
  1001. return Importer.getToContext().CharTy;
  1002. case BuiltinType::WChar_S:
  1003. case BuiltinType::WChar_U:
  1004. // FIXME: If not in C++, shall we translate to the C equivalent of
  1005. // wchar_t?
  1006. return Importer.getToContext().WCharTy;
  1007. }
  1008. llvm_unreachable("Invalid BuiltinType Kind!");
  1009. }
  1010. ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
  1011. ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
  1012. if (!ToOriginalTypeOrErr)
  1013. return ToOriginalTypeOrErr.takeError();
  1014. return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
  1015. }
  1016. ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
  1017. ExpectedType ToElementTypeOrErr = import(T->getElementType());
  1018. if (!ToElementTypeOrErr)
  1019. return ToElementTypeOrErr.takeError();
  1020. return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
  1021. }
  1022. ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
  1023. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
  1024. if (!ToPointeeTypeOrErr)
  1025. return ToPointeeTypeOrErr.takeError();
  1026. return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
  1027. }
  1028. ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
  1029. // FIXME: Check for blocks support in "to" context.
  1030. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
  1031. if (!ToPointeeTypeOrErr)
  1032. return ToPointeeTypeOrErr.takeError();
  1033. return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
  1034. }
  1035. ExpectedType
  1036. ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
  1037. // FIXME: Check for C++ support in "to" context.
  1038. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
  1039. if (!ToPointeeTypeOrErr)
  1040. return ToPointeeTypeOrErr.takeError();
  1041. return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
  1042. }
  1043. ExpectedType
  1044. ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
  1045. // FIXME: Check for C++0x support in "to" context.
  1046. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
  1047. if (!ToPointeeTypeOrErr)
  1048. return ToPointeeTypeOrErr.takeError();
  1049. return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
  1050. }
  1051. ExpectedType
  1052. ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
  1053. // FIXME: Check for C++ support in "to" context.
  1054. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
  1055. if (!ToPointeeTypeOrErr)
  1056. return ToPointeeTypeOrErr.takeError();
  1057. ExpectedTypePtr ClassTypeOrErr = import(T->getClass());
  1058. if (!ClassTypeOrErr)
  1059. return ClassTypeOrErr.takeError();
  1060. return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr,
  1061. *ClassTypeOrErr);
  1062. }
  1063. ExpectedType
  1064. ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
  1065. Error Err = Error::success();
  1066. auto ToElementType = importChecked(Err, T->getElementType());
  1067. auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
  1068. if (Err)
  1069. return std::move(Err);
  1070. return Importer.getToContext().getConstantArrayType(
  1071. ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
  1072. T->getIndexTypeCVRQualifiers());
  1073. }
  1074. ExpectedType
  1075. ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
  1076. ExpectedType ToElementTypeOrErr = import(T->getElementType());
  1077. if (!ToElementTypeOrErr)
  1078. return ToElementTypeOrErr.takeError();
  1079. return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
  1080. T->getSizeModifier(),
  1081. T->getIndexTypeCVRQualifiers());
  1082. }
  1083. ExpectedType
  1084. ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
  1085. Error Err = Error::success();
  1086. QualType ToElementType = importChecked(Err, T->getElementType());
  1087. Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
  1088. SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
  1089. if (Err)
  1090. return std::move(Err);
  1091. return Importer.getToContext().getVariableArrayType(
  1092. ToElementType, ToSizeExpr, T->getSizeModifier(),
  1093. T->getIndexTypeCVRQualifiers(), ToBracketsRange);
  1094. }
  1095. ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
  1096. const DependentSizedArrayType *T) {
  1097. Error Err = Error::success();
  1098. QualType ToElementType = importChecked(Err, T->getElementType());
  1099. Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
  1100. SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
  1101. if (Err)
  1102. return std::move(Err);
  1103. // SizeExpr may be null if size is not specified directly.
  1104. // For example, 'int a[]'.
  1105. return Importer.getToContext().getDependentSizedArrayType(
  1106. ToElementType, ToSizeExpr, T->getSizeModifier(),
  1107. T->getIndexTypeCVRQualifiers(), ToBracketsRange);
  1108. }
  1109. ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
  1110. ExpectedType ToElementTypeOrErr = import(T->getElementType());
  1111. if (!ToElementTypeOrErr)
  1112. return ToElementTypeOrErr.takeError();
  1113. return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
  1114. T->getNumElements(),
  1115. T->getVectorKind());
  1116. }
  1117. ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
  1118. ExpectedType ToElementTypeOrErr = import(T->getElementType());
  1119. if (!ToElementTypeOrErr)
  1120. return ToElementTypeOrErr.takeError();
  1121. return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
  1122. T->getNumElements());
  1123. }
  1124. ExpectedType
  1125. ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  1126. // FIXME: What happens if we're importing a function without a prototype
  1127. // into C++? Should we make it variadic?
  1128. ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
  1129. if (!ToReturnTypeOrErr)
  1130. return ToReturnTypeOrErr.takeError();
  1131. return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
  1132. T->getExtInfo());
  1133. }
  1134. ExpectedType
  1135. ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
  1136. ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
  1137. if (!ToReturnTypeOrErr)
  1138. return ToReturnTypeOrErr.takeError();
  1139. // Import argument types
  1140. SmallVector<QualType, 4> ArgTypes;
  1141. for (const auto &A : T->param_types()) {
  1142. ExpectedType TyOrErr = import(A);
  1143. if (!TyOrErr)
  1144. return TyOrErr.takeError();
  1145. ArgTypes.push_back(*TyOrErr);
  1146. }
  1147. // Import exception types
  1148. SmallVector<QualType, 4> ExceptionTypes;
  1149. for (const auto &E : T->exceptions()) {
  1150. ExpectedType TyOrErr = import(E);
  1151. if (!TyOrErr)
  1152. return TyOrErr.takeError();
  1153. ExceptionTypes.push_back(*TyOrErr);
  1154. }
  1155. FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
  1156. Error Err = Error::success();
  1157. FunctionProtoType::ExtProtoInfo ToEPI;
  1158. ToEPI.ExtInfo = FromEPI.ExtInfo;
  1159. ToEPI.Variadic = FromEPI.Variadic;
  1160. ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
  1161. ToEPI.TypeQuals = FromEPI.TypeQuals;
  1162. ToEPI.RefQualifier = FromEPI.RefQualifier;
  1163. ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
  1164. ToEPI.ExceptionSpec.NoexceptExpr =
  1165. importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
  1166. ToEPI.ExceptionSpec.SourceDecl =
  1167. importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
  1168. ToEPI.ExceptionSpec.SourceTemplate =
  1169. importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
  1170. ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
  1171. if (Err)
  1172. return std::move(Err);
  1173. return Importer.getToContext().getFunctionType(
  1174. *ToReturnTypeOrErr, ArgTypes, ToEPI);
  1175. }
  1176. ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
  1177. const UnresolvedUsingType *T) {
  1178. Error Err = Error::success();
  1179. auto ToD = importChecked(Err, T->getDecl());
  1180. auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
  1181. if (Err)
  1182. return std::move(Err);
  1183. return Importer.getToContext().getTypeDeclType(
  1184. ToD, cast_or_null<TypeDecl>(ToPrevD));
  1185. }
  1186. ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
  1187. ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
  1188. if (!ToInnerTypeOrErr)
  1189. return ToInnerTypeOrErr.takeError();
  1190. return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
  1191. }
  1192. ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
  1193. Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
  1194. if (!ToDeclOrErr)
  1195. return ToDeclOrErr.takeError();
  1196. ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
  1197. if (!ToUnderlyingTypeOrErr)
  1198. return ToUnderlyingTypeOrErr.takeError();
  1199. return Importer.getToContext().getTypedefType(*ToDeclOrErr,
  1200. *ToUnderlyingTypeOrErr);
  1201. }
  1202. ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
  1203. ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
  1204. if (!ToExprOrErr)
  1205. return ToExprOrErr.takeError();
  1206. return Importer.getToContext().getTypeOfExprType(*ToExprOrErr, T->getKind());
  1207. }
  1208. ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
  1209. ExpectedType ToUnderlyingTypeOrErr = import(T->getUnmodifiedType());
  1210. if (!ToUnderlyingTypeOrErr)
  1211. return ToUnderlyingTypeOrErr.takeError();
  1212. return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr,
  1213. T->getKind());
  1214. }
  1215. ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
  1216. Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl());
  1217. if (!FoundOrErr)
  1218. return FoundOrErr.takeError();
  1219. Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType());
  1220. if (!UnderlyingOrErr)
  1221. return UnderlyingOrErr.takeError();
  1222. return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr);
  1223. }
  1224. ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
  1225. // FIXME: Make sure that the "to" context supports C++0x!
  1226. ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
  1227. if (!ToExprOrErr)
  1228. return ToExprOrErr.takeError();
  1229. ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
  1230. if (!ToUnderlyingTypeOrErr)
  1231. return ToUnderlyingTypeOrErr.takeError();
  1232. return Importer.getToContext().getDecltypeType(
  1233. *ToExprOrErr, *ToUnderlyingTypeOrErr);
  1234. }
  1235. ExpectedType
  1236. ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
  1237. ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
  1238. if (!ToBaseTypeOrErr)
  1239. return ToBaseTypeOrErr.takeError();
  1240. ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
  1241. if (!ToUnderlyingTypeOrErr)
  1242. return ToUnderlyingTypeOrErr.takeError();
  1243. return Importer.getToContext().getUnaryTransformType(
  1244. *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
  1245. }
  1246. ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
  1247. // FIXME: Make sure that the "to" context supports C++11!
  1248. ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
  1249. if (!ToDeducedTypeOrErr)
  1250. return ToDeducedTypeOrErr.takeError();
  1251. ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
  1252. if (!ToTypeConstraintConcept)
  1253. return ToTypeConstraintConcept.takeError();
  1254. SmallVector<TemplateArgument, 2> ToTemplateArgs;
  1255. if (Error Err = ImportTemplateArguments(T->getTypeConstraintArguments(),
  1256. ToTemplateArgs))
  1257. return std::move(Err);
  1258. return Importer.getToContext().getAutoType(
  1259. *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
  1260. /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
  1261. ToTemplateArgs);
  1262. }
  1263. ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
  1264. const DeducedTemplateSpecializationType *T) {
  1265. // FIXME: Make sure that the "to" context supports C++17!
  1266. Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
  1267. if (!ToTemplateNameOrErr)
  1268. return ToTemplateNameOrErr.takeError();
  1269. ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
  1270. if (!ToDeducedTypeOrErr)
  1271. return ToDeducedTypeOrErr.takeError();
  1272. return Importer.getToContext().getDeducedTemplateSpecializationType(
  1273. *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
  1274. }
  1275. ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
  1276. const InjectedClassNameType *T) {
  1277. Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
  1278. if (!ToDeclOrErr)
  1279. return ToDeclOrErr.takeError();
  1280. ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
  1281. if (!ToInjTypeOrErr)
  1282. return ToInjTypeOrErr.takeError();
  1283. // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
  1284. // See comments in InjectedClassNameType definition for details
  1285. // return Importer.getToContext().getInjectedClassNameType(D, InjType);
  1286. enum {
  1287. TypeAlignmentInBits = 4,
  1288. TypeAlignment = 1 << TypeAlignmentInBits
  1289. };
  1290. return QualType(new (Importer.getToContext(), TypeAlignment)
  1291. InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
  1292. }
  1293. ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
  1294. Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
  1295. if (!ToDeclOrErr)
  1296. return ToDeclOrErr.takeError();
  1297. return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
  1298. }
  1299. ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
  1300. Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
  1301. if (!ToDeclOrErr)
  1302. return ToDeclOrErr.takeError();
  1303. return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
  1304. }
  1305. ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
  1306. ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
  1307. if (!ToModifiedTypeOrErr)
  1308. return ToModifiedTypeOrErr.takeError();
  1309. ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
  1310. if (!ToEquivalentTypeOrErr)
  1311. return ToEquivalentTypeOrErr.takeError();
  1312. return Importer.getToContext().getAttributedType(T->getAttrKind(),
  1313. *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
  1314. }
  1315. ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
  1316. const TemplateTypeParmType *T) {
  1317. Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
  1318. if (!ToDeclOrErr)
  1319. return ToDeclOrErr.takeError();
  1320. return Importer.getToContext().getTemplateTypeParmType(
  1321. T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
  1322. }
  1323. ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
  1324. const SubstTemplateTypeParmType *T) {
  1325. Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
  1326. if (!ReplacedOrErr)
  1327. return ReplacedOrErr.takeError();
  1328. ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
  1329. if (!ToReplacementTypeOrErr)
  1330. return ToReplacementTypeOrErr.takeError();
  1331. return Importer.getToContext().getSubstTemplateTypeParmType(
  1332. *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(),
  1333. T->getPackIndex());
  1334. }
  1335. ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
  1336. const SubstTemplateTypeParmPackType *T) {
  1337. Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
  1338. if (!ReplacedOrErr)
  1339. return ReplacedOrErr.takeError();
  1340. Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
  1341. if (!ToArgumentPack)
  1342. return ToArgumentPack.takeError();
  1343. return Importer.getToContext().getSubstTemplateTypeParmPackType(
  1344. *ReplacedOrErr, T->getIndex(), T->getFinal(), *ToArgumentPack);
  1345. }
  1346. ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
  1347. const TemplateSpecializationType *T) {
  1348. auto ToTemplateOrErr = import(T->getTemplateName());
  1349. if (!ToTemplateOrErr)
  1350. return ToTemplateOrErr.takeError();
  1351. SmallVector<TemplateArgument, 2> ToTemplateArgs;
  1352. if (Error Err =
  1353. ImportTemplateArguments(T->template_arguments(), ToTemplateArgs))
  1354. return std::move(Err);
  1355. QualType ToCanonType;
  1356. if (!T->isCanonicalUnqualified()) {
  1357. QualType FromCanonType
  1358. = Importer.getFromContext().getCanonicalType(QualType(T, 0));
  1359. if (ExpectedType TyOrErr = import(FromCanonType))
  1360. ToCanonType = *TyOrErr;
  1361. else
  1362. return TyOrErr.takeError();
  1363. }
  1364. return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
  1365. ToTemplateArgs,
  1366. ToCanonType);
  1367. }
  1368. ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
  1369. // Note: the qualifier in an ElaboratedType is optional.
  1370. auto ToQualifierOrErr = import(T->getQualifier());
  1371. if (!ToQualifierOrErr)
  1372. return ToQualifierOrErr.takeError();
  1373. ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
  1374. if (!ToNamedTypeOrErr)
  1375. return ToNamedTypeOrErr.takeError();
  1376. Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
  1377. if (!ToOwnedTagDeclOrErr)
  1378. return ToOwnedTagDeclOrErr.takeError();
  1379. return Importer.getToContext().getElaboratedType(T->getKeyword(),
  1380. *ToQualifierOrErr,
  1381. *ToNamedTypeOrErr,
  1382. *ToOwnedTagDeclOrErr);
  1383. }
  1384. ExpectedType
  1385. ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
  1386. ExpectedType ToPatternOrErr = import(T->getPattern());
  1387. if (!ToPatternOrErr)
  1388. return ToPatternOrErr.takeError();
  1389. return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
  1390. T->getNumExpansions(),
  1391. /*ExpactPack=*/false);
  1392. }
  1393. ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
  1394. const DependentTemplateSpecializationType *T) {
  1395. auto ToQualifierOrErr = import(T->getQualifier());
  1396. if (!ToQualifierOrErr)
  1397. return ToQualifierOrErr.takeError();
  1398. IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
  1399. SmallVector<TemplateArgument, 2> ToPack;
  1400. ToPack.reserve(T->template_arguments().size());
  1401. if (Error Err = ImportTemplateArguments(T->template_arguments(), ToPack))
  1402. return std::move(Err);
  1403. return Importer.getToContext().getDependentTemplateSpecializationType(
  1404. T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
  1405. }
  1406. ExpectedType
  1407. ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
  1408. auto ToQualifierOrErr = import(T->getQualifier());
  1409. if (!ToQualifierOrErr)
  1410. return ToQualifierOrErr.takeError();
  1411. IdentifierInfo *Name = Importer.Import(T->getIdentifier());
  1412. QualType Canon;
  1413. if (T != T->getCanonicalTypeInternal().getTypePtr()) {
  1414. if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
  1415. Canon = (*TyOrErr).getCanonicalType();
  1416. else
  1417. return TyOrErr.takeError();
  1418. }
  1419. return Importer.getToContext().getDependentNameType(T->getKeyword(),
  1420. *ToQualifierOrErr,
  1421. Name, Canon);
  1422. }
  1423. ExpectedType
  1424. ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
  1425. Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
  1426. if (!ToDeclOrErr)
  1427. return ToDeclOrErr.takeError();
  1428. return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
  1429. }
  1430. ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
  1431. ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
  1432. if (!ToBaseTypeOrErr)
  1433. return ToBaseTypeOrErr.takeError();
  1434. SmallVector<QualType, 4> TypeArgs;
  1435. for (auto TypeArg : T->getTypeArgsAsWritten()) {
  1436. if (ExpectedType TyOrErr = import(TypeArg))
  1437. TypeArgs.push_back(*TyOrErr);
  1438. else
  1439. return TyOrErr.takeError();
  1440. }
  1441. SmallVector<ObjCProtocolDecl *, 4> Protocols;
  1442. for (auto *P : T->quals()) {
  1443. if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
  1444. Protocols.push_back(*ProtocolOrErr);
  1445. else
  1446. return ProtocolOrErr.takeError();
  1447. }
  1448. return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
  1449. Protocols,
  1450. T->isKindOfTypeAsWritten());
  1451. }
  1452. ExpectedType
  1453. ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  1454. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
  1455. if (!ToPointeeTypeOrErr)
  1456. return ToPointeeTypeOrErr.takeError();
  1457. return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
  1458. }
  1459. //----------------------------------------------------------------------------
  1460. // Import Declarations
  1461. //----------------------------------------------------------------------------
  1462. Error ASTNodeImporter::ImportDeclParts(
  1463. NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
  1464. DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
  1465. // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
  1466. // example: int struct_in_proto(struct data_t{int a;int b;} *d);
  1467. // FIXME: We could support these constructs by importing a different type of
  1468. // this parameter and by importing the original type of the parameter only
  1469. // after the FunctionDecl is created. See
  1470. // VisitFunctionDecl::UsedDifferentProtoType.
  1471. DeclContext *OrigDC = D->getDeclContext();
  1472. FunctionDecl *FunDecl;
  1473. if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
  1474. FunDecl->hasBody()) {
  1475. auto getLeafPointeeType = [](const Type *T) {
  1476. while (T->isPointerType() || T->isArrayType()) {
  1477. T = T->getPointeeOrArrayElementType();
  1478. }
  1479. return T;
  1480. };
  1481. for (const ParmVarDecl *P : FunDecl->parameters()) {
  1482. const Type *LeafT =
  1483. getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
  1484. auto *RT = dyn_cast<RecordType>(LeafT);
  1485. if (RT && RT->getDecl() == D) {
  1486. Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
  1487. << D->getDeclKindName();
  1488. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  1489. }
  1490. }
  1491. }
  1492. // Import the context of this declaration.
  1493. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  1494. return Err;
  1495. // Import the name of this declaration.
  1496. if (Error Err = importInto(Name, D->getDeclName()))
  1497. return Err;
  1498. // Import the location of this declaration.
  1499. if (Error Err = importInto(Loc, D->getLocation()))
  1500. return Err;
  1501. ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
  1502. if (ToD)
  1503. if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
  1504. return Err;
  1505. return Error::success();
  1506. }
  1507. Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
  1508. NamedDecl *&ToD, SourceLocation &Loc) {
  1509. // Import the name of this declaration.
  1510. if (Error Err = importInto(Name, D->getDeclName()))
  1511. return Err;
  1512. // Import the location of this declaration.
  1513. if (Error Err = importInto(Loc, D->getLocation()))
  1514. return Err;
  1515. ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
  1516. if (ToD)
  1517. if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
  1518. return Err;
  1519. return Error::success();
  1520. }
  1521. Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
  1522. if (!FromD)
  1523. return Error::success();
  1524. if (!ToD)
  1525. if (Error Err = importInto(ToD, FromD))
  1526. return Err;
  1527. if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
  1528. if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
  1529. if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
  1530. !ToRecord->getDefinition()) {
  1531. if (Error Err = ImportDefinition(FromRecord, ToRecord))
  1532. return Err;
  1533. }
  1534. }
  1535. return Error::success();
  1536. }
  1537. if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
  1538. if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
  1539. if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
  1540. if (Error Err = ImportDefinition(FromEnum, ToEnum))
  1541. return Err;
  1542. }
  1543. }
  1544. return Error::success();
  1545. }
  1546. return Error::success();
  1547. }
  1548. Error
  1549. ASTNodeImporter::ImportDeclarationNameLoc(
  1550. const DeclarationNameInfo &From, DeclarationNameInfo& To) {
  1551. // NOTE: To.Name and To.Loc are already imported.
  1552. // We only have to import To.LocInfo.
  1553. switch (To.getName().getNameKind()) {
  1554. case DeclarationName::Identifier:
  1555. case DeclarationName::ObjCZeroArgSelector:
  1556. case DeclarationName::ObjCOneArgSelector:
  1557. case DeclarationName::ObjCMultiArgSelector:
  1558. case DeclarationName::CXXUsingDirective:
  1559. case DeclarationName::CXXDeductionGuideName:
  1560. return Error::success();
  1561. case DeclarationName::CXXOperatorName: {
  1562. if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
  1563. To.setCXXOperatorNameRange(*ToRangeOrErr);
  1564. else
  1565. return ToRangeOrErr.takeError();
  1566. return Error::success();
  1567. }
  1568. case DeclarationName::CXXLiteralOperatorName: {
  1569. if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
  1570. To.setCXXLiteralOperatorNameLoc(*LocOrErr);
  1571. else
  1572. return LocOrErr.takeError();
  1573. return Error::success();
  1574. }
  1575. case DeclarationName::CXXConstructorName:
  1576. case DeclarationName::CXXDestructorName:
  1577. case DeclarationName::CXXConversionFunctionName: {
  1578. if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
  1579. To.setNamedTypeInfo(*ToTInfoOrErr);
  1580. else
  1581. return ToTInfoOrErr.takeError();
  1582. return Error::success();
  1583. }
  1584. }
  1585. llvm_unreachable("Unknown name kind.");
  1586. }
  1587. Error
  1588. ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
  1589. if (Importer.isMinimalImport() && !ForceImport) {
  1590. auto ToDCOrErr = Importer.ImportContext(FromDC);
  1591. return ToDCOrErr.takeError();
  1592. }
  1593. // We use strict error handling in case of records and enums, but not
  1594. // with e.g. namespaces.
  1595. //
  1596. // FIXME Clients of the ASTImporter should be able to choose an
  1597. // appropriate error handling strategy for their needs. For instance,
  1598. // they may not want to mark an entire namespace as erroneous merely
  1599. // because there is an ODR error with two typedefs. As another example,
  1600. // the client may allow EnumConstantDecls with same names but with
  1601. // different values in two distinct translation units.
  1602. ChildErrorHandlingStrategy HandleChildErrors(FromDC);
  1603. Error ChildErrors = Error::success();
  1604. for (auto *From : FromDC->decls()) {
  1605. ExpectedDecl ImportedOrErr = import(From);
  1606. // If we are in the process of ImportDefinition(...) for a RecordDecl we
  1607. // want to make sure that we are also completing each FieldDecl. There
  1608. // are currently cases where this does not happen and this is correctness
  1609. // fix since operations such as code generation will expect this to be so.
  1610. if (ImportedOrErr) {
  1611. FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
  1612. Decl *ImportedDecl = *ImportedOrErr;
  1613. FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
  1614. if (FieldFrom && FieldTo) {
  1615. RecordDecl *FromRecordDecl = nullptr;
  1616. RecordDecl *ToRecordDecl = nullptr;
  1617. // If we have a field that is an ArrayType we need to check if the array
  1618. // element is a RecordDecl and if so we need to import the definition.
  1619. if (FieldFrom->getType()->isArrayType()) {
  1620. // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
  1621. FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
  1622. ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
  1623. }
  1624. if (!FromRecordDecl || !ToRecordDecl) {
  1625. const RecordType *RecordFrom =
  1626. FieldFrom->getType()->getAs<RecordType>();
  1627. const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
  1628. if (RecordFrom && RecordTo) {
  1629. FromRecordDecl = RecordFrom->getDecl();
  1630. ToRecordDecl = RecordTo->getDecl();
  1631. }
  1632. }
  1633. if (FromRecordDecl && ToRecordDecl) {
  1634. if (FromRecordDecl->isCompleteDefinition() &&
  1635. !ToRecordDecl->isCompleteDefinition()) {
  1636. Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
  1637. HandleChildErrors.handleChildImportResult(ChildErrors,
  1638. std::move(Err));
  1639. }
  1640. }
  1641. }
  1642. } else {
  1643. HandleChildErrors.handleChildImportResult(ChildErrors,
  1644. ImportedOrErr.takeError());
  1645. }
  1646. }
  1647. // We reorder declarations in RecordDecls because they may have another order
  1648. // in the "to" context than they have in the "from" context. This may happen
  1649. // e.g when we import a class like this:
  1650. // struct declToImport {
  1651. // int a = c + b;
  1652. // int b = 1;
  1653. // int c = 2;
  1654. // };
  1655. // During the import of `a` we import first the dependencies in sequence,
  1656. // thus the order would be `c`, `b`, `a`. We will get the normal order by
  1657. // first removing the already imported members and then adding them in the
  1658. // order as they apper in the "from" context.
  1659. //
  1660. // Keeping field order is vital because it determines structure layout.
  1661. //
  1662. // Here and below, we cannot call field_begin() method and its callers on
  1663. // ToDC if it has an external storage. Calling field_begin() will
  1664. // automatically load all the fields by calling
  1665. // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
  1666. // call ASTImporter::Import(). This is because the ExternalASTSource
  1667. // interface in LLDB is implemented by the means of the ASTImporter. However,
  1668. // calling an import at this point would result in an uncontrolled import, we
  1669. // must avoid that.
  1670. const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
  1671. if (!FromRD)
  1672. return ChildErrors;
  1673. auto ToDCOrErr = Importer.ImportContext(FromDC);
  1674. if (!ToDCOrErr) {
  1675. consumeError(std::move(ChildErrors));
  1676. return ToDCOrErr.takeError();
  1677. }
  1678. DeclContext *ToDC = *ToDCOrErr;
  1679. // Remove all declarations, which may be in wrong order in the
  1680. // lexical DeclContext and then add them in the proper order.
  1681. for (auto *D : FromRD->decls()) {
  1682. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
  1683. assert(D && "DC contains a null decl");
  1684. Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
  1685. // Remove only the decls which we successfully imported.
  1686. if (ToD) {
  1687. assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
  1688. // Remove the decl from its wrong place in the linked list.
  1689. ToDC->removeDecl(ToD);
  1690. // Add the decl to the end of the linked list.
  1691. // This time it will be at the proper place because the enclosing for
  1692. // loop iterates in the original (good) order of the decls.
  1693. ToDC->addDeclInternal(ToD);
  1694. }
  1695. }
  1696. }
  1697. return ChildErrors;
  1698. }
  1699. Error ASTNodeImporter::ImportDeclContext(
  1700. Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
  1701. auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
  1702. if (!ToDCOrErr)
  1703. return ToDCOrErr.takeError();
  1704. ToDC = *ToDCOrErr;
  1705. if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
  1706. auto ToLexicalDCOrErr = Importer.ImportContext(
  1707. FromD->getLexicalDeclContext());
  1708. if (!ToLexicalDCOrErr)
  1709. return ToLexicalDCOrErr.takeError();
  1710. ToLexicalDC = *ToLexicalDCOrErr;
  1711. } else
  1712. ToLexicalDC = ToDC;
  1713. return Error::success();
  1714. }
  1715. Error ASTNodeImporter::ImportImplicitMethods(
  1716. const CXXRecordDecl *From, CXXRecordDecl *To) {
  1717. assert(From->isCompleteDefinition() && To->getDefinition() == To &&
  1718. "Import implicit methods to or from non-definition");
  1719. for (CXXMethodDecl *FromM : From->methods())
  1720. if (FromM->isImplicit()) {
  1721. Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
  1722. if (!ToMOrErr)
  1723. return ToMOrErr.takeError();
  1724. }
  1725. return Error::success();
  1726. }
  1727. static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
  1728. ASTImporter &Importer) {
  1729. if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
  1730. if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
  1731. To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
  1732. else
  1733. return ToTypedefOrErr.takeError();
  1734. }
  1735. return Error::success();
  1736. }
  1737. Error ASTNodeImporter::ImportDefinition(
  1738. RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
  1739. auto DefinitionCompleter = [To]() {
  1740. // There are cases in LLDB when we first import a class without its
  1741. // members. The class will have DefinitionData, but no members. Then,
  1742. // importDefinition is called from LLDB, which tries to get the members, so
  1743. // when we get here, the class already has the DefinitionData set, so we
  1744. // must unset the CompleteDefinition here to be able to complete again the
  1745. // definition.
  1746. To->setCompleteDefinition(false);
  1747. To->completeDefinition();
  1748. };
  1749. if (To->getDefinition() || To->isBeingDefined()) {
  1750. if (Kind == IDK_Everything ||
  1751. // In case of lambdas, the class already has a definition ptr set, but
  1752. // the contained decls are not imported yet. Also, isBeingDefined was
  1753. // set in CXXRecordDecl::CreateLambda. We must import the contained
  1754. // decls here and finish the definition.
  1755. (To->isLambda() && shouldForceImportDeclContext(Kind))) {
  1756. if (To->isLambda()) {
  1757. auto *FromCXXRD = cast<CXXRecordDecl>(From);
  1758. SmallVector<LambdaCapture, 8> ToCaptures;
  1759. ToCaptures.reserve(FromCXXRD->capture_size());
  1760. for (const auto &FromCapture : FromCXXRD->captures()) {
  1761. if (auto ToCaptureOrErr = import(FromCapture))
  1762. ToCaptures.push_back(*ToCaptureOrErr);
  1763. else
  1764. return ToCaptureOrErr.takeError();
  1765. }
  1766. cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
  1767. ToCaptures);
  1768. }
  1769. Error Result = ImportDeclContext(From, /*ForceImport=*/true);
  1770. // Finish the definition of the lambda, set isBeingDefined to false.
  1771. if (To->isLambda())
  1772. DefinitionCompleter();
  1773. return Result;
  1774. }
  1775. return Error::success();
  1776. }
  1777. To->startDefinition();
  1778. // Set the definition to complete even if it is really not complete during
  1779. // import. Some AST constructs (expressions) require the record layout
  1780. // to be calculated (see 'clang::computeDependence') at the time they are
  1781. // constructed. Import of such AST node is possible during import of the
  1782. // same record, there is no way to have a completely defined record (all
  1783. // fields imported) at that time without multiple AST import passes.
  1784. if (!Importer.isMinimalImport())
  1785. To->setCompleteDefinition(true);
  1786. // Complete the definition even if error is returned.
  1787. // The RecordDecl may be already part of the AST so it is better to
  1788. // have it in complete state even if something is wrong with it.
  1789. auto DefinitionCompleterScopeExit =
  1790. llvm::make_scope_exit(DefinitionCompleter);
  1791. if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
  1792. return Err;
  1793. // Add base classes.
  1794. auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
  1795. auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
  1796. if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
  1797. struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
  1798. struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
  1799. #define FIELD(Name, Width, Merge) \
  1800. ToData.Name = FromData.Name;
  1801. #include "clang/AST/CXXRecordDeclDefinitionBits.def"
  1802. // Copy over the data stored in RecordDeclBits
  1803. ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
  1804. SmallVector<CXXBaseSpecifier *, 4> Bases;
  1805. for (const auto &Base1 : FromCXX->bases()) {
  1806. ExpectedType TyOrErr = import(Base1.getType());
  1807. if (!TyOrErr)
  1808. return TyOrErr.takeError();
  1809. SourceLocation EllipsisLoc;
  1810. if (Base1.isPackExpansion()) {
  1811. if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
  1812. EllipsisLoc = *LocOrErr;
  1813. else
  1814. return LocOrErr.takeError();
  1815. }
  1816. // Ensure that we have a definition for the base.
  1817. if (Error Err =
  1818. ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
  1819. return Err;
  1820. auto RangeOrErr = import(Base1.getSourceRange());
  1821. if (!RangeOrErr)
  1822. return RangeOrErr.takeError();
  1823. auto TSIOrErr = import(Base1.getTypeSourceInfo());
  1824. if (!TSIOrErr)
  1825. return TSIOrErr.takeError();
  1826. Bases.push_back(
  1827. new (Importer.getToContext()) CXXBaseSpecifier(
  1828. *RangeOrErr,
  1829. Base1.isVirtual(),
  1830. Base1.isBaseOfClass(),
  1831. Base1.getAccessSpecifierAsWritten(),
  1832. *TSIOrErr,
  1833. EllipsisLoc));
  1834. }
  1835. if (!Bases.empty())
  1836. ToCXX->setBases(Bases.data(), Bases.size());
  1837. }
  1838. if (shouldForceImportDeclContext(Kind)) {
  1839. if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
  1840. return Err;
  1841. }
  1842. return Error::success();
  1843. }
  1844. Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
  1845. if (To->getAnyInitializer())
  1846. return Error::success();
  1847. Expr *FromInit = From->getInit();
  1848. if (!FromInit)
  1849. return Error::success();
  1850. ExpectedExpr ToInitOrErr = import(FromInit);
  1851. if (!ToInitOrErr)
  1852. return ToInitOrErr.takeError();
  1853. To->setInit(*ToInitOrErr);
  1854. if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
  1855. EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
  1856. ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
  1857. ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
  1858. // FIXME: Also import the initializer value.
  1859. }
  1860. // FIXME: Other bits to merge?
  1861. return Error::success();
  1862. }
  1863. Error ASTNodeImporter::ImportDefinition(
  1864. EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
  1865. if (To->getDefinition() || To->isBeingDefined()) {
  1866. if (Kind == IDK_Everything)
  1867. return ImportDeclContext(From, /*ForceImport=*/true);
  1868. return Error::success();
  1869. }
  1870. To->startDefinition();
  1871. if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
  1872. return Err;
  1873. ExpectedType ToTypeOrErr =
  1874. import(Importer.getFromContext().getTypeDeclType(From));
  1875. if (!ToTypeOrErr)
  1876. return ToTypeOrErr.takeError();
  1877. ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
  1878. if (!ToPromotionTypeOrErr)
  1879. return ToPromotionTypeOrErr.takeError();
  1880. if (shouldForceImportDeclContext(Kind))
  1881. if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
  1882. return Err;
  1883. // FIXME: we might need to merge the number of positive or negative bits
  1884. // if the enumerator lists don't match.
  1885. To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
  1886. From->getNumPositiveBits(),
  1887. From->getNumNegativeBits());
  1888. return Error::success();
  1889. }
  1890. Error ASTNodeImporter::ImportTemplateArguments(
  1891. ArrayRef<TemplateArgument> FromArgs,
  1892. SmallVectorImpl<TemplateArgument> &ToArgs) {
  1893. for (const auto &Arg : FromArgs) {
  1894. if (auto ToOrErr = import(Arg))
  1895. ToArgs.push_back(*ToOrErr);
  1896. else
  1897. return ToOrErr.takeError();
  1898. }
  1899. return Error::success();
  1900. }
  1901. // FIXME: Do not forget to remove this and use only 'import'.
  1902. Expected<TemplateArgument>
  1903. ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
  1904. return import(From);
  1905. }
  1906. template <typename InContainerTy>
  1907. Error ASTNodeImporter::ImportTemplateArgumentListInfo(
  1908. const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
  1909. for (const auto &FromLoc : Container) {
  1910. if (auto ToLocOrErr = import(FromLoc))
  1911. ToTAInfo.addArgument(*ToLocOrErr);
  1912. else
  1913. return ToLocOrErr.takeError();
  1914. }
  1915. return Error::success();
  1916. }
  1917. static StructuralEquivalenceKind
  1918. getStructuralEquivalenceKind(const ASTImporter &Importer) {
  1919. return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
  1920. : StructuralEquivalenceKind::Default;
  1921. }
  1922. bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
  1923. // Eliminate a potential failure point where we attempt to re-import
  1924. // something we're trying to import while completing ToRecord.
  1925. Decl *ToOrigin = Importer.GetOriginalDecl(To);
  1926. if (ToOrigin) {
  1927. To = ToOrigin;
  1928. }
  1929. StructuralEquivalenceContext Ctx(
  1930. Importer.getFromContext(), Importer.getToContext(),
  1931. Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
  1932. false, Complain);
  1933. return Ctx.IsEquivalent(From, To);
  1934. }
  1935. ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
  1936. Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
  1937. << D->getDeclKindName();
  1938. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  1939. }
  1940. ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
  1941. Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
  1942. << D->getDeclKindName();
  1943. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  1944. }
  1945. ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
  1946. // Import the context of this declaration.
  1947. DeclContext *DC, *LexicalDC;
  1948. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  1949. return std::move(Err);
  1950. // Import the location of this declaration.
  1951. ExpectedSLoc LocOrErr = import(D->getLocation());
  1952. if (!LocOrErr)
  1953. return LocOrErr.takeError();
  1954. EmptyDecl *ToD;
  1955. if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
  1956. return ToD;
  1957. ToD->setLexicalDeclContext(LexicalDC);
  1958. LexicalDC->addDeclInternal(ToD);
  1959. return ToD;
  1960. }
  1961. ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  1962. TranslationUnitDecl *ToD =
  1963. Importer.getToContext().getTranslationUnitDecl();
  1964. Importer.MapImported(D, ToD);
  1965. return ToD;
  1966. }
  1967. ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) {
  1968. DeclContext *DC, *LexicalDC;
  1969. DeclarationName Name;
  1970. SourceLocation Loc;
  1971. NamedDecl *ToND;
  1972. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
  1973. return std::move(Err);
  1974. if (ToND)
  1975. return ToND;
  1976. BindingDecl *ToD;
  1977. if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
  1978. Name.getAsIdentifierInfo()))
  1979. return ToD;
  1980. Error Err = Error::success();
  1981. QualType ToType = importChecked(Err, D->getType());
  1982. Expr *ToBinding = importChecked(Err, D->getBinding());
  1983. ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
  1984. if (Err)
  1985. return std::move(Err);
  1986. ToD->setBinding(ToType, ToBinding);
  1987. ToD->setDecomposedDecl(ToDecomposedDecl);
  1988. addDeclToContexts(D, ToD);
  1989. return ToD;
  1990. }
  1991. ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
  1992. ExpectedSLoc LocOrErr = import(D->getLocation());
  1993. if (!LocOrErr)
  1994. return LocOrErr.takeError();
  1995. auto ColonLocOrErr = import(D->getColonLoc());
  1996. if (!ColonLocOrErr)
  1997. return ColonLocOrErr.takeError();
  1998. // Import the context of this declaration.
  1999. auto DCOrErr = Importer.ImportContext(D->getDeclContext());
  2000. if (!DCOrErr)
  2001. return DCOrErr.takeError();
  2002. DeclContext *DC = *DCOrErr;
  2003. AccessSpecDecl *ToD;
  2004. if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
  2005. DC, *LocOrErr, *ColonLocOrErr))
  2006. return ToD;
  2007. // Lexical DeclContext and Semantic DeclContext
  2008. // is always the same for the accessSpec.
  2009. ToD->setLexicalDeclContext(DC);
  2010. DC->addDeclInternal(ToD);
  2011. return ToD;
  2012. }
  2013. ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
  2014. auto DCOrErr = Importer.ImportContext(D->getDeclContext());
  2015. if (!DCOrErr)
  2016. return DCOrErr.takeError();
  2017. DeclContext *DC = *DCOrErr;
  2018. DeclContext *LexicalDC = DC;
  2019. Error Err = Error::success();
  2020. auto ToLocation = importChecked(Err, D->getLocation());
  2021. auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
  2022. auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
  2023. auto ToMessage = importChecked(Err, D->getMessage());
  2024. if (Err)
  2025. return std::move(Err);
  2026. StaticAssertDecl *ToD;
  2027. if (GetImportedOrCreateDecl(
  2028. ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
  2029. ToRParenLoc, D->isFailed()))
  2030. return ToD;
  2031. ToD->setLexicalDeclContext(LexicalDC);
  2032. LexicalDC->addDeclInternal(ToD);
  2033. return ToD;
  2034. }
  2035. ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
  2036. // Import the major distinguishing characteristics of this namespace.
  2037. DeclContext *DC, *LexicalDC;
  2038. DeclarationName Name;
  2039. SourceLocation Loc;
  2040. NamedDecl *ToD;
  2041. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2042. return std::move(Err);
  2043. if (ToD)
  2044. return ToD;
  2045. NamespaceDecl *MergeWithNamespace = nullptr;
  2046. if (!Name) {
  2047. // This is an anonymous namespace. Adopt an existing anonymous
  2048. // namespace if we can.
  2049. // FIXME: Not testable.
  2050. if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
  2051. MergeWithNamespace = TU->getAnonymousNamespace();
  2052. else
  2053. MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
  2054. } else {
  2055. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2056. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  2057. for (auto *FoundDecl : FoundDecls) {
  2058. if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
  2059. continue;
  2060. if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
  2061. MergeWithNamespace = FoundNS;
  2062. ConflictingDecls.clear();
  2063. break;
  2064. }
  2065. ConflictingDecls.push_back(FoundDecl);
  2066. }
  2067. if (!ConflictingDecls.empty()) {
  2068. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2069. Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
  2070. ConflictingDecls.size());
  2071. if (NameOrErr)
  2072. Name = NameOrErr.get();
  2073. else
  2074. return NameOrErr.takeError();
  2075. }
  2076. }
  2077. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  2078. if (!BeginLocOrErr)
  2079. return BeginLocOrErr.takeError();
  2080. ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
  2081. if (!RBraceLocOrErr)
  2082. return RBraceLocOrErr.takeError();
  2083. // Create the "to" namespace, if needed.
  2084. NamespaceDecl *ToNamespace = MergeWithNamespace;
  2085. if (!ToNamespace) {
  2086. if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC,
  2087. D->isInline(), *BeginLocOrErr, Loc,
  2088. Name.getAsIdentifierInfo(),
  2089. /*PrevDecl=*/nullptr, D->isNested()))
  2090. return ToNamespace;
  2091. ToNamespace->setRBraceLoc(*RBraceLocOrErr);
  2092. ToNamespace->setLexicalDeclContext(LexicalDC);
  2093. LexicalDC->addDeclInternal(ToNamespace);
  2094. // If this is an anonymous namespace, register it as the anonymous
  2095. // namespace within its context.
  2096. if (!Name) {
  2097. if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
  2098. TU->setAnonymousNamespace(ToNamespace);
  2099. else
  2100. cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
  2101. }
  2102. }
  2103. Importer.MapImported(D, ToNamespace);
  2104. if (Error Err = ImportDeclContext(D))
  2105. return std::move(Err);
  2106. return ToNamespace;
  2107. }
  2108. ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  2109. // Import the major distinguishing characteristics of this namespace.
  2110. DeclContext *DC, *LexicalDC;
  2111. DeclarationName Name;
  2112. SourceLocation Loc;
  2113. NamedDecl *LookupD;
  2114. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
  2115. return std::move(Err);
  2116. if (LookupD)
  2117. return LookupD;
  2118. // NOTE: No conflict resolution is done for namespace aliases now.
  2119. Error Err = Error::success();
  2120. auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
  2121. auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
  2122. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  2123. auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
  2124. auto ToNamespace = importChecked(Err, D->getNamespace());
  2125. if (Err)
  2126. return std::move(Err);
  2127. IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
  2128. NamespaceAliasDecl *ToD;
  2129. if (GetImportedOrCreateDecl(
  2130. ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
  2131. ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
  2132. return ToD;
  2133. ToD->setLexicalDeclContext(LexicalDC);
  2134. LexicalDC->addDeclInternal(ToD);
  2135. return ToD;
  2136. }
  2137. ExpectedDecl
  2138. ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
  2139. // Import the major distinguishing characteristics of this typedef.
  2140. DeclarationName Name;
  2141. SourceLocation Loc;
  2142. NamedDecl *ToD;
  2143. // Do not import the DeclContext, we will import it once the TypedefNameDecl
  2144. // is created.
  2145. if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
  2146. return std::move(Err);
  2147. if (ToD)
  2148. return ToD;
  2149. DeclContext *DC = cast_or_null<DeclContext>(
  2150. Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
  2151. DeclContext *LexicalDC =
  2152. cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
  2153. cast<Decl>(D->getLexicalDeclContext())));
  2154. // If this typedef is not in block scope, determine whether we've
  2155. // seen a typedef with the same name (that we can merge with) or any
  2156. // other entity by that name (which name lookup could conflict with).
  2157. // Note: Repeated typedefs are not valid in C99:
  2158. // 'typedef int T; typedef int T;' is invalid
  2159. // We do not care about this now.
  2160. if (DC && !DC->isFunctionOrMethod()) {
  2161. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2162. unsigned IDNS = Decl::IDNS_Ordinary;
  2163. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  2164. for (auto *FoundDecl : FoundDecls) {
  2165. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  2166. continue;
  2167. if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
  2168. if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
  2169. continue;
  2170. QualType FromUT = D->getUnderlyingType();
  2171. QualType FoundUT = FoundTypedef->getUnderlyingType();
  2172. if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
  2173. // If the "From" context has a complete underlying type but we
  2174. // already have a complete underlying type then return with that.
  2175. if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
  2176. return Importer.MapImported(D, FoundTypedef);
  2177. // FIXME Handle redecl chain. When you do that make consistent changes
  2178. // in ASTImporterLookupTable too.
  2179. } else {
  2180. ConflictingDecls.push_back(FoundDecl);
  2181. }
  2182. }
  2183. }
  2184. if (!ConflictingDecls.empty()) {
  2185. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2186. Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
  2187. if (NameOrErr)
  2188. Name = NameOrErr.get();
  2189. else
  2190. return NameOrErr.takeError();
  2191. }
  2192. }
  2193. Error Err = Error::success();
  2194. auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
  2195. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  2196. auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
  2197. if (Err)
  2198. return std::move(Err);
  2199. // Create the new typedef node.
  2200. // FIXME: ToUnderlyingType is not used.
  2201. (void)ToUnderlyingType;
  2202. TypedefNameDecl *ToTypedef;
  2203. if (IsAlias) {
  2204. if (GetImportedOrCreateDecl<TypeAliasDecl>(
  2205. ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
  2206. Name.getAsIdentifierInfo(), ToTypeSourceInfo))
  2207. return ToTypedef;
  2208. } else if (GetImportedOrCreateDecl<TypedefDecl>(
  2209. ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
  2210. Name.getAsIdentifierInfo(), ToTypeSourceInfo))
  2211. return ToTypedef;
  2212. // Import the DeclContext and set it to the Typedef.
  2213. if ((Err = ImportDeclContext(D, DC, LexicalDC)))
  2214. return std::move(Err);
  2215. ToTypedef->setDeclContext(DC);
  2216. ToTypedef->setLexicalDeclContext(LexicalDC);
  2217. // Add to the lookupTable because we could not do that in MapImported.
  2218. Importer.AddToLookupTable(ToTypedef);
  2219. ToTypedef->setAccess(D->getAccess());
  2220. // Templated declarations should not appear in DeclContext.
  2221. TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
  2222. if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
  2223. LexicalDC->addDeclInternal(ToTypedef);
  2224. return ToTypedef;
  2225. }
  2226. ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
  2227. return VisitTypedefNameDecl(D, /*IsAlias=*/false);
  2228. }
  2229. ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
  2230. return VisitTypedefNameDecl(D, /*IsAlias=*/true);
  2231. }
  2232. ExpectedDecl
  2233. ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  2234. // Import the major distinguishing characteristics of this typedef.
  2235. DeclContext *DC, *LexicalDC;
  2236. DeclarationName Name;
  2237. SourceLocation Loc;
  2238. NamedDecl *FoundD;
  2239. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
  2240. return std::move(Err);
  2241. if (FoundD)
  2242. return FoundD;
  2243. // If this typedef is not in block scope, determine whether we've
  2244. // seen a typedef with the same name (that we can merge with) or any
  2245. // other entity by that name (which name lookup could conflict with).
  2246. if (!DC->isFunctionOrMethod()) {
  2247. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2248. unsigned IDNS = Decl::IDNS_Ordinary;
  2249. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  2250. for (auto *FoundDecl : FoundDecls) {
  2251. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  2252. continue;
  2253. if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
  2254. return Importer.MapImported(D, FoundAlias);
  2255. ConflictingDecls.push_back(FoundDecl);
  2256. }
  2257. if (!ConflictingDecls.empty()) {
  2258. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2259. Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
  2260. if (NameOrErr)
  2261. Name = NameOrErr.get();
  2262. else
  2263. return NameOrErr.takeError();
  2264. }
  2265. }
  2266. Error Err = Error::success();
  2267. auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
  2268. auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
  2269. if (Err)
  2270. return std::move(Err);
  2271. TypeAliasTemplateDecl *ToAlias;
  2272. if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
  2273. Name, ToTemplateParameters, ToTemplatedDecl))
  2274. return ToAlias;
  2275. ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
  2276. ToAlias->setAccess(D->getAccess());
  2277. ToAlias->setLexicalDeclContext(LexicalDC);
  2278. LexicalDC->addDeclInternal(ToAlias);
  2279. if (DC != Importer.getToContext().getTranslationUnitDecl())
  2280. updateLookupTableForTemplateParameters(*ToTemplateParameters);
  2281. return ToAlias;
  2282. }
  2283. ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
  2284. // Import the major distinguishing characteristics of this label.
  2285. DeclContext *DC, *LexicalDC;
  2286. DeclarationName Name;
  2287. SourceLocation Loc;
  2288. NamedDecl *ToD;
  2289. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2290. return std::move(Err);
  2291. if (ToD)
  2292. return ToD;
  2293. assert(LexicalDC->isFunctionOrMethod());
  2294. LabelDecl *ToLabel;
  2295. if (D->isGnuLocal()) {
  2296. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  2297. if (!BeginLocOrErr)
  2298. return BeginLocOrErr.takeError();
  2299. if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
  2300. Name.getAsIdentifierInfo(), *BeginLocOrErr))
  2301. return ToLabel;
  2302. } else {
  2303. if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
  2304. Name.getAsIdentifierInfo()))
  2305. return ToLabel;
  2306. }
  2307. Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
  2308. if (!ToStmtOrErr)
  2309. return ToStmtOrErr.takeError();
  2310. ToLabel->setStmt(*ToStmtOrErr);
  2311. ToLabel->setLexicalDeclContext(LexicalDC);
  2312. LexicalDC->addDeclInternal(ToLabel);
  2313. return ToLabel;
  2314. }
  2315. ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
  2316. // Import the major distinguishing characteristics of this enum.
  2317. DeclContext *DC, *LexicalDC;
  2318. DeclarationName Name;
  2319. SourceLocation Loc;
  2320. NamedDecl *ToD;
  2321. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2322. return std::move(Err);
  2323. if (ToD)
  2324. return ToD;
  2325. // Figure out what enum name we're looking for.
  2326. unsigned IDNS = Decl::IDNS_Tag;
  2327. DeclarationName SearchName = Name;
  2328. if (!SearchName && D->getTypedefNameForAnonDecl()) {
  2329. if (Error Err = importInto(
  2330. SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
  2331. return std::move(Err);
  2332. IDNS = Decl::IDNS_Ordinary;
  2333. } else if (Importer.getToContext().getLangOpts().CPlusPlus)
  2334. IDNS |= Decl::IDNS_Ordinary;
  2335. // We may already have an enum of the same name; try to find and match it.
  2336. EnumDecl *PrevDecl = nullptr;
  2337. if (!DC->isFunctionOrMethod() && SearchName) {
  2338. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2339. auto FoundDecls =
  2340. Importer.findDeclsInToCtx(DC, SearchName);
  2341. for (auto *FoundDecl : FoundDecls) {
  2342. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  2343. continue;
  2344. if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
  2345. if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
  2346. FoundDecl = Tag->getDecl();
  2347. }
  2348. if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
  2349. if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
  2350. continue;
  2351. if (IsStructuralMatch(D, FoundEnum)) {
  2352. EnumDecl *FoundDef = FoundEnum->getDefinition();
  2353. if (D->isThisDeclarationADefinition() && FoundDef)
  2354. return Importer.MapImported(D, FoundDef);
  2355. PrevDecl = FoundEnum->getMostRecentDecl();
  2356. break;
  2357. }
  2358. ConflictingDecls.push_back(FoundDecl);
  2359. }
  2360. }
  2361. if (!ConflictingDecls.empty()) {
  2362. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2363. SearchName, DC, IDNS, ConflictingDecls.data(),
  2364. ConflictingDecls.size());
  2365. if (NameOrErr)
  2366. Name = NameOrErr.get();
  2367. else
  2368. return NameOrErr.takeError();
  2369. }
  2370. }
  2371. Error Err = Error::success();
  2372. auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
  2373. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  2374. auto ToIntegerType = importChecked(Err, D->getIntegerType());
  2375. auto ToBraceRange = importChecked(Err, D->getBraceRange());
  2376. if (Err)
  2377. return std::move(Err);
  2378. // Create the enum declaration.
  2379. EnumDecl *D2;
  2380. if (GetImportedOrCreateDecl(
  2381. D2, D, Importer.getToContext(), DC, ToBeginLoc,
  2382. Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
  2383. D->isScopedUsingClassTag(), D->isFixed()))
  2384. return D2;
  2385. D2->setQualifierInfo(ToQualifierLoc);
  2386. D2->setIntegerType(ToIntegerType);
  2387. D2->setBraceRange(ToBraceRange);
  2388. D2->setAccess(D->getAccess());
  2389. D2->setLexicalDeclContext(LexicalDC);
  2390. addDeclToContexts(D, D2);
  2391. if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
  2392. TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
  2393. EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
  2394. if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
  2395. D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
  2396. else
  2397. return ToInstOrErr.takeError();
  2398. if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
  2399. D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
  2400. else
  2401. return POIOrErr.takeError();
  2402. }
  2403. // Import the definition
  2404. if (D->isCompleteDefinition())
  2405. if (Error Err = ImportDefinition(D, D2))
  2406. return std::move(Err);
  2407. return D2;
  2408. }
  2409. ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
  2410. bool IsFriendTemplate = false;
  2411. if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
  2412. IsFriendTemplate =
  2413. DCXX->getDescribedClassTemplate() &&
  2414. DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
  2415. Decl::FOK_None;
  2416. }
  2417. // Import the major distinguishing characteristics of this record.
  2418. DeclContext *DC = nullptr, *LexicalDC = nullptr;
  2419. DeclarationName Name;
  2420. SourceLocation Loc;
  2421. NamedDecl *ToD = nullptr;
  2422. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2423. return std::move(Err);
  2424. if (ToD)
  2425. return ToD;
  2426. // Figure out what structure name we're looking for.
  2427. unsigned IDNS = Decl::IDNS_Tag;
  2428. DeclarationName SearchName = Name;
  2429. if (!SearchName && D->getTypedefNameForAnonDecl()) {
  2430. if (Error Err = importInto(
  2431. SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
  2432. return std::move(Err);
  2433. IDNS = Decl::IDNS_Ordinary;
  2434. } else if (Importer.getToContext().getLangOpts().CPlusPlus)
  2435. IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
  2436. // We may already have a record of the same name; try to find and match it.
  2437. RecordDecl *PrevDecl = nullptr;
  2438. if (!DC->isFunctionOrMethod() && !D->isLambda()) {
  2439. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2440. auto FoundDecls =
  2441. Importer.findDeclsInToCtx(DC, SearchName);
  2442. if (!FoundDecls.empty()) {
  2443. // We're going to have to compare D against potentially conflicting Decls,
  2444. // so complete it.
  2445. if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
  2446. D->getASTContext().getExternalSource()->CompleteType(D);
  2447. }
  2448. for (auto *FoundDecl : FoundDecls) {
  2449. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  2450. continue;
  2451. Decl *Found = FoundDecl;
  2452. if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
  2453. if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
  2454. Found = Tag->getDecl();
  2455. }
  2456. if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
  2457. // Do not emit false positive diagnostic in case of unnamed
  2458. // struct/union and in case of anonymous structs. Would be false
  2459. // because there may be several anonymous/unnamed structs in a class.
  2460. // E.g. these are both valid:
  2461. // struct A { // unnamed structs
  2462. // struct { struct A *next; } entry0;
  2463. // struct { struct A *next; } entry1;
  2464. // };
  2465. // struct X { struct { int a; }; struct { int b; }; }; // anon structs
  2466. if (!SearchName)
  2467. if (!IsStructuralMatch(D, FoundRecord, false))
  2468. continue;
  2469. if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
  2470. continue;
  2471. if (IsStructuralMatch(D, FoundRecord)) {
  2472. RecordDecl *FoundDef = FoundRecord->getDefinition();
  2473. if (D->isThisDeclarationADefinition() && FoundDef) {
  2474. // FIXME: Structural equivalence check should check for same
  2475. // user-defined methods.
  2476. Importer.MapImported(D, FoundDef);
  2477. if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
  2478. auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
  2479. assert(FoundCXX && "Record type mismatch");
  2480. if (!Importer.isMinimalImport())
  2481. // FoundDef may not have every implicit method that D has
  2482. // because implicit methods are created only if they are used.
  2483. if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
  2484. return std::move(Err);
  2485. }
  2486. }
  2487. PrevDecl = FoundRecord->getMostRecentDecl();
  2488. break;
  2489. }
  2490. ConflictingDecls.push_back(FoundDecl);
  2491. } // kind is RecordDecl
  2492. } // for
  2493. if (!ConflictingDecls.empty() && SearchName) {
  2494. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2495. SearchName, DC, IDNS, ConflictingDecls.data(),
  2496. ConflictingDecls.size());
  2497. if (NameOrErr)
  2498. Name = NameOrErr.get();
  2499. else
  2500. return NameOrErr.takeError();
  2501. }
  2502. }
  2503. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  2504. if (!BeginLocOrErr)
  2505. return BeginLocOrErr.takeError();
  2506. // Create the record declaration.
  2507. RecordDecl *D2 = nullptr;
  2508. CXXRecordDecl *D2CXX = nullptr;
  2509. if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
  2510. if (DCXX->isLambda()) {
  2511. auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
  2512. if (!TInfoOrErr)
  2513. return TInfoOrErr.takeError();
  2514. if (GetImportedOrCreateSpecialDecl(
  2515. D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
  2516. DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(),
  2517. DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
  2518. return D2CXX;
  2519. ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
  2520. if (!CDeclOrErr)
  2521. return CDeclOrErr.takeError();
  2522. D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
  2523. DCXX->hasKnownLambdaInternalLinkage());
  2524. D2CXX->setDeviceLambdaManglingNumber(
  2525. DCXX->getDeviceLambdaManglingNumber());
  2526. } else if (DCXX->isInjectedClassName()) {
  2527. // We have to be careful to do a similar dance to the one in
  2528. // Sema::ActOnStartCXXMemberDeclarations
  2529. const bool DelayTypeCreation = true;
  2530. if (GetImportedOrCreateDecl(
  2531. D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
  2532. *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
  2533. cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
  2534. return D2CXX;
  2535. Importer.getToContext().getTypeDeclType(
  2536. D2CXX, dyn_cast<CXXRecordDecl>(DC));
  2537. } else {
  2538. if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
  2539. D->getTagKind(), DC, *BeginLocOrErr, Loc,
  2540. Name.getAsIdentifierInfo(),
  2541. cast_or_null<CXXRecordDecl>(PrevDecl)))
  2542. return D2CXX;
  2543. }
  2544. D2 = D2CXX;
  2545. D2->setAccess(D->getAccess());
  2546. D2->setLexicalDeclContext(LexicalDC);
  2547. addDeclToContexts(D, D2);
  2548. if (ClassTemplateDecl *FromDescribed =
  2549. DCXX->getDescribedClassTemplate()) {
  2550. ClassTemplateDecl *ToDescribed;
  2551. if (Error Err = importInto(ToDescribed, FromDescribed))
  2552. return std::move(Err);
  2553. D2CXX->setDescribedClassTemplate(ToDescribed);
  2554. if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
  2555. // In a record describing a template the type should be an
  2556. // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
  2557. // previously set type to the correct value here (ToDescribed is not
  2558. // available at record create).
  2559. // FIXME: The previous type is cleared but not removed from
  2560. // ASTContext's internal storage.
  2561. CXXRecordDecl *Injected = nullptr;
  2562. for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
  2563. auto *Record = dyn_cast<CXXRecordDecl>(Found);
  2564. if (Record && Record->isInjectedClassName()) {
  2565. Injected = Record;
  2566. break;
  2567. }
  2568. }
  2569. // Create an injected type for the whole redecl chain.
  2570. SmallVector<Decl *, 2> Redecls =
  2571. getCanonicalForwardRedeclChain(D2CXX);
  2572. for (auto *R : Redecls) {
  2573. auto *RI = cast<CXXRecordDecl>(R);
  2574. RI->setTypeForDecl(nullptr);
  2575. // Below we create a new injected type and assign that to the
  2576. // canonical decl, subsequent declarations in the chain will reuse
  2577. // that type.
  2578. Importer.getToContext().getInjectedClassNameType(
  2579. RI, ToDescribed->getInjectedClassNameSpecialization());
  2580. }
  2581. // Set the new type for the previous injected decl too.
  2582. if (Injected) {
  2583. Injected->setTypeForDecl(nullptr);
  2584. Importer.getToContext().getTypeDeclType(Injected, D2CXX);
  2585. }
  2586. }
  2587. } else if (MemberSpecializationInfo *MemberInfo =
  2588. DCXX->getMemberSpecializationInfo()) {
  2589. TemplateSpecializationKind SK =
  2590. MemberInfo->getTemplateSpecializationKind();
  2591. CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
  2592. if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
  2593. D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
  2594. else
  2595. return ToInstOrErr.takeError();
  2596. if (ExpectedSLoc POIOrErr =
  2597. import(MemberInfo->getPointOfInstantiation()))
  2598. D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
  2599. *POIOrErr);
  2600. else
  2601. return POIOrErr.takeError();
  2602. }
  2603. } else {
  2604. if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
  2605. D->getTagKind(), DC, *BeginLocOrErr, Loc,
  2606. Name.getAsIdentifierInfo(), PrevDecl))
  2607. return D2;
  2608. D2->setLexicalDeclContext(LexicalDC);
  2609. addDeclToContexts(D, D2);
  2610. }
  2611. if (auto BraceRangeOrErr = import(D->getBraceRange()))
  2612. D2->setBraceRange(*BraceRangeOrErr);
  2613. else
  2614. return BraceRangeOrErr.takeError();
  2615. if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
  2616. D2->setQualifierInfo(*QualifierLocOrErr);
  2617. else
  2618. return QualifierLocOrErr.takeError();
  2619. if (D->isAnonymousStructOrUnion())
  2620. D2->setAnonymousStructOrUnion(true);
  2621. if (D->isCompleteDefinition())
  2622. if (Error Err = ImportDefinition(D, D2, IDK_Default))
  2623. return std::move(Err);
  2624. return D2;
  2625. }
  2626. ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
  2627. // Import the major distinguishing characteristics of this enumerator.
  2628. DeclContext *DC, *LexicalDC;
  2629. DeclarationName Name;
  2630. SourceLocation Loc;
  2631. NamedDecl *ToD;
  2632. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2633. return std::move(Err);
  2634. if (ToD)
  2635. return ToD;
  2636. // Determine whether there are any other declarations with the same name and
  2637. // in the same context.
  2638. if (!LexicalDC->isFunctionOrMethod()) {
  2639. SmallVector<NamedDecl *, 4> ConflictingDecls;
  2640. unsigned IDNS = Decl::IDNS_Ordinary;
  2641. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  2642. for (auto *FoundDecl : FoundDecls) {
  2643. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  2644. continue;
  2645. if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
  2646. if (IsStructuralMatch(D, FoundEnumConstant))
  2647. return Importer.MapImported(D, FoundEnumConstant);
  2648. ConflictingDecls.push_back(FoundDecl);
  2649. }
  2650. }
  2651. if (!ConflictingDecls.empty()) {
  2652. ExpectedName NameOrErr = Importer.HandleNameConflict(
  2653. Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
  2654. if (NameOrErr)
  2655. Name = NameOrErr.get();
  2656. else
  2657. return NameOrErr.takeError();
  2658. }
  2659. }
  2660. ExpectedType TypeOrErr = import(D->getType());
  2661. if (!TypeOrErr)
  2662. return TypeOrErr.takeError();
  2663. ExpectedExpr InitOrErr = import(D->getInitExpr());
  2664. if (!InitOrErr)
  2665. return InitOrErr.takeError();
  2666. EnumConstantDecl *ToEnumerator;
  2667. if (GetImportedOrCreateDecl(
  2668. ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
  2669. Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
  2670. return ToEnumerator;
  2671. ToEnumerator->setAccess(D->getAccess());
  2672. ToEnumerator->setLexicalDeclContext(LexicalDC);
  2673. LexicalDC->addDeclInternal(ToEnumerator);
  2674. return ToEnumerator;
  2675. }
  2676. Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
  2677. DeclaratorDecl *ToD) {
  2678. unsigned int Num = FromD->getNumTemplateParameterLists();
  2679. if (Num == 0)
  2680. return Error::success();
  2681. SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
  2682. for (unsigned int I = 0; I < Num; ++I)
  2683. if (Expected<TemplateParameterList *> ToTPListOrErr =
  2684. import(FromD->getTemplateParameterList(I)))
  2685. ToTPLists[I] = *ToTPListOrErr;
  2686. else
  2687. return ToTPListOrErr.takeError();
  2688. ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
  2689. return Error::success();
  2690. }
  2691. Error ASTNodeImporter::ImportTemplateInformation(
  2692. FunctionDecl *FromFD, FunctionDecl *ToFD) {
  2693. switch (FromFD->getTemplatedKind()) {
  2694. case FunctionDecl::TK_NonTemplate:
  2695. case FunctionDecl::TK_FunctionTemplate:
  2696. return Error::success();
  2697. case FunctionDecl::TK_DependentNonTemplate:
  2698. if (Expected<FunctionDecl *> InstFDOrErr =
  2699. import(FromFD->getInstantiatedFromDecl()))
  2700. ToFD->setInstantiatedFromDecl(*InstFDOrErr);
  2701. return Error::success();
  2702. case FunctionDecl::TK_MemberSpecialization: {
  2703. TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
  2704. if (Expected<FunctionDecl *> InstFDOrErr =
  2705. import(FromFD->getInstantiatedFromMemberFunction()))
  2706. ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
  2707. else
  2708. return InstFDOrErr.takeError();
  2709. if (ExpectedSLoc POIOrErr = import(
  2710. FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
  2711. ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
  2712. else
  2713. return POIOrErr.takeError();
  2714. return Error::success();
  2715. }
  2716. case FunctionDecl::TK_FunctionTemplateSpecialization: {
  2717. auto FunctionAndArgsOrErr =
  2718. ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
  2719. if (!FunctionAndArgsOrErr)
  2720. return FunctionAndArgsOrErr.takeError();
  2721. TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
  2722. Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
  2723. auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
  2724. TemplateArgumentListInfo ToTAInfo;
  2725. const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
  2726. if (FromTAArgsAsWritten)
  2727. if (Error Err = ImportTemplateArgumentListInfo(
  2728. *FromTAArgsAsWritten, ToTAInfo))
  2729. return Err;
  2730. ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
  2731. if (!POIOrErr)
  2732. return POIOrErr.takeError();
  2733. if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
  2734. return Err;
  2735. TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
  2736. ToFD->setFunctionTemplateSpecialization(
  2737. std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
  2738. TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
  2739. return Error::success();
  2740. }
  2741. case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
  2742. auto *FromInfo = FromFD->getDependentSpecializationInfo();
  2743. UnresolvedSet<8> TemplDecls;
  2744. unsigned NumTemplates = FromInfo->getNumTemplates();
  2745. for (unsigned I = 0; I < NumTemplates; I++) {
  2746. if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
  2747. import(FromInfo->getTemplate(I)))
  2748. TemplDecls.addDecl(*ToFTDOrErr);
  2749. else
  2750. return ToFTDOrErr.takeError();
  2751. }
  2752. // Import TemplateArgumentListInfo.
  2753. TemplateArgumentListInfo ToTAInfo;
  2754. if (Error Err = ImportTemplateArgumentListInfo(
  2755. FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
  2756. llvm::ArrayRef(FromInfo->getTemplateArgs(),
  2757. FromInfo->getNumTemplateArgs()),
  2758. ToTAInfo))
  2759. return Err;
  2760. ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
  2761. TemplDecls, ToTAInfo);
  2762. return Error::success();
  2763. }
  2764. }
  2765. llvm_unreachable("All cases should be covered!");
  2766. }
  2767. Expected<FunctionDecl *>
  2768. ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
  2769. auto FunctionAndArgsOrErr =
  2770. ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
  2771. if (!FunctionAndArgsOrErr)
  2772. return FunctionAndArgsOrErr.takeError();
  2773. FunctionTemplateDecl *Template;
  2774. TemplateArgsTy ToTemplArgs;
  2775. std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
  2776. void *InsertPos = nullptr;
  2777. auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
  2778. return FoundSpec;
  2779. }
  2780. Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
  2781. FunctionDecl *ToFD) {
  2782. if (Stmt *FromBody = FromFD->getBody()) {
  2783. if (ExpectedStmt ToBodyOrErr = import(FromBody))
  2784. ToFD->setBody(*ToBodyOrErr);
  2785. else
  2786. return ToBodyOrErr.takeError();
  2787. }
  2788. return Error::success();
  2789. }
  2790. // Returns true if the given D has a DeclContext up to the TranslationUnitDecl
  2791. // which is equal to the given DC, or D is equal to DC.
  2792. static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
  2793. const DeclContext *DCi = dyn_cast<DeclContext>(D);
  2794. if (!DCi)
  2795. DCi = D->getDeclContext();
  2796. assert(DCi && "Declaration should have a context");
  2797. while (DCi != D->getTranslationUnitDecl()) {
  2798. if (DCi == DC)
  2799. return true;
  2800. DCi = DCi->getParent();
  2801. }
  2802. return false;
  2803. }
  2804. // Check if there is a declaration that has 'DC' as parent context and is
  2805. // referenced from statement 'S' or one of its children. The search is done in
  2806. // BFS order through children of 'S'.
  2807. static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
  2808. SmallVector<const Stmt *> ToProcess;
  2809. ToProcess.push_back(S);
  2810. while (!ToProcess.empty()) {
  2811. const Stmt *CurrentS = ToProcess.pop_back_val();
  2812. ToProcess.append(CurrentS->child_begin(), CurrentS->child_end());
  2813. if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CurrentS))
  2814. if (const Decl *D = DeclRef->getDecl())
  2815. if (isAncestorDeclContextOf(DC, D))
  2816. return true;
  2817. }
  2818. return false;
  2819. }
  2820. namespace {
  2821. /// Check if a type has any reference to a declaration that is inside the body
  2822. /// of a function.
  2823. /// The \c CheckType(QualType) function should be used to determine
  2824. /// this property.
  2825. ///
  2826. /// The type visitor visits one type object only (not recursive).
  2827. /// To find all referenced declarations we must discover all type objects until
  2828. /// the canonical type is reached (walk over typedef and similar objects). This
  2829. /// is done by loop over all "sugar" type objects. For every such type we must
  2830. /// check all declarations that are referenced from it. For this check the
  2831. /// visitor is used. In the visit functions all referenced declarations except
  2832. /// the one that follows in the sugar chain (if any) must be checked. For this
  2833. /// check the same visitor is re-used (it has no state-dependent data).
  2834. ///
  2835. /// The visit functions have 3 possible return values:
  2836. /// - True, found a declaration inside \c ParentDC.
  2837. /// - False, found declarations only outside \c ParentDC and it is not possible
  2838. /// to find more declarations (the "sugar" chain does not continue).
  2839. /// - Empty optional value, found no declarations or only outside \c ParentDC,
  2840. /// but it is possible to find more declarations in the type "sugar" chain.
  2841. /// The loop over the "sugar" types can be implemented by using type visit
  2842. /// functions only (call \c CheckType with the desugared type). With the current
  2843. /// solution no visit function is needed if the type has only a desugared type
  2844. /// as data.
  2845. class IsTypeDeclaredInsideVisitor
  2846. : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
  2847. public:
  2848. IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
  2849. : ParentDC(ParentDC) {}
  2850. bool CheckType(QualType T) {
  2851. // Check the chain of "sugar" types.
  2852. // The "sugar" types are typedef or similar types that have the same
  2853. // canonical type.
  2854. if (std::optional<bool> Res = Visit(T.getTypePtr()))
  2855. return *Res;
  2856. QualType DsT =
  2857. T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
  2858. while (DsT != T) {
  2859. if (std::optional<bool> Res = Visit(DsT.getTypePtr()))
  2860. return *Res;
  2861. T = DsT;
  2862. DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
  2863. }
  2864. return false;
  2865. }
  2866. std::optional<bool> VisitTagType(const TagType *T) {
  2867. if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl()))
  2868. for (const auto &Arg : Spec->getTemplateArgs().asArray())
  2869. if (checkTemplateArgument(Arg))
  2870. return true;
  2871. return isAncestorDeclContextOf(ParentDC, T->getDecl());
  2872. }
  2873. std::optional<bool> VisitPointerType(const PointerType *T) {
  2874. return CheckType(T->getPointeeType());
  2875. }
  2876. std::optional<bool> VisitReferenceType(const ReferenceType *T) {
  2877. return CheckType(T->getPointeeTypeAsWritten());
  2878. }
  2879. std::optional<bool> VisitTypedefType(const TypedefType *T) {
  2880. const TypedefNameDecl *TD = T->getDecl();
  2881. assert(TD);
  2882. return isAncestorDeclContextOf(ParentDC, TD);
  2883. }
  2884. std::optional<bool> VisitUsingType(const UsingType *T) {
  2885. if (T->getFoundDecl() &&
  2886. isAncestorDeclContextOf(ParentDC, T->getFoundDecl()))
  2887. return true;
  2888. return {};
  2889. }
  2890. std::optional<bool>
  2891. VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
  2892. for (const auto &Arg : T->template_arguments())
  2893. if (checkTemplateArgument(Arg))
  2894. return true;
  2895. // This type is a "sugar" to a record type, it can have a desugared type.
  2896. return {};
  2897. }
  2898. std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
  2899. if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr()))
  2900. return true;
  2901. return CheckType(T->getElementType());
  2902. }
  2903. std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
  2904. llvm_unreachable(
  2905. "Variable array should not occur in deduced return type of a function");
  2906. }
  2907. std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
  2908. llvm_unreachable("Incomplete array should not occur in deduced return type "
  2909. "of a function");
  2910. }
  2911. std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
  2912. llvm_unreachable("Dependent array should not occur in deduced return type "
  2913. "of a function");
  2914. }
  2915. private:
  2916. const DeclContext *const ParentDC;
  2917. bool checkTemplateArgument(const TemplateArgument &Arg) {
  2918. switch (Arg.getKind()) {
  2919. case TemplateArgument::Null:
  2920. return false;
  2921. case TemplateArgument::Integral:
  2922. return CheckType(Arg.getIntegralType());
  2923. case TemplateArgument::Type:
  2924. return CheckType(Arg.getAsType());
  2925. case TemplateArgument::Expression:
  2926. return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr());
  2927. case TemplateArgument::Declaration:
  2928. // FIXME: The declaration in this case is not allowed to be in a function?
  2929. return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl());
  2930. case TemplateArgument::NullPtr:
  2931. // FIXME: The type is not allowed to be in the function?
  2932. return CheckType(Arg.getNullPtrType());
  2933. case TemplateArgument::Pack:
  2934. for (const auto &PackArg : Arg.getPackAsArray())
  2935. if (checkTemplateArgument(PackArg))
  2936. return true;
  2937. return false;
  2938. case TemplateArgument::Template:
  2939. // Templates can not be defined locally in functions.
  2940. // A template passed as argument can be not in ParentDC.
  2941. return false;
  2942. case TemplateArgument::TemplateExpansion:
  2943. // Templates can not be defined locally in functions.
  2944. // A template passed as argument can be not in ParentDC.
  2945. return false;
  2946. }
  2947. llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
  2948. };
  2949. };
  2950. } // namespace
  2951. bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
  2952. QualType FromTy = D->getType();
  2953. const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
  2954. assert(FromFPT && "Must be called on FunctionProtoType");
  2955. QualType RetT = FromFPT->getReturnType();
  2956. if (isa<AutoType>(RetT.getTypePtr())) {
  2957. FunctionDecl *Def = D->getDefinition();
  2958. IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
  2959. return Visitor.CheckType(RetT);
  2960. }
  2961. return false;
  2962. }
  2963. ExplicitSpecifier
  2964. ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
  2965. Expr *ExplicitExpr = ESpec.getExpr();
  2966. if (ExplicitExpr)
  2967. ExplicitExpr = importChecked(Err, ESpec.getExpr());
  2968. return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
  2969. }
  2970. ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
  2971. SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
  2972. auto RedeclIt = Redecls.begin();
  2973. // Import the first part of the decl chain. I.e. import all previous
  2974. // declarations starting from the canonical decl.
  2975. for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
  2976. ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
  2977. if (!ToRedeclOrErr)
  2978. return ToRedeclOrErr.takeError();
  2979. }
  2980. assert(*RedeclIt == D);
  2981. // Import the major distinguishing characteristics of this function.
  2982. DeclContext *DC, *LexicalDC;
  2983. DeclarationName Name;
  2984. SourceLocation Loc;
  2985. NamedDecl *ToD;
  2986. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  2987. return std::move(Err);
  2988. if (ToD)
  2989. return ToD;
  2990. FunctionDecl *FoundByLookup = nullptr;
  2991. FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
  2992. // If this is a function template specialization, then try to find the same
  2993. // existing specialization in the "to" context. The lookup below will not
  2994. // find any specialization, but would find the primary template; thus, we
  2995. // have to skip normal lookup in case of specializations.
  2996. // FIXME handle member function templates (TK_MemberSpecialization) similarly?
  2997. if (D->getTemplatedKind() ==
  2998. FunctionDecl::TK_FunctionTemplateSpecialization) {
  2999. auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
  3000. if (!FoundFunctionOrErr)
  3001. return FoundFunctionOrErr.takeError();
  3002. if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
  3003. if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
  3004. return Def;
  3005. FoundByLookup = FoundFunction;
  3006. }
  3007. }
  3008. // Try to find a function in our own ("to") context with the same name, same
  3009. // type, and in the same context as the function we're importing.
  3010. else if (!LexicalDC->isFunctionOrMethod()) {
  3011. SmallVector<NamedDecl *, 4> ConflictingDecls;
  3012. unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
  3013. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3014. for (auto *FoundDecl : FoundDecls) {
  3015. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  3016. continue;
  3017. if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
  3018. if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
  3019. continue;
  3020. if (IsStructuralMatch(D, FoundFunction)) {
  3021. if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
  3022. return Def;
  3023. FoundByLookup = FoundFunction;
  3024. break;
  3025. }
  3026. // FIXME: Check for overloading more carefully, e.g., by boosting
  3027. // Sema::IsOverload out to the AST library.
  3028. // Function overloading is okay in C++.
  3029. if (Importer.getToContext().getLangOpts().CPlusPlus)
  3030. continue;
  3031. // Complain about inconsistent function types.
  3032. Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
  3033. << Name << D->getType() << FoundFunction->getType();
  3034. Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
  3035. << FoundFunction->getType();
  3036. ConflictingDecls.push_back(FoundDecl);
  3037. }
  3038. }
  3039. if (!ConflictingDecls.empty()) {
  3040. ExpectedName NameOrErr = Importer.HandleNameConflict(
  3041. Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
  3042. if (NameOrErr)
  3043. Name = NameOrErr.get();
  3044. else
  3045. return NameOrErr.takeError();
  3046. }
  3047. }
  3048. // We do not allow more than one in-class declaration of a function. This is
  3049. // because AST clients like VTableBuilder asserts on this. VTableBuilder
  3050. // assumes there is only one in-class declaration. Building a redecl
  3051. // chain would result in more than one in-class declaration for
  3052. // overrides (even if they are part of the same redecl chain inside the
  3053. // derived class.)
  3054. if (FoundByLookup) {
  3055. if (isa<CXXMethodDecl>(FoundByLookup)) {
  3056. if (D->getLexicalDeclContext() == D->getDeclContext()) {
  3057. if (!D->doesThisDeclarationHaveABody()) {
  3058. if (FunctionTemplateDecl *DescribedD =
  3059. D->getDescribedFunctionTemplate()) {
  3060. // Handle a "templated" function together with its described
  3061. // template. This avoids need for a similar check at import of the
  3062. // described template.
  3063. assert(FoundByLookup->getDescribedFunctionTemplate() &&
  3064. "Templated function mapped to non-templated?");
  3065. Importer.MapImported(DescribedD,
  3066. FoundByLookup->getDescribedFunctionTemplate());
  3067. }
  3068. return Importer.MapImported(D, FoundByLookup);
  3069. } else {
  3070. // Let's continue and build up the redecl chain in this case.
  3071. // FIXME Merge the functions into one decl.
  3072. }
  3073. }
  3074. }
  3075. }
  3076. DeclarationNameInfo NameInfo(Name, Loc);
  3077. // Import additional name location/type info.
  3078. if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
  3079. return std::move(Err);
  3080. QualType FromTy = D->getType();
  3081. TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
  3082. // Set to true if we do not import the type of the function as is. There are
  3083. // cases when the original type would result in an infinite recursion during
  3084. // the import. To avoid an infinite recursion when importing, we create the
  3085. // FunctionDecl with a simplified function type and update it only after the
  3086. // relevant AST nodes are already imported.
  3087. // The type is related to TypeSourceInfo (it references the type), so we must
  3088. // do the same with TypeSourceInfo.
  3089. bool UsedDifferentProtoType = false;
  3090. if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
  3091. QualType FromReturnTy = FromFPT->getReturnType();
  3092. // Functions with auto return type may define a struct inside their body
  3093. // and the return type could refer to that struct.
  3094. // E.g.: auto foo() { struct X{}; return X(); }
  3095. // To avoid an infinite recursion when importing, create the FunctionDecl
  3096. // with a simplified return type.
  3097. if (hasAutoReturnTypeDeclaredInside(D)) {
  3098. FromReturnTy = Importer.getFromContext().VoidTy;
  3099. UsedDifferentProtoType = true;
  3100. }
  3101. FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
  3102. // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
  3103. // FunctionDecl that we are importing the FunctionProtoType for.
  3104. // To avoid an infinite recursion when importing, create the FunctionDecl
  3105. // with a simplified function type.
  3106. if (FromEPI.ExceptionSpec.SourceDecl ||
  3107. FromEPI.ExceptionSpec.SourceTemplate ||
  3108. FromEPI.ExceptionSpec.NoexceptExpr) {
  3109. FunctionProtoType::ExtProtoInfo DefaultEPI;
  3110. FromEPI = DefaultEPI;
  3111. UsedDifferentProtoType = true;
  3112. }
  3113. FromTy = Importer.getFromContext().getFunctionType(
  3114. FromReturnTy, FromFPT->getParamTypes(), FromEPI);
  3115. FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
  3116. FromTy, D->getBeginLoc());
  3117. }
  3118. Error Err = Error::success();
  3119. auto T = importChecked(Err, FromTy);
  3120. auto TInfo = importChecked(Err, FromTSI);
  3121. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  3122. auto ToEndLoc = importChecked(Err, D->getEndLoc());
  3123. auto ToDefaultLoc = importChecked(Err, D->getDefaultLoc());
  3124. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  3125. auto TrailingRequiresClause =
  3126. importChecked(Err, D->getTrailingRequiresClause());
  3127. if (Err)
  3128. return std::move(Err);
  3129. // Import the function parameters.
  3130. SmallVector<ParmVarDecl *, 8> Parameters;
  3131. for (auto *P : D->parameters()) {
  3132. if (Expected<ParmVarDecl *> ToPOrErr = import(P))
  3133. Parameters.push_back(*ToPOrErr);
  3134. else
  3135. return ToPOrErr.takeError();
  3136. }
  3137. // Create the imported function.
  3138. FunctionDecl *ToFunction = nullptr;
  3139. if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
  3140. ExplicitSpecifier ESpec =
  3141. importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
  3142. if (Err)
  3143. return std::move(Err);
  3144. auto ToInheritedConstructor = InheritedConstructor();
  3145. if (FromConstructor->isInheritingConstructor()) {
  3146. Expected<InheritedConstructor> ImportedInheritedCtor =
  3147. import(FromConstructor->getInheritedConstructor());
  3148. if (!ImportedInheritedCtor)
  3149. return ImportedInheritedCtor.takeError();
  3150. ToInheritedConstructor = *ImportedInheritedCtor;
  3151. }
  3152. if (GetImportedOrCreateDecl<CXXConstructorDecl>(
  3153. ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
  3154. ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
  3155. D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
  3156. ToInheritedConstructor, TrailingRequiresClause))
  3157. return ToFunction;
  3158. } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
  3159. Error Err = Error::success();
  3160. auto ToOperatorDelete = importChecked(
  3161. Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
  3162. auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
  3163. if (Err)
  3164. return std::move(Err);
  3165. if (GetImportedOrCreateDecl<CXXDestructorDecl>(
  3166. ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
  3167. ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
  3168. D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
  3169. TrailingRequiresClause))
  3170. return ToFunction;
  3171. CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
  3172. ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
  3173. } else if (CXXConversionDecl *FromConversion =
  3174. dyn_cast<CXXConversionDecl>(D)) {
  3175. ExplicitSpecifier ESpec =
  3176. importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
  3177. if (Err)
  3178. return std::move(Err);
  3179. if (GetImportedOrCreateDecl<CXXConversionDecl>(
  3180. ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
  3181. ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
  3182. D->isInlineSpecified(), ESpec, D->getConstexprKind(),
  3183. SourceLocation(), TrailingRequiresClause))
  3184. return ToFunction;
  3185. } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  3186. if (GetImportedOrCreateDecl<CXXMethodDecl>(
  3187. ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
  3188. ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
  3189. Method->UsesFPIntrin(), Method->isInlineSpecified(),
  3190. D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
  3191. return ToFunction;
  3192. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  3193. ExplicitSpecifier ESpec =
  3194. importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
  3195. CXXConstructorDecl *Ctor =
  3196. importChecked(Err, Guide->getCorrespondingConstructor());
  3197. if (Err)
  3198. return std::move(Err);
  3199. if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
  3200. ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
  3201. NameInfo, T, TInfo, ToEndLoc, Ctor))
  3202. return ToFunction;
  3203. cast<CXXDeductionGuideDecl>(ToFunction)
  3204. ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
  3205. } else {
  3206. if (GetImportedOrCreateDecl(
  3207. ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
  3208. NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
  3209. D->isInlineSpecified(), D->hasWrittenPrototype(),
  3210. D->getConstexprKind(), TrailingRequiresClause))
  3211. return ToFunction;
  3212. }
  3213. // Connect the redecl chain.
  3214. if (FoundByLookup) {
  3215. auto *Recent = const_cast<FunctionDecl *>(
  3216. FoundByLookup->getMostRecentDecl());
  3217. ToFunction->setPreviousDecl(Recent);
  3218. // FIXME Probably we should merge exception specifications. E.g. In the
  3219. // "To" context the existing function may have exception specification with
  3220. // noexcept-unevaluated, while the newly imported function may have an
  3221. // evaluated noexcept. A call to adjustExceptionSpec() on the imported
  3222. // decl and its redeclarations may be required.
  3223. }
  3224. ToFunction->setQualifierInfo(ToQualifierLoc);
  3225. ToFunction->setAccess(D->getAccess());
  3226. ToFunction->setLexicalDeclContext(LexicalDC);
  3227. ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
  3228. ToFunction->setTrivial(D->isTrivial());
  3229. ToFunction->setPure(D->isPure());
  3230. ToFunction->setDefaulted(D->isDefaulted());
  3231. ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
  3232. ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
  3233. ToFunction->setFriendConstraintRefersToEnclosingTemplate(
  3234. D->FriendConstraintRefersToEnclosingTemplate());
  3235. ToFunction->setRangeEnd(ToEndLoc);
  3236. ToFunction->setDefaultLoc(ToDefaultLoc);
  3237. // Set the parameters.
  3238. for (auto *Param : Parameters) {
  3239. Param->setOwningFunction(ToFunction);
  3240. ToFunction->addDeclInternal(Param);
  3241. if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
  3242. LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
  3243. }
  3244. ToFunction->setParams(Parameters);
  3245. // We need to complete creation of FunctionProtoTypeLoc manually with setting
  3246. // params it refers to.
  3247. if (TInfo) {
  3248. if (auto ProtoLoc =
  3249. TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
  3250. for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
  3251. ProtoLoc.setParam(I, Parameters[I]);
  3252. }
  3253. }
  3254. // Import the describing template function, if any.
  3255. if (FromFT) {
  3256. auto ToFTOrErr = import(FromFT);
  3257. if (!ToFTOrErr)
  3258. return ToFTOrErr.takeError();
  3259. }
  3260. // Import Ctor initializers.
  3261. if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
  3262. if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
  3263. SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
  3264. // Import first, then allocate memory and copy if there was no error.
  3265. if (Error Err = ImportContainerChecked(
  3266. FromConstructor->inits(), CtorInitializers))
  3267. return std::move(Err);
  3268. auto **Memory =
  3269. new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
  3270. std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
  3271. auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
  3272. ToCtor->setCtorInitializers(Memory);
  3273. ToCtor->setNumCtorInitializers(NumInitializers);
  3274. }
  3275. }
  3276. // If it is a template, import all related things.
  3277. if (Error Err = ImportTemplateInformation(D, ToFunction))
  3278. return std::move(Err);
  3279. if (D->doesThisDeclarationHaveABody()) {
  3280. Error Err = ImportFunctionDeclBody(D, ToFunction);
  3281. if (Err)
  3282. return std::move(Err);
  3283. }
  3284. // Import and set the original type in case we used another type.
  3285. if (UsedDifferentProtoType) {
  3286. if (ExpectedType TyOrErr = import(D->getType()))
  3287. ToFunction->setType(*TyOrErr);
  3288. else
  3289. return TyOrErr.takeError();
  3290. if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
  3291. ToFunction->setTypeSourceInfo(*TSIOrErr);
  3292. else
  3293. return TSIOrErr.takeError();
  3294. }
  3295. // FIXME: Other bits to merge?
  3296. addDeclToContexts(D, ToFunction);
  3297. if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
  3298. if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
  3299. FromCXXMethod))
  3300. return std::move(Err);
  3301. // Import the rest of the chain. I.e. import all subsequent declarations.
  3302. for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
  3303. ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
  3304. if (!ToRedeclOrErr)
  3305. return ToRedeclOrErr.takeError();
  3306. }
  3307. return ToFunction;
  3308. }
  3309. ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
  3310. return VisitFunctionDecl(D);
  3311. }
  3312. ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  3313. return VisitCXXMethodDecl(D);
  3314. }
  3315. ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  3316. return VisitCXXMethodDecl(D);
  3317. }
  3318. ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
  3319. return VisitCXXMethodDecl(D);
  3320. }
  3321. ExpectedDecl
  3322. ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  3323. return VisitFunctionDecl(D);
  3324. }
  3325. ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
  3326. // Import the major distinguishing characteristics of a variable.
  3327. DeclContext *DC, *LexicalDC;
  3328. DeclarationName Name;
  3329. SourceLocation Loc;
  3330. NamedDecl *ToD;
  3331. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3332. return std::move(Err);
  3333. if (ToD)
  3334. return ToD;
  3335. // Determine whether we've already imported this field.
  3336. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3337. for (auto *FoundDecl : FoundDecls) {
  3338. if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
  3339. // For anonymous fields, match up by index.
  3340. if (!Name &&
  3341. ASTImporter::getFieldIndex(D) !=
  3342. ASTImporter::getFieldIndex(FoundField))
  3343. continue;
  3344. if (Importer.IsStructurallyEquivalent(D->getType(),
  3345. FoundField->getType())) {
  3346. Importer.MapImported(D, FoundField);
  3347. // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
  3348. // initializer of a FieldDecl might not had been instantiated in the
  3349. // "To" context. However, the "From" context might instantiated that,
  3350. // thus we have to merge that.
  3351. // Note: `hasInClassInitializer()` is not the same as non-null
  3352. // `getInClassInitializer()` value.
  3353. if (Expr *FromInitializer = D->getInClassInitializer()) {
  3354. if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) {
  3355. // Import of the FromInitializer may result in the setting of
  3356. // InClassInitializer. If not, set it here.
  3357. assert(FoundField->hasInClassInitializer() &&
  3358. "Field should have an in-class initializer if it has an "
  3359. "expression for it.");
  3360. if (!FoundField->getInClassInitializer())
  3361. FoundField->setInClassInitializer(*ToInitializerOrErr);
  3362. } else {
  3363. return ToInitializerOrErr.takeError();
  3364. }
  3365. }
  3366. return FoundField;
  3367. }
  3368. // FIXME: Why is this case not handled with calling HandleNameConflict?
  3369. Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
  3370. << Name << D->getType() << FoundField->getType();
  3371. Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
  3372. << FoundField->getType();
  3373. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3374. }
  3375. }
  3376. Error Err = Error::success();
  3377. auto ToType = importChecked(Err, D->getType());
  3378. auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
  3379. auto ToBitWidth = importChecked(Err, D->getBitWidth());
  3380. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  3381. auto ToInitializer = importChecked(Err, D->getInClassInitializer());
  3382. if (Err)
  3383. return std::move(Err);
  3384. const Type *ToCapturedVLAType = nullptr;
  3385. if (Error Err = Importer.importInto(
  3386. ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
  3387. return std::move(Err);
  3388. FieldDecl *ToField;
  3389. if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
  3390. ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
  3391. ToType, ToTInfo, ToBitWidth, D->isMutable(),
  3392. D->getInClassInitStyle()))
  3393. return ToField;
  3394. ToField->setAccess(D->getAccess());
  3395. ToField->setLexicalDeclContext(LexicalDC);
  3396. if (ToInitializer)
  3397. ToField->setInClassInitializer(ToInitializer);
  3398. ToField->setImplicit(D->isImplicit());
  3399. if (ToCapturedVLAType)
  3400. ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
  3401. LexicalDC->addDeclInternal(ToField);
  3402. return ToField;
  3403. }
  3404. ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  3405. // Import the major distinguishing characteristics of a variable.
  3406. DeclContext *DC, *LexicalDC;
  3407. DeclarationName Name;
  3408. SourceLocation Loc;
  3409. NamedDecl *ToD;
  3410. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3411. return std::move(Err);
  3412. if (ToD)
  3413. return ToD;
  3414. // Determine whether we've already imported this field.
  3415. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3416. for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
  3417. if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
  3418. // For anonymous indirect fields, match up by index.
  3419. if (!Name &&
  3420. ASTImporter::getFieldIndex(D) !=
  3421. ASTImporter::getFieldIndex(FoundField))
  3422. continue;
  3423. if (Importer.IsStructurallyEquivalent(D->getType(),
  3424. FoundField->getType(),
  3425. !Name.isEmpty())) {
  3426. Importer.MapImported(D, FoundField);
  3427. return FoundField;
  3428. }
  3429. // If there are more anonymous fields to check, continue.
  3430. if (!Name && I < N-1)
  3431. continue;
  3432. // FIXME: Why is this case not handled with calling HandleNameConflict?
  3433. Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
  3434. << Name << D->getType() << FoundField->getType();
  3435. Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
  3436. << FoundField->getType();
  3437. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3438. }
  3439. }
  3440. // Import the type.
  3441. auto TypeOrErr = import(D->getType());
  3442. if (!TypeOrErr)
  3443. return TypeOrErr.takeError();
  3444. auto **NamedChain =
  3445. new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
  3446. unsigned i = 0;
  3447. for (auto *PI : D->chain())
  3448. if (Expected<NamedDecl *> ToD = import(PI))
  3449. NamedChain[i++] = *ToD;
  3450. else
  3451. return ToD.takeError();
  3452. llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
  3453. IndirectFieldDecl *ToIndirectField;
  3454. if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
  3455. Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
  3456. // FIXME here we leak `NamedChain` which is allocated before
  3457. return ToIndirectField;
  3458. ToIndirectField->setAccess(D->getAccess());
  3459. ToIndirectField->setLexicalDeclContext(LexicalDC);
  3460. LexicalDC->addDeclInternal(ToIndirectField);
  3461. return ToIndirectField;
  3462. }
  3463. /// Used as return type of getFriendCountAndPosition.
  3464. struct FriendCountAndPosition {
  3465. /// Number of similar looking friends.
  3466. unsigned int TotalCount;
  3467. /// Index of the specific FriendDecl.
  3468. unsigned int IndexOfDecl;
  3469. };
  3470. template <class T>
  3471. static FriendCountAndPosition getFriendCountAndPosition(
  3472. const FriendDecl *FD,
  3473. llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
  3474. unsigned int FriendCount = 0;
  3475. std::optional<unsigned int> FriendPosition;
  3476. const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
  3477. T TypeOrDecl = GetCanTypeOrDecl(FD);
  3478. for (const FriendDecl *FoundFriend : RD->friends()) {
  3479. if (FoundFriend == FD) {
  3480. FriendPosition = FriendCount;
  3481. ++FriendCount;
  3482. } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
  3483. GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
  3484. ++FriendCount;
  3485. }
  3486. }
  3487. assert(FriendPosition && "Friend decl not found in own parent.");
  3488. return {FriendCount, *FriendPosition};
  3489. }
  3490. static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
  3491. if (FD->getFriendType())
  3492. return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
  3493. if (TypeSourceInfo *TSI = F->getFriendType())
  3494. return TSI->getType().getCanonicalType();
  3495. llvm_unreachable("Wrong friend object type.");
  3496. });
  3497. else
  3498. return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
  3499. if (Decl *D = F->getFriendDecl())
  3500. return D->getCanonicalDecl();
  3501. llvm_unreachable("Wrong friend object type.");
  3502. });
  3503. }
  3504. ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
  3505. // Import the major distinguishing characteristics of a declaration.
  3506. DeclContext *DC, *LexicalDC;
  3507. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  3508. return std::move(Err);
  3509. // Determine whether we've already imported this decl.
  3510. // FriendDecl is not a NamedDecl so we cannot use lookup.
  3511. // We try to maintain order and count of redundant friend declarations.
  3512. const auto *RD = cast<CXXRecordDecl>(DC);
  3513. FriendDecl *ImportedFriend = RD->getFirstFriend();
  3514. SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
  3515. while (ImportedFriend) {
  3516. bool Match = false;
  3517. if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
  3518. Match =
  3519. IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
  3520. /*Complain=*/false);
  3521. } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
  3522. Match = Importer.IsStructurallyEquivalent(
  3523. D->getFriendType()->getType(),
  3524. ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
  3525. }
  3526. if (Match)
  3527. ImportedEquivalentFriends.push_back(ImportedFriend);
  3528. ImportedFriend = ImportedFriend->getNextFriend();
  3529. }
  3530. FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
  3531. assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
  3532. "Class with non-matching friends is imported, ODR check wrong?");
  3533. if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
  3534. return Importer.MapImported(
  3535. D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
  3536. // Not found. Create it.
  3537. // The declarations will be put into order later by ImportDeclContext.
  3538. FriendDecl::FriendUnion ToFU;
  3539. if (NamedDecl *FriendD = D->getFriendDecl()) {
  3540. NamedDecl *ToFriendD;
  3541. if (Error Err = importInto(ToFriendD, FriendD))
  3542. return std::move(Err);
  3543. if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
  3544. !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
  3545. ToFriendD->setObjectOfFriendDecl(false);
  3546. ToFU = ToFriendD;
  3547. } else { // The friend is a type, not a decl.
  3548. if (auto TSIOrErr = import(D->getFriendType()))
  3549. ToFU = *TSIOrErr;
  3550. else
  3551. return TSIOrErr.takeError();
  3552. }
  3553. SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
  3554. auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
  3555. for (unsigned I = 0; I < D->NumTPLists; I++) {
  3556. if (auto ListOrErr = import(FromTPLists[I]))
  3557. ToTPLists[I] = *ListOrErr;
  3558. else
  3559. return ListOrErr.takeError();
  3560. }
  3561. auto LocationOrErr = import(D->getLocation());
  3562. if (!LocationOrErr)
  3563. return LocationOrErr.takeError();
  3564. auto FriendLocOrErr = import(D->getFriendLoc());
  3565. if (!FriendLocOrErr)
  3566. return FriendLocOrErr.takeError();
  3567. FriendDecl *FrD;
  3568. if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
  3569. *LocationOrErr, ToFU,
  3570. *FriendLocOrErr, ToTPLists))
  3571. return FrD;
  3572. FrD->setAccess(D->getAccess());
  3573. FrD->setLexicalDeclContext(LexicalDC);
  3574. LexicalDC->addDeclInternal(FrD);
  3575. return FrD;
  3576. }
  3577. ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
  3578. // Import the major distinguishing characteristics of an ivar.
  3579. DeclContext *DC, *LexicalDC;
  3580. DeclarationName Name;
  3581. SourceLocation Loc;
  3582. NamedDecl *ToD;
  3583. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3584. return std::move(Err);
  3585. if (ToD)
  3586. return ToD;
  3587. // Determine whether we've already imported this ivar
  3588. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3589. for (auto *FoundDecl : FoundDecls) {
  3590. if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
  3591. if (Importer.IsStructurallyEquivalent(D->getType(),
  3592. FoundIvar->getType())) {
  3593. Importer.MapImported(D, FoundIvar);
  3594. return FoundIvar;
  3595. }
  3596. Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
  3597. << Name << D->getType() << FoundIvar->getType();
  3598. Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
  3599. << FoundIvar->getType();
  3600. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3601. }
  3602. }
  3603. Error Err = Error::success();
  3604. auto ToType = importChecked(Err, D->getType());
  3605. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  3606. auto ToBitWidth = importChecked(Err, D->getBitWidth());
  3607. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  3608. if (Err)
  3609. return std::move(Err);
  3610. ObjCIvarDecl *ToIvar;
  3611. if (GetImportedOrCreateDecl(
  3612. ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
  3613. ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
  3614. ToType, ToTypeSourceInfo,
  3615. D->getAccessControl(),ToBitWidth, D->getSynthesize()))
  3616. return ToIvar;
  3617. ToIvar->setLexicalDeclContext(LexicalDC);
  3618. LexicalDC->addDeclInternal(ToIvar);
  3619. return ToIvar;
  3620. }
  3621. ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
  3622. SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
  3623. auto RedeclIt = Redecls.begin();
  3624. // Import the first part of the decl chain. I.e. import all previous
  3625. // declarations starting from the canonical decl.
  3626. for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
  3627. ExpectedDecl RedeclOrErr = import(*RedeclIt);
  3628. if (!RedeclOrErr)
  3629. return RedeclOrErr.takeError();
  3630. }
  3631. assert(*RedeclIt == D);
  3632. // Import the major distinguishing characteristics of a variable.
  3633. DeclContext *DC, *LexicalDC;
  3634. DeclarationName Name;
  3635. SourceLocation Loc;
  3636. NamedDecl *ToD;
  3637. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3638. return std::move(Err);
  3639. if (ToD)
  3640. return ToD;
  3641. // Try to find a variable in our own ("to") context with the same name and
  3642. // in the same context as the variable we're importing.
  3643. VarDecl *FoundByLookup = nullptr;
  3644. if (D->isFileVarDecl()) {
  3645. SmallVector<NamedDecl *, 4> ConflictingDecls;
  3646. unsigned IDNS = Decl::IDNS_Ordinary;
  3647. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3648. for (auto *FoundDecl : FoundDecls) {
  3649. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  3650. continue;
  3651. if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
  3652. if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
  3653. continue;
  3654. if (Importer.IsStructurallyEquivalent(D->getType(),
  3655. FoundVar->getType())) {
  3656. // The VarDecl in the "From" context has a definition, but in the
  3657. // "To" context we already have a definition.
  3658. VarDecl *FoundDef = FoundVar->getDefinition();
  3659. if (D->isThisDeclarationADefinition() && FoundDef)
  3660. // FIXME Check for ODR error if the two definitions have
  3661. // different initializers?
  3662. return Importer.MapImported(D, FoundDef);
  3663. // The VarDecl in the "From" context has an initializer, but in the
  3664. // "To" context we already have an initializer.
  3665. const VarDecl *FoundDInit = nullptr;
  3666. if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
  3667. // FIXME Diagnose ODR error if the two initializers are different?
  3668. return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
  3669. FoundByLookup = FoundVar;
  3670. break;
  3671. }
  3672. const ArrayType *FoundArray
  3673. = Importer.getToContext().getAsArrayType(FoundVar->getType());
  3674. const ArrayType *TArray
  3675. = Importer.getToContext().getAsArrayType(D->getType());
  3676. if (FoundArray && TArray) {
  3677. if (isa<IncompleteArrayType>(FoundArray) &&
  3678. isa<ConstantArrayType>(TArray)) {
  3679. // Import the type.
  3680. if (auto TyOrErr = import(D->getType()))
  3681. FoundVar->setType(*TyOrErr);
  3682. else
  3683. return TyOrErr.takeError();
  3684. FoundByLookup = FoundVar;
  3685. break;
  3686. } else if (isa<IncompleteArrayType>(TArray) &&
  3687. isa<ConstantArrayType>(FoundArray)) {
  3688. FoundByLookup = FoundVar;
  3689. break;
  3690. }
  3691. }
  3692. Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
  3693. << Name << D->getType() << FoundVar->getType();
  3694. Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
  3695. << FoundVar->getType();
  3696. ConflictingDecls.push_back(FoundDecl);
  3697. }
  3698. }
  3699. if (!ConflictingDecls.empty()) {
  3700. ExpectedName NameOrErr = Importer.HandleNameConflict(
  3701. Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
  3702. if (NameOrErr)
  3703. Name = NameOrErr.get();
  3704. else
  3705. return NameOrErr.takeError();
  3706. }
  3707. }
  3708. Error Err = Error::success();
  3709. auto ToType = importChecked(Err, D->getType());
  3710. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  3711. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  3712. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  3713. if (Err)
  3714. return std::move(Err);
  3715. VarDecl *ToVar;
  3716. if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
  3717. SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
  3718. if (Error Err =
  3719. ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
  3720. return std::move(Err);
  3721. DecompositionDecl *ToDecomp;
  3722. if (GetImportedOrCreateDecl(
  3723. ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
  3724. Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
  3725. return ToDecomp;
  3726. ToVar = ToDecomp;
  3727. } else {
  3728. // Create the imported variable.
  3729. if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
  3730. ToInnerLocStart, Loc,
  3731. Name.getAsIdentifierInfo(), ToType,
  3732. ToTypeSourceInfo, D->getStorageClass()))
  3733. return ToVar;
  3734. }
  3735. ToVar->setTSCSpec(D->getTSCSpec());
  3736. ToVar->setQualifierInfo(ToQualifierLoc);
  3737. ToVar->setAccess(D->getAccess());
  3738. ToVar->setLexicalDeclContext(LexicalDC);
  3739. if (FoundByLookup) {
  3740. auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
  3741. ToVar->setPreviousDecl(Recent);
  3742. }
  3743. // Import the described template, if any.
  3744. if (D->getDescribedVarTemplate()) {
  3745. auto ToVTOrErr = import(D->getDescribedVarTemplate());
  3746. if (!ToVTOrErr)
  3747. return ToVTOrErr.takeError();
  3748. }
  3749. if (Error Err = ImportInitializer(D, ToVar))
  3750. return std::move(Err);
  3751. if (D->isConstexpr())
  3752. ToVar->setConstexpr(true);
  3753. addDeclToContexts(D, ToVar);
  3754. // Import the rest of the chain. I.e. import all subsequent declarations.
  3755. for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
  3756. ExpectedDecl RedeclOrErr = import(*RedeclIt);
  3757. if (!RedeclOrErr)
  3758. return RedeclOrErr.takeError();
  3759. }
  3760. return ToVar;
  3761. }
  3762. ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
  3763. // Parameters are created in the translation unit's context, then moved
  3764. // into the function declaration's context afterward.
  3765. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
  3766. Error Err = Error::success();
  3767. auto ToDeclName = importChecked(Err, D->getDeclName());
  3768. auto ToLocation = importChecked(Err, D->getLocation());
  3769. auto ToType = importChecked(Err, D->getType());
  3770. if (Err)
  3771. return std::move(Err);
  3772. // Create the imported parameter.
  3773. ImplicitParamDecl *ToParm = nullptr;
  3774. if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
  3775. ToLocation, ToDeclName.getAsIdentifierInfo(),
  3776. ToType, D->getParameterKind()))
  3777. return ToParm;
  3778. return ToParm;
  3779. }
  3780. Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
  3781. const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
  3782. ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
  3783. ToParam->setKNRPromoted(FromParam->isKNRPromoted());
  3784. if (FromParam->hasUninstantiatedDefaultArg()) {
  3785. if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
  3786. ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
  3787. else
  3788. return ToDefArgOrErr.takeError();
  3789. } else if (FromParam->hasUnparsedDefaultArg()) {
  3790. ToParam->setUnparsedDefaultArg();
  3791. } else if (FromParam->hasDefaultArg()) {
  3792. if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
  3793. ToParam->setDefaultArg(*ToDefArgOrErr);
  3794. else
  3795. return ToDefArgOrErr.takeError();
  3796. }
  3797. return Error::success();
  3798. }
  3799. Expected<InheritedConstructor>
  3800. ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) {
  3801. Error Err = Error::success();
  3802. CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor());
  3803. ConstructorUsingShadowDecl *ToShadow =
  3804. importChecked(Err, From.getShadowDecl());
  3805. if (Err)
  3806. return std::move(Err);
  3807. return InheritedConstructor(ToShadow, ToBaseCtor);
  3808. }
  3809. ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
  3810. // Parameters are created in the translation unit's context, then moved
  3811. // into the function declaration's context afterward.
  3812. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
  3813. Error Err = Error::success();
  3814. auto ToDeclName = importChecked(Err, D->getDeclName());
  3815. auto ToLocation = importChecked(Err, D->getLocation());
  3816. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  3817. auto ToType = importChecked(Err, D->getType());
  3818. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  3819. if (Err)
  3820. return std::move(Err);
  3821. ParmVarDecl *ToParm;
  3822. if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
  3823. ToInnerLocStart, ToLocation,
  3824. ToDeclName.getAsIdentifierInfo(), ToType,
  3825. ToTypeSourceInfo, D->getStorageClass(),
  3826. /*DefaultArg*/ nullptr))
  3827. return ToParm;
  3828. // Set the default argument. It should be no problem if it was already done.
  3829. // Do not import the default expression before GetImportedOrCreateDecl call
  3830. // to avoid possible infinite import loop because circular dependency.
  3831. if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
  3832. return std::move(Err);
  3833. if (D->isObjCMethodParameter()) {
  3834. ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
  3835. ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
  3836. } else {
  3837. ToParm->setScopeInfo(D->getFunctionScopeDepth(),
  3838. D->getFunctionScopeIndex());
  3839. }
  3840. return ToParm;
  3841. }
  3842. ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
  3843. // Import the major distinguishing characteristics of a method.
  3844. DeclContext *DC, *LexicalDC;
  3845. DeclarationName Name;
  3846. SourceLocation Loc;
  3847. NamedDecl *ToD;
  3848. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3849. return std::move(Err);
  3850. if (ToD)
  3851. return ToD;
  3852. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  3853. for (auto *FoundDecl : FoundDecls) {
  3854. if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
  3855. if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
  3856. continue;
  3857. // Check return types.
  3858. if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
  3859. FoundMethod->getReturnType())) {
  3860. Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
  3861. << D->isInstanceMethod() << Name << D->getReturnType()
  3862. << FoundMethod->getReturnType();
  3863. Importer.ToDiag(FoundMethod->getLocation(),
  3864. diag::note_odr_objc_method_here)
  3865. << D->isInstanceMethod() << Name;
  3866. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3867. }
  3868. // Check the number of parameters.
  3869. if (D->param_size() != FoundMethod->param_size()) {
  3870. Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
  3871. << D->isInstanceMethod() << Name
  3872. << D->param_size() << FoundMethod->param_size();
  3873. Importer.ToDiag(FoundMethod->getLocation(),
  3874. diag::note_odr_objc_method_here)
  3875. << D->isInstanceMethod() << Name;
  3876. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3877. }
  3878. // Check parameter types.
  3879. for (ObjCMethodDecl::param_iterator P = D->param_begin(),
  3880. PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
  3881. P != PEnd; ++P, ++FoundP) {
  3882. if (!Importer.IsStructurallyEquivalent((*P)->getType(),
  3883. (*FoundP)->getType())) {
  3884. Importer.FromDiag((*P)->getLocation(),
  3885. diag::warn_odr_objc_method_param_type_inconsistent)
  3886. << D->isInstanceMethod() << Name
  3887. << (*P)->getType() << (*FoundP)->getType();
  3888. Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
  3889. << (*FoundP)->getType();
  3890. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3891. }
  3892. }
  3893. // Check variadic/non-variadic.
  3894. // Check the number of parameters.
  3895. if (D->isVariadic() != FoundMethod->isVariadic()) {
  3896. Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
  3897. << D->isInstanceMethod() << Name;
  3898. Importer.ToDiag(FoundMethod->getLocation(),
  3899. diag::note_odr_objc_method_here)
  3900. << D->isInstanceMethod() << Name;
  3901. return make_error<ASTImportError>(ASTImportError::NameConflict);
  3902. }
  3903. // FIXME: Any other bits we need to merge?
  3904. return Importer.MapImported(D, FoundMethod);
  3905. }
  3906. }
  3907. Error Err = Error::success();
  3908. auto ToEndLoc = importChecked(Err, D->getEndLoc());
  3909. auto ToReturnType = importChecked(Err, D->getReturnType());
  3910. auto ToReturnTypeSourceInfo =
  3911. importChecked(Err, D->getReturnTypeSourceInfo());
  3912. if (Err)
  3913. return std::move(Err);
  3914. ObjCMethodDecl *ToMethod;
  3915. if (GetImportedOrCreateDecl(
  3916. ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
  3917. Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
  3918. D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
  3919. D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
  3920. D->getImplementationControl(), D->hasRelatedResultType()))
  3921. return ToMethod;
  3922. // FIXME: When we decide to merge method definitions, we'll need to
  3923. // deal with implicit parameters.
  3924. // Import the parameters
  3925. SmallVector<ParmVarDecl *, 5> ToParams;
  3926. for (auto *FromP : D->parameters()) {
  3927. if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
  3928. ToParams.push_back(*ToPOrErr);
  3929. else
  3930. return ToPOrErr.takeError();
  3931. }
  3932. // Set the parameters.
  3933. for (auto *ToParam : ToParams) {
  3934. ToParam->setOwningFunction(ToMethod);
  3935. ToMethod->addDeclInternal(ToParam);
  3936. }
  3937. SmallVector<SourceLocation, 12> FromSelLocs;
  3938. D->getSelectorLocs(FromSelLocs);
  3939. SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
  3940. if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
  3941. return std::move(Err);
  3942. ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
  3943. ToMethod->setLexicalDeclContext(LexicalDC);
  3944. LexicalDC->addDeclInternal(ToMethod);
  3945. // Implicit params are declared when Sema encounters the definition but this
  3946. // never happens when the method is imported. Manually declare the implicit
  3947. // params now that the MethodDecl knows its class interface.
  3948. if (D->getSelfDecl())
  3949. ToMethod->createImplicitParams(Importer.getToContext(),
  3950. ToMethod->getClassInterface());
  3951. return ToMethod;
  3952. }
  3953. ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
  3954. // Import the major distinguishing characteristics of a category.
  3955. DeclContext *DC, *LexicalDC;
  3956. DeclarationName Name;
  3957. SourceLocation Loc;
  3958. NamedDecl *ToD;
  3959. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3960. return std::move(Err);
  3961. if (ToD)
  3962. return ToD;
  3963. Error Err = Error::success();
  3964. auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
  3965. auto ToLocation = importChecked(Err, D->getLocation());
  3966. auto ToColonLoc = importChecked(Err, D->getColonLoc());
  3967. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  3968. if (Err)
  3969. return std::move(Err);
  3970. ObjCTypeParamDecl *Result;
  3971. if (GetImportedOrCreateDecl(
  3972. Result, D, Importer.getToContext(), DC, D->getVariance(),
  3973. ToVarianceLoc, D->getIndex(),
  3974. ToLocation, Name.getAsIdentifierInfo(),
  3975. ToColonLoc, ToTypeSourceInfo))
  3976. return Result;
  3977. Result->setLexicalDeclContext(LexicalDC);
  3978. return Result;
  3979. }
  3980. ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
  3981. // Import the major distinguishing characteristics of a category.
  3982. DeclContext *DC, *LexicalDC;
  3983. DeclarationName Name;
  3984. SourceLocation Loc;
  3985. NamedDecl *ToD;
  3986. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  3987. return std::move(Err);
  3988. if (ToD)
  3989. return ToD;
  3990. ObjCInterfaceDecl *ToInterface;
  3991. if (Error Err = importInto(ToInterface, D->getClassInterface()))
  3992. return std::move(Err);
  3993. // Determine if we've already encountered this category.
  3994. ObjCCategoryDecl *MergeWithCategory
  3995. = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
  3996. ObjCCategoryDecl *ToCategory = MergeWithCategory;
  3997. if (!ToCategory) {
  3998. Error Err = Error::success();
  3999. auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
  4000. auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
  4001. auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
  4002. auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
  4003. if (Err)
  4004. return std::move(Err);
  4005. if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
  4006. ToAtStartLoc, Loc,
  4007. ToCategoryNameLoc,
  4008. Name.getAsIdentifierInfo(), ToInterface,
  4009. /*TypeParamList=*/nullptr,
  4010. ToIvarLBraceLoc,
  4011. ToIvarRBraceLoc))
  4012. return ToCategory;
  4013. ToCategory->setLexicalDeclContext(LexicalDC);
  4014. LexicalDC->addDeclInternal(ToCategory);
  4015. // Import the type parameter list after MapImported, to avoid
  4016. // loops when bringing in their DeclContext.
  4017. if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
  4018. ToCategory->setTypeParamList(*PListOrErr);
  4019. else
  4020. return PListOrErr.takeError();
  4021. // Import protocols
  4022. SmallVector<ObjCProtocolDecl *, 4> Protocols;
  4023. SmallVector<SourceLocation, 4> ProtocolLocs;
  4024. ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
  4025. = D->protocol_loc_begin();
  4026. for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
  4027. FromProtoEnd = D->protocol_end();
  4028. FromProto != FromProtoEnd;
  4029. ++FromProto, ++FromProtoLoc) {
  4030. if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
  4031. Protocols.push_back(*ToProtoOrErr);
  4032. else
  4033. return ToProtoOrErr.takeError();
  4034. if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
  4035. ProtocolLocs.push_back(*ToProtoLocOrErr);
  4036. else
  4037. return ToProtoLocOrErr.takeError();
  4038. }
  4039. // FIXME: If we're merging, make sure that the protocol list is the same.
  4040. ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
  4041. ProtocolLocs.data(), Importer.getToContext());
  4042. } else {
  4043. Importer.MapImported(D, ToCategory);
  4044. }
  4045. // Import all of the members of this category.
  4046. if (Error Err = ImportDeclContext(D))
  4047. return std::move(Err);
  4048. // If we have an implementation, import it as well.
  4049. if (D->getImplementation()) {
  4050. if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
  4051. import(D->getImplementation()))
  4052. ToCategory->setImplementation(*ToImplOrErr);
  4053. else
  4054. return ToImplOrErr.takeError();
  4055. }
  4056. return ToCategory;
  4057. }
  4058. Error ASTNodeImporter::ImportDefinition(
  4059. ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
  4060. if (To->getDefinition()) {
  4061. if (shouldForceImportDeclContext(Kind))
  4062. if (Error Err = ImportDeclContext(From))
  4063. return Err;
  4064. return Error::success();
  4065. }
  4066. // Start the protocol definition
  4067. To->startDefinition();
  4068. // Import protocols
  4069. SmallVector<ObjCProtocolDecl *, 4> Protocols;
  4070. SmallVector<SourceLocation, 4> ProtocolLocs;
  4071. ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
  4072. From->protocol_loc_begin();
  4073. for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
  4074. FromProtoEnd = From->protocol_end();
  4075. FromProto != FromProtoEnd;
  4076. ++FromProto, ++FromProtoLoc) {
  4077. if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
  4078. Protocols.push_back(*ToProtoOrErr);
  4079. else
  4080. return ToProtoOrErr.takeError();
  4081. if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
  4082. ProtocolLocs.push_back(*ToProtoLocOrErr);
  4083. else
  4084. return ToProtoLocOrErr.takeError();
  4085. }
  4086. // FIXME: If we're merging, make sure that the protocol list is the same.
  4087. To->setProtocolList(Protocols.data(), Protocols.size(),
  4088. ProtocolLocs.data(), Importer.getToContext());
  4089. if (shouldForceImportDeclContext(Kind)) {
  4090. // Import all of the members of this protocol.
  4091. if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
  4092. return Err;
  4093. }
  4094. return Error::success();
  4095. }
  4096. ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
  4097. // If this protocol has a definition in the translation unit we're coming
  4098. // from, but this particular declaration is not that definition, import the
  4099. // definition and map to that.
  4100. ObjCProtocolDecl *Definition = D->getDefinition();
  4101. if (Definition && Definition != D) {
  4102. if (ExpectedDecl ImportedDefOrErr = import(Definition))
  4103. return Importer.MapImported(D, *ImportedDefOrErr);
  4104. else
  4105. return ImportedDefOrErr.takeError();
  4106. }
  4107. // Import the major distinguishing characteristics of a protocol.
  4108. DeclContext *DC, *LexicalDC;
  4109. DeclarationName Name;
  4110. SourceLocation Loc;
  4111. NamedDecl *ToD;
  4112. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4113. return std::move(Err);
  4114. if (ToD)
  4115. return ToD;
  4116. ObjCProtocolDecl *MergeWithProtocol = nullptr;
  4117. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  4118. for (auto *FoundDecl : FoundDecls) {
  4119. if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
  4120. continue;
  4121. if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
  4122. break;
  4123. }
  4124. ObjCProtocolDecl *ToProto = MergeWithProtocol;
  4125. if (!ToProto) {
  4126. auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
  4127. if (!ToAtBeginLocOrErr)
  4128. return ToAtBeginLocOrErr.takeError();
  4129. if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
  4130. Name.getAsIdentifierInfo(), Loc,
  4131. *ToAtBeginLocOrErr,
  4132. /*PrevDecl=*/nullptr))
  4133. return ToProto;
  4134. ToProto->setLexicalDeclContext(LexicalDC);
  4135. LexicalDC->addDeclInternal(ToProto);
  4136. }
  4137. Importer.MapImported(D, ToProto);
  4138. if (D->isThisDeclarationADefinition())
  4139. if (Error Err = ImportDefinition(D, ToProto))
  4140. return std::move(Err);
  4141. return ToProto;
  4142. }
  4143. ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
  4144. DeclContext *DC, *LexicalDC;
  4145. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  4146. return std::move(Err);
  4147. ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
  4148. if (!ExternLocOrErr)
  4149. return ExternLocOrErr.takeError();
  4150. ExpectedSLoc LangLocOrErr = import(D->getLocation());
  4151. if (!LangLocOrErr)
  4152. return LangLocOrErr.takeError();
  4153. bool HasBraces = D->hasBraces();
  4154. LinkageSpecDecl *ToLinkageSpec;
  4155. if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
  4156. *ExternLocOrErr, *LangLocOrErr,
  4157. D->getLanguage(), HasBraces))
  4158. return ToLinkageSpec;
  4159. if (HasBraces) {
  4160. ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
  4161. if (!RBraceLocOrErr)
  4162. return RBraceLocOrErr.takeError();
  4163. ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
  4164. }
  4165. ToLinkageSpec->setLexicalDeclContext(LexicalDC);
  4166. LexicalDC->addDeclInternal(ToLinkageSpec);
  4167. return ToLinkageSpec;
  4168. }
  4169. ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
  4170. BaseUsingDecl *ToSI) {
  4171. for (UsingShadowDecl *FromShadow : D->shadows()) {
  4172. if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
  4173. ToSI->addShadowDecl(*ToShadowOrErr);
  4174. else
  4175. // FIXME: We return error here but the definition is already created
  4176. // and available with lookups. How to fix this?..
  4177. return ToShadowOrErr.takeError();
  4178. }
  4179. return ToSI;
  4180. }
  4181. ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
  4182. DeclContext *DC, *LexicalDC;
  4183. DeclarationName Name;
  4184. SourceLocation Loc;
  4185. NamedDecl *ToD = nullptr;
  4186. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4187. return std::move(Err);
  4188. if (ToD)
  4189. return ToD;
  4190. Error Err = Error::success();
  4191. auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
  4192. auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
  4193. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  4194. if (Err)
  4195. return std::move(Err);
  4196. DeclarationNameInfo NameInfo(Name, ToLoc);
  4197. if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
  4198. return std::move(Err);
  4199. UsingDecl *ToUsing;
  4200. if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
  4201. ToUsingLoc, ToQualifierLoc, NameInfo,
  4202. D->hasTypename()))
  4203. return ToUsing;
  4204. ToUsing->setLexicalDeclContext(LexicalDC);
  4205. LexicalDC->addDeclInternal(ToUsing);
  4206. if (NamedDecl *FromPattern =
  4207. Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
  4208. if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
  4209. Importer.getToContext().setInstantiatedFromUsingDecl(
  4210. ToUsing, *ToPatternOrErr);
  4211. else
  4212. return ToPatternOrErr.takeError();
  4213. }
  4214. return ImportUsingShadowDecls(D, ToUsing);
  4215. }
  4216. ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
  4217. DeclContext *DC, *LexicalDC;
  4218. DeclarationName Name;
  4219. SourceLocation Loc;
  4220. NamedDecl *ToD = nullptr;
  4221. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4222. return std::move(Err);
  4223. if (ToD)
  4224. return ToD;
  4225. Error Err = Error::success();
  4226. auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
  4227. auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
  4228. auto ToNameLoc = importChecked(Err, D->getLocation());
  4229. auto *ToEnumType = importChecked(Err, D->getEnumType());
  4230. if (Err)
  4231. return std::move(Err);
  4232. UsingEnumDecl *ToUsingEnum;
  4233. if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
  4234. ToUsingLoc, ToEnumLoc, ToNameLoc, ToEnumType))
  4235. return ToUsingEnum;
  4236. ToUsingEnum->setLexicalDeclContext(LexicalDC);
  4237. LexicalDC->addDeclInternal(ToUsingEnum);
  4238. if (UsingEnumDecl *FromPattern =
  4239. Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) {
  4240. if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
  4241. Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
  4242. *ToPatternOrErr);
  4243. else
  4244. return ToPatternOrErr.takeError();
  4245. }
  4246. return ImportUsingShadowDecls(D, ToUsingEnum);
  4247. }
  4248. ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
  4249. DeclContext *DC, *LexicalDC;
  4250. DeclarationName Name;
  4251. SourceLocation Loc;
  4252. NamedDecl *ToD = nullptr;
  4253. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4254. return std::move(Err);
  4255. if (ToD)
  4256. return ToD;
  4257. Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
  4258. if (!ToIntroducerOrErr)
  4259. return ToIntroducerOrErr.takeError();
  4260. Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
  4261. if (!ToTargetOrErr)
  4262. return ToTargetOrErr.takeError();
  4263. UsingShadowDecl *ToShadow;
  4264. if (auto *FromConstructorUsingShadow =
  4265. dyn_cast<ConstructorUsingShadowDecl>(D)) {
  4266. Error Err = Error::success();
  4267. ConstructorUsingShadowDecl *Nominated = importChecked(
  4268. Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
  4269. if (Err)
  4270. return std::move(Err);
  4271. // The 'Target' parameter of ConstructorUsingShadowDecl constructor
  4272. // is really the "NominatedBaseClassShadowDecl" value if it exists
  4273. // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
  4274. // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
  4275. // get the correct values.
  4276. if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
  4277. ToShadow, D, Importer.getToContext(), DC, Loc,
  4278. cast<UsingDecl>(*ToIntroducerOrErr),
  4279. Nominated ? Nominated : *ToTargetOrErr,
  4280. FromConstructorUsingShadow->constructsVirtualBase()))
  4281. return ToShadow;
  4282. } else {
  4283. if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
  4284. Name, *ToIntroducerOrErr, *ToTargetOrErr))
  4285. return ToShadow;
  4286. }
  4287. ToShadow->setLexicalDeclContext(LexicalDC);
  4288. ToShadow->setAccess(D->getAccess());
  4289. if (UsingShadowDecl *FromPattern =
  4290. Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
  4291. if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
  4292. Importer.getToContext().setInstantiatedFromUsingShadowDecl(
  4293. ToShadow, *ToPatternOrErr);
  4294. else
  4295. // FIXME: We return error here but the definition is already created
  4296. // and available with lookups. How to fix this?..
  4297. return ToPatternOrErr.takeError();
  4298. }
  4299. LexicalDC->addDeclInternal(ToShadow);
  4300. return ToShadow;
  4301. }
  4302. ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  4303. DeclContext *DC, *LexicalDC;
  4304. DeclarationName Name;
  4305. SourceLocation Loc;
  4306. NamedDecl *ToD = nullptr;
  4307. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4308. return std::move(Err);
  4309. if (ToD)
  4310. return ToD;
  4311. auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
  4312. if (!ToComAncestorOrErr)
  4313. return ToComAncestorOrErr.takeError();
  4314. Error Err = Error::success();
  4315. auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
  4316. auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
  4317. auto ToNamespaceKeyLocation =
  4318. importChecked(Err, D->getNamespaceKeyLocation());
  4319. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  4320. auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
  4321. if (Err)
  4322. return std::move(Err);
  4323. UsingDirectiveDecl *ToUsingDir;
  4324. if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
  4325. ToUsingLoc,
  4326. ToNamespaceKeyLocation,
  4327. ToQualifierLoc,
  4328. ToIdentLocation,
  4329. ToNominatedNamespace, *ToComAncestorOrErr))
  4330. return ToUsingDir;
  4331. ToUsingDir->setLexicalDeclContext(LexicalDC);
  4332. LexicalDC->addDeclInternal(ToUsingDir);
  4333. return ToUsingDir;
  4334. }
  4335. ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
  4336. DeclContext *DC, *LexicalDC;
  4337. DeclarationName Name;
  4338. SourceLocation Loc;
  4339. NamedDecl *ToD = nullptr;
  4340. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4341. return std::move(Err);
  4342. if (ToD)
  4343. return ToD;
  4344. auto ToInstantiatedFromUsingOrErr =
  4345. Importer.Import(D->getInstantiatedFromUsingDecl());
  4346. if (!ToInstantiatedFromUsingOrErr)
  4347. return ToInstantiatedFromUsingOrErr.takeError();
  4348. SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
  4349. if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
  4350. return std::move(Err);
  4351. UsingPackDecl *ToUsingPack;
  4352. if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
  4353. cast<NamedDecl>(*ToInstantiatedFromUsingOrErr),
  4354. Expansions))
  4355. return ToUsingPack;
  4356. addDeclToContexts(D, ToUsingPack);
  4357. return ToUsingPack;
  4358. }
  4359. ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
  4360. UnresolvedUsingValueDecl *D) {
  4361. DeclContext *DC, *LexicalDC;
  4362. DeclarationName Name;
  4363. SourceLocation Loc;
  4364. NamedDecl *ToD = nullptr;
  4365. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4366. return std::move(Err);
  4367. if (ToD)
  4368. return ToD;
  4369. Error Err = Error::success();
  4370. auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
  4371. auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
  4372. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  4373. auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
  4374. if (Err)
  4375. return std::move(Err);
  4376. DeclarationNameInfo NameInfo(Name, ToLoc);
  4377. if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
  4378. return std::move(Err);
  4379. UnresolvedUsingValueDecl *ToUsingValue;
  4380. if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
  4381. ToUsingLoc, ToQualifierLoc, NameInfo,
  4382. ToEllipsisLoc))
  4383. return ToUsingValue;
  4384. ToUsingValue->setAccess(D->getAccess());
  4385. ToUsingValue->setLexicalDeclContext(LexicalDC);
  4386. LexicalDC->addDeclInternal(ToUsingValue);
  4387. return ToUsingValue;
  4388. }
  4389. ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
  4390. UnresolvedUsingTypenameDecl *D) {
  4391. DeclContext *DC, *LexicalDC;
  4392. DeclarationName Name;
  4393. SourceLocation Loc;
  4394. NamedDecl *ToD = nullptr;
  4395. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4396. return std::move(Err);
  4397. if (ToD)
  4398. return ToD;
  4399. Error Err = Error::success();
  4400. auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
  4401. auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
  4402. auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
  4403. auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
  4404. if (Err)
  4405. return std::move(Err);
  4406. UnresolvedUsingTypenameDecl *ToUsing;
  4407. if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
  4408. ToUsingLoc, ToTypenameLoc,
  4409. ToQualifierLoc, Loc, Name, ToEllipsisLoc))
  4410. return ToUsing;
  4411. ToUsing->setAccess(D->getAccess());
  4412. ToUsing->setLexicalDeclContext(LexicalDC);
  4413. LexicalDC->addDeclInternal(ToUsing);
  4414. return ToUsing;
  4415. }
  4416. ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  4417. Decl* ToD = nullptr;
  4418. switch (D->getBuiltinTemplateKind()) {
  4419. case BuiltinTemplateKind::BTK__make_integer_seq:
  4420. ToD = Importer.getToContext().getMakeIntegerSeqDecl();
  4421. break;
  4422. case BuiltinTemplateKind::BTK__type_pack_element:
  4423. ToD = Importer.getToContext().getTypePackElementDecl();
  4424. break;
  4425. }
  4426. assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
  4427. Importer.MapImported(D, ToD);
  4428. return ToD;
  4429. }
  4430. Error ASTNodeImporter::ImportDefinition(
  4431. ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
  4432. if (To->getDefinition()) {
  4433. // Check consistency of superclass.
  4434. ObjCInterfaceDecl *FromSuper = From->getSuperClass();
  4435. if (FromSuper) {
  4436. if (auto FromSuperOrErr = import(FromSuper))
  4437. FromSuper = *FromSuperOrErr;
  4438. else
  4439. return FromSuperOrErr.takeError();
  4440. }
  4441. ObjCInterfaceDecl *ToSuper = To->getSuperClass();
  4442. if ((bool)FromSuper != (bool)ToSuper ||
  4443. (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
  4444. Importer.ToDiag(To->getLocation(),
  4445. diag::warn_odr_objc_superclass_inconsistent)
  4446. << To->getDeclName();
  4447. if (ToSuper)
  4448. Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
  4449. << To->getSuperClass()->getDeclName();
  4450. else
  4451. Importer.ToDiag(To->getLocation(),
  4452. diag::note_odr_objc_missing_superclass);
  4453. if (From->getSuperClass())
  4454. Importer.FromDiag(From->getSuperClassLoc(),
  4455. diag::note_odr_objc_superclass)
  4456. << From->getSuperClass()->getDeclName();
  4457. else
  4458. Importer.FromDiag(From->getLocation(),
  4459. diag::note_odr_objc_missing_superclass);
  4460. }
  4461. if (shouldForceImportDeclContext(Kind))
  4462. if (Error Err = ImportDeclContext(From))
  4463. return Err;
  4464. return Error::success();
  4465. }
  4466. // Start the definition.
  4467. To->startDefinition();
  4468. // If this class has a superclass, import it.
  4469. if (From->getSuperClass()) {
  4470. if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
  4471. To->setSuperClass(*SuperTInfoOrErr);
  4472. else
  4473. return SuperTInfoOrErr.takeError();
  4474. }
  4475. // Import protocols
  4476. SmallVector<ObjCProtocolDecl *, 4> Protocols;
  4477. SmallVector<SourceLocation, 4> ProtocolLocs;
  4478. ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
  4479. From->protocol_loc_begin();
  4480. for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
  4481. FromProtoEnd = From->protocol_end();
  4482. FromProto != FromProtoEnd;
  4483. ++FromProto, ++FromProtoLoc) {
  4484. if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
  4485. Protocols.push_back(*ToProtoOrErr);
  4486. else
  4487. return ToProtoOrErr.takeError();
  4488. if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
  4489. ProtocolLocs.push_back(*ToProtoLocOrErr);
  4490. else
  4491. return ToProtoLocOrErr.takeError();
  4492. }
  4493. // FIXME: If we're merging, make sure that the protocol list is the same.
  4494. To->setProtocolList(Protocols.data(), Protocols.size(),
  4495. ProtocolLocs.data(), Importer.getToContext());
  4496. // Import categories. When the categories themselves are imported, they'll
  4497. // hook themselves into this interface.
  4498. for (auto *Cat : From->known_categories()) {
  4499. auto ToCatOrErr = import(Cat);
  4500. if (!ToCatOrErr)
  4501. return ToCatOrErr.takeError();
  4502. }
  4503. // If we have an @implementation, import it as well.
  4504. if (From->getImplementation()) {
  4505. if (Expected<ObjCImplementationDecl *> ToImplOrErr =
  4506. import(From->getImplementation()))
  4507. To->setImplementation(*ToImplOrErr);
  4508. else
  4509. return ToImplOrErr.takeError();
  4510. }
  4511. // Import all of the members of this class.
  4512. if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
  4513. return Err;
  4514. return Error::success();
  4515. }
  4516. Expected<ObjCTypeParamList *>
  4517. ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
  4518. if (!list)
  4519. return nullptr;
  4520. SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
  4521. for (auto *fromTypeParam : *list) {
  4522. if (auto toTypeParamOrErr = import(fromTypeParam))
  4523. toTypeParams.push_back(*toTypeParamOrErr);
  4524. else
  4525. return toTypeParamOrErr.takeError();
  4526. }
  4527. auto LAngleLocOrErr = import(list->getLAngleLoc());
  4528. if (!LAngleLocOrErr)
  4529. return LAngleLocOrErr.takeError();
  4530. auto RAngleLocOrErr = import(list->getRAngleLoc());
  4531. if (!RAngleLocOrErr)
  4532. return RAngleLocOrErr.takeError();
  4533. return ObjCTypeParamList::create(Importer.getToContext(),
  4534. *LAngleLocOrErr,
  4535. toTypeParams,
  4536. *RAngleLocOrErr);
  4537. }
  4538. ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  4539. // If this class has a definition in the translation unit we're coming from,
  4540. // but this particular declaration is not that definition, import the
  4541. // definition and map to that.
  4542. ObjCInterfaceDecl *Definition = D->getDefinition();
  4543. if (Definition && Definition != D) {
  4544. if (ExpectedDecl ImportedDefOrErr = import(Definition))
  4545. return Importer.MapImported(D, *ImportedDefOrErr);
  4546. else
  4547. return ImportedDefOrErr.takeError();
  4548. }
  4549. // Import the major distinguishing characteristics of an @interface.
  4550. DeclContext *DC, *LexicalDC;
  4551. DeclarationName Name;
  4552. SourceLocation Loc;
  4553. NamedDecl *ToD;
  4554. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4555. return std::move(Err);
  4556. if (ToD)
  4557. return ToD;
  4558. // Look for an existing interface with the same name.
  4559. ObjCInterfaceDecl *MergeWithIface = nullptr;
  4560. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  4561. for (auto *FoundDecl : FoundDecls) {
  4562. if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  4563. continue;
  4564. if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
  4565. break;
  4566. }
  4567. // Create an interface declaration, if one does not already exist.
  4568. ObjCInterfaceDecl *ToIface = MergeWithIface;
  4569. if (!ToIface) {
  4570. ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
  4571. if (!AtBeginLocOrErr)
  4572. return AtBeginLocOrErr.takeError();
  4573. if (GetImportedOrCreateDecl(
  4574. ToIface, D, Importer.getToContext(), DC,
  4575. *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
  4576. /*TypeParamList=*/nullptr,
  4577. /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
  4578. return ToIface;
  4579. ToIface->setLexicalDeclContext(LexicalDC);
  4580. LexicalDC->addDeclInternal(ToIface);
  4581. }
  4582. Importer.MapImported(D, ToIface);
  4583. // Import the type parameter list after MapImported, to avoid
  4584. // loops when bringing in their DeclContext.
  4585. if (auto ToPListOrErr =
  4586. ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
  4587. ToIface->setTypeParamList(*ToPListOrErr);
  4588. else
  4589. return ToPListOrErr.takeError();
  4590. if (D->isThisDeclarationADefinition())
  4591. if (Error Err = ImportDefinition(D, ToIface))
  4592. return std::move(Err);
  4593. return ToIface;
  4594. }
  4595. ExpectedDecl
  4596. ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
  4597. ObjCCategoryDecl *Category;
  4598. if (Error Err = importInto(Category, D->getCategoryDecl()))
  4599. return std::move(Err);
  4600. ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
  4601. if (!ToImpl) {
  4602. DeclContext *DC, *LexicalDC;
  4603. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  4604. return std::move(Err);
  4605. Error Err = Error::success();
  4606. auto ToLocation = importChecked(Err, D->getLocation());
  4607. auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
  4608. auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
  4609. if (Err)
  4610. return std::move(Err);
  4611. if (GetImportedOrCreateDecl(
  4612. ToImpl, D, Importer.getToContext(), DC,
  4613. Importer.Import(D->getIdentifier()), Category->getClassInterface(),
  4614. ToLocation, ToAtStartLoc, ToCategoryNameLoc))
  4615. return ToImpl;
  4616. ToImpl->setLexicalDeclContext(LexicalDC);
  4617. LexicalDC->addDeclInternal(ToImpl);
  4618. Category->setImplementation(ToImpl);
  4619. }
  4620. Importer.MapImported(D, ToImpl);
  4621. if (Error Err = ImportDeclContext(D))
  4622. return std::move(Err);
  4623. return ToImpl;
  4624. }
  4625. ExpectedDecl
  4626. ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
  4627. // Find the corresponding interface.
  4628. ObjCInterfaceDecl *Iface;
  4629. if (Error Err = importInto(Iface, D->getClassInterface()))
  4630. return std::move(Err);
  4631. // Import the superclass, if any.
  4632. ObjCInterfaceDecl *Super;
  4633. if (Error Err = importInto(Super, D->getSuperClass()))
  4634. return std::move(Err);
  4635. ObjCImplementationDecl *Impl = Iface->getImplementation();
  4636. if (!Impl) {
  4637. // We haven't imported an implementation yet. Create a new @implementation
  4638. // now.
  4639. DeclContext *DC, *LexicalDC;
  4640. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  4641. return std::move(Err);
  4642. Error Err = Error::success();
  4643. auto ToLocation = importChecked(Err, D->getLocation());
  4644. auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
  4645. auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
  4646. auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
  4647. auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
  4648. if (Err)
  4649. return std::move(Err);
  4650. if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
  4651. DC, Iface, Super,
  4652. ToLocation,
  4653. ToAtStartLoc,
  4654. ToSuperClassLoc,
  4655. ToIvarLBraceLoc,
  4656. ToIvarRBraceLoc))
  4657. return Impl;
  4658. Impl->setLexicalDeclContext(LexicalDC);
  4659. // Associate the implementation with the class it implements.
  4660. Iface->setImplementation(Impl);
  4661. Importer.MapImported(D, Iface->getImplementation());
  4662. } else {
  4663. Importer.MapImported(D, Iface->getImplementation());
  4664. // Verify that the existing @implementation has the same superclass.
  4665. if ((Super && !Impl->getSuperClass()) ||
  4666. (!Super && Impl->getSuperClass()) ||
  4667. (Super && Impl->getSuperClass() &&
  4668. !declaresSameEntity(Super->getCanonicalDecl(),
  4669. Impl->getSuperClass()))) {
  4670. Importer.ToDiag(Impl->getLocation(),
  4671. diag::warn_odr_objc_superclass_inconsistent)
  4672. << Iface->getDeclName();
  4673. // FIXME: It would be nice to have the location of the superclass
  4674. // below.
  4675. if (Impl->getSuperClass())
  4676. Importer.ToDiag(Impl->getLocation(),
  4677. diag::note_odr_objc_superclass)
  4678. << Impl->getSuperClass()->getDeclName();
  4679. else
  4680. Importer.ToDiag(Impl->getLocation(),
  4681. diag::note_odr_objc_missing_superclass);
  4682. if (D->getSuperClass())
  4683. Importer.FromDiag(D->getLocation(),
  4684. diag::note_odr_objc_superclass)
  4685. << D->getSuperClass()->getDeclName();
  4686. else
  4687. Importer.FromDiag(D->getLocation(),
  4688. diag::note_odr_objc_missing_superclass);
  4689. return make_error<ASTImportError>(ASTImportError::NameConflict);
  4690. }
  4691. }
  4692. // Import all of the members of this @implementation.
  4693. if (Error Err = ImportDeclContext(D))
  4694. return std::move(Err);
  4695. return Impl;
  4696. }
  4697. ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
  4698. // Import the major distinguishing characteristics of an @property.
  4699. DeclContext *DC, *LexicalDC;
  4700. DeclarationName Name;
  4701. SourceLocation Loc;
  4702. NamedDecl *ToD;
  4703. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4704. return std::move(Err);
  4705. if (ToD)
  4706. return ToD;
  4707. // Check whether we have already imported this property.
  4708. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  4709. for (auto *FoundDecl : FoundDecls) {
  4710. if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
  4711. // Instance and class properties can share the same name but are different
  4712. // declarations.
  4713. if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
  4714. continue;
  4715. // Check property types.
  4716. if (!Importer.IsStructurallyEquivalent(D->getType(),
  4717. FoundProp->getType())) {
  4718. Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
  4719. << Name << D->getType() << FoundProp->getType();
  4720. Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
  4721. << FoundProp->getType();
  4722. return make_error<ASTImportError>(ASTImportError::NameConflict);
  4723. }
  4724. // FIXME: Check property attributes, getters, setters, etc.?
  4725. // Consider these properties to be equivalent.
  4726. Importer.MapImported(D, FoundProp);
  4727. return FoundProp;
  4728. }
  4729. }
  4730. Error Err = Error::success();
  4731. auto ToType = importChecked(Err, D->getType());
  4732. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  4733. auto ToAtLoc = importChecked(Err, D->getAtLoc());
  4734. auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
  4735. if (Err)
  4736. return std::move(Err);
  4737. // Create the new property.
  4738. ObjCPropertyDecl *ToProperty;
  4739. if (GetImportedOrCreateDecl(
  4740. ToProperty, D, Importer.getToContext(), DC, Loc,
  4741. Name.getAsIdentifierInfo(), ToAtLoc,
  4742. ToLParenLoc, ToType,
  4743. ToTypeSourceInfo, D->getPropertyImplementation()))
  4744. return ToProperty;
  4745. auto ToGetterName = importChecked(Err, D->getGetterName());
  4746. auto ToSetterName = importChecked(Err, D->getSetterName());
  4747. auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
  4748. auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
  4749. auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
  4750. auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
  4751. auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
  4752. if (Err)
  4753. return std::move(Err);
  4754. ToProperty->setLexicalDeclContext(LexicalDC);
  4755. LexicalDC->addDeclInternal(ToProperty);
  4756. ToProperty->setPropertyAttributes(D->getPropertyAttributes());
  4757. ToProperty->setPropertyAttributesAsWritten(
  4758. D->getPropertyAttributesAsWritten());
  4759. ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
  4760. ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
  4761. ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
  4762. ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
  4763. ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
  4764. return ToProperty;
  4765. }
  4766. ExpectedDecl
  4767. ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
  4768. ObjCPropertyDecl *Property;
  4769. if (Error Err = importInto(Property, D->getPropertyDecl()))
  4770. return std::move(Err);
  4771. DeclContext *DC, *LexicalDC;
  4772. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  4773. return std::move(Err);
  4774. auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
  4775. // Import the ivar (for an @synthesize).
  4776. ObjCIvarDecl *Ivar = nullptr;
  4777. if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
  4778. return std::move(Err);
  4779. ObjCPropertyImplDecl *ToImpl
  4780. = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
  4781. Property->getQueryKind());
  4782. if (!ToImpl) {
  4783. Error Err = Error::success();
  4784. auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
  4785. auto ToLocation = importChecked(Err, D->getLocation());
  4786. auto ToPropertyIvarDeclLoc =
  4787. importChecked(Err, D->getPropertyIvarDeclLoc());
  4788. if (Err)
  4789. return std::move(Err);
  4790. if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
  4791. ToBeginLoc,
  4792. ToLocation, Property,
  4793. D->getPropertyImplementation(), Ivar,
  4794. ToPropertyIvarDeclLoc))
  4795. return ToImpl;
  4796. ToImpl->setLexicalDeclContext(LexicalDC);
  4797. LexicalDC->addDeclInternal(ToImpl);
  4798. } else {
  4799. // Check that we have the same kind of property implementation (@synthesize
  4800. // vs. @dynamic).
  4801. if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
  4802. Importer.ToDiag(ToImpl->getLocation(),
  4803. diag::warn_odr_objc_property_impl_kind_inconsistent)
  4804. << Property->getDeclName()
  4805. << (ToImpl->getPropertyImplementation()
  4806. == ObjCPropertyImplDecl::Dynamic);
  4807. Importer.FromDiag(D->getLocation(),
  4808. diag::note_odr_objc_property_impl_kind)
  4809. << D->getPropertyDecl()->getDeclName()
  4810. << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
  4811. return make_error<ASTImportError>(ASTImportError::NameConflict);
  4812. }
  4813. // For @synthesize, check that we have the same
  4814. if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
  4815. Ivar != ToImpl->getPropertyIvarDecl()) {
  4816. Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
  4817. diag::warn_odr_objc_synthesize_ivar_inconsistent)
  4818. << Property->getDeclName()
  4819. << ToImpl->getPropertyIvarDecl()->getDeclName()
  4820. << Ivar->getDeclName();
  4821. Importer.FromDiag(D->getPropertyIvarDeclLoc(),
  4822. diag::note_odr_objc_synthesize_ivar_here)
  4823. << D->getPropertyIvarDecl()->getDeclName();
  4824. return make_error<ASTImportError>(ASTImportError::NameConflict);
  4825. }
  4826. // Merge the existing implementation with the new implementation.
  4827. Importer.MapImported(D, ToImpl);
  4828. }
  4829. return ToImpl;
  4830. }
  4831. ExpectedDecl
  4832. ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
  4833. // For template arguments, we adopt the translation unit as our declaration
  4834. // context. This context will be fixed when the actual template declaration
  4835. // is created.
  4836. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  4837. if (!BeginLocOrErr)
  4838. return BeginLocOrErr.takeError();
  4839. ExpectedSLoc LocationOrErr = import(D->getLocation());
  4840. if (!LocationOrErr)
  4841. return LocationOrErr.takeError();
  4842. TemplateTypeParmDecl *ToD = nullptr;
  4843. if (GetImportedOrCreateDecl(
  4844. ToD, D, Importer.getToContext(),
  4845. Importer.getToContext().getTranslationUnitDecl(),
  4846. *BeginLocOrErr, *LocationOrErr,
  4847. D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
  4848. D->wasDeclaredWithTypename(), D->isParameterPack(),
  4849. D->hasTypeConstraint()))
  4850. return ToD;
  4851. // Import the type-constraint
  4852. if (const TypeConstraint *TC = D->getTypeConstraint()) {
  4853. Error Err = Error::success();
  4854. auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc());
  4855. auto ToName = importChecked(Err, TC->getConceptNameInfo().getName());
  4856. auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc());
  4857. auto ToFoundDecl = importChecked(Err, TC->getFoundDecl());
  4858. auto ToNamedConcept = importChecked(Err, TC->getNamedConcept());
  4859. auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
  4860. if (Err)
  4861. return std::move(Err);
  4862. TemplateArgumentListInfo ToTAInfo;
  4863. const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten();
  4864. if (ASTTemplateArgs)
  4865. if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs,
  4866. ToTAInfo))
  4867. return std::move(Err);
  4868. ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc),
  4869. ToFoundDecl, ToNamedConcept,
  4870. ASTTemplateArgs ?
  4871. ASTTemplateArgumentListInfo::Create(Importer.getToContext(),
  4872. ToTAInfo) : nullptr,
  4873. ToIDC);
  4874. }
  4875. if (D->hasDefaultArgument()) {
  4876. Expected<TypeSourceInfo *> ToDefaultArgOrErr =
  4877. import(D->getDefaultArgumentInfo());
  4878. if (!ToDefaultArgOrErr)
  4879. return ToDefaultArgOrErr.takeError();
  4880. ToD->setDefaultArgument(*ToDefaultArgOrErr);
  4881. }
  4882. return ToD;
  4883. }
  4884. ExpectedDecl
  4885. ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  4886. Error Err = Error::success();
  4887. auto ToDeclName = importChecked(Err, D->getDeclName());
  4888. auto ToLocation = importChecked(Err, D->getLocation());
  4889. auto ToType = importChecked(Err, D->getType());
  4890. auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
  4891. auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
  4892. if (Err)
  4893. return std::move(Err);
  4894. NonTypeTemplateParmDecl *ToD = nullptr;
  4895. if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
  4896. Importer.getToContext().getTranslationUnitDecl(),
  4897. ToInnerLocStart, ToLocation, D->getDepth(),
  4898. D->getPosition(),
  4899. ToDeclName.getAsIdentifierInfo(), ToType,
  4900. D->isParameterPack(), ToTypeSourceInfo))
  4901. return ToD;
  4902. if (D->hasDefaultArgument()) {
  4903. ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
  4904. if (!ToDefaultArgOrErr)
  4905. return ToDefaultArgOrErr.takeError();
  4906. ToD->setDefaultArgument(*ToDefaultArgOrErr);
  4907. }
  4908. return ToD;
  4909. }
  4910. ExpectedDecl
  4911. ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
  4912. // Import the name of this declaration.
  4913. auto NameOrErr = import(D->getDeclName());
  4914. if (!NameOrErr)
  4915. return NameOrErr.takeError();
  4916. // Import the location of this declaration.
  4917. ExpectedSLoc LocationOrErr = import(D->getLocation());
  4918. if (!LocationOrErr)
  4919. return LocationOrErr.takeError();
  4920. // Import template parameters.
  4921. auto TemplateParamsOrErr = import(D->getTemplateParameters());
  4922. if (!TemplateParamsOrErr)
  4923. return TemplateParamsOrErr.takeError();
  4924. TemplateTemplateParmDecl *ToD = nullptr;
  4925. if (GetImportedOrCreateDecl(
  4926. ToD, D, Importer.getToContext(),
  4927. Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
  4928. D->getDepth(), D->getPosition(), D->isParameterPack(),
  4929. (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
  4930. return ToD;
  4931. if (D->hasDefaultArgument()) {
  4932. Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
  4933. import(D->getDefaultArgument());
  4934. if (!ToDefaultArgOrErr)
  4935. return ToDefaultArgOrErr.takeError();
  4936. ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
  4937. }
  4938. return ToD;
  4939. }
  4940. // Returns the definition for a (forward) declaration of a TemplateDecl, if
  4941. // it has any definition in the redecl chain.
  4942. template <typename T> static auto getTemplateDefinition(T *D) -> T * {
  4943. assert(D->getTemplatedDecl() && "Should be called on templates only");
  4944. auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
  4945. if (!ToTemplatedDef)
  4946. return nullptr;
  4947. auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
  4948. return cast_or_null<T>(TemplateWithDef);
  4949. }
  4950. ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  4951. // Import the major distinguishing characteristics of this class template.
  4952. DeclContext *DC, *LexicalDC;
  4953. DeclarationName Name;
  4954. SourceLocation Loc;
  4955. NamedDecl *ToD;
  4956. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  4957. return std::move(Err);
  4958. if (ToD)
  4959. return ToD;
  4960. ClassTemplateDecl *FoundByLookup = nullptr;
  4961. // We may already have a template of the same name; try to find and match it.
  4962. if (!DC->isFunctionOrMethod()) {
  4963. SmallVector<NamedDecl *, 4> ConflictingDecls;
  4964. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  4965. for (auto *FoundDecl : FoundDecls) {
  4966. if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
  4967. Decl::IDNS_TagFriend))
  4968. continue;
  4969. Decl *Found = FoundDecl;
  4970. auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
  4971. if (FoundTemplate) {
  4972. if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
  4973. continue;
  4974. if (IsStructuralMatch(D, FoundTemplate)) {
  4975. ClassTemplateDecl *TemplateWithDef =
  4976. getTemplateDefinition(FoundTemplate);
  4977. if (D->isThisDeclarationADefinition() && TemplateWithDef)
  4978. return Importer.MapImported(D, TemplateWithDef);
  4979. if (!FoundByLookup)
  4980. FoundByLookup = FoundTemplate;
  4981. // Search in all matches because there may be multiple decl chains,
  4982. // see ASTTests test ImportExistingFriendClassTemplateDef.
  4983. continue;
  4984. }
  4985. ConflictingDecls.push_back(FoundDecl);
  4986. }
  4987. }
  4988. if (!ConflictingDecls.empty()) {
  4989. ExpectedName NameOrErr = Importer.HandleNameConflict(
  4990. Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
  4991. ConflictingDecls.size());
  4992. if (NameOrErr)
  4993. Name = NameOrErr.get();
  4994. else
  4995. return NameOrErr.takeError();
  4996. }
  4997. }
  4998. CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
  4999. auto TemplateParamsOrErr = import(D->getTemplateParameters());
  5000. if (!TemplateParamsOrErr)
  5001. return TemplateParamsOrErr.takeError();
  5002. // Create the declaration that is being templated.
  5003. CXXRecordDecl *ToTemplated;
  5004. if (Error Err = importInto(ToTemplated, FromTemplated))
  5005. return std::move(Err);
  5006. // Create the class template declaration itself.
  5007. ClassTemplateDecl *D2;
  5008. if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
  5009. *TemplateParamsOrErr, ToTemplated))
  5010. return D2;
  5011. ToTemplated->setDescribedClassTemplate(D2);
  5012. D2->setAccess(D->getAccess());
  5013. D2->setLexicalDeclContext(LexicalDC);
  5014. addDeclToContexts(D, D2);
  5015. updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
  5016. if (FoundByLookup) {
  5017. auto *Recent =
  5018. const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
  5019. // It is possible that during the import of the class template definition
  5020. // we start the import of a fwd friend decl of the very same class template
  5021. // and we add the fwd friend decl to the lookup table. But the ToTemplated
  5022. // had been created earlier and by that time the lookup could not find
  5023. // anything existing, so it has no previous decl. Later, (still during the
  5024. // import of the fwd friend decl) we start to import the definition again
  5025. // and this time the lookup finds the previous fwd friend class template.
  5026. // In this case we must set up the previous decl for the templated decl.
  5027. if (!ToTemplated->getPreviousDecl()) {
  5028. assert(FoundByLookup->getTemplatedDecl() &&
  5029. "Found decl must have its templated decl set");
  5030. CXXRecordDecl *PrevTemplated =
  5031. FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
  5032. if (ToTemplated != PrevTemplated)
  5033. ToTemplated->setPreviousDecl(PrevTemplated);
  5034. }
  5035. D2->setPreviousDecl(Recent);
  5036. }
  5037. return D2;
  5038. }
  5039. ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
  5040. ClassTemplateSpecializationDecl *D) {
  5041. ClassTemplateDecl *ClassTemplate;
  5042. if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
  5043. return std::move(Err);
  5044. // Import the context of this declaration.
  5045. DeclContext *DC, *LexicalDC;
  5046. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  5047. return std::move(Err);
  5048. // Import template arguments.
  5049. SmallVector<TemplateArgument, 2> TemplateArgs;
  5050. if (Error Err =
  5051. ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
  5052. return std::move(Err);
  5053. // Try to find an existing specialization with these template arguments and
  5054. // template parameter list.
  5055. void *InsertPos = nullptr;
  5056. ClassTemplateSpecializationDecl *PrevDecl = nullptr;
  5057. ClassTemplatePartialSpecializationDecl *PartialSpec =
  5058. dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
  5059. // Import template parameters.
  5060. TemplateParameterList *ToTPList = nullptr;
  5061. if (PartialSpec) {
  5062. auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
  5063. if (!ToTPListOrErr)
  5064. return ToTPListOrErr.takeError();
  5065. ToTPList = *ToTPListOrErr;
  5066. PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
  5067. *ToTPListOrErr,
  5068. InsertPos);
  5069. } else
  5070. PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
  5071. if (PrevDecl) {
  5072. if (IsStructuralMatch(D, PrevDecl)) {
  5073. CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
  5074. if (D->isThisDeclarationADefinition() && PrevDefinition) {
  5075. Importer.MapImported(D, PrevDefinition);
  5076. // Import those default field initializers which have been
  5077. // instantiated in the "From" context, but not in the "To" context.
  5078. for (auto *FromField : D->fields()) {
  5079. auto ToOrErr = import(FromField);
  5080. if (!ToOrErr)
  5081. return ToOrErr.takeError();
  5082. }
  5083. // Import those methods which have been instantiated in the
  5084. // "From" context, but not in the "To" context.
  5085. for (CXXMethodDecl *FromM : D->methods()) {
  5086. auto ToOrErr = import(FromM);
  5087. if (!ToOrErr)
  5088. return ToOrErr.takeError();
  5089. }
  5090. // TODO Import instantiated default arguments.
  5091. // TODO Import instantiated exception specifications.
  5092. //
  5093. // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
  5094. // what else could be fused during an AST merge.
  5095. return PrevDefinition;
  5096. }
  5097. } else { // ODR violation.
  5098. // FIXME HandleNameConflict
  5099. return make_error<ASTImportError>(ASTImportError::NameConflict);
  5100. }
  5101. }
  5102. // Import the location of this declaration.
  5103. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  5104. if (!BeginLocOrErr)
  5105. return BeginLocOrErr.takeError();
  5106. ExpectedSLoc IdLocOrErr = import(D->getLocation());
  5107. if (!IdLocOrErr)
  5108. return IdLocOrErr.takeError();
  5109. // Create the specialization.
  5110. ClassTemplateSpecializationDecl *D2 = nullptr;
  5111. if (PartialSpec) {
  5112. // Import TemplateArgumentListInfo.
  5113. TemplateArgumentListInfo ToTAInfo;
  5114. const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
  5115. if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
  5116. return std::move(Err);
  5117. QualType CanonInjType;
  5118. if (Error Err = importInto(
  5119. CanonInjType, PartialSpec->getInjectedSpecializationType()))
  5120. return std::move(Err);
  5121. CanonInjType = CanonInjType.getCanonicalType();
  5122. if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
  5123. D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr,
  5124. *IdLocOrErr, ToTPList, ClassTemplate,
  5125. llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()), ToTAInfo,
  5126. CanonInjType,
  5127. cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
  5128. return D2;
  5129. // Update InsertPos, because preceding import calls may have invalidated
  5130. // it by adding new specializations.
  5131. auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
  5132. if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
  5133. InsertPos))
  5134. // Add this partial specialization to the class template.
  5135. ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
  5136. updateLookupTableForTemplateParameters(*ToTPList);
  5137. } else { // Not a partial specialization.
  5138. if (GetImportedOrCreateDecl(
  5139. D2, D, Importer.getToContext(), D->getTagKind(), DC,
  5140. *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
  5141. PrevDecl))
  5142. return D2;
  5143. // Update InsertPos, because preceding import calls may have invalidated
  5144. // it by adding new specializations.
  5145. if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
  5146. // Add this specialization to the class template.
  5147. ClassTemplate->AddSpecialization(D2, InsertPos);
  5148. }
  5149. D2->setSpecializationKind(D->getSpecializationKind());
  5150. // Set the context of this specialization/instantiation.
  5151. D2->setLexicalDeclContext(LexicalDC);
  5152. // Add to the DC only if it was an explicit specialization/instantiation.
  5153. if (D2->isExplicitInstantiationOrSpecialization()) {
  5154. LexicalDC->addDeclInternal(D2);
  5155. }
  5156. if (auto BraceRangeOrErr = import(D->getBraceRange()))
  5157. D2->setBraceRange(*BraceRangeOrErr);
  5158. else
  5159. return BraceRangeOrErr.takeError();
  5160. // Import the qualifier, if any.
  5161. if (auto LocOrErr = import(D->getQualifierLoc()))
  5162. D2->setQualifierInfo(*LocOrErr);
  5163. else
  5164. return LocOrErr.takeError();
  5165. if (auto *TSI = D->getTypeAsWritten()) {
  5166. if (auto TInfoOrErr = import(TSI))
  5167. D2->setTypeAsWritten(*TInfoOrErr);
  5168. else
  5169. return TInfoOrErr.takeError();
  5170. if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
  5171. D2->setTemplateKeywordLoc(*LocOrErr);
  5172. else
  5173. return LocOrErr.takeError();
  5174. if (auto LocOrErr = import(D->getExternLoc()))
  5175. D2->setExternLoc(*LocOrErr);
  5176. else
  5177. return LocOrErr.takeError();
  5178. }
  5179. if (D->getPointOfInstantiation().isValid()) {
  5180. if (auto POIOrErr = import(D->getPointOfInstantiation()))
  5181. D2->setPointOfInstantiation(*POIOrErr);
  5182. else
  5183. return POIOrErr.takeError();
  5184. }
  5185. D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
  5186. if (auto P = D->getInstantiatedFrom()) {
  5187. if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) {
  5188. if (auto CTDorErr = import(CTD))
  5189. D2->setInstantiationOf(*CTDorErr);
  5190. } else {
  5191. auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(P);
  5192. auto CTPSDOrErr = import(CTPSD);
  5193. if (!CTPSDOrErr)
  5194. return CTPSDOrErr.takeError();
  5195. const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs();
  5196. SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size());
  5197. for (unsigned I = 0; I < DArgs.size(); ++I) {
  5198. const TemplateArgument &DArg = DArgs[I];
  5199. if (auto ArgOrErr = import(DArg))
  5200. D2ArgsVec[I] = *ArgOrErr;
  5201. else
  5202. return ArgOrErr.takeError();
  5203. }
  5204. D2->setInstantiationOf(
  5205. *CTPSDOrErr,
  5206. TemplateArgumentList::CreateCopy(Importer.getToContext(), D2ArgsVec));
  5207. }
  5208. }
  5209. if (D->isCompleteDefinition())
  5210. if (Error Err = ImportDefinition(D, D2))
  5211. return std::move(Err);
  5212. return D2;
  5213. }
  5214. ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
  5215. // Import the major distinguishing characteristics of this variable template.
  5216. DeclContext *DC, *LexicalDC;
  5217. DeclarationName Name;
  5218. SourceLocation Loc;
  5219. NamedDecl *ToD;
  5220. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  5221. return std::move(Err);
  5222. if (ToD)
  5223. return ToD;
  5224. // We may already have a template of the same name; try to find and match it.
  5225. assert(!DC->isFunctionOrMethod() &&
  5226. "Variable templates cannot be declared at function scope");
  5227. SmallVector<NamedDecl *, 4> ConflictingDecls;
  5228. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  5229. VarTemplateDecl *FoundByLookup = nullptr;
  5230. for (auto *FoundDecl : FoundDecls) {
  5231. if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  5232. continue;
  5233. if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
  5234. // Use the templated decl, some linkage flags are set only there.
  5235. if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
  5236. D->getTemplatedDecl()))
  5237. continue;
  5238. if (IsStructuralMatch(D, FoundTemplate)) {
  5239. // The Decl in the "From" context has a definition, but in the
  5240. // "To" context we already have a definition.
  5241. VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
  5242. if (D->isThisDeclarationADefinition() && FoundDef)
  5243. // FIXME Check for ODR error if the two definitions have
  5244. // different initializers?
  5245. return Importer.MapImported(D, FoundDef);
  5246. FoundByLookup = FoundTemplate;
  5247. break;
  5248. }
  5249. ConflictingDecls.push_back(FoundDecl);
  5250. }
  5251. }
  5252. if (!ConflictingDecls.empty()) {
  5253. ExpectedName NameOrErr = Importer.HandleNameConflict(
  5254. Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
  5255. ConflictingDecls.size());
  5256. if (NameOrErr)
  5257. Name = NameOrErr.get();
  5258. else
  5259. return NameOrErr.takeError();
  5260. }
  5261. VarDecl *DTemplated = D->getTemplatedDecl();
  5262. // Import the type.
  5263. // FIXME: Value not used?
  5264. ExpectedType TypeOrErr = import(DTemplated->getType());
  5265. if (!TypeOrErr)
  5266. return TypeOrErr.takeError();
  5267. // Create the declaration that is being templated.
  5268. VarDecl *ToTemplated;
  5269. if (Error Err = importInto(ToTemplated, DTemplated))
  5270. return std::move(Err);
  5271. // Create the variable template declaration itself.
  5272. auto TemplateParamsOrErr = import(D->getTemplateParameters());
  5273. if (!TemplateParamsOrErr)
  5274. return TemplateParamsOrErr.takeError();
  5275. VarTemplateDecl *ToVarTD;
  5276. if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
  5277. Name, *TemplateParamsOrErr, ToTemplated))
  5278. return ToVarTD;
  5279. ToTemplated->setDescribedVarTemplate(ToVarTD);
  5280. ToVarTD->setAccess(D->getAccess());
  5281. ToVarTD->setLexicalDeclContext(LexicalDC);
  5282. LexicalDC->addDeclInternal(ToVarTD);
  5283. if (DC != Importer.getToContext().getTranslationUnitDecl())
  5284. updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
  5285. if (FoundByLookup) {
  5286. auto *Recent =
  5287. const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
  5288. if (!ToTemplated->getPreviousDecl()) {
  5289. auto *PrevTemplated =
  5290. FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
  5291. if (ToTemplated != PrevTemplated)
  5292. ToTemplated->setPreviousDecl(PrevTemplated);
  5293. }
  5294. ToVarTD->setPreviousDecl(Recent);
  5295. }
  5296. return ToVarTD;
  5297. }
  5298. ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
  5299. VarTemplateSpecializationDecl *D) {
  5300. // If this record has a definition in the translation unit we're coming from,
  5301. // but this particular declaration is not that definition, import the
  5302. // definition and map to that.
  5303. VarDecl *Definition = D->getDefinition();
  5304. if (Definition && Definition != D) {
  5305. if (ExpectedDecl ImportedDefOrErr = import(Definition))
  5306. return Importer.MapImported(D, *ImportedDefOrErr);
  5307. else
  5308. return ImportedDefOrErr.takeError();
  5309. }
  5310. VarTemplateDecl *VarTemplate = nullptr;
  5311. if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
  5312. return std::move(Err);
  5313. // Import the context of this declaration.
  5314. DeclContext *DC, *LexicalDC;
  5315. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  5316. return std::move(Err);
  5317. // Import the location of this declaration.
  5318. ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
  5319. if (!BeginLocOrErr)
  5320. return BeginLocOrErr.takeError();
  5321. auto IdLocOrErr = import(D->getLocation());
  5322. if (!IdLocOrErr)
  5323. return IdLocOrErr.takeError();
  5324. // Import template arguments.
  5325. SmallVector<TemplateArgument, 2> TemplateArgs;
  5326. if (Error Err =
  5327. ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
  5328. return std::move(Err);
  5329. // Try to find an existing specialization with these template arguments.
  5330. void *InsertPos = nullptr;
  5331. VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
  5332. TemplateArgs, InsertPos);
  5333. if (D2) {
  5334. // We already have a variable template specialization with these template
  5335. // arguments.
  5336. // FIXME: Check for specialization vs. instantiation errors.
  5337. if (VarDecl *FoundDef = D2->getDefinition()) {
  5338. if (!D->isThisDeclarationADefinition() ||
  5339. IsStructuralMatch(D, FoundDef)) {
  5340. // The record types structurally match, or the "from" translation
  5341. // unit only had a forward declaration anyway; call it the same
  5342. // variable.
  5343. return Importer.MapImported(D, FoundDef);
  5344. }
  5345. }
  5346. } else {
  5347. TemplateArgumentListInfo ToTAInfo;
  5348. if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) {
  5349. if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo))
  5350. return std::move(Err);
  5351. }
  5352. using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
  5353. // Create a new specialization.
  5354. if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
  5355. // Import TemplateArgumentListInfo
  5356. TemplateArgumentListInfo ArgInfos;
  5357. const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
  5358. // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
  5359. if (Error Err = ImportTemplateArgumentListInfo(
  5360. *FromTAArgsAsWritten, ArgInfos))
  5361. return std::move(Err);
  5362. auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
  5363. if (!ToTPListOrErr)
  5364. return ToTPListOrErr.takeError();
  5365. PartVarSpecDecl *ToPartial;
  5366. if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
  5367. *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
  5368. VarTemplate, QualType(), nullptr,
  5369. D->getStorageClass(), TemplateArgs, ArgInfos))
  5370. return ToPartial;
  5371. if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
  5372. FromPartial->getInstantiatedFromMember()))
  5373. ToPartial->setInstantiatedFromMember(*ToInstOrErr);
  5374. else
  5375. return ToInstOrErr.takeError();
  5376. if (FromPartial->isMemberSpecialization())
  5377. ToPartial->setMemberSpecialization();
  5378. D2 = ToPartial;
  5379. // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
  5380. // to adopt template parameters.
  5381. // updateLookupTableForTemplateParameters(**ToTPListOrErr);
  5382. } else { // Full specialization
  5383. if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
  5384. *BeginLocOrErr, *IdLocOrErr, VarTemplate,
  5385. QualType(), nullptr, D->getStorageClass(),
  5386. TemplateArgs))
  5387. return D2;
  5388. }
  5389. QualType T;
  5390. if (Error Err = importInto(T, D->getType()))
  5391. return std::move(Err);
  5392. D2->setType(T);
  5393. auto TInfoOrErr = import(D->getTypeSourceInfo());
  5394. if (!TInfoOrErr)
  5395. return TInfoOrErr.takeError();
  5396. D2->setTypeSourceInfo(*TInfoOrErr);
  5397. if (D->getPointOfInstantiation().isValid()) {
  5398. if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
  5399. D2->setPointOfInstantiation(*POIOrErr);
  5400. else
  5401. return POIOrErr.takeError();
  5402. }
  5403. D2->setSpecializationKind(D->getSpecializationKind());
  5404. D2->setTemplateArgsInfo(ToTAInfo);
  5405. // Add this specialization to the class template.
  5406. VarTemplate->AddSpecialization(D2, InsertPos);
  5407. // Import the qualifier, if any.
  5408. if (auto LocOrErr = import(D->getQualifierLoc()))
  5409. D2->setQualifierInfo(*LocOrErr);
  5410. else
  5411. return LocOrErr.takeError();
  5412. if (D->isConstexpr())
  5413. D2->setConstexpr(true);
  5414. // Add the specialization to this context.
  5415. D2->setLexicalDeclContext(LexicalDC);
  5416. LexicalDC->addDeclInternal(D2);
  5417. D2->setAccess(D->getAccess());
  5418. }
  5419. if (Error Err = ImportInitializer(D, D2))
  5420. return std::move(Err);
  5421. return D2;
  5422. }
  5423. ExpectedDecl
  5424. ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  5425. DeclContext *DC, *LexicalDC;
  5426. DeclarationName Name;
  5427. SourceLocation Loc;
  5428. NamedDecl *ToD;
  5429. if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
  5430. return std::move(Err);
  5431. if (ToD)
  5432. return ToD;
  5433. const FunctionTemplateDecl *FoundByLookup = nullptr;
  5434. // Try to find a function in our own ("to") context with the same name, same
  5435. // type, and in the same context as the function we're importing.
  5436. // FIXME Split this into a separate function.
  5437. if (!LexicalDC->isFunctionOrMethod()) {
  5438. unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
  5439. auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
  5440. for (auto *FoundDecl : FoundDecls) {
  5441. if (!FoundDecl->isInIdentifierNamespace(IDNS))
  5442. continue;
  5443. if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
  5444. if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
  5445. continue;
  5446. if (IsStructuralMatch(D, FoundTemplate)) {
  5447. FunctionTemplateDecl *TemplateWithDef =
  5448. getTemplateDefinition(FoundTemplate);
  5449. if (D->isThisDeclarationADefinition() && TemplateWithDef)
  5450. return Importer.MapImported(D, TemplateWithDef);
  5451. FoundByLookup = FoundTemplate;
  5452. break;
  5453. // TODO: handle conflicting names
  5454. }
  5455. }
  5456. }
  5457. }
  5458. auto ParamsOrErr = import(D->getTemplateParameters());
  5459. if (!ParamsOrErr)
  5460. return ParamsOrErr.takeError();
  5461. TemplateParameterList *Params = *ParamsOrErr;
  5462. FunctionDecl *TemplatedFD;
  5463. if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
  5464. return std::move(Err);
  5465. // At creation of the template the template parameters are "adopted"
  5466. // (DeclContext is changed). After this possible change the lookup table
  5467. // must be updated.
  5468. // At deduction guides the DeclContext of the template parameters may be
  5469. // different from what we would expect, it may be the class template, or a
  5470. // probably different CXXDeductionGuideDecl. This may come from the fact that
  5471. // the template parameter objects may be shared between deduction guides or
  5472. // the class template, and at creation of multiple FunctionTemplateDecl
  5473. // objects (for deduction guides) the same parameters are re-used. The
  5474. // "adoption" happens multiple times with different parent, even recursively
  5475. // for TemplateTemplateParmDecl. The same happens at import when the
  5476. // FunctionTemplateDecl objects are created, but in different order.
  5477. // In this way the DeclContext of these template parameters is not necessarily
  5478. // the same as in the "from" context.
  5479. SmallVector<DeclContext *, 2> OldParamDC;
  5480. OldParamDC.reserve(Params->size());
  5481. llvm::transform(*Params, std::back_inserter(OldParamDC),
  5482. [](NamedDecl *ND) { return ND->getDeclContext(); });
  5483. FunctionTemplateDecl *ToFunc;
  5484. if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
  5485. Params, TemplatedFD))
  5486. return ToFunc;
  5487. TemplatedFD->setDescribedFunctionTemplate(ToFunc);
  5488. ToFunc->setAccess(D->getAccess());
  5489. ToFunc->setLexicalDeclContext(LexicalDC);
  5490. LexicalDC->addDeclInternal(ToFunc);
  5491. ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
  5492. if (LT && !OldParamDC.empty()) {
  5493. for (unsigned int I = 0; I < OldParamDC.size(); ++I)
  5494. LT->updateForced(Params->getParam(I), OldParamDC[I]);
  5495. }
  5496. if (FoundByLookup) {
  5497. auto *Recent =
  5498. const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
  5499. if (!TemplatedFD->getPreviousDecl()) {
  5500. assert(FoundByLookup->getTemplatedDecl() &&
  5501. "Found decl must have its templated decl set");
  5502. auto *PrevTemplated =
  5503. FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
  5504. if (TemplatedFD != PrevTemplated)
  5505. TemplatedFD->setPreviousDecl(PrevTemplated);
  5506. }
  5507. ToFunc->setPreviousDecl(Recent);
  5508. }
  5509. return ToFunc;
  5510. }
  5511. //----------------------------------------------------------------------------
  5512. // Import Statements
  5513. //----------------------------------------------------------------------------
  5514. ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
  5515. Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
  5516. << S->getStmtClassName();
  5517. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  5518. }
  5519. ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
  5520. if (Importer.returnWithErrorInTest())
  5521. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  5522. SmallVector<IdentifierInfo *, 4> Names;
  5523. for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
  5524. IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
  5525. // ToII is nullptr when no symbolic name is given for output operand
  5526. // see ParseStmtAsm::ParseAsmOperandsOpt
  5527. Names.push_back(ToII);
  5528. }
  5529. for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
  5530. IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
  5531. // ToII is nullptr when no symbolic name is given for input operand
  5532. // see ParseStmtAsm::ParseAsmOperandsOpt
  5533. Names.push_back(ToII);
  5534. }
  5535. SmallVector<StringLiteral *, 4> Clobbers;
  5536. for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
  5537. if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
  5538. Clobbers.push_back(*ClobberOrErr);
  5539. else
  5540. return ClobberOrErr.takeError();
  5541. }
  5542. SmallVector<StringLiteral *, 4> Constraints;
  5543. for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
  5544. if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
  5545. Constraints.push_back(*OutputOrErr);
  5546. else
  5547. return OutputOrErr.takeError();
  5548. }
  5549. for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
  5550. if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
  5551. Constraints.push_back(*InputOrErr);
  5552. else
  5553. return InputOrErr.takeError();
  5554. }
  5555. SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
  5556. S->getNumLabels());
  5557. if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
  5558. return std::move(Err);
  5559. if (Error Err =
  5560. ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
  5561. return std::move(Err);
  5562. if (Error Err = ImportArrayChecked(
  5563. S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
  5564. return std::move(Err);
  5565. ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
  5566. if (!AsmLocOrErr)
  5567. return AsmLocOrErr.takeError();
  5568. auto AsmStrOrErr = import(S->getAsmString());
  5569. if (!AsmStrOrErr)
  5570. return AsmStrOrErr.takeError();
  5571. ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
  5572. if (!RParenLocOrErr)
  5573. return RParenLocOrErr.takeError();
  5574. return new (Importer.getToContext()) GCCAsmStmt(
  5575. Importer.getToContext(),
  5576. *AsmLocOrErr,
  5577. S->isSimple(),
  5578. S->isVolatile(),
  5579. S->getNumOutputs(),
  5580. S->getNumInputs(),
  5581. Names.data(),
  5582. Constraints.data(),
  5583. Exprs.data(),
  5584. *AsmStrOrErr,
  5585. S->getNumClobbers(),
  5586. Clobbers.data(),
  5587. S->getNumLabels(),
  5588. *RParenLocOrErr);
  5589. }
  5590. ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
  5591. Error Err = Error::success();
  5592. auto ToDG = importChecked(Err, S->getDeclGroup());
  5593. auto ToBeginLoc = importChecked(Err, S->getBeginLoc());
  5594. auto ToEndLoc = importChecked(Err, S->getEndLoc());
  5595. if (Err)
  5596. return std::move(Err);
  5597. return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
  5598. }
  5599. ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
  5600. ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
  5601. if (!ToSemiLocOrErr)
  5602. return ToSemiLocOrErr.takeError();
  5603. return new (Importer.getToContext()) NullStmt(
  5604. *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
  5605. }
  5606. ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
  5607. SmallVector<Stmt *, 8> ToStmts(S->size());
  5608. if (Error Err = ImportContainerChecked(S->body(), ToStmts))
  5609. return std::move(Err);
  5610. ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
  5611. if (!ToLBracLocOrErr)
  5612. return ToLBracLocOrErr.takeError();
  5613. ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
  5614. if (!ToRBracLocOrErr)
  5615. return ToRBracLocOrErr.takeError();
  5616. FPOptionsOverride FPO =
  5617. S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride();
  5618. return CompoundStmt::Create(Importer.getToContext(), ToStmts, FPO,
  5619. *ToLBracLocOrErr, *ToRBracLocOrErr);
  5620. }
  5621. ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
  5622. Error Err = Error::success();
  5623. auto ToLHS = importChecked(Err, S->getLHS());
  5624. auto ToRHS = importChecked(Err, S->getRHS());
  5625. auto ToSubStmt = importChecked(Err, S->getSubStmt());
  5626. auto ToCaseLoc = importChecked(Err, S->getCaseLoc());
  5627. auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc());
  5628. auto ToColonLoc = importChecked(Err, S->getColonLoc());
  5629. if (Err)
  5630. return std::move(Err);
  5631. auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
  5632. ToCaseLoc, ToEllipsisLoc, ToColonLoc);
  5633. ToStmt->setSubStmt(ToSubStmt);
  5634. return ToStmt;
  5635. }
  5636. ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
  5637. Error Err = Error::success();
  5638. auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc());
  5639. auto ToColonLoc = importChecked(Err, S->getColonLoc());
  5640. auto ToSubStmt = importChecked(Err, S->getSubStmt());
  5641. if (Err)
  5642. return std::move(Err);
  5643. return new (Importer.getToContext()) DefaultStmt(
  5644. ToDefaultLoc, ToColonLoc, ToSubStmt);
  5645. }
  5646. ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
  5647. Error Err = Error::success();
  5648. auto ToIdentLoc = importChecked(Err, S->getIdentLoc());
  5649. auto ToLabelDecl = importChecked(Err, S->getDecl());
  5650. auto ToSubStmt = importChecked(Err, S->getSubStmt());
  5651. if (Err)
  5652. return std::move(Err);
  5653. return new (Importer.getToContext()) LabelStmt(
  5654. ToIdentLoc, ToLabelDecl, ToSubStmt);
  5655. }
  5656. ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
  5657. ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
  5658. if (!ToAttrLocOrErr)
  5659. return ToAttrLocOrErr.takeError();
  5660. ArrayRef<const Attr*> FromAttrs(S->getAttrs());
  5661. SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
  5662. if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
  5663. return std::move(Err);
  5664. ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
  5665. if (!ToSubStmtOrErr)
  5666. return ToSubStmtOrErr.takeError();
  5667. return AttributedStmt::Create(
  5668. Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
  5669. }
  5670. ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
  5671. Error Err = Error::success();
  5672. auto ToIfLoc = importChecked(Err, S->getIfLoc());
  5673. auto ToInit = importChecked(Err, S->getInit());
  5674. auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
  5675. auto ToCond = importChecked(Err, S->getCond());
  5676. auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
  5677. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5678. auto ToThen = importChecked(Err, S->getThen());
  5679. auto ToElseLoc = importChecked(Err, S->getElseLoc());
  5680. auto ToElse = importChecked(Err, S->getElse());
  5681. if (Err)
  5682. return std::move(Err);
  5683. return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->getStatementKind(),
  5684. ToInit, ToConditionVariable, ToCond, ToLParenLoc,
  5685. ToRParenLoc, ToThen, ToElseLoc, ToElse);
  5686. }
  5687. ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
  5688. Error Err = Error::success();
  5689. auto ToInit = importChecked(Err, S->getInit());
  5690. auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
  5691. auto ToCond = importChecked(Err, S->getCond());
  5692. auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
  5693. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5694. auto ToBody = importChecked(Err, S->getBody());
  5695. auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc());
  5696. if (Err)
  5697. return std::move(Err);
  5698. auto *ToStmt =
  5699. SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable,
  5700. ToCond, ToLParenLoc, ToRParenLoc);
  5701. ToStmt->setBody(ToBody);
  5702. ToStmt->setSwitchLoc(ToSwitchLoc);
  5703. // Now we have to re-chain the cases.
  5704. SwitchCase *LastChainedSwitchCase = nullptr;
  5705. for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
  5706. SC = SC->getNextSwitchCase()) {
  5707. Expected<SwitchCase *> ToSCOrErr = import(SC);
  5708. if (!ToSCOrErr)
  5709. return ToSCOrErr.takeError();
  5710. if (LastChainedSwitchCase)
  5711. LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
  5712. else
  5713. ToStmt->setSwitchCaseList(*ToSCOrErr);
  5714. LastChainedSwitchCase = *ToSCOrErr;
  5715. }
  5716. return ToStmt;
  5717. }
  5718. ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
  5719. Error Err = Error::success();
  5720. auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
  5721. auto ToCond = importChecked(Err, S->getCond());
  5722. auto ToBody = importChecked(Err, S->getBody());
  5723. auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
  5724. auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
  5725. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5726. if (Err)
  5727. return std::move(Err);
  5728. return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
  5729. ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc);
  5730. }
  5731. ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
  5732. Error Err = Error::success();
  5733. auto ToBody = importChecked(Err, S->getBody());
  5734. auto ToCond = importChecked(Err, S->getCond());
  5735. auto ToDoLoc = importChecked(Err, S->getDoLoc());
  5736. auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
  5737. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5738. if (Err)
  5739. return std::move(Err);
  5740. return new (Importer.getToContext()) DoStmt(
  5741. ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
  5742. }
  5743. ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
  5744. Error Err = Error::success();
  5745. auto ToInit = importChecked(Err, S->getInit());
  5746. auto ToCond = importChecked(Err, S->getCond());
  5747. auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
  5748. auto ToInc = importChecked(Err, S->getInc());
  5749. auto ToBody = importChecked(Err, S->getBody());
  5750. auto ToForLoc = importChecked(Err, S->getForLoc());
  5751. auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
  5752. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5753. if (Err)
  5754. return std::move(Err);
  5755. return new (Importer.getToContext()) ForStmt(
  5756. Importer.getToContext(),
  5757. ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
  5758. ToRParenLoc);
  5759. }
  5760. ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
  5761. Error Err = Error::success();
  5762. auto ToLabel = importChecked(Err, S->getLabel());
  5763. auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
  5764. auto ToLabelLoc = importChecked(Err, S->getLabelLoc());
  5765. if (Err)
  5766. return std::move(Err);
  5767. return new (Importer.getToContext()) GotoStmt(
  5768. ToLabel, ToGotoLoc, ToLabelLoc);
  5769. }
  5770. ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
  5771. Error Err = Error::success();
  5772. auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
  5773. auto ToStarLoc = importChecked(Err, S->getStarLoc());
  5774. auto ToTarget = importChecked(Err, S->getTarget());
  5775. if (Err)
  5776. return std::move(Err);
  5777. return new (Importer.getToContext()) IndirectGotoStmt(
  5778. ToGotoLoc, ToStarLoc, ToTarget);
  5779. }
  5780. ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
  5781. ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
  5782. if (!ToContinueLocOrErr)
  5783. return ToContinueLocOrErr.takeError();
  5784. return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
  5785. }
  5786. ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
  5787. auto ToBreakLocOrErr = import(S->getBreakLoc());
  5788. if (!ToBreakLocOrErr)
  5789. return ToBreakLocOrErr.takeError();
  5790. return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
  5791. }
  5792. ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
  5793. Error Err = Error::success();
  5794. auto ToReturnLoc = importChecked(Err, S->getReturnLoc());
  5795. auto ToRetValue = importChecked(Err, S->getRetValue());
  5796. auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate());
  5797. if (Err)
  5798. return std::move(Err);
  5799. return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
  5800. ToNRVOCandidate);
  5801. }
  5802. ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
  5803. Error Err = Error::success();
  5804. auto ToCatchLoc = importChecked(Err, S->getCatchLoc());
  5805. auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl());
  5806. auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock());
  5807. if (Err)
  5808. return std::move(Err);
  5809. return new (Importer.getToContext()) CXXCatchStmt (
  5810. ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
  5811. }
  5812. ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
  5813. ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
  5814. if (!ToTryLocOrErr)
  5815. return ToTryLocOrErr.takeError();
  5816. ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
  5817. if (!ToTryBlockOrErr)
  5818. return ToTryBlockOrErr.takeError();
  5819. SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
  5820. for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
  5821. CXXCatchStmt *FromHandler = S->getHandler(HI);
  5822. if (auto ToHandlerOrErr = import(FromHandler))
  5823. ToHandlers[HI] = *ToHandlerOrErr;
  5824. else
  5825. return ToHandlerOrErr.takeError();
  5826. }
  5827. return CXXTryStmt::Create(
  5828. Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers);
  5829. }
  5830. ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
  5831. Error Err = Error::success();
  5832. auto ToInit = importChecked(Err, S->getInit());
  5833. auto ToRangeStmt = importChecked(Err, S->getRangeStmt());
  5834. auto ToBeginStmt = importChecked(Err, S->getBeginStmt());
  5835. auto ToEndStmt = importChecked(Err, S->getEndStmt());
  5836. auto ToCond = importChecked(Err, S->getCond());
  5837. auto ToInc = importChecked(Err, S->getInc());
  5838. auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt());
  5839. auto ToBody = importChecked(Err, S->getBody());
  5840. auto ToForLoc = importChecked(Err, S->getForLoc());
  5841. auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc());
  5842. auto ToColonLoc = importChecked(Err, S->getColonLoc());
  5843. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5844. if (Err)
  5845. return std::move(Err);
  5846. return new (Importer.getToContext()) CXXForRangeStmt(
  5847. ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
  5848. ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
  5849. }
  5850. ExpectedStmt
  5851. ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
  5852. Error Err = Error::success();
  5853. auto ToElement = importChecked(Err, S->getElement());
  5854. auto ToCollection = importChecked(Err, S->getCollection());
  5855. auto ToBody = importChecked(Err, S->getBody());
  5856. auto ToForLoc = importChecked(Err, S->getForLoc());
  5857. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5858. if (Err)
  5859. return std::move(Err);
  5860. return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
  5861. ToCollection,
  5862. ToBody,
  5863. ToForLoc,
  5864. ToRParenLoc);
  5865. }
  5866. ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
  5867. Error Err = Error::success();
  5868. auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc());
  5869. auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
  5870. auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl());
  5871. auto ToCatchBody = importChecked(Err, S->getCatchBody());
  5872. if (Err)
  5873. return std::move(Err);
  5874. return new (Importer.getToContext()) ObjCAtCatchStmt (
  5875. ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
  5876. }
  5877. ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
  5878. ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
  5879. if (!ToAtFinallyLocOrErr)
  5880. return ToAtFinallyLocOrErr.takeError();
  5881. ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
  5882. if (!ToAtFinallyStmtOrErr)
  5883. return ToAtFinallyStmtOrErr.takeError();
  5884. return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
  5885. *ToAtFinallyStmtOrErr);
  5886. }
  5887. ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
  5888. Error Err = Error::success();
  5889. auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc());
  5890. auto ToTryBody = importChecked(Err, S->getTryBody());
  5891. auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt());
  5892. if (Err)
  5893. return std::move(Err);
  5894. SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
  5895. for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
  5896. ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
  5897. if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
  5898. ToCatchStmts[CI] = *ToCatchStmtOrErr;
  5899. else
  5900. return ToCatchStmtOrErr.takeError();
  5901. }
  5902. return ObjCAtTryStmt::Create(Importer.getToContext(),
  5903. ToAtTryLoc, ToTryBody,
  5904. ToCatchStmts.begin(), ToCatchStmts.size(),
  5905. ToFinallyStmt);
  5906. }
  5907. ExpectedStmt
  5908. ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  5909. Error Err = Error::success();
  5910. auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc());
  5911. auto ToSynchExpr = importChecked(Err, S->getSynchExpr());
  5912. auto ToSynchBody = importChecked(Err, S->getSynchBody());
  5913. if (Err)
  5914. return std::move(Err);
  5915. return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
  5916. ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
  5917. }
  5918. ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
  5919. ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
  5920. if (!ToThrowLocOrErr)
  5921. return ToThrowLocOrErr.takeError();
  5922. ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
  5923. if (!ToThrowExprOrErr)
  5924. return ToThrowExprOrErr.takeError();
  5925. return new (Importer.getToContext()) ObjCAtThrowStmt(
  5926. *ToThrowLocOrErr, *ToThrowExprOrErr);
  5927. }
  5928. ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
  5929. ObjCAutoreleasePoolStmt *S) {
  5930. ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
  5931. if (!ToAtLocOrErr)
  5932. return ToAtLocOrErr.takeError();
  5933. ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
  5934. if (!ToSubStmtOrErr)
  5935. return ToSubStmtOrErr.takeError();
  5936. return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
  5937. *ToSubStmtOrErr);
  5938. }
  5939. //----------------------------------------------------------------------------
  5940. // Import Expressions
  5941. //----------------------------------------------------------------------------
  5942. ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
  5943. Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
  5944. << E->getStmtClassName();
  5945. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  5946. }
  5947. ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) {
  5948. Error Err = Error::success();
  5949. auto ToType = importChecked(Err, E->getType());
  5950. auto BLoc = importChecked(Err, E->getBeginLoc());
  5951. auto RParenLoc = importChecked(Err, E->getEndLoc());
  5952. if (Err)
  5953. return std::move(Err);
  5954. auto ParentContextOrErr = Importer.ImportContext(E->getParentContext());
  5955. if (!ParentContextOrErr)
  5956. return ParentContextOrErr.takeError();
  5957. return new (Importer.getToContext())
  5958. SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc,
  5959. RParenLoc, *ParentContextOrErr);
  5960. }
  5961. ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
  5962. Error Err = Error::success();
  5963. auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
  5964. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  5965. auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo());
  5966. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  5967. auto ToType = importChecked(Err, E->getType());
  5968. if (Err)
  5969. return std::move(Err);
  5970. return new (Importer.getToContext()) VAArgExpr(
  5971. ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
  5972. E->isMicrosoftABI());
  5973. }
  5974. ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
  5975. Error Err = Error::success();
  5976. auto ToCond = importChecked(Err, E->getCond());
  5977. auto ToLHS = importChecked(Err, E->getLHS());
  5978. auto ToRHS = importChecked(Err, E->getRHS());
  5979. auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
  5980. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  5981. auto ToType = importChecked(Err, E->getType());
  5982. if (Err)
  5983. return std::move(Err);
  5984. ExprValueKind VK = E->getValueKind();
  5985. ExprObjectKind OK = E->getObjectKind();
  5986. // The value of CondIsTrue only matters if the value is not
  5987. // condition-dependent.
  5988. bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
  5989. return new (Importer.getToContext())
  5990. ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
  5991. ToRParenLoc, CondIsTrue);
  5992. }
  5993. ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
  5994. Error Err = Error::success();
  5995. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  5996. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  5997. auto ToType = importChecked(Err, E->getType());
  5998. const unsigned NumSubExprs = E->getNumSubExprs();
  5999. llvm::SmallVector<Expr *, 8> ToSubExprs;
  6000. llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs);
  6001. ToSubExprs.resize(NumSubExprs);
  6002. if ((Err = ImportContainerChecked(FromSubExprs, ToSubExprs)))
  6003. return std::move(Err);
  6004. return new (Importer.getToContext()) ShuffleVectorExpr(
  6005. Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc);
  6006. }
  6007. ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
  6008. ExpectedType TypeOrErr = import(E->getType());
  6009. if (!TypeOrErr)
  6010. return TypeOrErr.takeError();
  6011. ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
  6012. if (!BeginLocOrErr)
  6013. return BeginLocOrErr.takeError();
  6014. return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
  6015. }
  6016. ExpectedStmt
  6017. ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
  6018. Error Err = Error::success();
  6019. auto ToGenericLoc = importChecked(Err, E->getGenericLoc());
  6020. auto *ToControllingExpr = importChecked(Err, E->getControllingExpr());
  6021. auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc());
  6022. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6023. if (Err)
  6024. return std::move(Err);
  6025. ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
  6026. SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
  6027. if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes))
  6028. return std::move(Err);
  6029. ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
  6030. SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
  6031. if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs))
  6032. return std::move(Err);
  6033. const ASTContext &ToCtx = Importer.getToContext();
  6034. if (E->isResultDependent()) {
  6035. return GenericSelectionExpr::Create(
  6036. ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
  6037. llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
  6038. E->containsUnexpandedParameterPack());
  6039. }
  6040. return GenericSelectionExpr::Create(
  6041. ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
  6042. llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
  6043. E->containsUnexpandedParameterPack(), E->getResultIndex());
  6044. }
  6045. ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
  6046. Error Err = Error::success();
  6047. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  6048. auto ToType = importChecked(Err, E->getType());
  6049. auto ToFunctionName = importChecked(Err, E->getFunctionName());
  6050. if (Err)
  6051. return std::move(Err);
  6052. return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
  6053. E->getIdentKind(), ToFunctionName);
  6054. }
  6055. ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
  6056. Error Err = Error::success();
  6057. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  6058. auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
  6059. auto ToDecl = importChecked(Err, E->getDecl());
  6060. auto ToLocation = importChecked(Err, E->getLocation());
  6061. auto ToType = importChecked(Err, E->getType());
  6062. if (Err)
  6063. return std::move(Err);
  6064. NamedDecl *ToFoundD = nullptr;
  6065. if (E->getDecl() != E->getFoundDecl()) {
  6066. auto FoundDOrErr = import(E->getFoundDecl());
  6067. if (!FoundDOrErr)
  6068. return FoundDOrErr.takeError();
  6069. ToFoundD = *FoundDOrErr;
  6070. }
  6071. TemplateArgumentListInfo ToTAInfo;
  6072. TemplateArgumentListInfo *ToResInfo = nullptr;
  6073. if (E->hasExplicitTemplateArgs()) {
  6074. if (Error Err =
  6075. ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
  6076. E->template_arguments(), ToTAInfo))
  6077. return std::move(Err);
  6078. ToResInfo = &ToTAInfo;
  6079. }
  6080. auto *ToE = DeclRefExpr::Create(
  6081. Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
  6082. E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
  6083. E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
  6084. if (E->hadMultipleCandidates())
  6085. ToE->setHadMultipleCandidates(true);
  6086. return ToE;
  6087. }
  6088. ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  6089. ExpectedType TypeOrErr = import(E->getType());
  6090. if (!TypeOrErr)
  6091. return TypeOrErr.takeError();
  6092. return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
  6093. }
  6094. ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
  6095. ExpectedExpr ToInitOrErr = import(E->getInit());
  6096. if (!ToInitOrErr)
  6097. return ToInitOrErr.takeError();
  6098. ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
  6099. if (!ToEqualOrColonLocOrErr)
  6100. return ToEqualOrColonLocOrErr.takeError();
  6101. SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
  6102. // List elements from the second, the first is Init itself
  6103. for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
  6104. if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
  6105. ToIndexExprs[I - 1] = *ToArgOrErr;
  6106. else
  6107. return ToArgOrErr.takeError();
  6108. }
  6109. SmallVector<Designator, 4> ToDesignators(E->size());
  6110. if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
  6111. return std::move(Err);
  6112. return DesignatedInitExpr::Create(
  6113. Importer.getToContext(), ToDesignators,
  6114. ToIndexExprs, *ToEqualOrColonLocOrErr,
  6115. E->usesGNUSyntax(), *ToInitOrErr);
  6116. }
  6117. ExpectedStmt
  6118. ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
  6119. ExpectedType ToTypeOrErr = import(E->getType());
  6120. if (!ToTypeOrErr)
  6121. return ToTypeOrErr.takeError();
  6122. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6123. if (!ToLocationOrErr)
  6124. return ToLocationOrErr.takeError();
  6125. return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
  6126. *ToTypeOrErr, *ToLocationOrErr);
  6127. }
  6128. ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
  6129. ExpectedType ToTypeOrErr = import(E->getType());
  6130. if (!ToTypeOrErr)
  6131. return ToTypeOrErr.takeError();
  6132. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6133. if (!ToLocationOrErr)
  6134. return ToLocationOrErr.takeError();
  6135. return IntegerLiteral::Create(
  6136. Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
  6137. }
  6138. ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
  6139. ExpectedType ToTypeOrErr = import(E->getType());
  6140. if (!ToTypeOrErr)
  6141. return ToTypeOrErr.takeError();
  6142. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6143. if (!ToLocationOrErr)
  6144. return ToLocationOrErr.takeError();
  6145. return FloatingLiteral::Create(
  6146. Importer.getToContext(), E->getValue(), E->isExact(),
  6147. *ToTypeOrErr, *ToLocationOrErr);
  6148. }
  6149. ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
  6150. auto ToTypeOrErr = import(E->getType());
  6151. if (!ToTypeOrErr)
  6152. return ToTypeOrErr.takeError();
  6153. ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
  6154. if (!ToSubExprOrErr)
  6155. return ToSubExprOrErr.takeError();
  6156. return new (Importer.getToContext()) ImaginaryLiteral(
  6157. *ToSubExprOrErr, *ToTypeOrErr);
  6158. }
  6159. ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) {
  6160. auto ToTypeOrErr = import(E->getType());
  6161. if (!ToTypeOrErr)
  6162. return ToTypeOrErr.takeError();
  6163. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6164. if (!ToLocationOrErr)
  6165. return ToLocationOrErr.takeError();
  6166. return new (Importer.getToContext()) FixedPointLiteral(
  6167. Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
  6168. Importer.getToContext().getFixedPointScale(*ToTypeOrErr));
  6169. }
  6170. ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
  6171. ExpectedType ToTypeOrErr = import(E->getType());
  6172. if (!ToTypeOrErr)
  6173. return ToTypeOrErr.takeError();
  6174. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6175. if (!ToLocationOrErr)
  6176. return ToLocationOrErr.takeError();
  6177. return new (Importer.getToContext()) CharacterLiteral(
  6178. E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
  6179. }
  6180. ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
  6181. ExpectedType ToTypeOrErr = import(E->getType());
  6182. if (!ToTypeOrErr)
  6183. return ToTypeOrErr.takeError();
  6184. SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
  6185. if (Error Err = ImportArrayChecked(
  6186. E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
  6187. return std::move(Err);
  6188. return StringLiteral::Create(
  6189. Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
  6190. *ToTypeOrErr, ToLocations.data(), ToLocations.size());
  6191. }
  6192. ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  6193. Error Err = Error::success();
  6194. auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
  6195. auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
  6196. auto ToType = importChecked(Err, E->getType());
  6197. auto ToInitializer = importChecked(Err, E->getInitializer());
  6198. if (Err)
  6199. return std::move(Err);
  6200. return new (Importer.getToContext()) CompoundLiteralExpr(
  6201. ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
  6202. ToInitializer, E->isFileScope());
  6203. }
  6204. ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
  6205. Error Err = Error::success();
  6206. auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
  6207. auto ToType = importChecked(Err, E->getType());
  6208. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6209. if (Err)
  6210. return std::move(Err);
  6211. SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
  6212. if (Error Err = ImportArrayChecked(
  6213. E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
  6214. ToExprs.begin()))
  6215. return std::move(Err);
  6216. return new (Importer.getToContext()) AtomicExpr(
  6217. ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
  6218. }
  6219. ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
  6220. Error Err = Error::success();
  6221. auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc());
  6222. auto ToLabelLoc = importChecked(Err, E->getLabelLoc());
  6223. auto ToLabel = importChecked(Err, E->getLabel());
  6224. auto ToType = importChecked(Err, E->getType());
  6225. if (Err)
  6226. return std::move(Err);
  6227. return new (Importer.getToContext()) AddrLabelExpr(
  6228. ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
  6229. }
  6230. ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
  6231. Error Err = Error::success();
  6232. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  6233. auto ToResult = importChecked(Err, E->getAPValueResult());
  6234. if (Err)
  6235. return std::move(Err);
  6236. return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult);
  6237. }
  6238. ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
  6239. Error Err = Error::success();
  6240. auto ToLParen = importChecked(Err, E->getLParen());
  6241. auto ToRParen = importChecked(Err, E->getRParen());
  6242. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  6243. if (Err)
  6244. return std::move(Err);
  6245. return new (Importer.getToContext())
  6246. ParenExpr(ToLParen, ToRParen, ToSubExpr);
  6247. }
  6248. ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
  6249. SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
  6250. if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
  6251. return std::move(Err);
  6252. ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
  6253. if (!ToLParenLocOrErr)
  6254. return ToLParenLocOrErr.takeError();
  6255. ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
  6256. if (!ToRParenLocOrErr)
  6257. return ToRParenLocOrErr.takeError();
  6258. return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
  6259. ToExprs, *ToRParenLocOrErr);
  6260. }
  6261. ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
  6262. Error Err = Error::success();
  6263. auto ToSubStmt = importChecked(Err, E->getSubStmt());
  6264. auto ToType = importChecked(Err, E->getType());
  6265. auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
  6266. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6267. if (Err)
  6268. return std::move(Err);
  6269. return new (Importer.getToContext())
  6270. StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
  6271. E->getTemplateDepth());
  6272. }
  6273. ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
  6274. Error Err = Error::success();
  6275. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  6276. auto ToType = importChecked(Err, E->getType());
  6277. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6278. if (Err)
  6279. return std::move(Err);
  6280. return UnaryOperator::Create(
  6281. Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType,
  6282. E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(),
  6283. E->getFPOptionsOverride());
  6284. }
  6285. ExpectedStmt
  6286. ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
  6287. Error Err = Error::success();
  6288. auto ToType = importChecked(Err, E->getType());
  6289. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6290. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6291. if (Err)
  6292. return std::move(Err);
  6293. if (E->isArgumentType()) {
  6294. Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
  6295. import(E->getArgumentTypeInfo());
  6296. if (!ToArgumentTypeInfoOrErr)
  6297. return ToArgumentTypeInfoOrErr.takeError();
  6298. return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
  6299. E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
  6300. ToRParenLoc);
  6301. }
  6302. ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr());
  6303. if (!ToArgumentExprOrErr)
  6304. return ToArgumentExprOrErr.takeError();
  6305. return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
  6306. E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
  6307. }
  6308. ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
  6309. Error Err = Error::success();
  6310. auto ToLHS = importChecked(Err, E->getLHS());
  6311. auto ToRHS = importChecked(Err, E->getRHS());
  6312. auto ToType = importChecked(Err, E->getType());
  6313. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6314. if (Err)
  6315. return std::move(Err);
  6316. return BinaryOperator::Create(
  6317. Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
  6318. E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
  6319. E->getFPFeatures());
  6320. }
  6321. ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
  6322. Error Err = Error::success();
  6323. auto ToCond = importChecked(Err, E->getCond());
  6324. auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
  6325. auto ToLHS = importChecked(Err, E->getLHS());
  6326. auto ToColonLoc = importChecked(Err, E->getColonLoc());
  6327. auto ToRHS = importChecked(Err, E->getRHS());
  6328. auto ToType = importChecked(Err, E->getType());
  6329. if (Err)
  6330. return std::move(Err);
  6331. return new (Importer.getToContext()) ConditionalOperator(
  6332. ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
  6333. E->getValueKind(), E->getObjectKind());
  6334. }
  6335. ExpectedStmt
  6336. ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  6337. Error Err = Error::success();
  6338. auto ToCommon = importChecked(Err, E->getCommon());
  6339. auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue());
  6340. auto ToCond = importChecked(Err, E->getCond());
  6341. auto ToTrueExpr = importChecked(Err, E->getTrueExpr());
  6342. auto ToFalseExpr = importChecked(Err, E->getFalseExpr());
  6343. auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
  6344. auto ToColonLoc = importChecked(Err, E->getColonLoc());
  6345. auto ToType = importChecked(Err, E->getType());
  6346. if (Err)
  6347. return std::move(Err);
  6348. return new (Importer.getToContext()) BinaryConditionalOperator(
  6349. ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
  6350. ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
  6351. E->getObjectKind());
  6352. }
  6353. ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
  6354. Error Err = Error::success();
  6355. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  6356. auto ToQueriedTypeSourceInfo =
  6357. importChecked(Err, E->getQueriedTypeSourceInfo());
  6358. auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression());
  6359. auto ToEndLoc = importChecked(Err, E->getEndLoc());
  6360. auto ToType = importChecked(Err, E->getType());
  6361. if (Err)
  6362. return std::move(Err);
  6363. return new (Importer.getToContext()) ArrayTypeTraitExpr(
  6364. ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
  6365. ToDimensionExpression, ToEndLoc, ToType);
  6366. }
  6367. ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
  6368. Error Err = Error::success();
  6369. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  6370. auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression());
  6371. auto ToEndLoc = importChecked(Err, E->getEndLoc());
  6372. auto ToType = importChecked(Err, E->getType());
  6373. if (Err)
  6374. return std::move(Err);
  6375. return new (Importer.getToContext()) ExpressionTraitExpr(
  6376. ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
  6377. ToEndLoc, ToType);
  6378. }
  6379. ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  6380. Error Err = Error::success();
  6381. auto ToLocation = importChecked(Err, E->getLocation());
  6382. auto ToType = importChecked(Err, E->getType());
  6383. auto ToSourceExpr = importChecked(Err, E->getSourceExpr());
  6384. if (Err)
  6385. return std::move(Err);
  6386. return new (Importer.getToContext()) OpaqueValueExpr(
  6387. ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
  6388. }
  6389. ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  6390. Error Err = Error::success();
  6391. auto ToLHS = importChecked(Err, E->getLHS());
  6392. auto ToRHS = importChecked(Err, E->getRHS());
  6393. auto ToType = importChecked(Err, E->getType());
  6394. auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc());
  6395. if (Err)
  6396. return std::move(Err);
  6397. return new (Importer.getToContext()) ArraySubscriptExpr(
  6398. ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
  6399. ToRBracketLoc);
  6400. }
  6401. ExpectedStmt
  6402. ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
  6403. Error Err = Error::success();
  6404. auto ToLHS = importChecked(Err, E->getLHS());
  6405. auto ToRHS = importChecked(Err, E->getRHS());
  6406. auto ToType = importChecked(Err, E->getType());
  6407. auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType());
  6408. auto ToComputationResultType =
  6409. importChecked(Err, E->getComputationResultType());
  6410. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6411. if (Err)
  6412. return std::move(Err);
  6413. return CompoundAssignOperator::Create(
  6414. Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
  6415. E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
  6416. E->getFPFeatures(),
  6417. ToComputationLHSType, ToComputationResultType);
  6418. }
  6419. Expected<CXXCastPath>
  6420. ASTNodeImporter::ImportCastPath(CastExpr *CE) {
  6421. CXXCastPath Path;
  6422. for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
  6423. if (auto SpecOrErr = import(*I))
  6424. Path.push_back(*SpecOrErr);
  6425. else
  6426. return SpecOrErr.takeError();
  6427. }
  6428. return Path;
  6429. }
  6430. ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  6431. ExpectedType ToTypeOrErr = import(E->getType());
  6432. if (!ToTypeOrErr)
  6433. return ToTypeOrErr.takeError();
  6434. ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
  6435. if (!ToSubExprOrErr)
  6436. return ToSubExprOrErr.takeError();
  6437. Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
  6438. if (!ToBasePathOrErr)
  6439. return ToBasePathOrErr.takeError();
  6440. return ImplicitCastExpr::Create(
  6441. Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr,
  6442. &(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures());
  6443. }
  6444. ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
  6445. Error Err = Error::success();
  6446. auto ToType = importChecked(Err, E->getType());
  6447. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  6448. auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
  6449. if (Err)
  6450. return std::move(Err);
  6451. Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
  6452. if (!ToBasePathOrErr)
  6453. return ToBasePathOrErr.takeError();
  6454. CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
  6455. switch (E->getStmtClass()) {
  6456. case Stmt::CStyleCastExprClass: {
  6457. auto *CCE = cast<CStyleCastExpr>(E);
  6458. ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc());
  6459. if (!ToLParenLocOrErr)
  6460. return ToLParenLocOrErr.takeError();
  6461. ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc());
  6462. if (!ToRParenLocOrErr)
  6463. return ToRParenLocOrErr.takeError();
  6464. return CStyleCastExpr::Create(
  6465. Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(),
  6466. ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten,
  6467. *ToLParenLocOrErr, *ToRParenLocOrErr);
  6468. }
  6469. case Stmt::CXXFunctionalCastExprClass: {
  6470. auto *FCE = cast<CXXFunctionalCastExpr>(E);
  6471. ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc());
  6472. if (!ToLParenLocOrErr)
  6473. return ToLParenLocOrErr.takeError();
  6474. ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc());
  6475. if (!ToRParenLocOrErr)
  6476. return ToRParenLocOrErr.takeError();
  6477. return CXXFunctionalCastExpr::Create(
  6478. Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten,
  6479. E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(),
  6480. *ToLParenLocOrErr, *ToRParenLocOrErr);
  6481. }
  6482. case Stmt::ObjCBridgedCastExprClass: {
  6483. auto *OCE = cast<ObjCBridgedCastExpr>(E);
  6484. ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc());
  6485. if (!ToLParenLocOrErr)
  6486. return ToLParenLocOrErr.takeError();
  6487. ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc());
  6488. if (!ToBridgeKeywordLocOrErr)
  6489. return ToBridgeKeywordLocOrErr.takeError();
  6490. return new (Importer.getToContext()) ObjCBridgedCastExpr(
  6491. *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
  6492. *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
  6493. }
  6494. default:
  6495. llvm_unreachable("Cast expression of unsupported type!");
  6496. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  6497. }
  6498. }
  6499. ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
  6500. SmallVector<OffsetOfNode, 4> ToNodes;
  6501. for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
  6502. const OffsetOfNode &FromNode = E->getComponent(I);
  6503. SourceLocation ToBeginLoc, ToEndLoc;
  6504. if (FromNode.getKind() != OffsetOfNode::Base) {
  6505. Error Err = Error::success();
  6506. ToBeginLoc = importChecked(Err, FromNode.getBeginLoc());
  6507. ToEndLoc = importChecked(Err, FromNode.getEndLoc());
  6508. if (Err)
  6509. return std::move(Err);
  6510. }
  6511. switch (FromNode.getKind()) {
  6512. case OffsetOfNode::Array:
  6513. ToNodes.push_back(
  6514. OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
  6515. break;
  6516. case OffsetOfNode::Base: {
  6517. auto ToBSOrErr = import(FromNode.getBase());
  6518. if (!ToBSOrErr)
  6519. return ToBSOrErr.takeError();
  6520. ToNodes.push_back(OffsetOfNode(*ToBSOrErr));
  6521. break;
  6522. }
  6523. case OffsetOfNode::Field: {
  6524. auto ToFieldOrErr = import(FromNode.getField());
  6525. if (!ToFieldOrErr)
  6526. return ToFieldOrErr.takeError();
  6527. ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
  6528. break;
  6529. }
  6530. case OffsetOfNode::Identifier: {
  6531. IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName());
  6532. ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
  6533. break;
  6534. }
  6535. }
  6536. }
  6537. SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
  6538. for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
  6539. ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I));
  6540. if (!ToIndexExprOrErr)
  6541. return ToIndexExprOrErr.takeError();
  6542. ToExprs[I] = *ToIndexExprOrErr;
  6543. }
  6544. Error Err = Error::success();
  6545. auto ToType = importChecked(Err, E->getType());
  6546. auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
  6547. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6548. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6549. if (Err)
  6550. return std::move(Err);
  6551. return OffsetOfExpr::Create(
  6552. Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes,
  6553. ToExprs, ToRParenLoc);
  6554. }
  6555. ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
  6556. Error Err = Error::success();
  6557. auto ToType = importChecked(Err, E->getType());
  6558. auto ToOperand = importChecked(Err, E->getOperand());
  6559. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  6560. auto ToEndLoc = importChecked(Err, E->getEndLoc());
  6561. if (Err)
  6562. return std::move(Err);
  6563. CanThrowResult ToCanThrow;
  6564. if (E->isValueDependent())
  6565. ToCanThrow = CT_Dependent;
  6566. else
  6567. ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
  6568. return new (Importer.getToContext()) CXXNoexceptExpr(
  6569. ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
  6570. }
  6571. ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
  6572. Error Err = Error::success();
  6573. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  6574. auto ToType = importChecked(Err, E->getType());
  6575. auto ToThrowLoc = importChecked(Err, E->getThrowLoc());
  6576. if (Err)
  6577. return std::move(Err);
  6578. return new (Importer.getToContext()) CXXThrowExpr(
  6579. ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
  6580. }
  6581. ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  6582. ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation());
  6583. if (!ToUsedLocOrErr)
  6584. return ToUsedLocOrErr.takeError();
  6585. auto ToParamOrErr = import(E->getParam());
  6586. if (!ToParamOrErr)
  6587. return ToParamOrErr.takeError();
  6588. auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
  6589. if (!UsedContextOrErr)
  6590. return UsedContextOrErr.takeError();
  6591. // Import the default arg if it was not imported yet.
  6592. // This is needed because it can happen that during the import of the
  6593. // default expression (from VisitParmVarDecl) the same ParmVarDecl is
  6594. // encountered here. The default argument for a ParmVarDecl is set in the
  6595. // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
  6596. // see VisitParmVarDecl).
  6597. ParmVarDecl *ToParam = *ToParamOrErr;
  6598. if (!ToParam->getDefaultArg()) {
  6599. std::optional<ParmVarDecl *> FromParam =
  6600. Importer.getImportedFromDecl(ToParam);
  6601. assert(FromParam && "ParmVarDecl was not imported?");
  6602. if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam))
  6603. return std::move(Err);
  6604. }
  6605. Expr *RewrittenInit = nullptr;
  6606. if (E->hasRewrittenInit()) {
  6607. ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
  6608. if (!ExprOrErr)
  6609. return ExprOrErr.takeError();
  6610. RewrittenInit = ExprOrErr.get();
  6611. }
  6612. return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
  6613. *ToParamOrErr, RewrittenInit,
  6614. *UsedContextOrErr);
  6615. }
  6616. ExpectedStmt
  6617. ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  6618. Error Err = Error::success();
  6619. auto ToType = importChecked(Err, E->getType());
  6620. auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
  6621. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6622. if (Err)
  6623. return std::move(Err);
  6624. return new (Importer.getToContext()) CXXScalarValueInitExpr(
  6625. ToType, ToTypeSourceInfo, ToRParenLoc);
  6626. }
  6627. ExpectedStmt
  6628. ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  6629. ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
  6630. if (!ToSubExprOrErr)
  6631. return ToSubExprOrErr.takeError();
  6632. auto ToDtorOrErr = import(E->getTemporary()->getDestructor());
  6633. if (!ToDtorOrErr)
  6634. return ToDtorOrErr.takeError();
  6635. ASTContext &ToCtx = Importer.getToContext();
  6636. CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr);
  6637. return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr);
  6638. }
  6639. ExpectedStmt
  6640. ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
  6641. Error Err = Error::success();
  6642. auto ToConstructor = importChecked(Err, E->getConstructor());
  6643. auto ToType = importChecked(Err, E->getType());
  6644. auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
  6645. auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
  6646. if (Err)
  6647. return std::move(Err);
  6648. SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
  6649. if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
  6650. return std::move(Err);
  6651. return CXXTemporaryObjectExpr::Create(
  6652. Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs,
  6653. ToParenOrBraceRange, E->hadMultipleCandidates(),
  6654. E->isListInitialization(), E->isStdInitListInitialization(),
  6655. E->requiresZeroInitialization());
  6656. }
  6657. ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl(
  6658. LifetimeExtendedTemporaryDecl *D) {
  6659. DeclContext *DC, *LexicalDC;
  6660. if (Error Err = ImportDeclContext(D, DC, LexicalDC))
  6661. return std::move(Err);
  6662. Error Err = Error::success();
  6663. auto Temporary = importChecked(Err, D->getTemporaryExpr());
  6664. auto ExtendingDecl = importChecked(Err, D->getExtendingDecl());
  6665. if (Err)
  6666. return std::move(Err);
  6667. // FIXME: Should ManglingNumber get numbers associated with 'to' context?
  6668. LifetimeExtendedTemporaryDecl *To;
  6669. if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl,
  6670. D->getManglingNumber()))
  6671. return To;
  6672. To->setLexicalDeclContext(LexicalDC);
  6673. LexicalDC->addDeclInternal(To);
  6674. return To;
  6675. }
  6676. ExpectedStmt
  6677. ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
  6678. Error Err = Error::success();
  6679. auto ToType = importChecked(Err, E->getType());
  6680. Expr *ToTemporaryExpr = importChecked(
  6681. Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
  6682. auto ToMaterializedDecl =
  6683. importChecked(Err, E->getLifetimeExtendedTemporaryDecl());
  6684. if (Err)
  6685. return std::move(Err);
  6686. if (!ToTemporaryExpr)
  6687. ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr());
  6688. auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
  6689. ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
  6690. ToMaterializedDecl);
  6691. return ToMTE;
  6692. }
  6693. ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
  6694. Error Err = Error::success();
  6695. auto ToType = importChecked(Err, E->getType());
  6696. auto ToPattern = importChecked(Err, E->getPattern());
  6697. auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
  6698. if (Err)
  6699. return std::move(Err);
  6700. return new (Importer.getToContext()) PackExpansionExpr(
  6701. ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
  6702. }
  6703. ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
  6704. Error Err = Error::success();
  6705. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6706. auto ToPack = importChecked(Err, E->getPack());
  6707. auto ToPackLoc = importChecked(Err, E->getPackLoc());
  6708. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6709. if (Err)
  6710. return std::move(Err);
  6711. std::optional<unsigned> Length;
  6712. if (!E->isValueDependent())
  6713. Length = E->getPackLength();
  6714. SmallVector<TemplateArgument, 8> ToPartialArguments;
  6715. if (E->isPartiallySubstituted()) {
  6716. if (Error Err = ImportTemplateArguments(E->getPartialArguments(),
  6717. ToPartialArguments))
  6718. return std::move(Err);
  6719. }
  6720. return SizeOfPackExpr::Create(
  6721. Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc,
  6722. Length, ToPartialArguments);
  6723. }
  6724. ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
  6725. Error Err = Error::success();
  6726. auto ToOperatorNew = importChecked(Err, E->getOperatorNew());
  6727. auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
  6728. auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens());
  6729. auto ToArraySize = importChecked(Err, E->getArraySize());
  6730. auto ToInitializer = importChecked(Err, E->getInitializer());
  6731. auto ToType = importChecked(Err, E->getType());
  6732. auto ToAllocatedTypeSourceInfo =
  6733. importChecked(Err, E->getAllocatedTypeSourceInfo());
  6734. auto ToSourceRange = importChecked(Err, E->getSourceRange());
  6735. auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange());
  6736. if (Err)
  6737. return std::move(Err);
  6738. SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
  6739. if (Error Err =
  6740. ImportContainerChecked(E->placement_arguments(), ToPlacementArgs))
  6741. return std::move(Err);
  6742. return CXXNewExpr::Create(
  6743. Importer.getToContext(), E->isGlobalNew(), ToOperatorNew,
  6744. ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(),
  6745. ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(),
  6746. ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange,
  6747. ToDirectInitRange);
  6748. }
  6749. ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  6750. Error Err = Error::success();
  6751. auto ToType = importChecked(Err, E->getType());
  6752. auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
  6753. auto ToArgument = importChecked(Err, E->getArgument());
  6754. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  6755. if (Err)
  6756. return std::move(Err);
  6757. return new (Importer.getToContext()) CXXDeleteExpr(
  6758. ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
  6759. E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
  6760. ToBeginLoc);
  6761. }
  6762. ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
  6763. Error Err = Error::success();
  6764. auto ToType = importChecked(Err, E->getType());
  6765. auto ToLocation = importChecked(Err, E->getLocation());
  6766. auto ToConstructor = importChecked(Err, E->getConstructor());
  6767. auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
  6768. if (Err)
  6769. return std::move(Err);
  6770. SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
  6771. if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
  6772. return std::move(Err);
  6773. return CXXConstructExpr::Create(
  6774. Importer.getToContext(), ToType, ToLocation, ToConstructor,
  6775. E->isElidable(), ToArgs, E->hadMultipleCandidates(),
  6776. E->isListInitialization(), E->isStdInitListInitialization(),
  6777. E->requiresZeroInitialization(), E->getConstructionKind(),
  6778. ToParenOrBraceRange);
  6779. }
  6780. ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
  6781. ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
  6782. if (!ToSubExprOrErr)
  6783. return ToSubExprOrErr.takeError();
  6784. SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
  6785. if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects))
  6786. return std::move(Err);
  6787. return ExprWithCleanups::Create(
  6788. Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(),
  6789. ToObjects);
  6790. }
  6791. ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  6792. Error Err = Error::success();
  6793. auto ToCallee = importChecked(Err, E->getCallee());
  6794. auto ToType = importChecked(Err, E->getType());
  6795. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6796. if (Err)
  6797. return std::move(Err);
  6798. SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
  6799. if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
  6800. return std::move(Err);
  6801. return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs,
  6802. ToType, E->getValueKind(), ToRParenLoc,
  6803. E->getFPFeatures());
  6804. }
  6805. ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
  6806. ExpectedType ToTypeOrErr = import(E->getType());
  6807. if (!ToTypeOrErr)
  6808. return ToTypeOrErr.takeError();
  6809. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6810. if (!ToLocationOrErr)
  6811. return ToLocationOrErr.takeError();
  6812. return new (Importer.getToContext()) CXXThisExpr(
  6813. *ToLocationOrErr, *ToTypeOrErr, E->isImplicit());
  6814. }
  6815. ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
  6816. ExpectedType ToTypeOrErr = import(E->getType());
  6817. if (!ToTypeOrErr)
  6818. return ToTypeOrErr.takeError();
  6819. ExpectedSLoc ToLocationOrErr = import(E->getLocation());
  6820. if (!ToLocationOrErr)
  6821. return ToLocationOrErr.takeError();
  6822. return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(),
  6823. *ToTypeOrErr, *ToLocationOrErr);
  6824. }
  6825. ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
  6826. Error Err = Error::success();
  6827. auto ToBase = importChecked(Err, E->getBase());
  6828. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6829. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  6830. auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
  6831. auto ToMemberDecl = importChecked(Err, E->getMemberDecl());
  6832. auto ToType = importChecked(Err, E->getType());
  6833. auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl());
  6834. auto ToName = importChecked(Err, E->getMemberNameInfo().getName());
  6835. auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc());
  6836. if (Err)
  6837. return std::move(Err);
  6838. DeclAccessPair ToFoundDecl =
  6839. DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
  6840. DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
  6841. TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
  6842. if (E->hasExplicitTemplateArgs()) {
  6843. if (Error Err =
  6844. ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
  6845. E->template_arguments(), ToTAInfo))
  6846. return std::move(Err);
  6847. ResInfo = &ToTAInfo;
  6848. }
  6849. return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(),
  6850. ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
  6851. ToMemberDecl, ToFoundDecl, ToMemberNameInfo,
  6852. ResInfo, ToType, E->getValueKind(),
  6853. E->getObjectKind(), E->isNonOdrUse());
  6854. }
  6855. ExpectedStmt
  6856. ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
  6857. Error Err = Error::success();
  6858. auto ToBase = importChecked(Err, E->getBase());
  6859. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6860. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  6861. auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo());
  6862. auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc());
  6863. auto ToTildeLoc = importChecked(Err, E->getTildeLoc());
  6864. if (Err)
  6865. return std::move(Err);
  6866. PseudoDestructorTypeStorage Storage;
  6867. if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
  6868. IdentifierInfo *ToII = Importer.Import(FromII);
  6869. ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc());
  6870. if (!ToDestroyedTypeLocOrErr)
  6871. return ToDestroyedTypeLocOrErr.takeError();
  6872. Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
  6873. } else {
  6874. if (auto ToTIOrErr = import(E->getDestroyedTypeInfo()))
  6875. Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
  6876. else
  6877. return ToTIOrErr.takeError();
  6878. }
  6879. return new (Importer.getToContext()) CXXPseudoDestructorExpr(
  6880. Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
  6881. ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
  6882. }
  6883. ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
  6884. CXXDependentScopeMemberExpr *E) {
  6885. Error Err = Error::success();
  6886. auto ToType = importChecked(Err, E->getType());
  6887. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  6888. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  6889. auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
  6890. auto ToFirstQualifierFoundInScope =
  6891. importChecked(Err, E->getFirstQualifierFoundInScope());
  6892. if (Err)
  6893. return std::move(Err);
  6894. Expr *ToBase = nullptr;
  6895. if (!E->isImplicitAccess()) {
  6896. if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
  6897. ToBase = *ToBaseOrErr;
  6898. else
  6899. return ToBaseOrErr.takeError();
  6900. }
  6901. TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
  6902. if (E->hasExplicitTemplateArgs()) {
  6903. if (Error Err =
  6904. ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
  6905. E->template_arguments(), ToTAInfo))
  6906. return std::move(Err);
  6907. ResInfo = &ToTAInfo;
  6908. }
  6909. auto ToMember = importChecked(Err, E->getMember());
  6910. auto ToMemberLoc = importChecked(Err, E->getMemberLoc());
  6911. if (Err)
  6912. return std::move(Err);
  6913. DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
  6914. // Import additional name location/type info.
  6915. if (Error Err =
  6916. ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo))
  6917. return std::move(Err);
  6918. return CXXDependentScopeMemberExpr::Create(
  6919. Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc,
  6920. ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope,
  6921. ToMemberNameInfo, ResInfo);
  6922. }
  6923. ExpectedStmt
  6924. ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
  6925. Error Err = Error::success();
  6926. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  6927. auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
  6928. auto ToDeclName = importChecked(Err, E->getDeclName());
  6929. auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc());
  6930. auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc());
  6931. auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc());
  6932. if (Err)
  6933. return std::move(Err);
  6934. DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
  6935. if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
  6936. return std::move(Err);
  6937. TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
  6938. TemplateArgumentListInfo *ResInfo = nullptr;
  6939. if (E->hasExplicitTemplateArgs()) {
  6940. if (Error Err =
  6941. ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
  6942. return std::move(Err);
  6943. ResInfo = &ToTAInfo;
  6944. }
  6945. return DependentScopeDeclRefExpr::Create(
  6946. Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc,
  6947. ToNameInfo, ResInfo);
  6948. }
  6949. ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
  6950. CXXUnresolvedConstructExpr *E) {
  6951. Error Err = Error::success();
  6952. auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
  6953. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  6954. auto ToType = importChecked(Err, E->getType());
  6955. auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
  6956. if (Err)
  6957. return std::move(Err);
  6958. SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
  6959. if (Error Err =
  6960. ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
  6961. return std::move(Err);
  6962. return CXXUnresolvedConstructExpr::Create(
  6963. Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc,
  6964. llvm::ArrayRef(ToArgs), ToRParenLoc);
  6965. }
  6966. ExpectedStmt
  6967. ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
  6968. Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass());
  6969. if (!ToNamingClassOrErr)
  6970. return ToNamingClassOrErr.takeError();
  6971. auto ToQualifierLocOrErr = import(E->getQualifierLoc());
  6972. if (!ToQualifierLocOrErr)
  6973. return ToQualifierLocOrErr.takeError();
  6974. Error Err = Error::success();
  6975. auto ToName = importChecked(Err, E->getName());
  6976. auto ToNameLoc = importChecked(Err, E->getNameLoc());
  6977. if (Err)
  6978. return std::move(Err);
  6979. DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
  6980. // Import additional name location/type info.
  6981. if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
  6982. return std::move(Err);
  6983. UnresolvedSet<8> ToDecls;
  6984. for (auto *D : E->decls())
  6985. if (auto ToDOrErr = import(D))
  6986. ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
  6987. else
  6988. return ToDOrErr.takeError();
  6989. if (E->hasExplicitTemplateArgs()) {
  6990. TemplateArgumentListInfo ToTAInfo;
  6991. if (Error Err = ImportTemplateArgumentListInfo(
  6992. E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
  6993. ToTAInfo))
  6994. return std::move(Err);
  6995. ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
  6996. if (!ToTemplateKeywordLocOrErr)
  6997. return ToTemplateKeywordLocOrErr.takeError();
  6998. return UnresolvedLookupExpr::Create(
  6999. Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
  7000. *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
  7001. ToDecls.begin(), ToDecls.end());
  7002. }
  7003. return UnresolvedLookupExpr::Create(
  7004. Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
  7005. ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(),
  7006. ToDecls.end());
  7007. }
  7008. ExpectedStmt
  7009. ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
  7010. Error Err = Error::success();
  7011. auto ToType = importChecked(Err, E->getType());
  7012. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  7013. auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
  7014. auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
  7015. auto ToName = importChecked(Err, E->getName());
  7016. auto ToNameLoc = importChecked(Err, E->getNameLoc());
  7017. if (Err)
  7018. return std::move(Err);
  7019. DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
  7020. // Import additional name location/type info.
  7021. if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
  7022. return std::move(Err);
  7023. UnresolvedSet<8> ToDecls;
  7024. for (Decl *D : E->decls())
  7025. if (auto ToDOrErr = import(D))
  7026. ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
  7027. else
  7028. return ToDOrErr.takeError();
  7029. TemplateArgumentListInfo ToTAInfo;
  7030. TemplateArgumentListInfo *ResInfo = nullptr;
  7031. if (E->hasExplicitTemplateArgs()) {
  7032. TemplateArgumentListInfo FromTAInfo;
  7033. E->copyTemplateArgumentsInto(FromTAInfo);
  7034. if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo))
  7035. return std::move(Err);
  7036. ResInfo = &ToTAInfo;
  7037. }
  7038. Expr *ToBase = nullptr;
  7039. if (!E->isImplicitAccess()) {
  7040. if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
  7041. ToBase = *ToBaseOrErr;
  7042. else
  7043. return ToBaseOrErr.takeError();
  7044. }
  7045. return UnresolvedMemberExpr::Create(
  7046. Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType,
  7047. E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
  7048. ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end());
  7049. }
  7050. ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
  7051. Error Err = Error::success();
  7052. auto ToCallee = importChecked(Err, E->getCallee());
  7053. auto ToType = importChecked(Err, E->getType());
  7054. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  7055. if (Err)
  7056. return std::move(Err);
  7057. unsigned NumArgs = E->getNumArgs();
  7058. llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
  7059. if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
  7060. return std::move(Err);
  7061. if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  7062. return CXXOperatorCallExpr::Create(
  7063. Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType,
  7064. OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(),
  7065. OCE->getADLCallKind());
  7066. }
  7067. return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType,
  7068. E->getValueKind(), ToRParenLoc, E->getFPFeatures(),
  7069. /*MinNumArgs=*/0, E->getADLCallKind());
  7070. }
  7071. ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
  7072. CXXRecordDecl *FromClass = E->getLambdaClass();
  7073. auto ToClassOrErr = import(FromClass);
  7074. if (!ToClassOrErr)
  7075. return ToClassOrErr.takeError();
  7076. CXXRecordDecl *ToClass = *ToClassOrErr;
  7077. auto ToCallOpOrErr = import(E->getCallOperator());
  7078. if (!ToCallOpOrErr)
  7079. return ToCallOpOrErr.takeError();
  7080. SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
  7081. if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits))
  7082. return std::move(Err);
  7083. Error Err = Error::success();
  7084. auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange());
  7085. auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc());
  7086. auto ToEndLoc = importChecked(Err, E->getEndLoc());
  7087. if (Err)
  7088. return std::move(Err);
  7089. return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange,
  7090. E->getCaptureDefault(), ToCaptureDefaultLoc,
  7091. E->hasExplicitParameters(),
  7092. E->hasExplicitResultType(), ToCaptureInits,
  7093. ToEndLoc, E->containsUnexpandedParameterPack());
  7094. }
  7095. ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
  7096. Error Err = Error::success();
  7097. auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc());
  7098. auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc());
  7099. auto ToType = importChecked(Err, E->getType());
  7100. if (Err)
  7101. return std::move(Err);
  7102. SmallVector<Expr *, 4> ToExprs(E->getNumInits());
  7103. if (Error Err = ImportContainerChecked(E->inits(), ToExprs))
  7104. return std::move(Err);
  7105. ASTContext &ToCtx = Importer.getToContext();
  7106. InitListExpr *To = new (ToCtx) InitListExpr(
  7107. ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
  7108. To->setType(ToType);
  7109. if (E->hasArrayFiller()) {
  7110. if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller()))
  7111. To->setArrayFiller(*ToFillerOrErr);
  7112. else
  7113. return ToFillerOrErr.takeError();
  7114. }
  7115. if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
  7116. if (auto ToFDOrErr = import(FromFD))
  7117. To->setInitializedFieldInUnion(*ToFDOrErr);
  7118. else
  7119. return ToFDOrErr.takeError();
  7120. }
  7121. if (InitListExpr *SyntForm = E->getSyntacticForm()) {
  7122. if (auto ToSyntFormOrErr = import(SyntForm))
  7123. To->setSyntacticForm(*ToSyntFormOrErr);
  7124. else
  7125. return ToSyntFormOrErr.takeError();
  7126. }
  7127. // Copy InitListExprBitfields, which are not handled in the ctor of
  7128. // InitListExpr.
  7129. To->sawArrayRangeDesignator(E->hadArrayRangeDesignator());
  7130. return To;
  7131. }
  7132. ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
  7133. CXXStdInitializerListExpr *E) {
  7134. ExpectedType ToTypeOrErr = import(E->getType());
  7135. if (!ToTypeOrErr)
  7136. return ToTypeOrErr.takeError();
  7137. ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
  7138. if (!ToSubExprOrErr)
  7139. return ToSubExprOrErr.takeError();
  7140. return new (Importer.getToContext()) CXXStdInitializerListExpr(
  7141. *ToTypeOrErr, *ToSubExprOrErr);
  7142. }
  7143. ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
  7144. CXXInheritedCtorInitExpr *E) {
  7145. Error Err = Error::success();
  7146. auto ToLocation = importChecked(Err, E->getLocation());
  7147. auto ToType = importChecked(Err, E->getType());
  7148. auto ToConstructor = importChecked(Err, E->getConstructor());
  7149. if (Err)
  7150. return std::move(Err);
  7151. return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
  7152. ToLocation, ToType, ToConstructor, E->constructsVBase(),
  7153. E->inheritedFromVBase());
  7154. }
  7155. ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
  7156. Error Err = Error::success();
  7157. auto ToType = importChecked(Err, E->getType());
  7158. auto ToCommonExpr = importChecked(Err, E->getCommonExpr());
  7159. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  7160. if (Err)
  7161. return std::move(Err);
  7162. return new (Importer.getToContext()) ArrayInitLoopExpr(
  7163. ToType, ToCommonExpr, ToSubExpr);
  7164. }
  7165. ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
  7166. ExpectedType ToTypeOrErr = import(E->getType());
  7167. if (!ToTypeOrErr)
  7168. return ToTypeOrErr.takeError();
  7169. return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
  7170. }
  7171. ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
  7172. ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc());
  7173. if (!ToBeginLocOrErr)
  7174. return ToBeginLocOrErr.takeError();
  7175. auto ToFieldOrErr = import(E->getField());
  7176. if (!ToFieldOrErr)
  7177. return ToFieldOrErr.takeError();
  7178. auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
  7179. if (!UsedContextOrErr)
  7180. return UsedContextOrErr.takeError();
  7181. FieldDecl *ToField = *ToFieldOrErr;
  7182. assert(ToField->hasInClassInitializer() &&
  7183. "Field should have in-class initializer if there is a default init "
  7184. "expression that uses it.");
  7185. if (!ToField->getInClassInitializer()) {
  7186. // The in-class initializer may be not yet set in "To" AST even if the
  7187. // field is already there. This must be set here to make construction of
  7188. // CXXDefaultInitExpr work.
  7189. auto ToInClassInitializerOrErr =
  7190. import(E->getField()->getInClassInitializer());
  7191. if (!ToInClassInitializerOrErr)
  7192. return ToInClassInitializerOrErr.takeError();
  7193. ToField->setInClassInitializer(*ToInClassInitializerOrErr);
  7194. }
  7195. Expr *RewrittenInit = nullptr;
  7196. if (E->hasRewrittenInit()) {
  7197. ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
  7198. if (!ExprOrErr)
  7199. return ExprOrErr.takeError();
  7200. RewrittenInit = ExprOrErr.get();
  7201. }
  7202. return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr,
  7203. ToField, *UsedContextOrErr, RewrittenInit);
  7204. }
  7205. ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
  7206. Error Err = Error::success();
  7207. auto ToType = importChecked(Err, E->getType());
  7208. auto ToSubExpr = importChecked(Err, E->getSubExpr());
  7209. auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
  7210. auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
  7211. auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
  7212. auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets());
  7213. if (Err)
  7214. return std::move(Err);
  7215. ExprValueKind VK = E->getValueKind();
  7216. CastKind CK = E->getCastKind();
  7217. auto ToBasePathOrErr = ImportCastPath(E);
  7218. if (!ToBasePathOrErr)
  7219. return ToBasePathOrErr.takeError();
  7220. if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) {
  7221. return CXXStaticCastExpr::Create(
  7222. Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
  7223. ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc,
  7224. ToAngleBrackets);
  7225. } else if (isa<CXXDynamicCastExpr>(E)) {
  7226. return CXXDynamicCastExpr::Create(
  7227. Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
  7228. ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
  7229. } else if (isa<CXXReinterpretCastExpr>(E)) {
  7230. return CXXReinterpretCastExpr::Create(
  7231. Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
  7232. ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
  7233. } else if (isa<CXXConstCastExpr>(E)) {
  7234. return CXXConstCastExpr::Create(
  7235. Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten,
  7236. ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
  7237. } else {
  7238. llvm_unreachable("Unknown cast type");
  7239. return make_error<ASTImportError>();
  7240. }
  7241. }
  7242. ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
  7243. SubstNonTypeTemplateParmExpr *E) {
  7244. Error Err = Error::success();
  7245. auto ToType = importChecked(Err, E->getType());
  7246. auto ToExprLoc = importChecked(Err, E->getExprLoc());
  7247. auto ToAssociatedDecl = importChecked(Err, E->getAssociatedDecl());
  7248. auto ToReplacement = importChecked(Err, E->getReplacement());
  7249. if (Err)
  7250. return std::move(Err);
  7251. return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
  7252. ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl,
  7253. E->getIndex(), E->getPackIndex(), E->isReferenceParameter());
  7254. }
  7255. ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
  7256. Error Err = Error::success();
  7257. auto ToType = importChecked(Err, E->getType());
  7258. auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
  7259. auto ToEndLoc = importChecked(Err, E->getEndLoc());
  7260. if (Err)
  7261. return std::move(Err);
  7262. SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
  7263. if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs))
  7264. return std::move(Err);
  7265. // According to Sema::BuildTypeTrait(), if E is value-dependent,
  7266. // Value is always false.
  7267. bool ToValue = (E->isValueDependent() ? false : E->getValue());
  7268. return TypeTraitExpr::Create(
  7269. Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs,
  7270. ToEndLoc, ToValue);
  7271. }
  7272. ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
  7273. ExpectedType ToTypeOrErr = import(E->getType());
  7274. if (!ToTypeOrErr)
  7275. return ToTypeOrErr.takeError();
  7276. auto ToSourceRangeOrErr = import(E->getSourceRange());
  7277. if (!ToSourceRangeOrErr)
  7278. return ToSourceRangeOrErr.takeError();
  7279. if (E->isTypeOperand()) {
  7280. if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo()))
  7281. return new (Importer.getToContext()) CXXTypeidExpr(
  7282. *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
  7283. else
  7284. return ToTSIOrErr.takeError();
  7285. }
  7286. ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand());
  7287. if (!ToExprOperandOrErr)
  7288. return ToExprOperandOrErr.takeError();
  7289. return new (Importer.getToContext()) CXXTypeidExpr(
  7290. *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
  7291. }
  7292. ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
  7293. Error Err = Error::success();
  7294. QualType ToType = importChecked(Err, E->getType());
  7295. UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
  7296. SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
  7297. Expr *ToLHS = importChecked(Err, E->getLHS());
  7298. SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
  7299. Expr *ToRHS = importChecked(Err, E->getRHS());
  7300. SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
  7301. if (Err)
  7302. return std::move(Err);
  7303. return new (Importer.getToContext())
  7304. CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
  7305. ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
  7306. }
  7307. Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
  7308. CXXMethodDecl *FromMethod) {
  7309. Error ImportErrors = Error::success();
  7310. for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
  7311. if (auto ImportedOrErr = import(FromOverriddenMethod))
  7312. ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>(
  7313. (*ImportedOrErr)->getCanonicalDecl()));
  7314. else
  7315. ImportErrors =
  7316. joinErrors(std::move(ImportErrors), ImportedOrErr.takeError());
  7317. }
  7318. return ImportErrors;
  7319. }
  7320. ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
  7321. ASTContext &FromContext, FileManager &FromFileManager,
  7322. bool MinimalImport,
  7323. std::shared_ptr<ASTImporterSharedState> SharedState)
  7324. : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
  7325. ToFileManager(ToFileManager), FromFileManager(FromFileManager),
  7326. Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
  7327. // Create a default state without the lookup table: LLDB case.
  7328. if (!SharedState) {
  7329. this->SharedState = std::make_shared<ASTImporterSharedState>();
  7330. }
  7331. ImportedDecls[FromContext.getTranslationUnitDecl()] =
  7332. ToContext.getTranslationUnitDecl();
  7333. }
  7334. ASTImporter::~ASTImporter() = default;
  7335. std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
  7336. assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
  7337. "Try to get field index for non-field.");
  7338. auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
  7339. if (!Owner)
  7340. return std::nullopt;
  7341. unsigned Index = 0;
  7342. for (const auto *D : Owner->decls()) {
  7343. if (D == F)
  7344. return Index;
  7345. if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
  7346. ++Index;
  7347. }
  7348. llvm_unreachable("Field was not found in its parent context.");
  7349. return std::nullopt;
  7350. }
  7351. ASTImporter::FoundDeclsTy
  7352. ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
  7353. // We search in the redecl context because of transparent contexts.
  7354. // E.g. a simple C language enum is a transparent context:
  7355. // enum E { A, B };
  7356. // Now if we had a global variable in the TU
  7357. // int A;
  7358. // then the enum constant 'A' and the variable 'A' violates ODR.
  7359. // We can diagnose this only if we search in the redecl context.
  7360. DeclContext *ReDC = DC->getRedeclContext();
  7361. if (SharedState->getLookupTable()) {
  7362. ASTImporterLookupTable::LookupResult LookupResult =
  7363. SharedState->getLookupTable()->lookup(ReDC, Name);
  7364. return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
  7365. } else {
  7366. DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
  7367. FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
  7368. // We must search by the slow case of localUncachedLookup because that is
  7369. // working even if there is no LookupPtr for the DC. We could use
  7370. // DC::buildLookup() to create the LookupPtr, but that would load external
  7371. // decls again, we must avoid that case.
  7372. // Also, even if we had the LookupPtr, we must find Decls which are not
  7373. // in the LookupPtr, so we need the slow case.
  7374. // These cases are handled in ASTImporterLookupTable, but we cannot use
  7375. // that with LLDB since that traverses through the AST which initiates the
  7376. // load of external decls again via DC::decls(). And again, we must avoid
  7377. // loading external decls during the import.
  7378. if (Result.empty())
  7379. ReDC->localUncachedLookup(Name, Result);
  7380. return Result;
  7381. }
  7382. }
  7383. void ASTImporter::AddToLookupTable(Decl *ToD) {
  7384. SharedState->addDeclToLookup(ToD);
  7385. }
  7386. Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
  7387. // Import the decl using ASTNodeImporter.
  7388. ASTNodeImporter Importer(*this);
  7389. return Importer.Visit(FromD);
  7390. }
  7391. void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
  7392. MapImported(FromD, ToD);
  7393. }
  7394. llvm::Expected<ExprWithCleanups::CleanupObject>
  7395. ASTImporter::Import(ExprWithCleanups::CleanupObject From) {
  7396. if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
  7397. if (Expected<Expr *> R = Import(CLE))
  7398. return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R));
  7399. }
  7400. // FIXME: Handle BlockDecl when we implement importing BlockExpr in
  7401. // ASTNodeImporter.
  7402. return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
  7403. }
  7404. ExpectedTypePtr ASTImporter::Import(const Type *FromT) {
  7405. if (!FromT)
  7406. return FromT;
  7407. // Check whether we've already imported this type.
  7408. llvm::DenseMap<const Type *, const Type *>::iterator Pos =
  7409. ImportedTypes.find(FromT);
  7410. if (Pos != ImportedTypes.end())
  7411. return Pos->second;
  7412. // Import the type.
  7413. ASTNodeImporter Importer(*this);
  7414. ExpectedType ToTOrErr = Importer.Visit(FromT);
  7415. if (!ToTOrErr)
  7416. return ToTOrErr.takeError();
  7417. // Record the imported type.
  7418. ImportedTypes[FromT] = ToTOrErr->getTypePtr();
  7419. return ToTOrErr->getTypePtr();
  7420. }
  7421. Expected<QualType> ASTImporter::Import(QualType FromT) {
  7422. if (FromT.isNull())
  7423. return QualType{};
  7424. ExpectedTypePtr ToTyOrErr = Import(FromT.getTypePtr());
  7425. if (!ToTyOrErr)
  7426. return ToTyOrErr.takeError();
  7427. return ToContext.getQualifiedType(*ToTyOrErr, FromT.getLocalQualifiers());
  7428. }
  7429. Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
  7430. if (!FromTSI)
  7431. return FromTSI;
  7432. // FIXME: For now we just create a "trivial" type source info based
  7433. // on the type and a single location. Implement a real version of this.
  7434. ExpectedType TOrErr = Import(FromTSI->getType());
  7435. if (!TOrErr)
  7436. return TOrErr.takeError();
  7437. ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc());
  7438. if (!BeginLocOrErr)
  7439. return BeginLocOrErr.takeError();
  7440. return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
  7441. }
  7442. namespace {
  7443. // To use this object, it should be created before the new attribute is created,
  7444. // and destructed after it is created. The construction already performs the
  7445. // import of the data.
  7446. template <typename T> struct AttrArgImporter {
  7447. AttrArgImporter(const AttrArgImporter<T> &) = delete;
  7448. AttrArgImporter(AttrArgImporter<T> &&) = default;
  7449. AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete;
  7450. AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default;
  7451. AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From)
  7452. : To(I.importChecked(Err, From)) {}
  7453. const T &value() { return To; }
  7454. private:
  7455. T To;
  7456. };
  7457. // To use this object, it should be created before the new attribute is created,
  7458. // and destructed after it is created. The construction already performs the
  7459. // import of the data. The array data is accessible in a pointer form, this form
  7460. // is used by the attribute classes. This object should be created once for the
  7461. // array data to be imported (the array size is not imported, just copied).
  7462. template <typename T> struct AttrArgArrayImporter {
  7463. AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete;
  7464. AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default;
  7465. AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete;
  7466. AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default;
  7467. AttrArgArrayImporter(ASTNodeImporter &I, Error &Err,
  7468. const llvm::iterator_range<T *> &From,
  7469. unsigned ArraySize) {
  7470. if (Err)
  7471. return;
  7472. To.reserve(ArraySize);
  7473. Err = I.ImportContainerChecked(From, To);
  7474. }
  7475. T *value() { return To.data(); }
  7476. private:
  7477. llvm::SmallVector<T, 2> To;
  7478. };
  7479. class AttrImporter {
  7480. Error Err{Error::success()};
  7481. Attr *ToAttr = nullptr;
  7482. ASTImporter &Importer;
  7483. ASTNodeImporter NImporter;
  7484. public:
  7485. AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {}
  7486. // Create an "importer" for an attribute parameter.
  7487. // Result of the 'value()' of that object is to be passed to the function
  7488. // 'importAttr', in the order that is expected by the attribute class.
  7489. template <class T> AttrArgImporter<T> importArg(const T &From) {
  7490. return AttrArgImporter<T>(NImporter, Err, From);
  7491. }
  7492. // Create an "importer" for an attribute parameter that has array type.
  7493. // Result of the 'value()' of that object is to be passed to the function
  7494. // 'importAttr', then the size of the array as next argument.
  7495. template <typename T>
  7496. AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From,
  7497. unsigned ArraySize) {
  7498. return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize);
  7499. }
  7500. // Create an attribute object with the specified arguments.
  7501. // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg'
  7502. // should be values that are passed to the 'Create' function of the attribute.
  7503. // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is
  7504. // used here.) As much data is copied or imported from the old attribute
  7505. // as possible. The passed arguments should be already imported.
  7506. // If an import error happens, the internal error is set to it, and any
  7507. // further import attempt is ignored.
  7508. template <typename T, typename... Arg>
  7509. void importAttr(const T *FromAttr, Arg &&...ImportedArg) {
  7510. static_assert(std::is_base_of<Attr, T>::value,
  7511. "T should be subclass of Attr.");
  7512. assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
  7513. const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName());
  7514. const IdentifierInfo *ToScopeName =
  7515. Importer.Import(FromAttr->getScopeName());
  7516. SourceRange ToAttrRange =
  7517. NImporter.importChecked(Err, FromAttr->getRange());
  7518. SourceLocation ToScopeLoc =
  7519. NImporter.importChecked(Err, FromAttr->getScopeLoc());
  7520. if (Err)
  7521. return;
  7522. AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc,
  7523. FromAttr->getParsedKind(), FromAttr->getSyntax(),
  7524. FromAttr->getAttributeSpellingListIndex());
  7525. // The "SemanticSpelling" is not needed to be passed to the constructor.
  7526. // That value is recalculated from the SpellingListIndex if needed.
  7527. ToAttr = T::Create(Importer.getToContext(),
  7528. std::forward<Arg>(ImportedArg)..., ToI);
  7529. ToAttr->setImplicit(FromAttr->isImplicit());
  7530. ToAttr->setPackExpansion(FromAttr->isPackExpansion());
  7531. if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(ToAttr))
  7532. ToInheritableAttr->setInherited(FromAttr->isInherited());
  7533. }
  7534. // Create a clone of the 'FromAttr' and import its source range only.
  7535. // This causes objects with invalid references to be created if the 'FromAttr'
  7536. // contains other data that should be imported.
  7537. void cloneAttr(const Attr *FromAttr) {
  7538. assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
  7539. SourceRange ToRange = NImporter.importChecked(Err, FromAttr->getRange());
  7540. if (Err)
  7541. return;
  7542. ToAttr = FromAttr->clone(Importer.getToContext());
  7543. ToAttr->setRange(ToRange);
  7544. }
  7545. // Get the result of the previous import attempt (can be used only once).
  7546. llvm::Expected<Attr *> getResult() && {
  7547. if (Err)
  7548. return std::move(Err);
  7549. assert(ToAttr && "Attribute should be created.");
  7550. return ToAttr;
  7551. }
  7552. };
  7553. } // namespace
  7554. Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
  7555. AttrImporter AI(*this);
  7556. // FIXME: Is there some kind of AttrVisitor to use here?
  7557. switch (FromAttr->getKind()) {
  7558. case attr::Aligned: {
  7559. auto *From = cast<AlignedAttr>(FromAttr);
  7560. if (From->isAlignmentExpr())
  7561. AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value());
  7562. else
  7563. AI.importAttr(From, false,
  7564. AI.importArg(From->getAlignmentType()).value());
  7565. break;
  7566. }
  7567. case attr::Format: {
  7568. const auto *From = cast<FormatAttr>(FromAttr);
  7569. AI.importAttr(From, Import(From->getType()), From->getFormatIdx(),
  7570. From->getFirstArg());
  7571. break;
  7572. }
  7573. case attr::EnableIf: {
  7574. const auto *From = cast<EnableIfAttr>(FromAttr);
  7575. AI.importAttr(From, AI.importArg(From->getCond()).value(),
  7576. From->getMessage());
  7577. break;
  7578. }
  7579. case attr::AssertCapability: {
  7580. const auto *From = cast<AssertCapabilityAttr>(FromAttr);
  7581. AI.importAttr(From,
  7582. AI.importArrayArg(From->args(), From->args_size()).value(),
  7583. From->args_size());
  7584. break;
  7585. }
  7586. case attr::AcquireCapability: {
  7587. const auto *From = cast<AcquireCapabilityAttr>(FromAttr);
  7588. AI.importAttr(From,
  7589. AI.importArrayArg(From->args(), From->args_size()).value(),
  7590. From->args_size());
  7591. break;
  7592. }
  7593. case attr::TryAcquireCapability: {
  7594. const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr);
  7595. AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
  7596. AI.importArrayArg(From->args(), From->args_size()).value(),
  7597. From->args_size());
  7598. break;
  7599. }
  7600. case attr::ReleaseCapability: {
  7601. const auto *From = cast<ReleaseCapabilityAttr>(FromAttr);
  7602. AI.importAttr(From,
  7603. AI.importArrayArg(From->args(), From->args_size()).value(),
  7604. From->args_size());
  7605. break;
  7606. }
  7607. case attr::RequiresCapability: {
  7608. const auto *From = cast<RequiresCapabilityAttr>(FromAttr);
  7609. AI.importAttr(From,
  7610. AI.importArrayArg(From->args(), From->args_size()).value(),
  7611. From->args_size());
  7612. break;
  7613. }
  7614. case attr::GuardedBy: {
  7615. const auto *From = cast<GuardedByAttr>(FromAttr);
  7616. AI.importAttr(From, AI.importArg(From->getArg()).value());
  7617. break;
  7618. }
  7619. case attr::PtGuardedBy: {
  7620. const auto *From = cast<PtGuardedByAttr>(FromAttr);
  7621. AI.importAttr(From, AI.importArg(From->getArg()).value());
  7622. break;
  7623. }
  7624. case attr::AcquiredAfter: {
  7625. const auto *From = cast<AcquiredAfterAttr>(FromAttr);
  7626. AI.importAttr(From,
  7627. AI.importArrayArg(From->args(), From->args_size()).value(),
  7628. From->args_size());
  7629. break;
  7630. }
  7631. case attr::AcquiredBefore: {
  7632. const auto *From = cast<AcquiredBeforeAttr>(FromAttr);
  7633. AI.importAttr(From,
  7634. AI.importArrayArg(From->args(), From->args_size()).value(),
  7635. From->args_size());
  7636. break;
  7637. }
  7638. case attr::AssertExclusiveLock: {
  7639. const auto *From = cast<AssertExclusiveLockAttr>(FromAttr);
  7640. AI.importAttr(From,
  7641. AI.importArrayArg(From->args(), From->args_size()).value(),
  7642. From->args_size());
  7643. break;
  7644. }
  7645. case attr::AssertSharedLock: {
  7646. const auto *From = cast<AssertSharedLockAttr>(FromAttr);
  7647. AI.importAttr(From,
  7648. AI.importArrayArg(From->args(), From->args_size()).value(),
  7649. From->args_size());
  7650. break;
  7651. }
  7652. case attr::ExclusiveTrylockFunction: {
  7653. const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr);
  7654. AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
  7655. AI.importArrayArg(From->args(), From->args_size()).value(),
  7656. From->args_size());
  7657. break;
  7658. }
  7659. case attr::SharedTrylockFunction: {
  7660. const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr);
  7661. AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
  7662. AI.importArrayArg(From->args(), From->args_size()).value(),
  7663. From->args_size());
  7664. break;
  7665. }
  7666. case attr::LockReturned: {
  7667. const auto *From = cast<LockReturnedAttr>(FromAttr);
  7668. AI.importAttr(From, AI.importArg(From->getArg()).value());
  7669. break;
  7670. }
  7671. case attr::LocksExcluded: {
  7672. const auto *From = cast<LocksExcludedAttr>(FromAttr);
  7673. AI.importAttr(From,
  7674. AI.importArrayArg(From->args(), From->args_size()).value(),
  7675. From->args_size());
  7676. break;
  7677. }
  7678. default: {
  7679. // The default branch works for attributes that have no arguments to import.
  7680. // FIXME: Handle every attribute type that has arguments of type to import
  7681. // (most often Expr* or Decl* or type) in the switch above.
  7682. AI.cloneAttr(FromAttr);
  7683. break;
  7684. }
  7685. }
  7686. return std::move(AI).getResult();
  7687. }
  7688. Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
  7689. auto Pos = ImportedDecls.find(FromD);
  7690. if (Pos != ImportedDecls.end())
  7691. return Pos->second;
  7692. else
  7693. return nullptr;
  7694. }
  7695. TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
  7696. auto FromDPos = ImportedFromDecls.find(ToD);
  7697. if (FromDPos == ImportedFromDecls.end())
  7698. return nullptr;
  7699. return FromDPos->second->getTranslationUnitDecl();
  7700. }
  7701. Expected<Decl *> ASTImporter::Import(Decl *FromD) {
  7702. if (!FromD)
  7703. return nullptr;
  7704. // Push FromD to the stack, and remove that when we return.
  7705. ImportPath.push(FromD);
  7706. auto ImportPathBuilder =
  7707. llvm::make_scope_exit([this]() { ImportPath.pop(); });
  7708. // Check whether there was a previous failed import.
  7709. // If yes return the existing error.
  7710. if (auto Error = getImportDeclErrorIfAny(FromD))
  7711. return make_error<ASTImportError>(*Error);
  7712. // Check whether we've already imported this declaration.
  7713. Decl *ToD = GetAlreadyImportedOrNull(FromD);
  7714. if (ToD) {
  7715. // Already imported (possibly from another TU) and with an error.
  7716. if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
  7717. setImportDeclError(FromD, *Error);
  7718. return make_error<ASTImportError>(*Error);
  7719. }
  7720. // If FromD has some updated flags after last import, apply it.
  7721. updateFlags(FromD, ToD);
  7722. // If we encounter a cycle during an import then we save the relevant part
  7723. // of the import path associated to the Decl.
  7724. if (ImportPath.hasCycleAtBack())
  7725. SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack());
  7726. return ToD;
  7727. }
  7728. // Import the declaration.
  7729. ExpectedDecl ToDOrErr = ImportImpl(FromD);
  7730. if (!ToDOrErr) {
  7731. // Failed to import.
  7732. auto Pos = ImportedDecls.find(FromD);
  7733. if (Pos != ImportedDecls.end()) {
  7734. // Import failed after the object was created.
  7735. // Remove all references to it.
  7736. auto *ToD = Pos->second;
  7737. ImportedDecls.erase(Pos);
  7738. // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
  7739. // (e.g. with namespaces) that several decls from the 'from' context are
  7740. // mapped to the same decl in the 'to' context. If we removed entries
  7741. // from the LookupTable here then we may end up removing them multiple
  7742. // times.
  7743. // The Lookuptable contains decls only which are in the 'to' context.
  7744. // Remove from the Lookuptable only if it is *imported* into the 'to'
  7745. // context (and do not remove it if it was added during the initial
  7746. // traverse of the 'to' context).
  7747. auto PosF = ImportedFromDecls.find(ToD);
  7748. if (PosF != ImportedFromDecls.end()) {
  7749. // In the case of TypedefNameDecl we create the Decl first and only
  7750. // then we import and set its DeclContext. So, the DC might not be set
  7751. // when we reach here.
  7752. if (ToD->getDeclContext())
  7753. SharedState->removeDeclFromLookup(ToD);
  7754. ImportedFromDecls.erase(PosF);
  7755. }
  7756. // FIXME: AST may contain remaining references to the failed object.
  7757. // However, the ImportDeclErrors in the shared state contains all the
  7758. // failed objects together with their error.
  7759. }
  7760. // Error encountered for the first time.
  7761. // After takeError the error is not usable any more in ToDOrErr.
  7762. // Get a copy of the error object (any more simple solution for this?).
  7763. ASTImportError ErrOut;
  7764. handleAllErrors(ToDOrErr.takeError(),
  7765. [&ErrOut](const ASTImportError &E) { ErrOut = E; });
  7766. setImportDeclError(FromD, ErrOut);
  7767. // Set the error for the mapped to Decl, which is in the "to" context.
  7768. if (Pos != ImportedDecls.end())
  7769. SharedState->setImportDeclError(Pos->second, ErrOut);
  7770. // Set the error for all nodes which have been created before we
  7771. // recognized the error.
  7772. for (const auto &Path : SavedImportPaths[FromD]) {
  7773. // The import path contains import-dependency nodes first.
  7774. // Save the node that was imported as dependency of the current node.
  7775. Decl *PrevFromDi = FromD;
  7776. for (Decl *FromDi : Path) {
  7777. // Begin and end of the path equals 'FromD', skip it.
  7778. if (FromDi == FromD)
  7779. continue;
  7780. // We should not set import error on a node and all following nodes in
  7781. // the path if child import errors are ignored.
  7782. if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent(
  7783. PrevFromDi))
  7784. break;
  7785. PrevFromDi = FromDi;
  7786. setImportDeclError(FromDi, ErrOut);
  7787. //FIXME Should we remove these Decls from ImportedDecls?
  7788. // Set the error for the mapped to Decl, which is in the "to" context.
  7789. auto Ii = ImportedDecls.find(FromDi);
  7790. if (Ii != ImportedDecls.end())
  7791. SharedState->setImportDeclError(Ii->second, ErrOut);
  7792. // FIXME Should we remove these Decls from the LookupTable,
  7793. // and from ImportedFromDecls?
  7794. }
  7795. }
  7796. SavedImportPaths.erase(FromD);
  7797. // Do not return ToDOrErr, error was taken out of it.
  7798. return make_error<ASTImportError>(ErrOut);
  7799. }
  7800. ToD = *ToDOrErr;
  7801. // FIXME: Handle the "already imported with error" case. We can get here
  7802. // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
  7803. // previously failed create was requested).
  7804. // Later GetImportedOrCreateDecl can be updated to return the error.
  7805. if (!ToD) {
  7806. auto Err = getImportDeclErrorIfAny(FromD);
  7807. assert(Err);
  7808. return make_error<ASTImportError>(*Err);
  7809. }
  7810. // We could import from the current TU without error. But previously we
  7811. // already had imported a Decl as `ToD` from another TU (with another
  7812. // ASTImporter object) and with an error.
  7813. if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
  7814. setImportDeclError(FromD, *Error);
  7815. return make_error<ASTImportError>(*Error);
  7816. }
  7817. // Make sure that ImportImpl registered the imported decl.
  7818. assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
  7819. if (FromD->hasAttrs())
  7820. for (const Attr *FromAttr : FromD->getAttrs()) {
  7821. auto ToAttrOrErr = Import(FromAttr);
  7822. if (ToAttrOrErr)
  7823. ToD->addAttr(*ToAttrOrErr);
  7824. else
  7825. return ToAttrOrErr.takeError();
  7826. }
  7827. // Notify subclasses.
  7828. Imported(FromD, ToD);
  7829. updateFlags(FromD, ToD);
  7830. SavedImportPaths.erase(FromD);
  7831. return ToDOrErr;
  7832. }
  7833. llvm::Expected<InheritedConstructor>
  7834. ASTImporter::Import(const InheritedConstructor &From) {
  7835. return ASTNodeImporter(*this).ImportInheritedConstructor(From);
  7836. }
  7837. Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
  7838. if (!FromDC)
  7839. return FromDC;
  7840. ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC));
  7841. if (!ToDCOrErr)
  7842. return ToDCOrErr.takeError();
  7843. auto *ToDC = cast<DeclContext>(*ToDCOrErr);
  7844. // When we're using a record/enum/Objective-C class/protocol as a context, we
  7845. // need it to have a definition.
  7846. if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
  7847. auto *FromRecord = cast<RecordDecl>(FromDC);
  7848. if (ToRecord->isCompleteDefinition())
  7849. return ToDC;
  7850. // If FromRecord is not defined we need to force it to be.
  7851. // Simply calling CompleteDecl(...) for a RecordDecl will break some cases
  7852. // it will start the definition but we never finish it.
  7853. // If there are base classes they won't be imported and we will
  7854. // be missing anything that we inherit from those bases.
  7855. if (FromRecord->getASTContext().getExternalSource() &&
  7856. !FromRecord->isCompleteDefinition())
  7857. FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord);
  7858. if (FromRecord->isCompleteDefinition())
  7859. if (Error Err = ASTNodeImporter(*this).ImportDefinition(
  7860. FromRecord, ToRecord, ASTNodeImporter::IDK_Basic))
  7861. return std::move(Err);
  7862. } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
  7863. auto *FromEnum = cast<EnumDecl>(FromDC);
  7864. if (ToEnum->isCompleteDefinition()) {
  7865. // Do nothing.
  7866. } else if (FromEnum->isCompleteDefinition()) {
  7867. if (Error Err = ASTNodeImporter(*this).ImportDefinition(
  7868. FromEnum, ToEnum, ASTNodeImporter::IDK_Basic))
  7869. return std::move(Err);
  7870. } else {
  7871. CompleteDecl(ToEnum);
  7872. }
  7873. } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
  7874. auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
  7875. if (ToClass->getDefinition()) {
  7876. // Do nothing.
  7877. } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
  7878. if (Error Err = ASTNodeImporter(*this).ImportDefinition(
  7879. FromDef, ToClass, ASTNodeImporter::IDK_Basic))
  7880. return std::move(Err);
  7881. } else {
  7882. CompleteDecl(ToClass);
  7883. }
  7884. } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
  7885. auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
  7886. if (ToProto->getDefinition()) {
  7887. // Do nothing.
  7888. } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
  7889. if (Error Err = ASTNodeImporter(*this).ImportDefinition(
  7890. FromDef, ToProto, ASTNodeImporter::IDK_Basic))
  7891. return std::move(Err);
  7892. } else {
  7893. CompleteDecl(ToProto);
  7894. }
  7895. }
  7896. return ToDC;
  7897. }
  7898. Expected<Expr *> ASTImporter::Import(Expr *FromE) {
  7899. if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE)))
  7900. return cast_or_null<Expr>(*ToSOrErr);
  7901. else
  7902. return ToSOrErr.takeError();
  7903. }
  7904. Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
  7905. if (!FromS)
  7906. return nullptr;
  7907. // Check whether we've already imported this statement.
  7908. llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
  7909. if (Pos != ImportedStmts.end())
  7910. return Pos->second;
  7911. // Import the statement.
  7912. ASTNodeImporter Importer(*this);
  7913. ExpectedStmt ToSOrErr = Importer.Visit(FromS);
  7914. if (!ToSOrErr)
  7915. return ToSOrErr;
  7916. if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
  7917. auto *FromE = cast<Expr>(FromS);
  7918. // Copy ExprBitfields, which may not be handled in Expr subclasses
  7919. // constructors.
  7920. ToE->setValueKind(FromE->getValueKind());
  7921. ToE->setObjectKind(FromE->getObjectKind());
  7922. ToE->setDependence(FromE->getDependence());
  7923. }
  7924. // Record the imported statement object.
  7925. ImportedStmts[FromS] = *ToSOrErr;
  7926. return ToSOrErr;
  7927. }
  7928. Expected<NestedNameSpecifier *>
  7929. ASTImporter::Import(NestedNameSpecifier *FromNNS) {
  7930. if (!FromNNS)
  7931. return nullptr;
  7932. NestedNameSpecifier *Prefix = nullptr;
  7933. if (Error Err = importInto(Prefix, FromNNS->getPrefix()))
  7934. return std::move(Err);
  7935. switch (FromNNS->getKind()) {
  7936. case NestedNameSpecifier::Identifier:
  7937. assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
  7938. return NestedNameSpecifier::Create(ToContext, Prefix,
  7939. Import(FromNNS->getAsIdentifier()));
  7940. case NestedNameSpecifier::Namespace:
  7941. if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
  7942. return NestedNameSpecifier::Create(ToContext, Prefix,
  7943. cast<NamespaceDecl>(*NSOrErr));
  7944. } else
  7945. return NSOrErr.takeError();
  7946. case NestedNameSpecifier::NamespaceAlias:
  7947. if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
  7948. return NestedNameSpecifier::Create(ToContext, Prefix,
  7949. cast<NamespaceAliasDecl>(*NSADOrErr));
  7950. else
  7951. return NSADOrErr.takeError();
  7952. case NestedNameSpecifier::Global:
  7953. return NestedNameSpecifier::GlobalSpecifier(ToContext);
  7954. case NestedNameSpecifier::Super:
  7955. if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
  7956. return NestedNameSpecifier::SuperSpecifier(ToContext,
  7957. cast<CXXRecordDecl>(*RDOrErr));
  7958. else
  7959. return RDOrErr.takeError();
  7960. case NestedNameSpecifier::TypeSpec:
  7961. case NestedNameSpecifier::TypeSpecWithTemplate:
  7962. if (ExpectedTypePtr TyOrErr = Import(FromNNS->getAsType())) {
  7963. bool TSTemplate =
  7964. FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
  7965. return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate,
  7966. *TyOrErr);
  7967. } else {
  7968. return TyOrErr.takeError();
  7969. }
  7970. }
  7971. llvm_unreachable("Invalid nested name specifier kind");
  7972. }
  7973. Expected<NestedNameSpecifierLoc>
  7974. ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
  7975. // Copied from NestedNameSpecifier mostly.
  7976. SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
  7977. NestedNameSpecifierLoc NNS = FromNNS;
  7978. // Push each of the nested-name-specifiers's onto a stack for
  7979. // serialization in reverse order.
  7980. while (NNS) {
  7981. NestedNames.push_back(NNS);
  7982. NNS = NNS.getPrefix();
  7983. }
  7984. NestedNameSpecifierLocBuilder Builder;
  7985. while (!NestedNames.empty()) {
  7986. NNS = NestedNames.pop_back_val();
  7987. NestedNameSpecifier *Spec = nullptr;
  7988. if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier()))
  7989. return std::move(Err);
  7990. NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
  7991. SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
  7992. if (Kind != NestedNameSpecifier::Super) {
  7993. if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc()))
  7994. return std::move(Err);
  7995. if (Kind != NestedNameSpecifier::Global)
  7996. if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc()))
  7997. return std::move(Err);
  7998. }
  7999. switch (Kind) {
  8000. case NestedNameSpecifier::Identifier:
  8001. Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc,
  8002. ToLocalEndLoc);
  8003. break;
  8004. case NestedNameSpecifier::Namespace:
  8005. Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc,
  8006. ToLocalEndLoc);
  8007. break;
  8008. case NestedNameSpecifier::NamespaceAlias:
  8009. Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(),
  8010. ToLocalBeginLoc, ToLocalEndLoc);
  8011. break;
  8012. case NestedNameSpecifier::TypeSpec:
  8013. case NestedNameSpecifier::TypeSpecWithTemplate: {
  8014. SourceLocation ToTLoc;
  8015. if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc()))
  8016. return std::move(Err);
  8017. TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
  8018. QualType(Spec->getAsType(), 0), ToTLoc);
  8019. if (Kind == NestedNameSpecifier::TypeSpecWithTemplate)
  8020. // ToLocalBeginLoc is here the location of the 'template' keyword.
  8021. Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(),
  8022. ToLocalEndLoc);
  8023. else
  8024. // No location for 'template' keyword here.
  8025. Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(),
  8026. ToLocalEndLoc);
  8027. break;
  8028. }
  8029. case NestedNameSpecifier::Global:
  8030. Builder.MakeGlobal(getToContext(), ToLocalBeginLoc);
  8031. break;
  8032. case NestedNameSpecifier::Super: {
  8033. auto ToSourceRangeOrErr = Import(NNS.getSourceRange());
  8034. if (!ToSourceRangeOrErr)
  8035. return ToSourceRangeOrErr.takeError();
  8036. Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(),
  8037. ToSourceRangeOrErr->getBegin(),
  8038. ToSourceRangeOrErr->getEnd());
  8039. }
  8040. }
  8041. }
  8042. return Builder.getWithLocInContext(getToContext());
  8043. }
  8044. Expected<TemplateName> ASTImporter::Import(TemplateName From) {
  8045. switch (From.getKind()) {
  8046. case TemplateName::Template:
  8047. if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
  8048. return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr));
  8049. else
  8050. return ToTemplateOrErr.takeError();
  8051. case TemplateName::OverloadedTemplate: {
  8052. OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
  8053. UnresolvedSet<2> ToTemplates;
  8054. for (auto *I : *FromStorage) {
  8055. if (auto ToOrErr = Import(I))
  8056. ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
  8057. else
  8058. return ToOrErr.takeError();
  8059. }
  8060. return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
  8061. ToTemplates.end());
  8062. }
  8063. case TemplateName::AssumedTemplate: {
  8064. AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
  8065. auto DeclNameOrErr = Import(FromStorage->getDeclName());
  8066. if (!DeclNameOrErr)
  8067. return DeclNameOrErr.takeError();
  8068. return ToContext.getAssumedTemplateName(*DeclNameOrErr);
  8069. }
  8070. case TemplateName::QualifiedTemplate: {
  8071. QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
  8072. auto QualifierOrErr = Import(QTN->getQualifier());
  8073. if (!QualifierOrErr)
  8074. return QualifierOrErr.takeError();
  8075. auto TNOrErr = Import(QTN->getUnderlyingTemplate());
  8076. if (!TNOrErr)
  8077. return TNOrErr.takeError();
  8078. return ToContext.getQualifiedTemplateName(
  8079. *QualifierOrErr, QTN->hasTemplateKeyword(), *TNOrErr);
  8080. }
  8081. case TemplateName::DependentTemplate: {
  8082. DependentTemplateName *DTN = From.getAsDependentTemplateName();
  8083. auto QualifierOrErr = Import(DTN->getQualifier());
  8084. if (!QualifierOrErr)
  8085. return QualifierOrErr.takeError();
  8086. if (DTN->isIdentifier()) {
  8087. return ToContext.getDependentTemplateName(*QualifierOrErr,
  8088. Import(DTN->getIdentifier()));
  8089. }
  8090. return ToContext.getDependentTemplateName(*QualifierOrErr,
  8091. DTN->getOperator());
  8092. }
  8093. case TemplateName::SubstTemplateTemplateParm: {
  8094. SubstTemplateTemplateParmStorage *Subst =
  8095. From.getAsSubstTemplateTemplateParm();
  8096. auto ReplacementOrErr = Import(Subst->getReplacement());
  8097. if (!ReplacementOrErr)
  8098. return ReplacementOrErr.takeError();
  8099. auto AssociatedDeclOrErr = Import(Subst->getAssociatedDecl());
  8100. if (!AssociatedDeclOrErr)
  8101. return AssociatedDeclOrErr.takeError();
  8102. return ToContext.getSubstTemplateTemplateParm(
  8103. *ReplacementOrErr, *AssociatedDeclOrErr, Subst->getIndex(),
  8104. Subst->getPackIndex());
  8105. }
  8106. case TemplateName::SubstTemplateTemplateParmPack: {
  8107. SubstTemplateTemplateParmPackStorage *SubstPack =
  8108. From.getAsSubstTemplateTemplateParmPack();
  8109. ASTNodeImporter Importer(*this);
  8110. auto ArgPackOrErr =
  8111. Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
  8112. if (!ArgPackOrErr)
  8113. return ArgPackOrErr.takeError();
  8114. auto AssociatedDeclOrErr = Import(SubstPack->getAssociatedDecl());
  8115. if (!AssociatedDeclOrErr)
  8116. return AssociatedDeclOrErr.takeError();
  8117. return ToContext.getSubstTemplateTemplateParmPack(
  8118. *ArgPackOrErr, *AssociatedDeclOrErr, SubstPack->getIndex(),
  8119. SubstPack->getFinal());
  8120. }
  8121. case TemplateName::UsingTemplate: {
  8122. auto UsingOrError = Import(From.getAsUsingShadowDecl());
  8123. if (!UsingOrError)
  8124. return UsingOrError.takeError();
  8125. return TemplateName(cast<UsingShadowDecl>(*UsingOrError));
  8126. }
  8127. }
  8128. llvm_unreachable("Invalid template name kind");
  8129. }
  8130. Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
  8131. if (FromLoc.isInvalid())
  8132. return SourceLocation{};
  8133. SourceManager &FromSM = FromContext.getSourceManager();
  8134. bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc);
  8135. std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
  8136. Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
  8137. if (!ToFileIDOrErr)
  8138. return ToFileIDOrErr.takeError();
  8139. SourceManager &ToSM = ToContext.getSourceManager();
  8140. return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second);
  8141. }
  8142. Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
  8143. SourceLocation ToBegin, ToEnd;
  8144. if (Error Err = importInto(ToBegin, FromRange.getBegin()))
  8145. return std::move(Err);
  8146. if (Error Err = importInto(ToEnd, FromRange.getEnd()))
  8147. return std::move(Err);
  8148. return SourceRange(ToBegin, ToEnd);
  8149. }
  8150. Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
  8151. llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
  8152. if (Pos != ImportedFileIDs.end())
  8153. return Pos->second;
  8154. SourceManager &FromSM = FromContext.getSourceManager();
  8155. SourceManager &ToSM = ToContext.getSourceManager();
  8156. const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
  8157. // Map the FromID to the "to" source manager.
  8158. FileID ToID;
  8159. if (FromSLoc.isExpansion()) {
  8160. const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
  8161. ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc());
  8162. if (!ToSpLoc)
  8163. return ToSpLoc.takeError();
  8164. ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart());
  8165. if (!ToExLocS)
  8166. return ToExLocS.takeError();
  8167. unsigned ExLength = FromSM.getFileIDSize(FromID);
  8168. SourceLocation MLoc;
  8169. if (FromEx.isMacroArgExpansion()) {
  8170. MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, ExLength);
  8171. } else {
  8172. if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd()))
  8173. MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, ExLength,
  8174. FromEx.isExpansionTokenRange());
  8175. else
  8176. return ToExLocE.takeError();
  8177. }
  8178. ToID = ToSM.getFileID(MLoc);
  8179. } else {
  8180. const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
  8181. if (!IsBuiltin && !Cache->BufferOverridden) {
  8182. // Include location of this file.
  8183. ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
  8184. if (!ToIncludeLoc)
  8185. return ToIncludeLoc.takeError();
  8186. // Every FileID that is not the main FileID needs to have a valid include
  8187. // location so that the include chain points to the main FileID. When
  8188. // importing the main FileID (which has no include location), we need to
  8189. // create a fake include location in the main file to keep this property
  8190. // intact.
  8191. SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
  8192. if (FromID == FromSM.getMainFileID())
  8193. ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID());
  8194. if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
  8195. // FIXME: We probably want to use getVirtualFile(), so we don't hit the
  8196. // disk again
  8197. // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
  8198. // than mmap the files several times.
  8199. auto Entry =
  8200. ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName());
  8201. // FIXME: The filename may be a virtual name that does probably not
  8202. // point to a valid file and we get no Entry here. In this case try with
  8203. // the memory buffer below.
  8204. if (Entry)
  8205. ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc,
  8206. FromSLoc.getFile().getFileCharacteristic());
  8207. }
  8208. }
  8209. if (ToID.isInvalid() || IsBuiltin) {
  8210. // FIXME: We want to re-use the existing MemoryBuffer!
  8211. std::optional<llvm::MemoryBufferRef> FromBuf =
  8212. Cache->getBufferOrNone(FromContext.getDiagnostics(),
  8213. FromSM.getFileManager(), SourceLocation{});
  8214. if (!FromBuf)
  8215. return llvm::make_error<ASTImportError>(ASTImportError::Unknown);
  8216. std::unique_ptr<llvm::MemoryBuffer> ToBuf =
  8217. llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
  8218. FromBuf->getBufferIdentifier());
  8219. ToID = ToSM.createFileID(std::move(ToBuf),
  8220. FromSLoc.getFile().getFileCharacteristic());
  8221. }
  8222. }
  8223. assert(ToID.isValid() && "Unexpected invalid fileID was created.");
  8224. ImportedFileIDs[FromID] = ToID;
  8225. return ToID;
  8226. }
  8227. Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
  8228. ExpectedExpr ToExprOrErr = Import(From->getInit());
  8229. if (!ToExprOrErr)
  8230. return ToExprOrErr.takeError();
  8231. auto LParenLocOrErr = Import(From->getLParenLoc());
  8232. if (!LParenLocOrErr)
  8233. return LParenLocOrErr.takeError();
  8234. auto RParenLocOrErr = Import(From->getRParenLoc());
  8235. if (!RParenLocOrErr)
  8236. return RParenLocOrErr.takeError();
  8237. if (From->isBaseInitializer()) {
  8238. auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
  8239. if (!ToTInfoOrErr)
  8240. return ToTInfoOrErr.takeError();
  8241. SourceLocation EllipsisLoc;
  8242. if (From->isPackExpansion())
  8243. if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc()))
  8244. return std::move(Err);
  8245. return new (ToContext) CXXCtorInitializer(
  8246. ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
  8247. *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
  8248. } else if (From->isMemberInitializer()) {
  8249. ExpectedDecl ToFieldOrErr = Import(From->getMember());
  8250. if (!ToFieldOrErr)
  8251. return ToFieldOrErr.takeError();
  8252. auto MemberLocOrErr = Import(From->getMemberLocation());
  8253. if (!MemberLocOrErr)
  8254. return MemberLocOrErr.takeError();
  8255. return new (ToContext) CXXCtorInitializer(
  8256. ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr,
  8257. *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
  8258. } else if (From->isIndirectMemberInitializer()) {
  8259. ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
  8260. if (!ToIFieldOrErr)
  8261. return ToIFieldOrErr.takeError();
  8262. auto MemberLocOrErr = Import(From->getMemberLocation());
  8263. if (!MemberLocOrErr)
  8264. return MemberLocOrErr.takeError();
  8265. return new (ToContext) CXXCtorInitializer(
  8266. ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr),
  8267. *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
  8268. } else if (From->isDelegatingInitializer()) {
  8269. auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
  8270. if (!ToTInfoOrErr)
  8271. return ToTInfoOrErr.takeError();
  8272. return new (ToContext)
  8273. CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
  8274. *ToExprOrErr, *RParenLocOrErr);
  8275. } else {
  8276. // FIXME: assert?
  8277. return make_error<ASTImportError>();
  8278. }
  8279. }
  8280. Expected<CXXBaseSpecifier *>
  8281. ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
  8282. auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
  8283. if (Pos != ImportedCXXBaseSpecifiers.end())
  8284. return Pos->second;
  8285. Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange());
  8286. if (!ToSourceRange)
  8287. return ToSourceRange.takeError();
  8288. Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo());
  8289. if (!ToTSI)
  8290. return ToTSI.takeError();
  8291. ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc());
  8292. if (!ToEllipsisLoc)
  8293. return ToEllipsisLoc.takeError();
  8294. CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
  8295. *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
  8296. BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
  8297. ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
  8298. return Imported;
  8299. }
  8300. llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) {
  8301. ASTNodeImporter Importer(*this);
  8302. return Importer.ImportAPValue(FromValue);
  8303. }
  8304. Error ASTImporter::ImportDefinition(Decl *From) {
  8305. ExpectedDecl ToOrErr = Import(From);
  8306. if (!ToOrErr)
  8307. return ToOrErr.takeError();
  8308. Decl *To = *ToOrErr;
  8309. auto *FromDC = cast<DeclContext>(From);
  8310. ASTNodeImporter Importer(*this);
  8311. if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
  8312. if (!ToRecord->getDefinition()) {
  8313. return Importer.ImportDefinition(
  8314. cast<RecordDecl>(FromDC), ToRecord,
  8315. ASTNodeImporter::IDK_Everything);
  8316. }
  8317. }
  8318. if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
  8319. if (!ToEnum->getDefinition()) {
  8320. return Importer.ImportDefinition(
  8321. cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything);
  8322. }
  8323. }
  8324. if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
  8325. if (!ToIFace->getDefinition()) {
  8326. return Importer.ImportDefinition(
  8327. cast<ObjCInterfaceDecl>(FromDC), ToIFace,
  8328. ASTNodeImporter::IDK_Everything);
  8329. }
  8330. }
  8331. if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
  8332. if (!ToProto->getDefinition()) {
  8333. return Importer.ImportDefinition(
  8334. cast<ObjCProtocolDecl>(FromDC), ToProto,
  8335. ASTNodeImporter::IDK_Everything);
  8336. }
  8337. }
  8338. return Importer.ImportDeclContext(FromDC, true);
  8339. }
  8340. Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
  8341. if (!FromName)
  8342. return DeclarationName{};
  8343. switch (FromName.getNameKind()) {
  8344. case DeclarationName::Identifier:
  8345. return DeclarationName(Import(FromName.getAsIdentifierInfo()));
  8346. case DeclarationName::ObjCZeroArgSelector:
  8347. case DeclarationName::ObjCOneArgSelector:
  8348. case DeclarationName::ObjCMultiArgSelector:
  8349. if (auto ToSelOrErr = Import(FromName.getObjCSelector()))
  8350. return DeclarationName(*ToSelOrErr);
  8351. else
  8352. return ToSelOrErr.takeError();
  8353. case DeclarationName::CXXConstructorName: {
  8354. if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
  8355. return ToContext.DeclarationNames.getCXXConstructorName(
  8356. ToContext.getCanonicalType(*ToTyOrErr));
  8357. else
  8358. return ToTyOrErr.takeError();
  8359. }
  8360. case DeclarationName::CXXDestructorName: {
  8361. if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
  8362. return ToContext.DeclarationNames.getCXXDestructorName(
  8363. ToContext.getCanonicalType(*ToTyOrErr));
  8364. else
  8365. return ToTyOrErr.takeError();
  8366. }
  8367. case DeclarationName::CXXDeductionGuideName: {
  8368. if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
  8369. return ToContext.DeclarationNames.getCXXDeductionGuideName(
  8370. cast<TemplateDecl>(*ToTemplateOrErr));
  8371. else
  8372. return ToTemplateOrErr.takeError();
  8373. }
  8374. case DeclarationName::CXXConversionFunctionName: {
  8375. if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
  8376. return ToContext.DeclarationNames.getCXXConversionFunctionName(
  8377. ToContext.getCanonicalType(*ToTyOrErr));
  8378. else
  8379. return ToTyOrErr.takeError();
  8380. }
  8381. case DeclarationName::CXXOperatorName:
  8382. return ToContext.DeclarationNames.getCXXOperatorName(
  8383. FromName.getCXXOverloadedOperator());
  8384. case DeclarationName::CXXLiteralOperatorName:
  8385. return ToContext.DeclarationNames.getCXXLiteralOperatorName(
  8386. Import(FromName.getCXXLiteralIdentifier()));
  8387. case DeclarationName::CXXUsingDirective:
  8388. // FIXME: STATICS!
  8389. return DeclarationName::getUsingDirectiveName();
  8390. }
  8391. llvm_unreachable("Invalid DeclarationName Kind!");
  8392. }
  8393. IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
  8394. if (!FromId)
  8395. return nullptr;
  8396. IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
  8397. if (!ToId->getBuiltinID() && FromId->getBuiltinID())
  8398. ToId->setBuiltinID(FromId->getBuiltinID());
  8399. return ToId;
  8400. }
  8401. Expected<Selector> ASTImporter::Import(Selector FromSel) {
  8402. if (FromSel.isNull())
  8403. return Selector{};
  8404. SmallVector<IdentifierInfo *, 4> Idents;
  8405. Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
  8406. for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
  8407. Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
  8408. return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
  8409. }
  8410. llvm::Expected<APValue>
  8411. ASTNodeImporter::ImportAPValue(const APValue &FromValue) {
  8412. APValue Result;
  8413. llvm::Error Err = llvm::Error::success();
  8414. auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
  8415. for (unsigned Idx = 0; Idx < Size; Idx++) {
  8416. APValue Tmp = importChecked(Err, From[Idx]);
  8417. To[Idx] = Tmp;
  8418. }
  8419. };
  8420. switch (FromValue.getKind()) {
  8421. case APValue::None:
  8422. case APValue::Indeterminate:
  8423. case APValue::Int:
  8424. case APValue::Float:
  8425. case APValue::FixedPoint:
  8426. case APValue::ComplexInt:
  8427. case APValue::ComplexFloat:
  8428. Result = FromValue;
  8429. break;
  8430. case APValue::Vector: {
  8431. Result.MakeVector();
  8432. MutableArrayRef<APValue> Elts =
  8433. Result.setVectorUninit(FromValue.getVectorLength());
  8434. ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
  8435. Elts.data(), FromValue.getVectorLength());
  8436. break;
  8437. }
  8438. case APValue::Array:
  8439. Result.MakeArray(FromValue.getArrayInitializedElts(),
  8440. FromValue.getArraySize());
  8441. ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
  8442. ((const APValue::Arr *)(const char *)&Result.Data)->Elts,
  8443. FromValue.getArrayInitializedElts());
  8444. break;
  8445. case APValue::Struct:
  8446. Result.MakeStruct(FromValue.getStructNumBases(),
  8447. FromValue.getStructNumFields());
  8448. ImportLoop(
  8449. ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
  8450. ((const APValue::StructData *)(const char *)&Result.Data)->Elts,
  8451. FromValue.getStructNumBases() + FromValue.getStructNumFields());
  8452. break;
  8453. case APValue::Union: {
  8454. Result.MakeUnion();
  8455. const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField());
  8456. APValue ImpValue = importChecked(Err, FromValue.getUnionValue());
  8457. if (Err)
  8458. return std::move(Err);
  8459. Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue);
  8460. break;
  8461. }
  8462. case APValue::AddrLabelDiff: {
  8463. Result.MakeAddrLabelDiff();
  8464. const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS());
  8465. const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS());
  8466. if (Err)
  8467. return std::move(Err);
  8468. Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS),
  8469. cast<AddrLabelExpr>(ImpRHS));
  8470. break;
  8471. }
  8472. case APValue::MemberPointer: {
  8473. const Decl *ImpMemPtrDecl =
  8474. importChecked(Err, FromValue.getMemberPointerDecl());
  8475. if (Err)
  8476. return std::move(Err);
  8477. MutableArrayRef<const CXXRecordDecl *> ToPath =
  8478. Result.setMemberPointerUninit(
  8479. cast<const ValueDecl>(ImpMemPtrDecl),
  8480. FromValue.isMemberPointerToDerivedMember(),
  8481. FromValue.getMemberPointerPath().size());
  8482. llvm::ArrayRef<const CXXRecordDecl *> FromPath =
  8483. Result.getMemberPointerPath();
  8484. for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
  8485. Idx++) {
  8486. const Decl *ImpDecl = importChecked(Err, FromPath[Idx]);
  8487. if (Err)
  8488. return std::move(Err);
  8489. ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl());
  8490. }
  8491. break;
  8492. }
  8493. case APValue::LValue:
  8494. APValue::LValueBase Base;
  8495. QualType FromElemTy;
  8496. if (FromValue.getLValueBase()) {
  8497. assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
  8498. "in C++20 dynamic allocation are transient so they shouldn't "
  8499. "appear in the AST");
  8500. if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
  8501. if (const auto *E =
  8502. FromValue.getLValueBase().dyn_cast<const Expr *>()) {
  8503. FromElemTy = E->getType();
  8504. const Expr *ImpExpr = importChecked(Err, E);
  8505. if (Err)
  8506. return std::move(Err);
  8507. Base = APValue::LValueBase(ImpExpr,
  8508. FromValue.getLValueBase().getCallIndex(),
  8509. FromValue.getLValueBase().getVersion());
  8510. } else {
  8511. FromElemTy =
  8512. FromValue.getLValueBase().get<const ValueDecl *>()->getType();
  8513. const Decl *ImpDecl = importChecked(
  8514. Err, FromValue.getLValueBase().get<const ValueDecl *>());
  8515. if (Err)
  8516. return std::move(Err);
  8517. Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl),
  8518. FromValue.getLValueBase().getCallIndex(),
  8519. FromValue.getLValueBase().getVersion());
  8520. }
  8521. } else {
  8522. FromElemTy = FromValue.getLValueBase().getTypeInfoType();
  8523. const Type *ImpTypeInfo = importChecked(
  8524. Err, FromValue.getLValueBase().get<TypeInfoLValue>().getType());
  8525. QualType ImpType =
  8526. importChecked(Err, FromValue.getLValueBase().getTypeInfoType());
  8527. if (Err)
  8528. return std::move(Err);
  8529. Base = APValue::LValueBase::getTypeInfo(TypeInfoLValue(ImpTypeInfo),
  8530. ImpType);
  8531. }
  8532. }
  8533. CharUnits Offset = FromValue.getLValueOffset();
  8534. unsigned PathLength = FromValue.getLValuePath().size();
  8535. Result.MakeLValue();
  8536. if (FromValue.hasLValuePath()) {
  8537. MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
  8538. Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(),
  8539. FromValue.isNullPointer());
  8540. llvm::ArrayRef<APValue::LValuePathEntry> FromPath =
  8541. FromValue.getLValuePath();
  8542. for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
  8543. if (FromElemTy->isRecordType()) {
  8544. const Decl *FromDecl =
  8545. FromPath[LoopIdx].getAsBaseOrMember().getPointer();
  8546. const Decl *ImpDecl = importChecked(Err, FromDecl);
  8547. if (Err)
  8548. return std::move(Err);
  8549. if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl))
  8550. FromElemTy = Importer.FromContext.getRecordType(RD);
  8551. else
  8552. FromElemTy = cast<ValueDecl>(FromDecl)->getType();
  8553. ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType(
  8554. ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
  8555. } else {
  8556. FromElemTy =
  8557. Importer.FromContext.getAsArrayType(FromElemTy)->getElementType();
  8558. ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
  8559. FromPath[LoopIdx].getAsArrayIndex());
  8560. }
  8561. }
  8562. } else
  8563. Result.setLValue(Base, Offset, APValue::NoLValuePath{},
  8564. FromValue.isNullPointer());
  8565. }
  8566. if (Err)
  8567. return std::move(Err);
  8568. return Result;
  8569. }
  8570. Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name,
  8571. DeclContext *DC,
  8572. unsigned IDNS,
  8573. NamedDecl **Decls,
  8574. unsigned NumDecls) {
  8575. if (ODRHandling == ODRHandlingType::Conservative)
  8576. // Report error at any name conflict.
  8577. return make_error<ASTImportError>(ASTImportError::NameConflict);
  8578. else
  8579. // Allow to create the new Decl with the same name.
  8580. return Name;
  8581. }
  8582. DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
  8583. if (LastDiagFromFrom)
  8584. ToContext.getDiagnostics().notePriorDiagnosticFrom(
  8585. FromContext.getDiagnostics());
  8586. LastDiagFromFrom = false;
  8587. return ToContext.getDiagnostics().Report(Loc, DiagID);
  8588. }
  8589. DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
  8590. if (!LastDiagFromFrom)
  8591. FromContext.getDiagnostics().notePriorDiagnosticFrom(
  8592. ToContext.getDiagnostics());
  8593. LastDiagFromFrom = true;
  8594. return FromContext.getDiagnostics().Report(Loc, DiagID);
  8595. }
  8596. void ASTImporter::CompleteDecl (Decl *D) {
  8597. if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  8598. if (!ID->getDefinition())
  8599. ID->startDefinition();
  8600. }
  8601. else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
  8602. if (!PD->getDefinition())
  8603. PD->startDefinition();
  8604. }
  8605. else if (auto *TD = dyn_cast<TagDecl>(D)) {
  8606. if (!TD->getDefinition() && !TD->isBeingDefined()) {
  8607. TD->startDefinition();
  8608. TD->setCompleteDefinition(true);
  8609. }
  8610. }
  8611. else {
  8612. assert(0 && "CompleteDecl called on a Decl that can't be completed");
  8613. }
  8614. }
  8615. Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
  8616. llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
  8617. assert((Pos == ImportedDecls.end() || Pos->second == To) &&
  8618. "Try to import an already imported Decl");
  8619. if (Pos != ImportedDecls.end())
  8620. return Pos->second;
  8621. ImportedDecls[From] = To;
  8622. // This mapping should be maintained only in this function. Therefore do not
  8623. // check for additional consistency.
  8624. ImportedFromDecls[To] = From;
  8625. // In the case of TypedefNameDecl we create the Decl first and only then we
  8626. // import and set its DeclContext. So, the DC is still not set when we reach
  8627. // here from GetImportedOrCreateDecl.
  8628. if (To->getDeclContext())
  8629. AddToLookupTable(To);
  8630. return To;
  8631. }
  8632. std::optional<ASTImportError>
  8633. ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
  8634. auto Pos = ImportDeclErrors.find(FromD);
  8635. if (Pos != ImportDeclErrors.end())
  8636. return Pos->second;
  8637. else
  8638. return std::nullopt;
  8639. }
  8640. void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) {
  8641. auto InsertRes = ImportDeclErrors.insert({From, Error});
  8642. (void)InsertRes;
  8643. // Either we set the error for the first time, or we already had set one and
  8644. // now we want to set the same error.
  8645. assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
  8646. }
  8647. bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
  8648. bool Complain) {
  8649. llvm::DenseMap<const Type *, const Type *>::iterator Pos =
  8650. ImportedTypes.find(From.getTypePtr());
  8651. if (Pos != ImportedTypes.end()) {
  8652. if (ExpectedType ToFromOrErr = Import(From)) {
  8653. if (ToContext.hasSameType(*ToFromOrErr, To))
  8654. return true;
  8655. } else {
  8656. llvm::consumeError(ToFromOrErr.takeError());
  8657. }
  8658. }
  8659. StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
  8660. getStructuralEquivalenceKind(*this), false,
  8661. Complain);
  8662. return Ctx.IsEquivalent(From, To);
  8663. }