ASTImporter.cpp 354 KB

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