SemaInit.cpp 382 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792
  1. //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
  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 implements semantic analysis for initializers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclObjC.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/AST/ExprObjC.h"
  16. #include "clang/AST/ExprOpenMP.h"
  17. #include "clang/AST/TypeLoc.h"
  18. #include "clang/Basic/CharInfo.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/Sema/Designator.h"
  21. #include "clang/Sema/Initialization.h"
  22. #include "clang/Sema/Lookup.h"
  23. #include "clang/Sema/SemaInternal.h"
  24. #include "llvm/ADT/APInt.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace clang;
  29. //===----------------------------------------------------------------------===//
  30. // Sema Initialization Checking
  31. //===----------------------------------------------------------------------===//
  32. /// Check whether T is compatible with a wide character type (wchar_t,
  33. /// char16_t or char32_t).
  34. static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
  35. if (Context.typesAreCompatible(Context.getWideCharType(), T))
  36. return true;
  37. if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
  38. return Context.typesAreCompatible(Context.Char16Ty, T) ||
  39. Context.typesAreCompatible(Context.Char32Ty, T);
  40. }
  41. return false;
  42. }
  43. enum StringInitFailureKind {
  44. SIF_None,
  45. SIF_NarrowStringIntoWideChar,
  46. SIF_WideStringIntoChar,
  47. SIF_IncompatWideStringIntoWideChar,
  48. SIF_UTF8StringIntoPlainChar,
  49. SIF_PlainStringIntoUTF8Char,
  50. SIF_Other
  51. };
  52. /// Check whether the array of type AT can be initialized by the Init
  53. /// expression by means of string initialization. Returns SIF_None if so,
  54. /// otherwise returns a StringInitFailureKind that describes why the
  55. /// initialization would not work.
  56. static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
  57. ASTContext &Context) {
  58. if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
  59. return SIF_Other;
  60. // See if this is a string literal or @encode.
  61. Init = Init->IgnoreParens();
  62. // Handle @encode, which is a narrow string.
  63. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
  64. return SIF_None;
  65. // Otherwise we can only handle string literals.
  66. StringLiteral *SL = dyn_cast<StringLiteral>(Init);
  67. if (!SL)
  68. return SIF_Other;
  69. const QualType ElemTy =
  70. Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
  71. switch (SL->getKind()) {
  72. case StringLiteral::UTF8:
  73. // char8_t array can be initialized with a UTF-8 string.
  74. if (ElemTy->isChar8Type())
  75. return SIF_None;
  76. LLVM_FALLTHROUGH;
  77. case StringLiteral::Ascii:
  78. // char array can be initialized with a narrow string.
  79. // Only allow char x[] = "foo"; not char x[] = L"foo";
  80. if (ElemTy->isCharType())
  81. return (SL->getKind() == StringLiteral::UTF8 &&
  82. Context.getLangOpts().Char8)
  83. ? SIF_UTF8StringIntoPlainChar
  84. : SIF_None;
  85. if (ElemTy->isChar8Type())
  86. return SIF_PlainStringIntoUTF8Char;
  87. if (IsWideCharCompatible(ElemTy, Context))
  88. return SIF_NarrowStringIntoWideChar;
  89. return SIF_Other;
  90. // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
  91. // "An array with element type compatible with a qualified or unqualified
  92. // version of wchar_t, char16_t, or char32_t may be initialized by a wide
  93. // string literal with the corresponding encoding prefix (L, u, or U,
  94. // respectively), optionally enclosed in braces.
  95. case StringLiteral::UTF16:
  96. if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
  97. return SIF_None;
  98. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  99. return SIF_WideStringIntoChar;
  100. if (IsWideCharCompatible(ElemTy, Context))
  101. return SIF_IncompatWideStringIntoWideChar;
  102. return SIF_Other;
  103. case StringLiteral::UTF32:
  104. if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
  105. return SIF_None;
  106. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  107. return SIF_WideStringIntoChar;
  108. if (IsWideCharCompatible(ElemTy, Context))
  109. return SIF_IncompatWideStringIntoWideChar;
  110. return SIF_Other;
  111. case StringLiteral::Wide:
  112. if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
  113. return SIF_None;
  114. if (ElemTy->isCharType() || ElemTy->isChar8Type())
  115. return SIF_WideStringIntoChar;
  116. if (IsWideCharCompatible(ElemTy, Context))
  117. return SIF_IncompatWideStringIntoWideChar;
  118. return SIF_Other;
  119. }
  120. llvm_unreachable("missed a StringLiteral kind?");
  121. }
  122. static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
  123. ASTContext &Context) {
  124. const ArrayType *arrayType = Context.getAsArrayType(declType);
  125. if (!arrayType)
  126. return SIF_Other;
  127. return IsStringInit(init, arrayType, Context);
  128. }
  129. /// Update the type of a string literal, including any surrounding parentheses,
  130. /// to match the type of the object which it is initializing.
  131. static void updateStringLiteralType(Expr *E, QualType Ty) {
  132. while (true) {
  133. E->setType(Ty);
  134. E->setValueKind(VK_RValue);
  135. if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
  136. break;
  137. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  138. E = PE->getSubExpr();
  139. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  140. assert(UO->getOpcode() == UO_Extension);
  141. E = UO->getSubExpr();
  142. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  143. E = GSE->getResultExpr();
  144. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  145. E = CE->getChosenSubExpr();
  146. } else {
  147. llvm_unreachable("unexpected expr in string literal init");
  148. }
  149. }
  150. }
  151. /// Fix a compound literal initializing an array so it's correctly marked
  152. /// as an rvalue.
  153. static void updateGNUCompoundLiteralRValue(Expr *E) {
  154. while (true) {
  155. E->setValueKind(VK_RValue);
  156. if (isa<CompoundLiteralExpr>(E)) {
  157. break;
  158. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  159. E = PE->getSubExpr();
  160. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  161. assert(UO->getOpcode() == UO_Extension);
  162. E = UO->getSubExpr();
  163. } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
  164. E = GSE->getResultExpr();
  165. } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
  166. E = CE->getChosenSubExpr();
  167. } else {
  168. llvm_unreachable("unexpected expr in array compound literal init");
  169. }
  170. }
  171. }
  172. static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
  173. Sema &S) {
  174. // Get the length of the string as parsed.
  175. auto *ConstantArrayTy =
  176. cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
  177. uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
  178. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  179. // C99 6.7.8p14. We have an array of character type with unknown size
  180. // being initialized to a string literal.
  181. llvm::APInt ConstVal(32, StrLength);
  182. // Return a new array type (C99 6.7.8p22).
  183. DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
  184. ConstVal,
  185. ArrayType::Normal, 0);
  186. updateStringLiteralType(Str, DeclT);
  187. return;
  188. }
  189. const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
  190. // We have an array of character type with known size. However,
  191. // the size may be smaller or larger than the string we are initializing.
  192. // FIXME: Avoid truncation for 64-bit length strings.
  193. if (S.getLangOpts().CPlusPlus) {
  194. if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
  195. // For Pascal strings it's OK to strip off the terminating null character,
  196. // so the example below is valid:
  197. //
  198. // unsigned char a[2] = "\pa";
  199. if (SL->isPascal())
  200. StrLength--;
  201. }
  202. // [dcl.init.string]p2
  203. if (StrLength > CAT->getSize().getZExtValue())
  204. S.Diag(Str->getBeginLoc(),
  205. diag::err_initializer_string_for_char_array_too_long)
  206. << Str->getSourceRange();
  207. } else {
  208. // C99 6.7.8p14.
  209. if (StrLength-1 > CAT->getSize().getZExtValue())
  210. S.Diag(Str->getBeginLoc(),
  211. diag::ext_initializer_string_for_char_array_too_long)
  212. << Str->getSourceRange();
  213. }
  214. // Set the type to the actual size that we are initializing. If we have
  215. // something like:
  216. // char x[1] = "foo";
  217. // then this will set the string literal's type to char[1].
  218. updateStringLiteralType(Str, DeclT);
  219. }
  220. //===----------------------------------------------------------------------===//
  221. // Semantic checking for initializer lists.
  222. //===----------------------------------------------------------------------===//
  223. namespace {
  224. /// Semantic checking for initializer lists.
  225. ///
  226. /// The InitListChecker class contains a set of routines that each
  227. /// handle the initialization of a certain kind of entity, e.g.,
  228. /// arrays, vectors, struct/union types, scalars, etc. The
  229. /// InitListChecker itself performs a recursive walk of the subobject
  230. /// structure of the type to be initialized, while stepping through
  231. /// the initializer list one element at a time. The IList and Index
  232. /// parameters to each of the Check* routines contain the active
  233. /// (syntactic) initializer list and the index into that initializer
  234. /// list that represents the current initializer. Each routine is
  235. /// responsible for moving that Index forward as it consumes elements.
  236. ///
  237. /// Each Check* routine also has a StructuredList/StructuredIndex
  238. /// arguments, which contains the current "structured" (semantic)
  239. /// initializer list and the index into that initializer list where we
  240. /// are copying initializers as we map them over to the semantic
  241. /// list. Once we have completed our recursive walk of the subobject
  242. /// structure, we will have constructed a full semantic initializer
  243. /// list.
  244. ///
  245. /// C99 designators cause changes in the initializer list traversal,
  246. /// because they make the initialization "jump" into a specific
  247. /// subobject and then continue the initialization from that
  248. /// point. CheckDesignatedInitializer() recursively steps into the
  249. /// designated subobject and manages backing out the recursion to
  250. /// initialize the subobjects after the one designated.
  251. class InitListChecker {
  252. Sema &SemaRef;
  253. bool hadError;
  254. bool VerifyOnly; // no diagnostics, no structure building
  255. bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
  256. llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
  257. InitListExpr *FullyStructuredList;
  258. void CheckImplicitInitList(const InitializedEntity &Entity,
  259. InitListExpr *ParentIList, QualType T,
  260. unsigned &Index, InitListExpr *StructuredList,
  261. unsigned &StructuredIndex);
  262. void CheckExplicitInitList(const InitializedEntity &Entity,
  263. InitListExpr *IList, QualType &T,
  264. InitListExpr *StructuredList,
  265. bool TopLevelObject = false);
  266. void CheckListElementTypes(const InitializedEntity &Entity,
  267. InitListExpr *IList, QualType &DeclType,
  268. bool SubobjectIsDesignatorContext,
  269. unsigned &Index,
  270. InitListExpr *StructuredList,
  271. unsigned &StructuredIndex,
  272. bool TopLevelObject = false);
  273. void CheckSubElementType(const InitializedEntity &Entity,
  274. InitListExpr *IList, QualType ElemType,
  275. unsigned &Index,
  276. InitListExpr *StructuredList,
  277. unsigned &StructuredIndex);
  278. void CheckComplexType(const InitializedEntity &Entity,
  279. InitListExpr *IList, QualType DeclType,
  280. unsigned &Index,
  281. InitListExpr *StructuredList,
  282. unsigned &StructuredIndex);
  283. void CheckScalarType(const InitializedEntity &Entity,
  284. InitListExpr *IList, QualType DeclType,
  285. unsigned &Index,
  286. InitListExpr *StructuredList,
  287. unsigned &StructuredIndex);
  288. void CheckReferenceType(const InitializedEntity &Entity,
  289. InitListExpr *IList, QualType DeclType,
  290. unsigned &Index,
  291. InitListExpr *StructuredList,
  292. unsigned &StructuredIndex);
  293. void CheckVectorType(const InitializedEntity &Entity,
  294. InitListExpr *IList, QualType DeclType, unsigned &Index,
  295. InitListExpr *StructuredList,
  296. unsigned &StructuredIndex);
  297. void CheckStructUnionTypes(const InitializedEntity &Entity,
  298. InitListExpr *IList, QualType DeclType,
  299. CXXRecordDecl::base_class_range Bases,
  300. RecordDecl::field_iterator Field,
  301. bool SubobjectIsDesignatorContext, unsigned &Index,
  302. InitListExpr *StructuredList,
  303. unsigned &StructuredIndex,
  304. bool TopLevelObject = false);
  305. void CheckArrayType(const InitializedEntity &Entity,
  306. InitListExpr *IList, QualType &DeclType,
  307. llvm::APSInt elementIndex,
  308. bool SubobjectIsDesignatorContext, unsigned &Index,
  309. InitListExpr *StructuredList,
  310. unsigned &StructuredIndex);
  311. bool CheckDesignatedInitializer(const InitializedEntity &Entity,
  312. InitListExpr *IList, DesignatedInitExpr *DIE,
  313. unsigned DesigIdx,
  314. QualType &CurrentObjectType,
  315. RecordDecl::field_iterator *NextField,
  316. llvm::APSInt *NextElementIndex,
  317. unsigned &Index,
  318. InitListExpr *StructuredList,
  319. unsigned &StructuredIndex,
  320. bool FinishSubobjectInit,
  321. bool TopLevelObject);
  322. InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  323. QualType CurrentObjectType,
  324. InitListExpr *StructuredList,
  325. unsigned StructuredIndex,
  326. SourceRange InitRange,
  327. bool IsFullyOverwritten = false);
  328. void UpdateStructuredListElement(InitListExpr *StructuredList,
  329. unsigned &StructuredIndex,
  330. Expr *expr);
  331. int numArrayElements(QualType DeclType);
  332. int numStructUnionElements(QualType DeclType);
  333. static ExprResult PerformEmptyInit(Sema &SemaRef,
  334. SourceLocation Loc,
  335. const InitializedEntity &Entity,
  336. bool VerifyOnly,
  337. bool TreatUnavailableAsInvalid);
  338. // Explanation on the "FillWithNoInit" mode:
  339. //
  340. // Assume we have the following definitions (Case#1):
  341. // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
  342. // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
  343. //
  344. // l.lp.x[1][0..1] should not be filled with implicit initializers because the
  345. // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
  346. //
  347. // But if we have (Case#2):
  348. // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
  349. //
  350. // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
  351. // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
  352. //
  353. // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
  354. // in the InitListExpr, the "holes" in Case#1 are filled not with empty
  355. // initializers but with special "NoInitExpr" place holders, which tells the
  356. // CodeGen not to generate any initializers for these parts.
  357. void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
  358. const InitializedEntity &ParentEntity,
  359. InitListExpr *ILE, bool &RequiresSecondPass,
  360. bool FillWithNoInit);
  361. void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  362. const InitializedEntity &ParentEntity,
  363. InitListExpr *ILE, bool &RequiresSecondPass,
  364. bool FillWithNoInit = false);
  365. void FillInEmptyInitializations(const InitializedEntity &Entity,
  366. InitListExpr *ILE, bool &RequiresSecondPass,
  367. InitListExpr *OuterILE, unsigned OuterIndex,
  368. bool FillWithNoInit = false);
  369. bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
  370. Expr *InitExpr, FieldDecl *Field,
  371. bool TopLevelObject);
  372. void CheckEmptyInitializable(const InitializedEntity &Entity,
  373. SourceLocation Loc);
  374. public:
  375. InitListChecker(Sema &S, const InitializedEntity &Entity,
  376. InitListExpr *IL, QualType &T, bool VerifyOnly,
  377. bool TreatUnavailableAsInvalid);
  378. bool HadError() { return hadError; }
  379. // Retrieves the fully-structured initializer list used for
  380. // semantic analysis and code generation.
  381. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
  382. };
  383. } // end anonymous namespace
  384. ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
  385. SourceLocation Loc,
  386. const InitializedEntity &Entity,
  387. bool VerifyOnly,
  388. bool TreatUnavailableAsInvalid) {
  389. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  390. true);
  391. MultiExprArg SubInit;
  392. Expr *InitExpr;
  393. InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
  394. // C++ [dcl.init.aggr]p7:
  395. // If there are fewer initializer-clauses in the list than there are
  396. // members in the aggregate, then each member not explicitly initialized
  397. // ...
  398. bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
  399. Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
  400. if (EmptyInitList) {
  401. // C++1y / DR1070:
  402. // shall be initialized [...] from an empty initializer list.
  403. //
  404. // We apply the resolution of this DR to C++11 but not C++98, since C++98
  405. // does not have useful semantics for initialization from an init list.
  406. // We treat this as copy-initialization, because aggregate initialization
  407. // always performs copy-initialization on its elements.
  408. //
  409. // Only do this if we're initializing a class type, to avoid filling in
  410. // the initializer list where possible.
  411. InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
  412. InitListExpr(SemaRef.Context, Loc, None, Loc);
  413. InitExpr->setType(SemaRef.Context.VoidTy);
  414. SubInit = InitExpr;
  415. Kind = InitializationKind::CreateCopy(Loc, Loc);
  416. } else {
  417. // C++03:
  418. // shall be value-initialized.
  419. }
  420. InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
  421. // libstdc++4.6 marks the vector default constructor as explicit in
  422. // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
  423. // stlport does so too. Look for std::__debug for libstdc++, and for
  424. // std:: for stlport. This is effectively a compiler-side implementation of
  425. // LWG2193.
  426. if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
  427. InitializationSequence::FK_ExplicitConstructor) {
  428. OverloadCandidateSet::iterator Best;
  429. OverloadingResult O =
  430. InitSeq.getFailedCandidateSet()
  431. .BestViableFunction(SemaRef, Kind.getLocation(), Best);
  432. (void)O;
  433. assert(O == OR_Success && "Inconsistent overload resolution");
  434. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  435. CXXRecordDecl *R = CtorDecl->getParent();
  436. if (CtorDecl->getMinRequiredArguments() == 0 &&
  437. CtorDecl->isExplicit() && R->getDeclName() &&
  438. SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
  439. bool IsInStd = false;
  440. for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
  441. ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
  442. if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
  443. IsInStd = true;
  444. }
  445. if (IsInStd && llvm::StringSwitch<bool>(R->getName())
  446. .Cases("basic_string", "deque", "forward_list", true)
  447. .Cases("list", "map", "multimap", "multiset", true)
  448. .Cases("priority_queue", "queue", "set", "stack", true)
  449. .Cases("unordered_map", "unordered_set", "vector", true)
  450. .Default(false)) {
  451. InitSeq.InitializeFrom(
  452. SemaRef, Entity,
  453. InitializationKind::CreateValue(Loc, Loc, Loc, true),
  454. MultiExprArg(), /*TopLevelOfInitList=*/false,
  455. TreatUnavailableAsInvalid);
  456. // Emit a warning for this. System header warnings aren't shown
  457. // by default, but people working on system headers should see it.
  458. if (!VerifyOnly) {
  459. SemaRef.Diag(CtorDecl->getLocation(),
  460. diag::warn_invalid_initializer_from_system_header);
  461. if (Entity.getKind() == InitializedEntity::EK_Member)
  462. SemaRef.Diag(Entity.getDecl()->getLocation(),
  463. diag::note_used_in_initialization_here);
  464. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
  465. SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
  466. }
  467. }
  468. }
  469. }
  470. if (!InitSeq) {
  471. if (!VerifyOnly) {
  472. InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
  473. if (Entity.getKind() == InitializedEntity::EK_Member)
  474. SemaRef.Diag(Entity.getDecl()->getLocation(),
  475. diag::note_in_omitted_aggregate_initializer)
  476. << /*field*/1 << Entity.getDecl();
  477. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
  478. bool IsTrailingArrayNewMember =
  479. Entity.getParent() &&
  480. Entity.getParent()->isVariableLengthArrayNew();
  481. SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
  482. << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
  483. << Entity.getElementIndex();
  484. }
  485. }
  486. return ExprError();
  487. }
  488. return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
  489. : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
  490. }
  491. void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
  492. SourceLocation Loc) {
  493. assert(VerifyOnly &&
  494. "CheckEmptyInitializable is only inteded for verification mode.");
  495. if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
  496. TreatUnavailableAsInvalid).isInvalid())
  497. hadError = true;
  498. }
  499. void InitListChecker::FillInEmptyInitForBase(
  500. unsigned Init, const CXXBaseSpecifier &Base,
  501. const InitializedEntity &ParentEntity, InitListExpr *ILE,
  502. bool &RequiresSecondPass, bool FillWithNoInit) {
  503. assert(Init < ILE->getNumInits() && "should have been expanded");
  504. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  505. SemaRef.Context, &Base, false, &ParentEntity);
  506. if (!ILE->getInit(Init)) {
  507. ExprResult BaseInit =
  508. FillWithNoInit
  509. ? new (SemaRef.Context) NoInitExpr(Base.getType())
  510. : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
  511. /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
  512. if (BaseInit.isInvalid()) {
  513. hadError = true;
  514. return;
  515. }
  516. ILE->setInit(Init, BaseInit.getAs<Expr>());
  517. } else if (InitListExpr *InnerILE =
  518. dyn_cast<InitListExpr>(ILE->getInit(Init))) {
  519. FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
  520. ILE, Init, FillWithNoInit);
  521. } else if (DesignatedInitUpdateExpr *InnerDIUE =
  522. dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
  523. FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
  524. RequiresSecondPass, ILE, Init,
  525. /*FillWithNoInit =*/true);
  526. }
  527. }
  528. void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  529. const InitializedEntity &ParentEntity,
  530. InitListExpr *ILE,
  531. bool &RequiresSecondPass,
  532. bool FillWithNoInit) {
  533. SourceLocation Loc = ILE->getEndLoc();
  534. unsigned NumInits = ILE->getNumInits();
  535. InitializedEntity MemberEntity
  536. = InitializedEntity::InitializeMember(Field, &ParentEntity);
  537. if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
  538. if (!RType->getDecl()->isUnion())
  539. assert(Init < NumInits && "This ILE should have been expanded");
  540. if (Init >= NumInits || !ILE->getInit(Init)) {
  541. if (FillWithNoInit) {
  542. Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
  543. if (Init < NumInits)
  544. ILE->setInit(Init, Filler);
  545. else
  546. ILE->updateInit(SemaRef.Context, Init, Filler);
  547. return;
  548. }
  549. // C++1y [dcl.init.aggr]p7:
  550. // If there are fewer initializer-clauses in the list than there are
  551. // members in the aggregate, then each member not explicitly initialized
  552. // shall be initialized from its brace-or-equal-initializer [...]
  553. if (Field->hasInClassInitializer()) {
  554. ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
  555. if (DIE.isInvalid()) {
  556. hadError = true;
  557. return;
  558. }
  559. SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
  560. if (Init < NumInits)
  561. ILE->setInit(Init, DIE.get());
  562. else {
  563. ILE->updateInit(SemaRef.Context, Init, DIE.get());
  564. RequiresSecondPass = true;
  565. }
  566. return;
  567. }
  568. if (Field->getType()->isReferenceType()) {
  569. // C++ [dcl.init.aggr]p9:
  570. // If an incomplete or empty initializer-list leaves a
  571. // member of reference type uninitialized, the program is
  572. // ill-formed.
  573. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
  574. << Field->getType()
  575. << ILE->getSyntacticForm()->getSourceRange();
  576. SemaRef.Diag(Field->getLocation(),
  577. diag::note_uninit_reference_member);
  578. hadError = true;
  579. return;
  580. }
  581. ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
  582. /*VerifyOnly*/false,
  583. TreatUnavailableAsInvalid);
  584. if (MemberInit.isInvalid()) {
  585. hadError = true;
  586. return;
  587. }
  588. if (hadError) {
  589. // Do nothing
  590. } else if (Init < NumInits) {
  591. ILE->setInit(Init, MemberInit.getAs<Expr>());
  592. } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
  593. // Empty initialization requires a constructor call, so
  594. // extend the initializer list to include the constructor
  595. // call and make a note that we'll need to take another pass
  596. // through the initializer list.
  597. ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
  598. RequiresSecondPass = true;
  599. }
  600. } else if (InitListExpr *InnerILE
  601. = dyn_cast<InitListExpr>(ILE->getInit(Init)))
  602. FillInEmptyInitializations(MemberEntity, InnerILE,
  603. RequiresSecondPass, ILE, Init, FillWithNoInit);
  604. else if (DesignatedInitUpdateExpr *InnerDIUE
  605. = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
  606. FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
  607. RequiresSecondPass, ILE, Init,
  608. /*FillWithNoInit =*/true);
  609. }
  610. /// Recursively replaces NULL values within the given initializer list
  611. /// with expressions that perform value-initialization of the
  612. /// appropriate type, and finish off the InitListExpr formation.
  613. void
  614. InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
  615. InitListExpr *ILE,
  616. bool &RequiresSecondPass,
  617. InitListExpr *OuterILE,
  618. unsigned OuterIndex,
  619. bool FillWithNoInit) {
  620. assert((ILE->getType() != SemaRef.Context.VoidTy) &&
  621. "Should not have void type");
  622. // If this is a nested initializer list, we might have changed its contents
  623. // (and therefore some of its properties, such as instantiation-dependence)
  624. // while filling it in. Inform the outer initializer list so that its state
  625. // can be updated to match.
  626. // FIXME: We should fully build the inner initializers before constructing
  627. // the outer InitListExpr instead of mutating AST nodes after they have
  628. // been used as subexpressions of other nodes.
  629. struct UpdateOuterILEWithUpdatedInit {
  630. InitListExpr *Outer;
  631. unsigned OuterIndex;
  632. ~UpdateOuterILEWithUpdatedInit() {
  633. if (Outer)
  634. Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
  635. }
  636. } UpdateOuterRAII = {OuterILE, OuterIndex};
  637. // A transparent ILE is not performing aggregate initialization and should
  638. // not be filled in.
  639. if (ILE->isTransparent())
  640. return;
  641. if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
  642. const RecordDecl *RDecl = RType->getDecl();
  643. if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
  644. FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
  645. Entity, ILE, RequiresSecondPass, FillWithNoInit);
  646. else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
  647. cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
  648. for (auto *Field : RDecl->fields()) {
  649. if (Field->hasInClassInitializer()) {
  650. FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
  651. FillWithNoInit);
  652. break;
  653. }
  654. }
  655. } else {
  656. // The fields beyond ILE->getNumInits() are default initialized, so in
  657. // order to leave them uninitialized, the ILE is expanded and the extra
  658. // fields are then filled with NoInitExpr.
  659. unsigned NumElems = numStructUnionElements(ILE->getType());
  660. if (RDecl->hasFlexibleArrayMember())
  661. ++NumElems;
  662. if (ILE->getNumInits() < NumElems)
  663. ILE->resizeInits(SemaRef.Context, NumElems);
  664. unsigned Init = 0;
  665. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
  666. for (auto &Base : CXXRD->bases()) {
  667. if (hadError)
  668. return;
  669. FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
  670. FillWithNoInit);
  671. ++Init;
  672. }
  673. }
  674. for (auto *Field : RDecl->fields()) {
  675. if (Field->isUnnamedBitfield())
  676. continue;
  677. if (hadError)
  678. return;
  679. FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
  680. FillWithNoInit);
  681. if (hadError)
  682. return;
  683. ++Init;
  684. // Only look at the first initialization of a union.
  685. if (RDecl->isUnion())
  686. break;
  687. }
  688. }
  689. return;
  690. }
  691. QualType ElementType;
  692. InitializedEntity ElementEntity = Entity;
  693. unsigned NumInits = ILE->getNumInits();
  694. unsigned NumElements = NumInits;
  695. if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
  696. ElementType = AType->getElementType();
  697. if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
  698. NumElements = CAType->getSize().getZExtValue();
  699. // For an array new with an unknown bound, ask for one additional element
  700. // in order to populate the array filler.
  701. if (Entity.isVariableLengthArrayNew())
  702. ++NumElements;
  703. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  704. 0, Entity);
  705. } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
  706. ElementType = VType->getElementType();
  707. NumElements = VType->getNumElements();
  708. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  709. 0, Entity);
  710. } else
  711. ElementType = ILE->getType();
  712. for (unsigned Init = 0; Init != NumElements; ++Init) {
  713. if (hadError)
  714. return;
  715. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
  716. ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
  717. ElementEntity.setElementIndex(Init);
  718. if (Init >= NumInits && ILE->hasArrayFiller())
  719. return;
  720. Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
  721. if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
  722. ILE->setInit(Init, ILE->getArrayFiller());
  723. else if (!InitExpr && !ILE->hasArrayFiller()) {
  724. Expr *Filler = nullptr;
  725. if (FillWithNoInit)
  726. Filler = new (SemaRef.Context) NoInitExpr(ElementType);
  727. else {
  728. ExprResult ElementInit =
  729. PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
  730. /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
  731. if (ElementInit.isInvalid()) {
  732. hadError = true;
  733. return;
  734. }
  735. Filler = ElementInit.getAs<Expr>();
  736. }
  737. if (hadError) {
  738. // Do nothing
  739. } else if (Init < NumInits) {
  740. // For arrays, just set the expression used for value-initialization
  741. // of the "holes" in the array.
  742. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
  743. ILE->setArrayFiller(Filler);
  744. else
  745. ILE->setInit(Init, Filler);
  746. } else {
  747. // For arrays, just set the expression used for value-initialization
  748. // of the rest of elements and exit.
  749. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  750. ILE->setArrayFiller(Filler);
  751. return;
  752. }
  753. if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
  754. // Empty initialization requires a constructor call, so
  755. // extend the initializer list to include the constructor
  756. // call and make a note that we'll need to take another pass
  757. // through the initializer list.
  758. ILE->updateInit(SemaRef.Context, Init, Filler);
  759. RequiresSecondPass = true;
  760. }
  761. }
  762. } else if (InitListExpr *InnerILE
  763. = dyn_cast_or_null<InitListExpr>(InitExpr))
  764. FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
  765. ILE, Init, FillWithNoInit);
  766. else if (DesignatedInitUpdateExpr *InnerDIUE
  767. = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
  768. FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
  769. RequiresSecondPass, ILE, Init,
  770. /*FillWithNoInit =*/true);
  771. }
  772. }
  773. InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
  774. InitListExpr *IL, QualType &T,
  775. bool VerifyOnly,
  776. bool TreatUnavailableAsInvalid)
  777. : SemaRef(S), VerifyOnly(VerifyOnly),
  778. TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
  779. // FIXME: Check that IL isn't already the semantic form of some other
  780. // InitListExpr. If it is, we'd create a broken AST.
  781. hadError = false;
  782. FullyStructuredList =
  783. getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
  784. CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
  785. /*TopLevelObject=*/true);
  786. if (!hadError && !VerifyOnly) {
  787. bool RequiresSecondPass = false;
  788. FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
  789. /*OuterILE=*/nullptr, /*OuterIndex=*/0);
  790. if (RequiresSecondPass && !hadError)
  791. FillInEmptyInitializations(Entity, FullyStructuredList,
  792. RequiresSecondPass, nullptr, 0);
  793. }
  794. }
  795. int InitListChecker::numArrayElements(QualType DeclType) {
  796. // FIXME: use a proper constant
  797. int maxElements = 0x7FFFFFFF;
  798. if (const ConstantArrayType *CAT =
  799. SemaRef.Context.getAsConstantArrayType(DeclType)) {
  800. maxElements = static_cast<int>(CAT->getSize().getZExtValue());
  801. }
  802. return maxElements;
  803. }
  804. int InitListChecker::numStructUnionElements(QualType DeclType) {
  805. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  806. int InitializableMembers = 0;
  807. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
  808. InitializableMembers += CXXRD->getNumBases();
  809. for (const auto *Field : structDecl->fields())
  810. if (!Field->isUnnamedBitfield())
  811. ++InitializableMembers;
  812. if (structDecl->isUnion())
  813. return std::min(InitializableMembers, 1);
  814. return InitializableMembers - structDecl->hasFlexibleArrayMember();
  815. }
  816. /// Determine whether Entity is an entity for which it is idiomatic to elide
  817. /// the braces in aggregate initialization.
  818. static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
  819. // Recursive initialization of the one and only field within an aggregate
  820. // class is considered idiomatic. This case arises in particular for
  821. // initialization of std::array, where the C++ standard suggests the idiom of
  822. //
  823. // std::array<T, N> arr = {1, 2, 3};
  824. //
  825. // (where std::array is an aggregate struct containing a single array field.
  826. // FIXME: Should aggregate initialization of a struct with a single
  827. // base class and no members also suppress the warning?
  828. if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
  829. return false;
  830. auto *ParentRD =
  831. Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
  832. if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
  833. if (CXXRD->getNumBases())
  834. return false;
  835. auto FieldIt = ParentRD->field_begin();
  836. assert(FieldIt != ParentRD->field_end() &&
  837. "no fields but have initializer for member?");
  838. return ++FieldIt == ParentRD->field_end();
  839. }
  840. /// Check whether the range of the initializer \p ParentIList from element
  841. /// \p Index onwards can be used to initialize an object of type \p T. Update
  842. /// \p Index to indicate how many elements of the list were consumed.
  843. ///
  844. /// This also fills in \p StructuredList, from element \p StructuredIndex
  845. /// onwards, with the fully-braced, desugared form of the initialization.
  846. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
  847. InitListExpr *ParentIList,
  848. QualType T, unsigned &Index,
  849. InitListExpr *StructuredList,
  850. unsigned &StructuredIndex) {
  851. int maxElements = 0;
  852. if (T->isArrayType())
  853. maxElements = numArrayElements(T);
  854. else if (T->isRecordType())
  855. maxElements = numStructUnionElements(T);
  856. else if (T->isVectorType())
  857. maxElements = T->getAs<VectorType>()->getNumElements();
  858. else
  859. llvm_unreachable("CheckImplicitInitList(): Illegal type");
  860. if (maxElements == 0) {
  861. if (!VerifyOnly)
  862. SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
  863. diag::err_implicit_empty_initializer);
  864. ++Index;
  865. hadError = true;
  866. return;
  867. }
  868. // Build a structured initializer list corresponding to this subobject.
  869. InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
  870. ParentIList, Index, T, StructuredList, StructuredIndex,
  871. SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
  872. ParentIList->getSourceRange().getEnd()));
  873. unsigned StructuredSubobjectInitIndex = 0;
  874. // Check the element types and build the structural subobject.
  875. unsigned StartIndex = Index;
  876. CheckListElementTypes(Entity, ParentIList, T,
  877. /*SubobjectIsDesignatorContext=*/false, Index,
  878. StructuredSubobjectInitList,
  879. StructuredSubobjectInitIndex);
  880. if (!VerifyOnly) {
  881. StructuredSubobjectInitList->setType(T);
  882. unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
  883. // Update the structured sub-object initializer so that it's ending
  884. // range corresponds with the end of the last initializer it used.
  885. if (EndIndex < ParentIList->getNumInits() &&
  886. ParentIList->getInit(EndIndex)) {
  887. SourceLocation EndLoc
  888. = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
  889. StructuredSubobjectInitList->setRBraceLoc(EndLoc);
  890. }
  891. // Complain about missing braces.
  892. if ((T->isArrayType() || T->isRecordType()) &&
  893. !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
  894. !isIdiomaticBraceElisionEntity(Entity)) {
  895. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  896. diag::warn_missing_braces)
  897. << StructuredSubobjectInitList->getSourceRange()
  898. << FixItHint::CreateInsertion(
  899. StructuredSubobjectInitList->getBeginLoc(), "{")
  900. << FixItHint::CreateInsertion(
  901. SemaRef.getLocForEndOfToken(
  902. StructuredSubobjectInitList->getEndLoc()),
  903. "}");
  904. }
  905. // Warn if this type won't be an aggregate in future versions of C++.
  906. auto *CXXRD = T->getAsCXXRecordDecl();
  907. if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  908. SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
  909. diag::warn_cxx2a_compat_aggregate_init_with_ctors)
  910. << StructuredSubobjectInitList->getSourceRange() << T;
  911. }
  912. }
  913. }
  914. /// Warn that \p Entity was of scalar type and was initialized by a
  915. /// single-element braced initializer list.
  916. static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
  917. SourceRange Braces) {
  918. // Don't warn during template instantiation. If the initialization was
  919. // non-dependent, we warned during the initial parse; otherwise, the
  920. // type might not be scalar in some uses of the template.
  921. if (S.inTemplateInstantiation())
  922. return;
  923. unsigned DiagID = 0;
  924. switch (Entity.getKind()) {
  925. case InitializedEntity::EK_VectorElement:
  926. case InitializedEntity::EK_ComplexElement:
  927. case InitializedEntity::EK_ArrayElement:
  928. case InitializedEntity::EK_Parameter:
  929. case InitializedEntity::EK_Parameter_CF_Audited:
  930. case InitializedEntity::EK_Result:
  931. // Extra braces here are suspicious.
  932. DiagID = diag::warn_braces_around_scalar_init;
  933. break;
  934. case InitializedEntity::EK_Member:
  935. // Warn on aggregate initialization but not on ctor init list or
  936. // default member initializer.
  937. if (Entity.getParent())
  938. DiagID = diag::warn_braces_around_scalar_init;
  939. break;
  940. case InitializedEntity::EK_Variable:
  941. case InitializedEntity::EK_LambdaCapture:
  942. // No warning, might be direct-list-initialization.
  943. // FIXME: Should we warn for copy-list-initialization in these cases?
  944. break;
  945. case InitializedEntity::EK_New:
  946. case InitializedEntity::EK_Temporary:
  947. case InitializedEntity::EK_CompoundLiteralInit:
  948. // No warning, braces are part of the syntax of the underlying construct.
  949. break;
  950. case InitializedEntity::EK_RelatedResult:
  951. // No warning, we already warned when initializing the result.
  952. break;
  953. case InitializedEntity::EK_Exception:
  954. case InitializedEntity::EK_Base:
  955. case InitializedEntity::EK_Delegating:
  956. case InitializedEntity::EK_BlockElement:
  957. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  958. case InitializedEntity::EK_Binding:
  959. case InitializedEntity::EK_StmtExprResult:
  960. llvm_unreachable("unexpected braced scalar init");
  961. }
  962. if (DiagID) {
  963. S.Diag(Braces.getBegin(), DiagID)
  964. << Braces
  965. << FixItHint::CreateRemoval(Braces.getBegin())
  966. << FixItHint::CreateRemoval(Braces.getEnd());
  967. }
  968. }
  969. /// Check whether the initializer \p IList (that was written with explicit
  970. /// braces) can be used to initialize an object of type \p T.
  971. ///
  972. /// This also fills in \p StructuredList with the fully-braced, desugared
  973. /// form of the initialization.
  974. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
  975. InitListExpr *IList, QualType &T,
  976. InitListExpr *StructuredList,
  977. bool TopLevelObject) {
  978. if (!VerifyOnly) {
  979. SyntacticToSemantic[IList] = StructuredList;
  980. StructuredList->setSyntacticForm(IList);
  981. }
  982. unsigned Index = 0, StructuredIndex = 0;
  983. CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
  984. Index, StructuredList, StructuredIndex, TopLevelObject);
  985. if (!VerifyOnly) {
  986. QualType ExprTy = T;
  987. if (!ExprTy->isArrayType())
  988. ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
  989. IList->setType(ExprTy);
  990. StructuredList->setType(ExprTy);
  991. }
  992. if (hadError)
  993. return;
  994. if (Index < IList->getNumInits()) {
  995. // We have leftover initializers
  996. if (VerifyOnly) {
  997. if (SemaRef.getLangOpts().CPlusPlus ||
  998. (SemaRef.getLangOpts().OpenCL &&
  999. IList->getType()->isVectorType())) {
  1000. hadError = true;
  1001. }
  1002. return;
  1003. }
  1004. if (StructuredIndex == 1 &&
  1005. IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
  1006. SIF_None) {
  1007. unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
  1008. if (SemaRef.getLangOpts().CPlusPlus) {
  1009. DK = diag::err_excess_initializers_in_char_array_initializer;
  1010. hadError = true;
  1011. }
  1012. // Special-case
  1013. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1014. << IList->getInit(Index)->getSourceRange();
  1015. } else if (!T->isIncompleteType()) {
  1016. // Don't complain for incomplete types, since we'll get an error
  1017. // elsewhere
  1018. QualType CurrentObjectType = StructuredList->getType();
  1019. int initKind =
  1020. CurrentObjectType->isArrayType()? 0 :
  1021. CurrentObjectType->isVectorType()? 1 :
  1022. CurrentObjectType->isScalarType()? 2 :
  1023. CurrentObjectType->isUnionType()? 3 :
  1024. 4;
  1025. unsigned DK = diag::ext_excess_initializers;
  1026. if (SemaRef.getLangOpts().CPlusPlus) {
  1027. DK = diag::err_excess_initializers;
  1028. hadError = true;
  1029. }
  1030. if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
  1031. DK = diag::err_excess_initializers;
  1032. hadError = true;
  1033. }
  1034. SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
  1035. << initKind << IList->getInit(Index)->getSourceRange();
  1036. }
  1037. }
  1038. if (!VerifyOnly) {
  1039. if (T->isScalarType() && IList->getNumInits() == 1 &&
  1040. !isa<InitListExpr>(IList->getInit(0)))
  1041. warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
  1042. // Warn if this is a class type that won't be an aggregate in future
  1043. // versions of C++.
  1044. auto *CXXRD = T->getAsCXXRecordDecl();
  1045. if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
  1046. // Don't warn if there's an equivalent default constructor that would be
  1047. // used instead.
  1048. bool HasEquivCtor = false;
  1049. if (IList->getNumInits() == 0) {
  1050. auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
  1051. HasEquivCtor = CD && !CD->isDeleted();
  1052. }
  1053. if (!HasEquivCtor) {
  1054. SemaRef.Diag(IList->getBeginLoc(),
  1055. diag::warn_cxx2a_compat_aggregate_init_with_ctors)
  1056. << IList->getSourceRange() << T;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
  1062. InitListExpr *IList,
  1063. QualType &DeclType,
  1064. bool SubobjectIsDesignatorContext,
  1065. unsigned &Index,
  1066. InitListExpr *StructuredList,
  1067. unsigned &StructuredIndex,
  1068. bool TopLevelObject) {
  1069. if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
  1070. // Explicitly braced initializer for complex type can be real+imaginary
  1071. // parts.
  1072. CheckComplexType(Entity, IList, DeclType, Index,
  1073. StructuredList, StructuredIndex);
  1074. } else if (DeclType->isScalarType()) {
  1075. CheckScalarType(Entity, IList, DeclType, Index,
  1076. StructuredList, StructuredIndex);
  1077. } else if (DeclType->isVectorType()) {
  1078. CheckVectorType(Entity, IList, DeclType, Index,
  1079. StructuredList, StructuredIndex);
  1080. } else if (DeclType->isRecordType()) {
  1081. assert(DeclType->isAggregateType() &&
  1082. "non-aggregate records should be handed in CheckSubElementType");
  1083. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1084. auto Bases =
  1085. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  1086. CXXRecordDecl::base_class_iterator());
  1087. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1088. Bases = CXXRD->bases();
  1089. CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
  1090. SubobjectIsDesignatorContext, Index, StructuredList,
  1091. StructuredIndex, TopLevelObject);
  1092. } else if (DeclType->isArrayType()) {
  1093. llvm::APSInt Zero(
  1094. SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
  1095. false);
  1096. CheckArrayType(Entity, IList, DeclType, Zero,
  1097. SubobjectIsDesignatorContext, Index,
  1098. StructuredList, StructuredIndex);
  1099. } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
  1100. // This type is invalid, issue a diagnostic.
  1101. ++Index;
  1102. if (!VerifyOnly)
  1103. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1104. << DeclType;
  1105. hadError = true;
  1106. } else if (DeclType->isReferenceType()) {
  1107. CheckReferenceType(Entity, IList, DeclType, Index,
  1108. StructuredList, StructuredIndex);
  1109. } else if (DeclType->isObjCObjectType()) {
  1110. if (!VerifyOnly)
  1111. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
  1112. hadError = true;
  1113. } else if (DeclType->isOCLIntelSubgroupAVCType()) {
  1114. // Checks for scalar type are sufficient for these types too.
  1115. CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1116. StructuredIndex);
  1117. } else {
  1118. if (!VerifyOnly)
  1119. SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
  1120. << DeclType;
  1121. hadError = true;
  1122. }
  1123. }
  1124. void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
  1125. InitListExpr *IList,
  1126. QualType ElemType,
  1127. unsigned &Index,
  1128. InitListExpr *StructuredList,
  1129. unsigned &StructuredIndex) {
  1130. Expr *expr = IList->getInit(Index);
  1131. if (ElemType->isReferenceType())
  1132. return CheckReferenceType(Entity, IList, ElemType, Index,
  1133. StructuredList, StructuredIndex);
  1134. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
  1135. if (SubInitList->getNumInits() == 1 &&
  1136. IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
  1137. SIF_None) {
  1138. expr = SubInitList->getInit(0);
  1139. } else if (!SemaRef.getLangOpts().CPlusPlus) {
  1140. InitListExpr *InnerStructuredList
  1141. = getStructuredSubobjectInit(IList, Index, ElemType,
  1142. StructuredList, StructuredIndex,
  1143. SubInitList->getSourceRange(), true);
  1144. CheckExplicitInitList(Entity, SubInitList, ElemType,
  1145. InnerStructuredList);
  1146. if (!hadError && !VerifyOnly) {
  1147. bool RequiresSecondPass = false;
  1148. FillInEmptyInitializations(Entity, InnerStructuredList,
  1149. RequiresSecondPass, StructuredList,
  1150. StructuredIndex);
  1151. if (RequiresSecondPass && !hadError)
  1152. FillInEmptyInitializations(Entity, InnerStructuredList,
  1153. RequiresSecondPass, StructuredList,
  1154. StructuredIndex);
  1155. }
  1156. ++StructuredIndex;
  1157. ++Index;
  1158. return;
  1159. }
  1160. // C++ initialization is handled later.
  1161. } else if (isa<ImplicitValueInitExpr>(expr)) {
  1162. // This happens during template instantiation when we see an InitListExpr
  1163. // that we've already checked once.
  1164. assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
  1165. "found implicit initialization for the wrong type");
  1166. if (!VerifyOnly)
  1167. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1168. ++Index;
  1169. return;
  1170. }
  1171. if (SemaRef.getLangOpts().CPlusPlus) {
  1172. // C++ [dcl.init.aggr]p2:
  1173. // Each member is copy-initialized from the corresponding
  1174. // initializer-clause.
  1175. // FIXME: Better EqualLoc?
  1176. InitializationKind Kind =
  1177. InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
  1178. // Vector elements can be initialized from other vectors in which case
  1179. // we need initialization entity with a type of a vector (and not a vector
  1180. // element!) initializing multiple vector elements.
  1181. auto TmpEntity =
  1182. (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
  1183. ? InitializedEntity::InitializeTemporary(ElemType)
  1184. : Entity;
  1185. InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
  1186. /*TopLevelOfInitList*/ true);
  1187. // C++14 [dcl.init.aggr]p13:
  1188. // If the assignment-expression can initialize a member, the member is
  1189. // initialized. Otherwise [...] brace elision is assumed
  1190. //
  1191. // Brace elision is never performed if the element is not an
  1192. // assignment-expression.
  1193. if (Seq || isa<InitListExpr>(expr)) {
  1194. if (!VerifyOnly) {
  1195. ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
  1196. if (Result.isInvalid())
  1197. hadError = true;
  1198. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1199. Result.getAs<Expr>());
  1200. } else if (!Seq)
  1201. hadError = true;
  1202. ++Index;
  1203. return;
  1204. }
  1205. // Fall through for subaggregate initialization
  1206. } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
  1207. // FIXME: Need to handle atomic aggregate types with implicit init lists.
  1208. return CheckScalarType(Entity, IList, ElemType, Index,
  1209. StructuredList, StructuredIndex);
  1210. } else if (const ArrayType *arrayType =
  1211. SemaRef.Context.getAsArrayType(ElemType)) {
  1212. // arrayType can be incomplete if we're initializing a flexible
  1213. // array member. There's nothing we can do with the completed
  1214. // type here, though.
  1215. if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
  1216. if (!VerifyOnly) {
  1217. CheckStringInit(expr, ElemType, arrayType, SemaRef);
  1218. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1219. }
  1220. ++Index;
  1221. return;
  1222. }
  1223. // Fall through for subaggregate initialization.
  1224. } else {
  1225. assert((ElemType->isRecordType() || ElemType->isVectorType() ||
  1226. ElemType->isOpenCLSpecificType()) && "Unexpected type");
  1227. // C99 6.7.8p13:
  1228. //
  1229. // The initializer for a structure or union object that has
  1230. // automatic storage duration shall be either an initializer
  1231. // list as described below, or a single expression that has
  1232. // compatible structure or union type. In the latter case, the
  1233. // initial value of the object, including unnamed members, is
  1234. // that of the expression.
  1235. ExprResult ExprRes = expr;
  1236. if (SemaRef.CheckSingleAssignmentConstraints(
  1237. ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
  1238. if (ExprRes.isInvalid())
  1239. hadError = true;
  1240. else {
  1241. ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
  1242. if (ExprRes.isInvalid())
  1243. hadError = true;
  1244. }
  1245. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1246. ExprRes.getAs<Expr>());
  1247. ++Index;
  1248. return;
  1249. }
  1250. ExprRes.get();
  1251. // Fall through for subaggregate initialization
  1252. }
  1253. // C++ [dcl.init.aggr]p12:
  1254. //
  1255. // [...] Otherwise, if the member is itself a non-empty
  1256. // subaggregate, brace elision is assumed and the initializer is
  1257. // considered for the initialization of the first member of
  1258. // the subaggregate.
  1259. // OpenCL vector initializer is handled elsewhere.
  1260. if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
  1261. ElemType->isAggregateType()) {
  1262. CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
  1263. StructuredIndex);
  1264. ++StructuredIndex;
  1265. } else {
  1266. if (!VerifyOnly) {
  1267. // We cannot initialize this element, so let
  1268. // PerformCopyInitialization produce the appropriate diagnostic.
  1269. SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
  1270. /*TopLevelOfInitList=*/true);
  1271. }
  1272. hadError = true;
  1273. ++Index;
  1274. ++StructuredIndex;
  1275. }
  1276. }
  1277. void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
  1278. InitListExpr *IList, QualType DeclType,
  1279. unsigned &Index,
  1280. InitListExpr *StructuredList,
  1281. unsigned &StructuredIndex) {
  1282. assert(Index == 0 && "Index in explicit init list must be zero");
  1283. // As an extension, clang supports complex initializers, which initialize
  1284. // a complex number component-wise. When an explicit initializer list for
  1285. // a complex number contains two two initializers, this extension kicks in:
  1286. // it exepcts the initializer list to contain two elements convertible to
  1287. // the element type of the complex type. The first element initializes
  1288. // the real part, and the second element intitializes the imaginary part.
  1289. if (IList->getNumInits() != 2)
  1290. return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1291. StructuredIndex);
  1292. // This is an extension in C. (The builtin _Complex type does not exist
  1293. // in the C++ standard.)
  1294. if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
  1295. SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
  1296. << IList->getSourceRange();
  1297. // Initialize the complex number.
  1298. QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
  1299. InitializedEntity ElementEntity =
  1300. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1301. for (unsigned i = 0; i < 2; ++i) {
  1302. ElementEntity.setElementIndex(Index);
  1303. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1304. StructuredList, StructuredIndex);
  1305. }
  1306. }
  1307. void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
  1308. InitListExpr *IList, QualType DeclType,
  1309. unsigned &Index,
  1310. InitListExpr *StructuredList,
  1311. unsigned &StructuredIndex) {
  1312. if (Index >= IList->getNumInits()) {
  1313. if (!VerifyOnly)
  1314. SemaRef.Diag(IList->getBeginLoc(),
  1315. SemaRef.getLangOpts().CPlusPlus11
  1316. ? diag::warn_cxx98_compat_empty_scalar_initializer
  1317. : diag::err_empty_scalar_initializer)
  1318. << IList->getSourceRange();
  1319. hadError = !SemaRef.getLangOpts().CPlusPlus11;
  1320. ++Index;
  1321. ++StructuredIndex;
  1322. return;
  1323. }
  1324. Expr *expr = IList->getInit(Index);
  1325. if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
  1326. // FIXME: This is invalid, and accepting it causes overload resolution
  1327. // to pick the wrong overload in some corner cases.
  1328. if (!VerifyOnly)
  1329. SemaRef.Diag(SubIList->getBeginLoc(),
  1330. diag::ext_many_braces_around_scalar_init)
  1331. << SubIList->getSourceRange();
  1332. CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
  1333. StructuredIndex);
  1334. return;
  1335. } else if (isa<DesignatedInitExpr>(expr)) {
  1336. if (!VerifyOnly)
  1337. SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
  1338. << DeclType << expr->getSourceRange();
  1339. hadError = true;
  1340. ++Index;
  1341. ++StructuredIndex;
  1342. return;
  1343. }
  1344. if (VerifyOnly) {
  1345. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1346. hadError = true;
  1347. ++Index;
  1348. return;
  1349. }
  1350. ExprResult Result =
  1351. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1352. /*TopLevelOfInitList=*/true);
  1353. Expr *ResultExpr = nullptr;
  1354. if (Result.isInvalid())
  1355. hadError = true; // types weren't compatible.
  1356. else {
  1357. ResultExpr = Result.getAs<Expr>();
  1358. if (ResultExpr != expr) {
  1359. // The type was promoted, update initializer list.
  1360. IList->setInit(Index, ResultExpr);
  1361. }
  1362. }
  1363. if (hadError)
  1364. ++StructuredIndex;
  1365. else
  1366. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  1367. ++Index;
  1368. }
  1369. void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
  1370. InitListExpr *IList, QualType DeclType,
  1371. unsigned &Index,
  1372. InitListExpr *StructuredList,
  1373. unsigned &StructuredIndex) {
  1374. if (Index >= IList->getNumInits()) {
  1375. // FIXME: It would be wonderful if we could point at the actual member. In
  1376. // general, it would be useful to pass location information down the stack,
  1377. // so that we know the location (or decl) of the "current object" being
  1378. // initialized.
  1379. if (!VerifyOnly)
  1380. SemaRef.Diag(IList->getBeginLoc(),
  1381. diag::err_init_reference_member_uninitialized)
  1382. << DeclType << IList->getSourceRange();
  1383. hadError = true;
  1384. ++Index;
  1385. ++StructuredIndex;
  1386. return;
  1387. }
  1388. Expr *expr = IList->getInit(Index);
  1389. if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
  1390. if (!VerifyOnly)
  1391. SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
  1392. << DeclType << IList->getSourceRange();
  1393. hadError = true;
  1394. ++Index;
  1395. ++StructuredIndex;
  1396. return;
  1397. }
  1398. if (VerifyOnly) {
  1399. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1400. hadError = true;
  1401. ++Index;
  1402. return;
  1403. }
  1404. ExprResult Result =
  1405. SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
  1406. /*TopLevelOfInitList=*/true);
  1407. if (Result.isInvalid())
  1408. hadError = true;
  1409. expr = Result.getAs<Expr>();
  1410. IList->setInit(Index, expr);
  1411. if (hadError)
  1412. ++StructuredIndex;
  1413. else
  1414. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1415. ++Index;
  1416. }
  1417. void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
  1418. InitListExpr *IList, QualType DeclType,
  1419. unsigned &Index,
  1420. InitListExpr *StructuredList,
  1421. unsigned &StructuredIndex) {
  1422. const VectorType *VT = DeclType->getAs<VectorType>();
  1423. unsigned maxElements = VT->getNumElements();
  1424. unsigned numEltsInit = 0;
  1425. QualType elementType = VT->getElementType();
  1426. if (Index >= IList->getNumInits()) {
  1427. // Make sure the element type can be value-initialized.
  1428. if (VerifyOnly)
  1429. CheckEmptyInitializable(
  1430. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1431. IList->getEndLoc());
  1432. return;
  1433. }
  1434. if (!SemaRef.getLangOpts().OpenCL) {
  1435. // If the initializing element is a vector, try to copy-initialize
  1436. // instead of breaking it apart (which is doomed to failure anyway).
  1437. Expr *Init = IList->getInit(Index);
  1438. if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
  1439. if (VerifyOnly) {
  1440. if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
  1441. hadError = true;
  1442. ++Index;
  1443. return;
  1444. }
  1445. ExprResult Result =
  1446. SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
  1447. /*TopLevelOfInitList=*/true);
  1448. Expr *ResultExpr = nullptr;
  1449. if (Result.isInvalid())
  1450. hadError = true; // types weren't compatible.
  1451. else {
  1452. ResultExpr = Result.getAs<Expr>();
  1453. if (ResultExpr != Init) {
  1454. // The type was promoted, update initializer list.
  1455. IList->setInit(Index, ResultExpr);
  1456. }
  1457. }
  1458. if (hadError)
  1459. ++StructuredIndex;
  1460. else
  1461. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1462. ResultExpr);
  1463. ++Index;
  1464. return;
  1465. }
  1466. InitializedEntity ElementEntity =
  1467. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1468. for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
  1469. // Don't attempt to go past the end of the init list
  1470. if (Index >= IList->getNumInits()) {
  1471. if (VerifyOnly)
  1472. CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
  1473. break;
  1474. }
  1475. ElementEntity.setElementIndex(Index);
  1476. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1477. StructuredList, StructuredIndex);
  1478. }
  1479. if (VerifyOnly)
  1480. return;
  1481. bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
  1482. const VectorType *T = Entity.getType()->getAs<VectorType>();
  1483. if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
  1484. T->getVectorKind() == VectorType::NeonPolyVector)) {
  1485. // The ability to use vector initializer lists is a GNU vector extension
  1486. // and is unrelated to the NEON intrinsics in arm_neon.h. On little
  1487. // endian machines it works fine, however on big endian machines it
  1488. // exhibits surprising behaviour:
  1489. //
  1490. // uint32x2_t x = {42, 64};
  1491. // return vget_lane_u32(x, 0); // Will return 64.
  1492. //
  1493. // Because of this, explicitly call out that it is non-portable.
  1494. //
  1495. SemaRef.Diag(IList->getBeginLoc(),
  1496. diag::warn_neon_vector_initializer_non_portable);
  1497. const char *typeCode;
  1498. unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
  1499. if (elementType->isFloatingType())
  1500. typeCode = "f";
  1501. else if (elementType->isSignedIntegerType())
  1502. typeCode = "s";
  1503. else if (elementType->isUnsignedIntegerType())
  1504. typeCode = "u";
  1505. else
  1506. llvm_unreachable("Invalid element type!");
  1507. SemaRef.Diag(IList->getBeginLoc(),
  1508. SemaRef.Context.getTypeSize(VT) > 64
  1509. ? diag::note_neon_vector_initializer_non_portable_q
  1510. : diag::note_neon_vector_initializer_non_portable)
  1511. << typeCode << typeSize;
  1512. }
  1513. return;
  1514. }
  1515. InitializedEntity ElementEntity =
  1516. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1517. // OpenCL initializers allows vectors to be constructed from vectors.
  1518. for (unsigned i = 0; i < maxElements; ++i) {
  1519. // Don't attempt to go past the end of the init list
  1520. if (Index >= IList->getNumInits())
  1521. break;
  1522. ElementEntity.setElementIndex(Index);
  1523. QualType IType = IList->getInit(Index)->getType();
  1524. if (!IType->isVectorType()) {
  1525. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1526. StructuredList, StructuredIndex);
  1527. ++numEltsInit;
  1528. } else {
  1529. QualType VecType;
  1530. const VectorType *IVT = IType->getAs<VectorType>();
  1531. unsigned numIElts = IVT->getNumElements();
  1532. if (IType->isExtVectorType())
  1533. VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
  1534. else
  1535. VecType = SemaRef.Context.getVectorType(elementType, numIElts,
  1536. IVT->getVectorKind());
  1537. CheckSubElementType(ElementEntity, IList, VecType, Index,
  1538. StructuredList, StructuredIndex);
  1539. numEltsInit += numIElts;
  1540. }
  1541. }
  1542. // OpenCL requires all elements to be initialized.
  1543. if (numEltsInit != maxElements) {
  1544. if (!VerifyOnly)
  1545. SemaRef.Diag(IList->getBeginLoc(),
  1546. diag::err_vector_incorrect_num_initializers)
  1547. << (numEltsInit < maxElements) << maxElements << numEltsInit;
  1548. hadError = true;
  1549. }
  1550. }
  1551. /// Check if the type of a class element has an accessible destructor, and marks
  1552. /// it referenced. Returns true if we shouldn't form a reference to the
  1553. /// destructor.
  1554. ///
  1555. /// Aggregate initialization requires a class element's destructor be
  1556. /// accessible per 11.6.1 [dcl.init.aggr]:
  1557. ///
  1558. /// The destructor for each element of class type is potentially invoked
  1559. /// (15.4 [class.dtor]) from the context where the aggregate initialization
  1560. /// occurs.
  1561. static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
  1562. Sema &SemaRef) {
  1563. auto *CXXRD = ElementType->getAsCXXRecordDecl();
  1564. if (!CXXRD)
  1565. return false;
  1566. CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
  1567. SemaRef.CheckDestructorAccess(Loc, Destructor,
  1568. SemaRef.PDiag(diag::err_access_dtor_temp)
  1569. << ElementType);
  1570. SemaRef.MarkFunctionReferenced(Loc, Destructor);
  1571. return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
  1572. }
  1573. void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
  1574. InitListExpr *IList, QualType &DeclType,
  1575. llvm::APSInt elementIndex,
  1576. bool SubobjectIsDesignatorContext,
  1577. unsigned &Index,
  1578. InitListExpr *StructuredList,
  1579. unsigned &StructuredIndex) {
  1580. const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
  1581. if (!VerifyOnly) {
  1582. if (checkDestructorReference(arrayType->getElementType(),
  1583. IList->getEndLoc(), SemaRef)) {
  1584. hadError = true;
  1585. return;
  1586. }
  1587. }
  1588. // Check for the special-case of initializing an array with a string.
  1589. if (Index < IList->getNumInits()) {
  1590. if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
  1591. SIF_None) {
  1592. // We place the string literal directly into the resulting
  1593. // initializer list. This is the only place where the structure
  1594. // of the structured initializer list doesn't match exactly,
  1595. // because doing so would involve allocating one character
  1596. // constant for each string.
  1597. if (!VerifyOnly) {
  1598. CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
  1599. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1600. IList->getInit(Index));
  1601. StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
  1602. }
  1603. ++Index;
  1604. return;
  1605. }
  1606. }
  1607. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
  1608. // Check for VLAs; in standard C it would be possible to check this
  1609. // earlier, but I don't know where clang accepts VLAs (gcc accepts
  1610. // them in all sorts of strange places).
  1611. if (!VerifyOnly)
  1612. SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
  1613. diag::err_variable_object_no_init)
  1614. << VAT->getSizeExpr()->getSourceRange();
  1615. hadError = true;
  1616. ++Index;
  1617. ++StructuredIndex;
  1618. return;
  1619. }
  1620. // We might know the maximum number of elements in advance.
  1621. llvm::APSInt maxElements(elementIndex.getBitWidth(),
  1622. elementIndex.isUnsigned());
  1623. bool maxElementsKnown = false;
  1624. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
  1625. maxElements = CAT->getSize();
  1626. elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
  1627. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1628. maxElementsKnown = true;
  1629. }
  1630. QualType elementType = arrayType->getElementType();
  1631. while (Index < IList->getNumInits()) {
  1632. Expr *Init = IList->getInit(Index);
  1633. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1634. // If we're not the subobject that matches up with the '{' for
  1635. // the designator, we shouldn't be handling the
  1636. // designator. Return immediately.
  1637. if (!SubobjectIsDesignatorContext)
  1638. return;
  1639. // Handle this designated initializer. elementIndex will be
  1640. // updated to be the next array element we'll initialize.
  1641. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1642. DeclType, nullptr, &elementIndex, Index,
  1643. StructuredList, StructuredIndex, true,
  1644. false)) {
  1645. hadError = true;
  1646. continue;
  1647. }
  1648. if (elementIndex.getBitWidth() > maxElements.getBitWidth())
  1649. maxElements = maxElements.extend(elementIndex.getBitWidth());
  1650. else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
  1651. elementIndex = elementIndex.extend(maxElements.getBitWidth());
  1652. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1653. // If the array is of incomplete type, keep track of the number of
  1654. // elements in the initializer.
  1655. if (!maxElementsKnown && elementIndex > maxElements)
  1656. maxElements = elementIndex;
  1657. continue;
  1658. }
  1659. // If we know the maximum number of elements, and we've already
  1660. // hit it, stop consuming elements in the initializer list.
  1661. if (maxElementsKnown && elementIndex == maxElements)
  1662. break;
  1663. InitializedEntity ElementEntity =
  1664. InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
  1665. Entity);
  1666. // Check this element.
  1667. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1668. StructuredList, StructuredIndex);
  1669. ++elementIndex;
  1670. // If the array is of incomplete type, keep track of the number of
  1671. // elements in the initializer.
  1672. if (!maxElementsKnown && elementIndex > maxElements)
  1673. maxElements = elementIndex;
  1674. }
  1675. if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
  1676. // If this is an incomplete array type, the actual type needs to
  1677. // be calculated here.
  1678. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
  1679. if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
  1680. // Sizing an array implicitly to zero is not allowed by ISO C,
  1681. // but is supported by GNU.
  1682. SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
  1683. }
  1684. DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
  1685. ArrayType::Normal, 0);
  1686. }
  1687. if (!hadError && VerifyOnly) {
  1688. // If there are any members of the array that get value-initialized, check
  1689. // that is possible. That happens if we know the bound and don't have
  1690. // enough elements, or if we're performing an array new with an unknown
  1691. // bound.
  1692. // FIXME: This needs to detect holes left by designated initializers too.
  1693. if ((maxElementsKnown && elementIndex < maxElements) ||
  1694. Entity.isVariableLengthArrayNew())
  1695. CheckEmptyInitializable(
  1696. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1697. IList->getEndLoc());
  1698. }
  1699. }
  1700. bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
  1701. Expr *InitExpr,
  1702. FieldDecl *Field,
  1703. bool TopLevelObject) {
  1704. // Handle GNU flexible array initializers.
  1705. unsigned FlexArrayDiag;
  1706. if (isa<InitListExpr>(InitExpr) &&
  1707. cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
  1708. // Empty flexible array init always allowed as an extension
  1709. FlexArrayDiag = diag::ext_flexible_array_init;
  1710. } else if (SemaRef.getLangOpts().CPlusPlus) {
  1711. // Disallow flexible array init in C++; it is not required for gcc
  1712. // compatibility, and it needs work to IRGen correctly in general.
  1713. FlexArrayDiag = diag::err_flexible_array_init;
  1714. } else if (!TopLevelObject) {
  1715. // Disallow flexible array init on non-top-level object
  1716. FlexArrayDiag = diag::err_flexible_array_init;
  1717. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  1718. // Disallow flexible array init on anything which is not a variable.
  1719. FlexArrayDiag = diag::err_flexible_array_init;
  1720. } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
  1721. // Disallow flexible array init on local variables.
  1722. FlexArrayDiag = diag::err_flexible_array_init;
  1723. } else {
  1724. // Allow other cases.
  1725. FlexArrayDiag = diag::ext_flexible_array_init;
  1726. }
  1727. if (!VerifyOnly) {
  1728. SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
  1729. << InitExpr->getBeginLoc();
  1730. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1731. << Field;
  1732. }
  1733. return FlexArrayDiag != diag::ext_flexible_array_init;
  1734. }
  1735. void InitListChecker::CheckStructUnionTypes(
  1736. const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
  1737. CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
  1738. bool SubobjectIsDesignatorContext, unsigned &Index,
  1739. InitListExpr *StructuredList, unsigned &StructuredIndex,
  1740. bool TopLevelObject) {
  1741. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  1742. // If the record is invalid, some of it's members are invalid. To avoid
  1743. // confusion, we forgo checking the intializer for the entire record.
  1744. if (structDecl->isInvalidDecl()) {
  1745. // Assume it was supposed to consume a single initializer.
  1746. ++Index;
  1747. hadError = true;
  1748. return;
  1749. }
  1750. if (DeclType->isUnionType() && IList->getNumInits() == 0) {
  1751. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1752. if (!VerifyOnly)
  1753. for (FieldDecl *FD : RD->fields()) {
  1754. QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
  1755. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  1756. hadError = true;
  1757. return;
  1758. }
  1759. }
  1760. // If there's a default initializer, use it.
  1761. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
  1762. if (VerifyOnly)
  1763. return;
  1764. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1765. Field != FieldEnd; ++Field) {
  1766. if (Field->hasInClassInitializer()) {
  1767. StructuredList->setInitializedFieldInUnion(*Field);
  1768. // FIXME: Actually build a CXXDefaultInitExpr?
  1769. return;
  1770. }
  1771. }
  1772. }
  1773. // Value-initialize the first member of the union that isn't an unnamed
  1774. // bitfield.
  1775. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1776. Field != FieldEnd; ++Field) {
  1777. if (!Field->isUnnamedBitfield()) {
  1778. if (VerifyOnly)
  1779. CheckEmptyInitializable(
  1780. InitializedEntity::InitializeMember(*Field, &Entity),
  1781. IList->getEndLoc());
  1782. else
  1783. StructuredList->setInitializedFieldInUnion(*Field);
  1784. break;
  1785. }
  1786. }
  1787. return;
  1788. }
  1789. bool InitializedSomething = false;
  1790. // If we have any base classes, they are initialized prior to the fields.
  1791. for (auto &Base : Bases) {
  1792. Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
  1793. // Designated inits always initialize fields, so if we see one, all
  1794. // remaining base classes have no explicit initializer.
  1795. if (Init && isa<DesignatedInitExpr>(Init))
  1796. Init = nullptr;
  1797. SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
  1798. InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
  1799. SemaRef.Context, &Base, false, &Entity);
  1800. if (Init) {
  1801. CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
  1802. StructuredList, StructuredIndex);
  1803. InitializedSomething = true;
  1804. } else if (VerifyOnly) {
  1805. CheckEmptyInitializable(BaseEntity, InitLoc);
  1806. }
  1807. if (!VerifyOnly)
  1808. if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
  1809. hadError = true;
  1810. return;
  1811. }
  1812. }
  1813. // If structDecl is a forward declaration, this loop won't do
  1814. // anything except look at designated initializers; That's okay,
  1815. // because an error should get printed out elsewhere. It might be
  1816. // worthwhile to skip over the rest of the initializer, though.
  1817. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1818. RecordDecl::field_iterator FieldEnd = RD->field_end();
  1819. bool CheckForMissingFields =
  1820. !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
  1821. bool HasDesignatedInit = false;
  1822. while (Index < IList->getNumInits()) {
  1823. Expr *Init = IList->getInit(Index);
  1824. SourceLocation InitLoc = Init->getBeginLoc();
  1825. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1826. // If we're not the subobject that matches up with the '{' for
  1827. // the designator, we shouldn't be handling the
  1828. // designator. Return immediately.
  1829. if (!SubobjectIsDesignatorContext)
  1830. return;
  1831. HasDesignatedInit = true;
  1832. // Handle this designated initializer. Field will be updated to
  1833. // the next field that we'll be initializing.
  1834. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1835. DeclType, &Field, nullptr, Index,
  1836. StructuredList, StructuredIndex,
  1837. true, TopLevelObject))
  1838. hadError = true;
  1839. else if (!VerifyOnly) {
  1840. // Find the field named by the designated initializer.
  1841. RecordDecl::field_iterator F = RD->field_begin();
  1842. while (std::next(F) != Field)
  1843. ++F;
  1844. QualType ET = SemaRef.Context.getBaseElementType(F->getType());
  1845. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  1846. hadError = true;
  1847. return;
  1848. }
  1849. }
  1850. InitializedSomething = true;
  1851. // Disable check for missing fields when designators are used.
  1852. // This matches gcc behaviour.
  1853. CheckForMissingFields = false;
  1854. continue;
  1855. }
  1856. if (Field == FieldEnd) {
  1857. // We've run out of fields. We're done.
  1858. break;
  1859. }
  1860. // We've already initialized a member of a union. We're done.
  1861. if (InitializedSomething && DeclType->isUnionType())
  1862. break;
  1863. // If we've hit the flexible array member at the end, we're done.
  1864. if (Field->getType()->isIncompleteArrayType())
  1865. break;
  1866. if (Field->isUnnamedBitfield()) {
  1867. // Don't initialize unnamed bitfields, e.g. "int : 20;"
  1868. ++Field;
  1869. continue;
  1870. }
  1871. // Make sure we can use this declaration.
  1872. bool InvalidUse;
  1873. if (VerifyOnly)
  1874. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  1875. else
  1876. InvalidUse = SemaRef.DiagnoseUseOfDecl(
  1877. *Field, IList->getInit(Index)->getBeginLoc());
  1878. if (InvalidUse) {
  1879. ++Index;
  1880. ++Field;
  1881. hadError = true;
  1882. continue;
  1883. }
  1884. if (!VerifyOnly) {
  1885. QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
  1886. if (checkDestructorReference(ET, InitLoc, SemaRef)) {
  1887. hadError = true;
  1888. return;
  1889. }
  1890. }
  1891. InitializedEntity MemberEntity =
  1892. InitializedEntity::InitializeMember(*Field, &Entity);
  1893. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1894. StructuredList, StructuredIndex);
  1895. InitializedSomething = true;
  1896. if (DeclType->isUnionType() && !VerifyOnly) {
  1897. // Initialize the first field within the union.
  1898. StructuredList->setInitializedFieldInUnion(*Field);
  1899. }
  1900. ++Field;
  1901. }
  1902. // Emit warnings for missing struct field initializers.
  1903. if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
  1904. Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
  1905. !DeclType->isUnionType()) {
  1906. // It is possible we have one or more unnamed bitfields remaining.
  1907. // Find first (if any) named field and emit warning.
  1908. for (RecordDecl::field_iterator it = Field, end = RD->field_end();
  1909. it != end; ++it) {
  1910. if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
  1911. SemaRef.Diag(IList->getSourceRange().getEnd(),
  1912. diag::warn_missing_field_initializers) << *it;
  1913. break;
  1914. }
  1915. }
  1916. }
  1917. // Check that any remaining fields can be value-initialized.
  1918. if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
  1919. !Field->getType()->isIncompleteArrayType()) {
  1920. // FIXME: Should check for holes left by designated initializers too.
  1921. for (; Field != FieldEnd && !hadError; ++Field) {
  1922. if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
  1923. CheckEmptyInitializable(
  1924. InitializedEntity::InitializeMember(*Field, &Entity),
  1925. IList->getEndLoc());
  1926. }
  1927. }
  1928. // Check that the types of the remaining fields have accessible destructors.
  1929. if (!VerifyOnly) {
  1930. // If the initializer expression has a designated initializer, check the
  1931. // elements for which a designated initializer is not provided too.
  1932. RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
  1933. : Field;
  1934. for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
  1935. QualType ET = SemaRef.Context.getBaseElementType(I->getType());
  1936. if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
  1937. hadError = true;
  1938. return;
  1939. }
  1940. }
  1941. }
  1942. if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
  1943. Index >= IList->getNumInits())
  1944. return;
  1945. if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
  1946. TopLevelObject)) {
  1947. hadError = true;
  1948. ++Index;
  1949. return;
  1950. }
  1951. InitializedEntity MemberEntity =
  1952. InitializedEntity::InitializeMember(*Field, &Entity);
  1953. if (isa<InitListExpr>(IList->getInit(Index)))
  1954. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1955. StructuredList, StructuredIndex);
  1956. else
  1957. CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
  1958. StructuredList, StructuredIndex);
  1959. }
  1960. /// Expand a field designator that refers to a member of an
  1961. /// anonymous struct or union into a series of field designators that
  1962. /// refers to the field within the appropriate subobject.
  1963. ///
  1964. static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
  1965. DesignatedInitExpr *DIE,
  1966. unsigned DesigIdx,
  1967. IndirectFieldDecl *IndirectField) {
  1968. typedef DesignatedInitExpr::Designator Designator;
  1969. // Build the replacement designators.
  1970. SmallVector<Designator, 4> Replacements;
  1971. for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
  1972. PE = IndirectField->chain_end(); PI != PE; ++PI) {
  1973. if (PI + 1 == PE)
  1974. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1975. DIE->getDesignator(DesigIdx)->getDotLoc(),
  1976. DIE->getDesignator(DesigIdx)->getFieldLoc()));
  1977. else
  1978. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1979. SourceLocation(), SourceLocation()));
  1980. assert(isa<FieldDecl>(*PI));
  1981. Replacements.back().setField(cast<FieldDecl>(*PI));
  1982. }
  1983. // Expand the current designator into the set of replacement
  1984. // designators, so we have a full subobject path down to where the
  1985. // member of the anonymous struct/union is actually stored.
  1986. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
  1987. &Replacements[0] + Replacements.size());
  1988. }
  1989. static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
  1990. DesignatedInitExpr *DIE) {
  1991. unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
  1992. SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
  1993. for (unsigned I = 0; I < NumIndexExprs; ++I)
  1994. IndexExprs[I] = DIE->getSubExpr(I + 1);
  1995. return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
  1996. IndexExprs,
  1997. DIE->getEqualOrColonLoc(),
  1998. DIE->usesGNUSyntax(), DIE->getInit());
  1999. }
  2000. namespace {
  2001. // Callback to only accept typo corrections that are for field members of
  2002. // the given struct or union.
  2003. class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
  2004. public:
  2005. explicit FieldInitializerValidatorCCC(RecordDecl *RD)
  2006. : Record(RD) {}
  2007. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2008. FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
  2009. return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
  2010. }
  2011. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2012. return std::make_unique<FieldInitializerValidatorCCC>(*this);
  2013. }
  2014. private:
  2015. RecordDecl *Record;
  2016. };
  2017. } // end anonymous namespace
  2018. /// Check the well-formedness of a C99 designated initializer.
  2019. ///
  2020. /// Determines whether the designated initializer @p DIE, which
  2021. /// resides at the given @p Index within the initializer list @p
  2022. /// IList, is well-formed for a current object of type @p DeclType
  2023. /// (C99 6.7.8). The actual subobject that this designator refers to
  2024. /// within the current subobject is returned in either
  2025. /// @p NextField or @p NextElementIndex (whichever is appropriate).
  2026. ///
  2027. /// @param IList The initializer list in which this designated
  2028. /// initializer occurs.
  2029. ///
  2030. /// @param DIE The designated initializer expression.
  2031. ///
  2032. /// @param DesigIdx The index of the current designator.
  2033. ///
  2034. /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
  2035. /// into which the designation in @p DIE should refer.
  2036. ///
  2037. /// @param NextField If non-NULL and the first designator in @p DIE is
  2038. /// a field, this will be set to the field declaration corresponding
  2039. /// to the field named by the designator.
  2040. ///
  2041. /// @param NextElementIndex If non-NULL and the first designator in @p
  2042. /// DIE is an array designator or GNU array-range designator, this
  2043. /// will be set to the last index initialized by this designator.
  2044. ///
  2045. /// @param Index Index into @p IList where the designated initializer
  2046. /// @p DIE occurs.
  2047. ///
  2048. /// @param StructuredList The initializer list expression that
  2049. /// describes all of the subobject initializers in the order they'll
  2050. /// actually be initialized.
  2051. ///
  2052. /// @returns true if there was an error, false otherwise.
  2053. bool
  2054. InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
  2055. InitListExpr *IList,
  2056. DesignatedInitExpr *DIE,
  2057. unsigned DesigIdx,
  2058. QualType &CurrentObjectType,
  2059. RecordDecl::field_iterator *NextField,
  2060. llvm::APSInt *NextElementIndex,
  2061. unsigned &Index,
  2062. InitListExpr *StructuredList,
  2063. unsigned &StructuredIndex,
  2064. bool FinishSubobjectInit,
  2065. bool TopLevelObject) {
  2066. if (DesigIdx == DIE->size()) {
  2067. // Check the actual initialization for the designated object type.
  2068. bool prevHadError = hadError;
  2069. // Temporarily remove the designator expression from the
  2070. // initializer list that the child calls see, so that we don't try
  2071. // to re-process the designator.
  2072. unsigned OldIndex = Index;
  2073. IList->setInit(OldIndex, DIE->getInit());
  2074. CheckSubElementType(Entity, IList, CurrentObjectType, Index,
  2075. StructuredList, StructuredIndex);
  2076. // Restore the designated initializer expression in the syntactic
  2077. // form of the initializer list.
  2078. if (IList->getInit(OldIndex) != DIE->getInit())
  2079. DIE->setInit(IList->getInit(OldIndex));
  2080. IList->setInit(OldIndex, DIE);
  2081. return hadError && !prevHadError;
  2082. }
  2083. DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
  2084. bool IsFirstDesignator = (DesigIdx == 0);
  2085. if (!VerifyOnly) {
  2086. assert((IsFirstDesignator || StructuredList) &&
  2087. "Need a non-designated initializer list to start from");
  2088. // Determine the structural initializer list that corresponds to the
  2089. // current subobject.
  2090. if (IsFirstDesignator)
  2091. StructuredList = SyntacticToSemantic.lookup(IList);
  2092. else {
  2093. Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
  2094. StructuredList->getInit(StructuredIndex) : nullptr;
  2095. if (!ExistingInit && StructuredList->hasArrayFiller())
  2096. ExistingInit = StructuredList->getArrayFiller();
  2097. if (!ExistingInit)
  2098. StructuredList = getStructuredSubobjectInit(
  2099. IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
  2100. SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
  2101. else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
  2102. StructuredList = Result;
  2103. else {
  2104. if (DesignatedInitUpdateExpr *E =
  2105. dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
  2106. StructuredList = E->getUpdater();
  2107. else {
  2108. DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
  2109. DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
  2110. ExistingInit, DIE->getEndLoc());
  2111. StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
  2112. StructuredList = DIUE->getUpdater();
  2113. }
  2114. // We need to check on source range validity because the previous
  2115. // initializer does not have to be an explicit initializer. e.g.,
  2116. //
  2117. // struct P { int a, b; };
  2118. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  2119. //
  2120. // There is an overwrite taking place because the first braced initializer
  2121. // list "{ .a = 2 }" already provides value for .p.b (which is zero).
  2122. if (ExistingInit->getSourceRange().isValid()) {
  2123. // We are creating an initializer list that initializes the
  2124. // subobjects of the current object, but there was already an
  2125. // initialization that completely initialized the current
  2126. // subobject, e.g., by a compound literal:
  2127. //
  2128. // struct X { int a, b; };
  2129. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2130. //
  2131. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  2132. // designated initializer re-initializes the whole
  2133. // subobject [0], overwriting previous initializers.
  2134. SemaRef.Diag(D->getBeginLoc(),
  2135. diag::warn_subobject_initializer_overrides)
  2136. << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
  2137. SemaRef.Diag(ExistingInit->getBeginLoc(),
  2138. diag::note_previous_initializer)
  2139. << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
  2140. }
  2141. }
  2142. }
  2143. assert(StructuredList && "Expected a structured initializer list");
  2144. }
  2145. if (D->isFieldDesignator()) {
  2146. // C99 6.7.8p7:
  2147. //
  2148. // If a designator has the form
  2149. //
  2150. // . identifier
  2151. //
  2152. // then the current object (defined below) shall have
  2153. // structure or union type and the identifier shall be the
  2154. // name of a member of that type.
  2155. const RecordType *RT = CurrentObjectType->getAs<RecordType>();
  2156. if (!RT) {
  2157. SourceLocation Loc = D->getDotLoc();
  2158. if (Loc.isInvalid())
  2159. Loc = D->getFieldLoc();
  2160. if (!VerifyOnly)
  2161. SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
  2162. << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
  2163. ++Index;
  2164. return true;
  2165. }
  2166. FieldDecl *KnownField = D->getField();
  2167. if (!KnownField) {
  2168. IdentifierInfo *FieldName = D->getFieldName();
  2169. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
  2170. for (NamedDecl *ND : Lookup) {
  2171. if (auto *FD = dyn_cast<FieldDecl>(ND)) {
  2172. KnownField = FD;
  2173. break;
  2174. }
  2175. if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
  2176. // In verify mode, don't modify the original.
  2177. if (VerifyOnly)
  2178. DIE = CloneDesignatedInitExpr(SemaRef, DIE);
  2179. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
  2180. D = DIE->getDesignator(DesigIdx);
  2181. KnownField = cast<FieldDecl>(*IFD->chain_begin());
  2182. break;
  2183. }
  2184. }
  2185. if (!KnownField) {
  2186. if (VerifyOnly) {
  2187. ++Index;
  2188. return true; // No typo correction when just trying this out.
  2189. }
  2190. // Name lookup found something, but it wasn't a field.
  2191. if (!Lookup.empty()) {
  2192. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
  2193. << FieldName;
  2194. SemaRef.Diag(Lookup.front()->getLocation(),
  2195. diag::note_field_designator_found);
  2196. ++Index;
  2197. return true;
  2198. }
  2199. // Name lookup didn't find anything.
  2200. // Determine whether this was a typo for another field name.
  2201. FieldInitializerValidatorCCC CCC(RT->getDecl());
  2202. if (TypoCorrection Corrected = SemaRef.CorrectTypo(
  2203. DeclarationNameInfo(FieldName, D->getFieldLoc()),
  2204. Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
  2205. Sema::CTK_ErrorRecovery, RT->getDecl())) {
  2206. SemaRef.diagnoseTypo(
  2207. Corrected,
  2208. SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
  2209. << FieldName << CurrentObjectType);
  2210. KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
  2211. hadError = true;
  2212. } else {
  2213. // Typo correction didn't find anything.
  2214. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
  2215. << FieldName << CurrentObjectType;
  2216. ++Index;
  2217. return true;
  2218. }
  2219. }
  2220. }
  2221. unsigned FieldIndex = 0;
  2222. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2223. FieldIndex = CXXRD->getNumBases();
  2224. for (auto *FI : RT->getDecl()->fields()) {
  2225. if (FI->isUnnamedBitfield())
  2226. continue;
  2227. if (declaresSameEntity(KnownField, FI)) {
  2228. KnownField = FI;
  2229. break;
  2230. }
  2231. ++FieldIndex;
  2232. }
  2233. RecordDecl::field_iterator Field =
  2234. RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
  2235. // All of the fields of a union are located at the same place in
  2236. // the initializer list.
  2237. if (RT->getDecl()->isUnion()) {
  2238. FieldIndex = 0;
  2239. if (!VerifyOnly) {
  2240. FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
  2241. if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
  2242. assert(StructuredList->getNumInits() == 1
  2243. && "A union should never have more than one initializer!");
  2244. Expr *ExistingInit = StructuredList->getInit(0);
  2245. if (ExistingInit) {
  2246. // We're about to throw away an initializer, emit warning.
  2247. SemaRef.Diag(D->getFieldLoc(),
  2248. diag::warn_initializer_overrides)
  2249. << D->getSourceRange();
  2250. SemaRef.Diag(ExistingInit->getBeginLoc(),
  2251. diag::note_previous_initializer)
  2252. << /*FIXME:has side effects=*/0
  2253. << ExistingInit->getSourceRange();
  2254. }
  2255. // remove existing initializer
  2256. StructuredList->resizeInits(SemaRef.Context, 0);
  2257. StructuredList->setInitializedFieldInUnion(nullptr);
  2258. }
  2259. StructuredList->setInitializedFieldInUnion(*Field);
  2260. }
  2261. }
  2262. // Make sure we can use this declaration.
  2263. bool InvalidUse;
  2264. if (VerifyOnly)
  2265. InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
  2266. else
  2267. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
  2268. if (InvalidUse) {
  2269. ++Index;
  2270. return true;
  2271. }
  2272. if (!VerifyOnly) {
  2273. // Update the designator with the field declaration.
  2274. D->setField(*Field);
  2275. // Make sure that our non-designated initializer list has space
  2276. // for a subobject corresponding to this field.
  2277. if (FieldIndex >= StructuredList->getNumInits())
  2278. StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
  2279. }
  2280. // This designator names a flexible array member.
  2281. if (Field->getType()->isIncompleteArrayType()) {
  2282. bool Invalid = false;
  2283. if ((DesigIdx + 1) != DIE->size()) {
  2284. // We can't designate an object within the flexible array
  2285. // member (because GCC doesn't allow it).
  2286. if (!VerifyOnly) {
  2287. DesignatedInitExpr::Designator *NextD
  2288. = DIE->getDesignator(DesigIdx + 1);
  2289. SemaRef.Diag(NextD->getBeginLoc(),
  2290. diag::err_designator_into_flexible_array_member)
  2291. << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
  2292. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2293. << *Field;
  2294. }
  2295. Invalid = true;
  2296. }
  2297. if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
  2298. !isa<StringLiteral>(DIE->getInit())) {
  2299. // The initializer is not an initializer list.
  2300. if (!VerifyOnly) {
  2301. SemaRef.Diag(DIE->getInit()->getBeginLoc(),
  2302. diag::err_flexible_array_init_needs_braces)
  2303. << DIE->getInit()->getSourceRange();
  2304. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2305. << *Field;
  2306. }
  2307. Invalid = true;
  2308. }
  2309. // Check GNU flexible array initializer.
  2310. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
  2311. TopLevelObject))
  2312. Invalid = true;
  2313. if (Invalid) {
  2314. ++Index;
  2315. return true;
  2316. }
  2317. // Initialize the array.
  2318. bool prevHadError = hadError;
  2319. unsigned newStructuredIndex = FieldIndex;
  2320. unsigned OldIndex = Index;
  2321. IList->setInit(Index, DIE->getInit());
  2322. InitializedEntity MemberEntity =
  2323. InitializedEntity::InitializeMember(*Field, &Entity);
  2324. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2325. StructuredList, newStructuredIndex);
  2326. IList->setInit(OldIndex, DIE);
  2327. if (hadError && !prevHadError) {
  2328. ++Field;
  2329. ++FieldIndex;
  2330. if (NextField)
  2331. *NextField = Field;
  2332. StructuredIndex = FieldIndex;
  2333. return true;
  2334. }
  2335. } else {
  2336. // Recurse to check later designated subobjects.
  2337. QualType FieldType = Field->getType();
  2338. unsigned newStructuredIndex = FieldIndex;
  2339. InitializedEntity MemberEntity =
  2340. InitializedEntity::InitializeMember(*Field, &Entity);
  2341. if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
  2342. FieldType, nullptr, nullptr, Index,
  2343. StructuredList, newStructuredIndex,
  2344. FinishSubobjectInit, false))
  2345. return true;
  2346. }
  2347. // Find the position of the next field to be initialized in this
  2348. // subobject.
  2349. ++Field;
  2350. ++FieldIndex;
  2351. // If this the first designator, our caller will continue checking
  2352. // the rest of this struct/class/union subobject.
  2353. if (IsFirstDesignator) {
  2354. if (NextField)
  2355. *NextField = Field;
  2356. StructuredIndex = FieldIndex;
  2357. return false;
  2358. }
  2359. if (!FinishSubobjectInit)
  2360. return false;
  2361. // We've already initialized something in the union; we're done.
  2362. if (RT->getDecl()->isUnion())
  2363. return hadError;
  2364. // Check the remaining fields within this class/struct/union subobject.
  2365. bool prevHadError = hadError;
  2366. auto NoBases =
  2367. CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
  2368. CXXRecordDecl::base_class_iterator());
  2369. CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
  2370. false, Index, StructuredList, FieldIndex);
  2371. return hadError && !prevHadError;
  2372. }
  2373. // C99 6.7.8p6:
  2374. //
  2375. // If a designator has the form
  2376. //
  2377. // [ constant-expression ]
  2378. //
  2379. // then the current object (defined below) shall have array
  2380. // type and the expression shall be an integer constant
  2381. // expression. If the array is of unknown size, any
  2382. // nonnegative value is valid.
  2383. //
  2384. // Additionally, cope with the GNU extension that permits
  2385. // designators of the form
  2386. //
  2387. // [ constant-expression ... constant-expression ]
  2388. const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
  2389. if (!AT) {
  2390. if (!VerifyOnly)
  2391. SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
  2392. << CurrentObjectType;
  2393. ++Index;
  2394. return true;
  2395. }
  2396. Expr *IndexExpr = nullptr;
  2397. llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
  2398. if (D->isArrayDesignator()) {
  2399. IndexExpr = DIE->getArrayIndex(*D);
  2400. DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
  2401. DesignatedEndIndex = DesignatedStartIndex;
  2402. } else {
  2403. assert(D->isArrayRangeDesignator() && "Need array-range designator");
  2404. DesignatedStartIndex =
  2405. DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2406. DesignatedEndIndex =
  2407. DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2408. IndexExpr = DIE->getArrayRangeEnd(*D);
  2409. // Codegen can't handle evaluating array range designators that have side
  2410. // effects, because we replicate the AST value for each initialized element.
  2411. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
  2412. // elements with something that has a side effect, so codegen can emit an
  2413. // "error unsupported" error instead of miscompiling the app.
  2414. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
  2415. DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
  2416. FullyStructuredList->sawArrayRangeDesignator();
  2417. }
  2418. if (isa<ConstantArrayType>(AT)) {
  2419. llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
  2420. DesignatedStartIndex
  2421. = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
  2422. DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
  2423. DesignatedEndIndex
  2424. = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
  2425. DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
  2426. if (DesignatedEndIndex >= MaxElements) {
  2427. if (!VerifyOnly)
  2428. SemaRef.Diag(IndexExpr->getBeginLoc(),
  2429. diag::err_array_designator_too_large)
  2430. << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
  2431. << IndexExpr->getSourceRange();
  2432. ++Index;
  2433. return true;
  2434. }
  2435. } else {
  2436. unsigned DesignatedIndexBitWidth =
  2437. ConstantArrayType::getMaxSizeBits(SemaRef.Context);
  2438. DesignatedStartIndex =
  2439. DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
  2440. DesignatedEndIndex =
  2441. DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
  2442. DesignatedStartIndex.setIsUnsigned(true);
  2443. DesignatedEndIndex.setIsUnsigned(true);
  2444. }
  2445. if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
  2446. // We're modifying a string literal init; we have to decompose the string
  2447. // so we can modify the individual characters.
  2448. ASTContext &Context = SemaRef.Context;
  2449. Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
  2450. // Compute the character type
  2451. QualType CharTy = AT->getElementType();
  2452. // Compute the type of the integer literals.
  2453. QualType PromotedCharTy = CharTy;
  2454. if (CharTy->isPromotableIntegerType())
  2455. PromotedCharTy = Context.getPromotedIntegerType(CharTy);
  2456. unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
  2457. if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
  2458. // Get the length of the string.
  2459. uint64_t StrLen = SL->getLength();
  2460. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2461. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2462. StructuredList->resizeInits(Context, StrLen);
  2463. // Build a literal for each character in the string, and put them into
  2464. // the init list.
  2465. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2466. llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
  2467. Expr *Init = new (Context) IntegerLiteral(
  2468. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2469. if (CharTy != PromotedCharTy)
  2470. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2471. Init, nullptr, VK_RValue);
  2472. StructuredList->updateInit(Context, i, Init);
  2473. }
  2474. } else {
  2475. ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
  2476. std::string Str;
  2477. Context.getObjCEncodingForType(E->getEncodedType(), Str);
  2478. // Get the length of the string.
  2479. uint64_t StrLen = Str.size();
  2480. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2481. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2482. StructuredList->resizeInits(Context, StrLen);
  2483. // Build a literal for each character in the string, and put them into
  2484. // the init list.
  2485. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2486. llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
  2487. Expr *Init = new (Context) IntegerLiteral(
  2488. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2489. if (CharTy != PromotedCharTy)
  2490. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2491. Init, nullptr, VK_RValue);
  2492. StructuredList->updateInit(Context, i, Init);
  2493. }
  2494. }
  2495. }
  2496. // Make sure that our non-designated initializer list has space
  2497. // for a subobject corresponding to this array element.
  2498. if (!VerifyOnly &&
  2499. DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
  2500. StructuredList->resizeInits(SemaRef.Context,
  2501. DesignatedEndIndex.getZExtValue() + 1);
  2502. // Repeatedly perform subobject initializations in the range
  2503. // [DesignatedStartIndex, DesignatedEndIndex].
  2504. // Move to the next designator
  2505. unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
  2506. unsigned OldIndex = Index;
  2507. InitializedEntity ElementEntity =
  2508. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  2509. while (DesignatedStartIndex <= DesignatedEndIndex) {
  2510. // Recurse to check later designated subobjects.
  2511. QualType ElementType = AT->getElementType();
  2512. Index = OldIndex;
  2513. ElementEntity.setElementIndex(ElementIndex);
  2514. if (CheckDesignatedInitializer(
  2515. ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
  2516. nullptr, Index, StructuredList, ElementIndex,
  2517. FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
  2518. false))
  2519. return true;
  2520. // Move to the next index in the array that we'll be initializing.
  2521. ++DesignatedStartIndex;
  2522. ElementIndex = DesignatedStartIndex.getZExtValue();
  2523. }
  2524. // If this the first designator, our caller will continue checking
  2525. // the rest of this array subobject.
  2526. if (IsFirstDesignator) {
  2527. if (NextElementIndex)
  2528. *NextElementIndex = DesignatedStartIndex;
  2529. StructuredIndex = ElementIndex;
  2530. return false;
  2531. }
  2532. if (!FinishSubobjectInit)
  2533. return false;
  2534. // Check the remaining elements within this array subobject.
  2535. bool prevHadError = hadError;
  2536. CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
  2537. /*SubobjectIsDesignatorContext=*/false, Index,
  2538. StructuredList, ElementIndex);
  2539. return hadError && !prevHadError;
  2540. }
  2541. // Get the structured initializer list for a subobject of type
  2542. // @p CurrentObjectType.
  2543. InitListExpr *
  2544. InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  2545. QualType CurrentObjectType,
  2546. InitListExpr *StructuredList,
  2547. unsigned StructuredIndex,
  2548. SourceRange InitRange,
  2549. bool IsFullyOverwritten) {
  2550. if (VerifyOnly)
  2551. return nullptr; // No structured list in verification-only mode.
  2552. Expr *ExistingInit = nullptr;
  2553. if (!StructuredList)
  2554. ExistingInit = SyntacticToSemantic.lookup(IList);
  2555. else if (StructuredIndex < StructuredList->getNumInits())
  2556. ExistingInit = StructuredList->getInit(StructuredIndex);
  2557. if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
  2558. // There might have already been initializers for subobjects of the current
  2559. // object, but a subsequent initializer list will overwrite the entirety
  2560. // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
  2561. //
  2562. // struct P { char x[6]; };
  2563. // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
  2564. //
  2565. // The first designated initializer is ignored, and l.x is just "f".
  2566. if (!IsFullyOverwritten)
  2567. return Result;
  2568. if (ExistingInit) {
  2569. // We are creating an initializer list that initializes the
  2570. // subobjects of the current object, but there was already an
  2571. // initialization that completely initialized the current
  2572. // subobject, e.g., by a compound literal:
  2573. //
  2574. // struct X { int a, b; };
  2575. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2576. //
  2577. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  2578. // designated initializer re-initializes the whole
  2579. // subobject [0], overwriting previous initializers.
  2580. SemaRef.Diag(InitRange.getBegin(),
  2581. diag::warn_subobject_initializer_overrides)
  2582. << InitRange;
  2583. SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
  2584. << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
  2585. }
  2586. InitListExpr *Result
  2587. = new (SemaRef.Context) InitListExpr(SemaRef.Context,
  2588. InitRange.getBegin(), None,
  2589. InitRange.getEnd());
  2590. QualType ResultType = CurrentObjectType;
  2591. if (!ResultType->isArrayType())
  2592. ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
  2593. Result->setType(ResultType);
  2594. // Pre-allocate storage for the structured initializer list.
  2595. unsigned NumElements = 0;
  2596. unsigned NumInits = 0;
  2597. bool GotNumInits = false;
  2598. if (!StructuredList) {
  2599. NumInits = IList->getNumInits();
  2600. GotNumInits = true;
  2601. } else if (Index < IList->getNumInits()) {
  2602. if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
  2603. NumInits = SubList->getNumInits();
  2604. GotNumInits = true;
  2605. }
  2606. }
  2607. if (const ArrayType *AType
  2608. = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
  2609. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
  2610. NumElements = CAType->getSize().getZExtValue();
  2611. // Simple heuristic so that we don't allocate a very large
  2612. // initializer with many empty entries at the end.
  2613. if (GotNumInits && NumElements > NumInits)
  2614. NumElements = 0;
  2615. }
  2616. } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
  2617. NumElements = VType->getNumElements();
  2618. else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
  2619. RecordDecl *RDecl = RType->getDecl();
  2620. if (RDecl->isUnion())
  2621. NumElements = 1;
  2622. else
  2623. NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
  2624. }
  2625. Result->reserveInits(SemaRef.Context, NumElements);
  2626. // Link this new initializer list into the structured initializer
  2627. // lists.
  2628. if (StructuredList)
  2629. StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
  2630. else {
  2631. Result->setSyntacticForm(IList);
  2632. SyntacticToSemantic[IList] = Result;
  2633. }
  2634. return Result;
  2635. }
  2636. /// Update the initializer at index @p StructuredIndex within the
  2637. /// structured initializer list to the value @p expr.
  2638. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
  2639. unsigned &StructuredIndex,
  2640. Expr *expr) {
  2641. // No structured initializer list to update
  2642. if (!StructuredList)
  2643. return;
  2644. if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
  2645. StructuredIndex, expr)) {
  2646. // This initializer overwrites a previous initializer. Warn.
  2647. // We need to check on source range validity because the previous
  2648. // initializer does not have to be an explicit initializer.
  2649. // struct P { int a, b; };
  2650. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  2651. // There is an overwrite taking place because the first braced initializer
  2652. // list "{ .a = 2 }' already provides value for .p.b (which is zero).
  2653. if (PrevInit->getSourceRange().isValid()) {
  2654. SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
  2655. << expr->getSourceRange();
  2656. SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
  2657. << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
  2658. }
  2659. }
  2660. ++StructuredIndex;
  2661. }
  2662. /// Check that the given Index expression is a valid array designator
  2663. /// value. This is essentially just a wrapper around
  2664. /// VerifyIntegerConstantExpression that also checks for negative values
  2665. /// and produces a reasonable diagnostic if there is a
  2666. /// failure. Returns the index expression, possibly with an implicit cast
  2667. /// added, on success. If everything went okay, Value will receive the
  2668. /// value of the constant expression.
  2669. static ExprResult
  2670. CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
  2671. SourceLocation Loc = Index->getBeginLoc();
  2672. // Make sure this is an integer constant expression.
  2673. ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
  2674. if (Result.isInvalid())
  2675. return Result;
  2676. if (Value.isSigned() && Value.isNegative())
  2677. return S.Diag(Loc, diag::err_array_designator_negative)
  2678. << Value.toString(10) << Index->getSourceRange();
  2679. Value.setIsUnsigned(true);
  2680. return Result;
  2681. }
  2682. ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
  2683. SourceLocation Loc,
  2684. bool GNUSyntax,
  2685. ExprResult Init) {
  2686. typedef DesignatedInitExpr::Designator ASTDesignator;
  2687. bool Invalid = false;
  2688. SmallVector<ASTDesignator, 32> Designators;
  2689. SmallVector<Expr *, 32> InitExpressions;
  2690. // Build designators and check array designator expressions.
  2691. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
  2692. const Designator &D = Desig.getDesignator(Idx);
  2693. switch (D.getKind()) {
  2694. case Designator::FieldDesignator:
  2695. Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
  2696. D.getFieldLoc()));
  2697. break;
  2698. case Designator::ArrayDesignator: {
  2699. Expr *Index = static_cast<Expr *>(D.getArrayIndex());
  2700. llvm::APSInt IndexValue;
  2701. if (!Index->isTypeDependent() && !Index->isValueDependent())
  2702. Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
  2703. if (!Index)
  2704. Invalid = true;
  2705. else {
  2706. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2707. D.getLBracketLoc(),
  2708. D.getRBracketLoc()));
  2709. InitExpressions.push_back(Index);
  2710. }
  2711. break;
  2712. }
  2713. case Designator::ArrayRangeDesignator: {
  2714. Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
  2715. Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
  2716. llvm::APSInt StartValue;
  2717. llvm::APSInt EndValue;
  2718. bool StartDependent = StartIndex->isTypeDependent() ||
  2719. StartIndex->isValueDependent();
  2720. bool EndDependent = EndIndex->isTypeDependent() ||
  2721. EndIndex->isValueDependent();
  2722. if (!StartDependent)
  2723. StartIndex =
  2724. CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
  2725. if (!EndDependent)
  2726. EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
  2727. if (!StartIndex || !EndIndex)
  2728. Invalid = true;
  2729. else {
  2730. // Make sure we're comparing values with the same bit width.
  2731. if (StartDependent || EndDependent) {
  2732. // Nothing to compute.
  2733. } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
  2734. EndValue = EndValue.extend(StartValue.getBitWidth());
  2735. else if (StartValue.getBitWidth() < EndValue.getBitWidth())
  2736. StartValue = StartValue.extend(EndValue.getBitWidth());
  2737. if (!StartDependent && !EndDependent && EndValue < StartValue) {
  2738. Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
  2739. << StartValue.toString(10) << EndValue.toString(10)
  2740. << StartIndex->getSourceRange() << EndIndex->getSourceRange();
  2741. Invalid = true;
  2742. } else {
  2743. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2744. D.getLBracketLoc(),
  2745. D.getEllipsisLoc(),
  2746. D.getRBracketLoc()));
  2747. InitExpressions.push_back(StartIndex);
  2748. InitExpressions.push_back(EndIndex);
  2749. }
  2750. }
  2751. break;
  2752. }
  2753. }
  2754. }
  2755. if (Invalid || Init.isInvalid())
  2756. return ExprError();
  2757. // Clear out the expressions within the designation.
  2758. Desig.ClearExprs(*this);
  2759. DesignatedInitExpr *DIE
  2760. = DesignatedInitExpr::Create(Context,
  2761. Designators,
  2762. InitExpressions, Loc, GNUSyntax,
  2763. Init.getAs<Expr>());
  2764. if (!getLangOpts().C99)
  2765. Diag(DIE->getBeginLoc(), diag::ext_designated_init)
  2766. << DIE->getSourceRange();
  2767. return DIE;
  2768. }
  2769. //===----------------------------------------------------------------------===//
  2770. // Initialization entity
  2771. //===----------------------------------------------------------------------===//
  2772. InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
  2773. const InitializedEntity &Parent)
  2774. : Parent(&Parent), Index(Index)
  2775. {
  2776. if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
  2777. Kind = EK_ArrayElement;
  2778. Type = AT->getElementType();
  2779. } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
  2780. Kind = EK_VectorElement;
  2781. Type = VT->getElementType();
  2782. } else {
  2783. const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
  2784. assert(CT && "Unexpected type");
  2785. Kind = EK_ComplexElement;
  2786. Type = CT->getElementType();
  2787. }
  2788. }
  2789. InitializedEntity
  2790. InitializedEntity::InitializeBase(ASTContext &Context,
  2791. const CXXBaseSpecifier *Base,
  2792. bool IsInheritedVirtualBase,
  2793. const InitializedEntity *Parent) {
  2794. InitializedEntity Result;
  2795. Result.Kind = EK_Base;
  2796. Result.Parent = Parent;
  2797. Result.Base = reinterpret_cast<uintptr_t>(Base);
  2798. if (IsInheritedVirtualBase)
  2799. Result.Base |= 0x01;
  2800. Result.Type = Base->getType();
  2801. return Result;
  2802. }
  2803. DeclarationName InitializedEntity::getName() const {
  2804. switch (getKind()) {
  2805. case EK_Parameter:
  2806. case EK_Parameter_CF_Audited: {
  2807. ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2808. return (D ? D->getDeclName() : DeclarationName());
  2809. }
  2810. case EK_Variable:
  2811. case EK_Member:
  2812. case EK_Binding:
  2813. return Variable.VariableOrMember->getDeclName();
  2814. case EK_LambdaCapture:
  2815. return DeclarationName(Capture.VarID);
  2816. case EK_Result:
  2817. case EK_StmtExprResult:
  2818. case EK_Exception:
  2819. case EK_New:
  2820. case EK_Temporary:
  2821. case EK_Base:
  2822. case EK_Delegating:
  2823. case EK_ArrayElement:
  2824. case EK_VectorElement:
  2825. case EK_ComplexElement:
  2826. case EK_BlockElement:
  2827. case EK_LambdaToBlockConversionBlockElement:
  2828. case EK_CompoundLiteralInit:
  2829. case EK_RelatedResult:
  2830. return DeclarationName();
  2831. }
  2832. llvm_unreachable("Invalid EntityKind!");
  2833. }
  2834. ValueDecl *InitializedEntity::getDecl() const {
  2835. switch (getKind()) {
  2836. case EK_Variable:
  2837. case EK_Member:
  2838. case EK_Binding:
  2839. return Variable.VariableOrMember;
  2840. case EK_Parameter:
  2841. case EK_Parameter_CF_Audited:
  2842. return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2843. case EK_Result:
  2844. case EK_StmtExprResult:
  2845. case EK_Exception:
  2846. case EK_New:
  2847. case EK_Temporary:
  2848. case EK_Base:
  2849. case EK_Delegating:
  2850. case EK_ArrayElement:
  2851. case EK_VectorElement:
  2852. case EK_ComplexElement:
  2853. case EK_BlockElement:
  2854. case EK_LambdaToBlockConversionBlockElement:
  2855. case EK_LambdaCapture:
  2856. case EK_CompoundLiteralInit:
  2857. case EK_RelatedResult:
  2858. return nullptr;
  2859. }
  2860. llvm_unreachable("Invalid EntityKind!");
  2861. }
  2862. bool InitializedEntity::allowsNRVO() const {
  2863. switch (getKind()) {
  2864. case EK_Result:
  2865. case EK_Exception:
  2866. return LocAndNRVO.NRVO;
  2867. case EK_StmtExprResult:
  2868. case EK_Variable:
  2869. case EK_Parameter:
  2870. case EK_Parameter_CF_Audited:
  2871. case EK_Member:
  2872. case EK_Binding:
  2873. case EK_New:
  2874. case EK_Temporary:
  2875. case EK_CompoundLiteralInit:
  2876. case EK_Base:
  2877. case EK_Delegating:
  2878. case EK_ArrayElement:
  2879. case EK_VectorElement:
  2880. case EK_ComplexElement:
  2881. case EK_BlockElement:
  2882. case EK_LambdaToBlockConversionBlockElement:
  2883. case EK_LambdaCapture:
  2884. case EK_RelatedResult:
  2885. break;
  2886. }
  2887. return false;
  2888. }
  2889. unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
  2890. assert(getParent() != this);
  2891. unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
  2892. for (unsigned I = 0; I != Depth; ++I)
  2893. OS << "`-";
  2894. switch (getKind()) {
  2895. case EK_Variable: OS << "Variable"; break;
  2896. case EK_Parameter: OS << "Parameter"; break;
  2897. case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
  2898. break;
  2899. case EK_Result: OS << "Result"; break;
  2900. case EK_StmtExprResult: OS << "StmtExprResult"; break;
  2901. case EK_Exception: OS << "Exception"; break;
  2902. case EK_Member: OS << "Member"; break;
  2903. case EK_Binding: OS << "Binding"; break;
  2904. case EK_New: OS << "New"; break;
  2905. case EK_Temporary: OS << "Temporary"; break;
  2906. case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
  2907. case EK_RelatedResult: OS << "RelatedResult"; break;
  2908. case EK_Base: OS << "Base"; break;
  2909. case EK_Delegating: OS << "Delegating"; break;
  2910. case EK_ArrayElement: OS << "ArrayElement " << Index; break;
  2911. case EK_VectorElement: OS << "VectorElement " << Index; break;
  2912. case EK_ComplexElement: OS << "ComplexElement " << Index; break;
  2913. case EK_BlockElement: OS << "Block"; break;
  2914. case EK_LambdaToBlockConversionBlockElement:
  2915. OS << "Block (lambda)";
  2916. break;
  2917. case EK_LambdaCapture:
  2918. OS << "LambdaCapture ";
  2919. OS << DeclarationName(Capture.VarID);
  2920. break;
  2921. }
  2922. if (auto *D = getDecl()) {
  2923. OS << " ";
  2924. D->printQualifiedName(OS);
  2925. }
  2926. OS << " '" << getType().getAsString() << "'\n";
  2927. return Depth + 1;
  2928. }
  2929. LLVM_DUMP_METHOD void InitializedEntity::dump() const {
  2930. dumpImpl(llvm::errs());
  2931. }
  2932. //===----------------------------------------------------------------------===//
  2933. // Initialization sequence
  2934. //===----------------------------------------------------------------------===//
  2935. void InitializationSequence::Step::Destroy() {
  2936. switch (Kind) {
  2937. case SK_ResolveAddressOfOverloadedFunction:
  2938. case SK_CastDerivedToBaseRValue:
  2939. case SK_CastDerivedToBaseXValue:
  2940. case SK_CastDerivedToBaseLValue:
  2941. case SK_BindReference:
  2942. case SK_BindReferenceToTemporary:
  2943. case SK_FinalCopy:
  2944. case SK_ExtraneousCopyToTemporary:
  2945. case SK_UserConversion:
  2946. case SK_QualificationConversionRValue:
  2947. case SK_QualificationConversionXValue:
  2948. case SK_QualificationConversionLValue:
  2949. case SK_AtomicConversion:
  2950. case SK_ListInitialization:
  2951. case SK_UnwrapInitList:
  2952. case SK_RewrapInitList:
  2953. case SK_ConstructorInitialization:
  2954. case SK_ConstructorInitializationFromList:
  2955. case SK_ZeroInitialization:
  2956. case SK_CAssignment:
  2957. case SK_StringInit:
  2958. case SK_ObjCObjectConversion:
  2959. case SK_ArrayLoopIndex:
  2960. case SK_ArrayLoopInit:
  2961. case SK_ArrayInit:
  2962. case SK_GNUArrayInit:
  2963. case SK_ParenthesizedArrayInit:
  2964. case SK_PassByIndirectCopyRestore:
  2965. case SK_PassByIndirectRestore:
  2966. case SK_ProduceObjCObject:
  2967. case SK_StdInitializerList:
  2968. case SK_StdInitializerListConstructorCall:
  2969. case SK_OCLSamplerInit:
  2970. case SK_OCLZeroOpaqueType:
  2971. break;
  2972. case SK_ConversionSequence:
  2973. case SK_ConversionSequenceNoNarrowing:
  2974. delete ICS;
  2975. }
  2976. }
  2977. bool InitializationSequence::isDirectReferenceBinding() const {
  2978. // There can be some lvalue adjustments after the SK_BindReference step.
  2979. for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
  2980. if (I->Kind == SK_BindReference)
  2981. return true;
  2982. if (I->Kind == SK_BindReferenceToTemporary)
  2983. return false;
  2984. }
  2985. return false;
  2986. }
  2987. bool InitializationSequence::isAmbiguous() const {
  2988. if (!Failed())
  2989. return false;
  2990. switch (getFailureKind()) {
  2991. case FK_TooManyInitsForReference:
  2992. case FK_ParenthesizedListInitForReference:
  2993. case FK_ArrayNeedsInitList:
  2994. case FK_ArrayNeedsInitListOrStringLiteral:
  2995. case FK_ArrayNeedsInitListOrWideStringLiteral:
  2996. case FK_NarrowStringIntoWideCharArray:
  2997. case FK_WideStringIntoCharArray:
  2998. case FK_IncompatWideStringIntoWideChar:
  2999. case FK_PlainStringIntoUTF8Char:
  3000. case FK_UTF8StringIntoPlainChar:
  3001. case FK_AddressOfOverloadFailed: // FIXME: Could do better
  3002. case FK_NonConstLValueReferenceBindingToTemporary:
  3003. case FK_NonConstLValueReferenceBindingToBitfield:
  3004. case FK_NonConstLValueReferenceBindingToVectorElement:
  3005. case FK_NonConstLValueReferenceBindingToUnrelated:
  3006. case FK_RValueReferenceBindingToLValue:
  3007. case FK_ReferenceAddrspaceMismatchTemporary:
  3008. case FK_ReferenceInitDropsQualifiers:
  3009. case FK_ReferenceInitFailed:
  3010. case FK_ConversionFailed:
  3011. case FK_ConversionFromPropertyFailed:
  3012. case FK_TooManyInitsForScalar:
  3013. case FK_ParenthesizedListInitForScalar:
  3014. case FK_ReferenceBindingToInitList:
  3015. case FK_InitListBadDestinationType:
  3016. case FK_DefaultInitOfConst:
  3017. case FK_Incomplete:
  3018. case FK_ArrayTypeMismatch:
  3019. case FK_NonConstantArrayInit:
  3020. case FK_ListInitializationFailed:
  3021. case FK_VariableLengthArrayHasInitializer:
  3022. case FK_PlaceholderType:
  3023. case FK_ExplicitConstructor:
  3024. case FK_AddressOfUnaddressableFunction:
  3025. return false;
  3026. case FK_ReferenceInitOverloadFailed:
  3027. case FK_UserConversionOverloadFailed:
  3028. case FK_ConstructorOverloadFailed:
  3029. case FK_ListConstructorOverloadFailed:
  3030. return FailedOverloadResult == OR_Ambiguous;
  3031. }
  3032. llvm_unreachable("Invalid EntityKind!");
  3033. }
  3034. bool InitializationSequence::isConstructorInitialization() const {
  3035. return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
  3036. }
  3037. void
  3038. InitializationSequence
  3039. ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
  3040. DeclAccessPair Found,
  3041. bool HadMultipleCandidates) {
  3042. Step S;
  3043. S.Kind = SK_ResolveAddressOfOverloadedFunction;
  3044. S.Type = Function->getType();
  3045. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3046. S.Function.Function = Function;
  3047. S.Function.FoundDecl = Found;
  3048. Steps.push_back(S);
  3049. }
  3050. void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
  3051. ExprValueKind VK) {
  3052. Step S;
  3053. switch (VK) {
  3054. case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
  3055. case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
  3056. case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
  3057. }
  3058. S.Type = BaseType;
  3059. Steps.push_back(S);
  3060. }
  3061. void InitializationSequence::AddReferenceBindingStep(QualType T,
  3062. bool BindingTemporary) {
  3063. Step S;
  3064. S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
  3065. S.Type = T;
  3066. Steps.push_back(S);
  3067. }
  3068. void InitializationSequence::AddFinalCopy(QualType T) {
  3069. Step S;
  3070. S.Kind = SK_FinalCopy;
  3071. S.Type = T;
  3072. Steps.push_back(S);
  3073. }
  3074. void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
  3075. Step S;
  3076. S.Kind = SK_ExtraneousCopyToTemporary;
  3077. S.Type = T;
  3078. Steps.push_back(S);
  3079. }
  3080. void
  3081. InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
  3082. DeclAccessPair FoundDecl,
  3083. QualType T,
  3084. bool HadMultipleCandidates) {
  3085. Step S;
  3086. S.Kind = SK_UserConversion;
  3087. S.Type = T;
  3088. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3089. S.Function.Function = Function;
  3090. S.Function.FoundDecl = FoundDecl;
  3091. Steps.push_back(S);
  3092. }
  3093. void InitializationSequence::AddQualificationConversionStep(QualType Ty,
  3094. ExprValueKind VK) {
  3095. Step S;
  3096. S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
  3097. switch (VK) {
  3098. case VK_RValue:
  3099. S.Kind = SK_QualificationConversionRValue;
  3100. break;
  3101. case VK_XValue:
  3102. S.Kind = SK_QualificationConversionXValue;
  3103. break;
  3104. case VK_LValue:
  3105. S.Kind = SK_QualificationConversionLValue;
  3106. break;
  3107. }
  3108. S.Type = Ty;
  3109. Steps.push_back(S);
  3110. }
  3111. void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
  3112. Step S;
  3113. S.Kind = SK_AtomicConversion;
  3114. S.Type = Ty;
  3115. Steps.push_back(S);
  3116. }
  3117. void InitializationSequence::AddConversionSequenceStep(
  3118. const ImplicitConversionSequence &ICS, QualType T,
  3119. bool TopLevelOfInitList) {
  3120. Step S;
  3121. S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
  3122. : SK_ConversionSequence;
  3123. S.Type = T;
  3124. S.ICS = new ImplicitConversionSequence(ICS);
  3125. Steps.push_back(S);
  3126. }
  3127. void InitializationSequence::AddListInitializationStep(QualType T) {
  3128. Step S;
  3129. S.Kind = SK_ListInitialization;
  3130. S.Type = T;
  3131. Steps.push_back(S);
  3132. }
  3133. void InitializationSequence::AddConstructorInitializationStep(
  3134. DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
  3135. bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
  3136. Step S;
  3137. S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
  3138. : SK_ConstructorInitializationFromList
  3139. : SK_ConstructorInitialization;
  3140. S.Type = T;
  3141. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  3142. S.Function.Function = Constructor;
  3143. S.Function.FoundDecl = FoundDecl;
  3144. Steps.push_back(S);
  3145. }
  3146. void InitializationSequence::AddZeroInitializationStep(QualType T) {
  3147. Step S;
  3148. S.Kind = SK_ZeroInitialization;
  3149. S.Type = T;
  3150. Steps.push_back(S);
  3151. }
  3152. void InitializationSequence::AddCAssignmentStep(QualType T) {
  3153. Step S;
  3154. S.Kind = SK_CAssignment;
  3155. S.Type = T;
  3156. Steps.push_back(S);
  3157. }
  3158. void InitializationSequence::AddStringInitStep(QualType T) {
  3159. Step S;
  3160. S.Kind = SK_StringInit;
  3161. S.Type = T;
  3162. Steps.push_back(S);
  3163. }
  3164. void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
  3165. Step S;
  3166. S.Kind = SK_ObjCObjectConversion;
  3167. S.Type = T;
  3168. Steps.push_back(S);
  3169. }
  3170. void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
  3171. Step S;
  3172. S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
  3173. S.Type = T;
  3174. Steps.push_back(S);
  3175. }
  3176. void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
  3177. Step S;
  3178. S.Kind = SK_ArrayLoopIndex;
  3179. S.Type = EltT;
  3180. Steps.insert(Steps.begin(), S);
  3181. S.Kind = SK_ArrayLoopInit;
  3182. S.Type = T;
  3183. Steps.push_back(S);
  3184. }
  3185. void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
  3186. Step S;
  3187. S.Kind = SK_ParenthesizedArrayInit;
  3188. S.Type = T;
  3189. Steps.push_back(S);
  3190. }
  3191. void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
  3192. bool shouldCopy) {
  3193. Step s;
  3194. s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
  3195. : SK_PassByIndirectRestore);
  3196. s.Type = type;
  3197. Steps.push_back(s);
  3198. }
  3199. void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
  3200. Step S;
  3201. S.Kind = SK_ProduceObjCObject;
  3202. S.Type = T;
  3203. Steps.push_back(S);
  3204. }
  3205. void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
  3206. Step S;
  3207. S.Kind = SK_StdInitializerList;
  3208. S.Type = T;
  3209. Steps.push_back(S);
  3210. }
  3211. void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
  3212. Step S;
  3213. S.Kind = SK_OCLSamplerInit;
  3214. S.Type = T;
  3215. Steps.push_back(S);
  3216. }
  3217. void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
  3218. Step S;
  3219. S.Kind = SK_OCLZeroOpaqueType;
  3220. S.Type = T;
  3221. Steps.push_back(S);
  3222. }
  3223. void InitializationSequence::RewrapReferenceInitList(QualType T,
  3224. InitListExpr *Syntactic) {
  3225. assert(Syntactic->getNumInits() == 1 &&
  3226. "Can only rewrap trivial init lists.");
  3227. Step S;
  3228. S.Kind = SK_UnwrapInitList;
  3229. S.Type = Syntactic->getInit(0)->getType();
  3230. Steps.insert(Steps.begin(), S);
  3231. S.Kind = SK_RewrapInitList;
  3232. S.Type = T;
  3233. S.WrappingSyntacticList = Syntactic;
  3234. Steps.push_back(S);
  3235. }
  3236. void InitializationSequence::SetOverloadFailure(FailureKind Failure,
  3237. OverloadingResult Result) {
  3238. setSequenceKind(FailedSequence);
  3239. this->Failure = Failure;
  3240. this->FailedOverloadResult = Result;
  3241. }
  3242. //===----------------------------------------------------------------------===//
  3243. // Attempt initialization
  3244. //===----------------------------------------------------------------------===//
  3245. /// Tries to add a zero initializer. Returns true if that worked.
  3246. static bool
  3247. maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
  3248. const InitializedEntity &Entity) {
  3249. if (Entity.getKind() != InitializedEntity::EK_Variable)
  3250. return false;
  3251. VarDecl *VD = cast<VarDecl>(Entity.getDecl());
  3252. if (VD->getInit() || VD->getEndLoc().isMacroID())
  3253. return false;
  3254. QualType VariableTy = VD->getType().getCanonicalType();
  3255. SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
  3256. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  3257. if (!Init.empty()) {
  3258. Sequence.AddZeroInitializationStep(Entity.getType());
  3259. Sequence.SetZeroInitializationFixit(Init, Loc);
  3260. return true;
  3261. }
  3262. return false;
  3263. }
  3264. static void MaybeProduceObjCObject(Sema &S,
  3265. InitializationSequence &Sequence,
  3266. const InitializedEntity &Entity) {
  3267. if (!S.getLangOpts().ObjCAutoRefCount) return;
  3268. /// When initializing a parameter, produce the value if it's marked
  3269. /// __attribute__((ns_consumed)).
  3270. if (Entity.isParameterKind()) {
  3271. if (!Entity.isParameterConsumed())
  3272. return;
  3273. assert(Entity.getType()->isObjCRetainableType() &&
  3274. "consuming an object of unretainable type?");
  3275. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3276. /// When initializing a return value, if the return type is a
  3277. /// retainable type, then returns need to immediately retain the
  3278. /// object. If an autorelease is required, it will be done at the
  3279. /// last instant.
  3280. } else if (Entity.getKind() == InitializedEntity::EK_Result ||
  3281. Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
  3282. if (!Entity.getType()->isObjCRetainableType())
  3283. return;
  3284. Sequence.AddProduceObjCObjectStep(Entity.getType());
  3285. }
  3286. }
  3287. static void TryListInitialization(Sema &S,
  3288. const InitializedEntity &Entity,
  3289. const InitializationKind &Kind,
  3290. InitListExpr *InitList,
  3291. InitializationSequence &Sequence,
  3292. bool TreatUnavailableAsInvalid);
  3293. /// When initializing from init list via constructor, handle
  3294. /// initialization of an object of type std::initializer_list<T>.
  3295. ///
  3296. /// \return true if we have handled initialization of an object of type
  3297. /// std::initializer_list<T>, false otherwise.
  3298. static bool TryInitializerListConstruction(Sema &S,
  3299. InitListExpr *List,
  3300. QualType DestType,
  3301. InitializationSequence &Sequence,
  3302. bool TreatUnavailableAsInvalid) {
  3303. QualType E;
  3304. if (!S.isStdInitializerList(DestType, &E))
  3305. return false;
  3306. if (!S.isCompleteType(List->getExprLoc(), E)) {
  3307. Sequence.setIncompleteTypeFailure(E);
  3308. return true;
  3309. }
  3310. // Try initializing a temporary array from the init list.
  3311. QualType ArrayType = S.Context.getConstantArrayType(
  3312. E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  3313. List->getNumInits()),
  3314. clang::ArrayType::Normal, 0);
  3315. InitializedEntity HiddenArray =
  3316. InitializedEntity::InitializeTemporary(ArrayType);
  3317. InitializationKind Kind = InitializationKind::CreateDirectList(
  3318. List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
  3319. TryListInitialization(S, HiddenArray, Kind, List, Sequence,
  3320. TreatUnavailableAsInvalid);
  3321. if (Sequence)
  3322. Sequence.AddStdInitializerListConstructionStep(DestType);
  3323. return true;
  3324. }
  3325. /// Determine if the constructor has the signature of a copy or move
  3326. /// constructor for the type T of the class in which it was found. That is,
  3327. /// determine if its first parameter is of type T or reference to (possibly
  3328. /// cv-qualified) T.
  3329. static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
  3330. const ConstructorInfo &Info) {
  3331. if (Info.Constructor->getNumParams() == 0)
  3332. return false;
  3333. QualType ParmT =
  3334. Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
  3335. QualType ClassT =
  3336. Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
  3337. return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
  3338. }
  3339. static OverloadingResult
  3340. ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
  3341. MultiExprArg Args,
  3342. OverloadCandidateSet &CandidateSet,
  3343. QualType DestType,
  3344. DeclContext::lookup_result Ctors,
  3345. OverloadCandidateSet::iterator &Best,
  3346. bool CopyInitializing, bool AllowExplicit,
  3347. bool OnlyListConstructors, bool IsListInit,
  3348. bool SecondStepOfCopyInit = false) {
  3349. CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
  3350. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  3351. for (NamedDecl *D : Ctors) {
  3352. auto Info = getConstructorInfo(D);
  3353. if (!Info.Constructor || Info.Constructor->isInvalidDecl())
  3354. continue;
  3355. if (!AllowExplicit && Info.Constructor->isExplicit())
  3356. continue;
  3357. if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
  3358. continue;
  3359. // C++11 [over.best.ics]p4:
  3360. // ... and the constructor or user-defined conversion function is a
  3361. // candidate by
  3362. // - 13.3.1.3, when the argument is the temporary in the second step
  3363. // of a class copy-initialization, or
  3364. // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
  3365. // - the second phase of 13.3.1.7 when the initializer list has exactly
  3366. // one element that is itself an initializer list, and the target is
  3367. // the first parameter of a constructor of class X, and the conversion
  3368. // is to X or reference to (possibly cv-qualified X),
  3369. // user-defined conversion sequences are not considered.
  3370. bool SuppressUserConversions =
  3371. SecondStepOfCopyInit ||
  3372. (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  3373. hasCopyOrMoveCtorParam(S.Context, Info));
  3374. if (Info.ConstructorTmpl)
  3375. S.AddTemplateOverloadCandidate(
  3376. Info.ConstructorTmpl, Info.FoundDecl,
  3377. /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
  3378. /*PartialOverloading=*/false, AllowExplicit);
  3379. else {
  3380. // C++ [over.match.copy]p1:
  3381. // - When initializing a temporary to be bound to the first parameter
  3382. // of a constructor [for type T] that takes a reference to possibly
  3383. // cv-qualified T as its first argument, called with a single
  3384. // argument in the context of direct-initialization, explicit
  3385. // conversion functions are also considered.
  3386. // FIXME: What if a constructor template instantiates to such a signature?
  3387. bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
  3388. Args.size() == 1 &&
  3389. hasCopyOrMoveCtorParam(S.Context, Info);
  3390. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
  3391. CandidateSet, SuppressUserConversions,
  3392. /*PartialOverloading=*/false, AllowExplicit,
  3393. AllowExplicitConv);
  3394. }
  3395. }
  3396. // FIXME: Work around a bug in C++17 guaranteed copy elision.
  3397. //
  3398. // When initializing an object of class type T by constructor
  3399. // ([over.match.ctor]) or by list-initialization ([over.match.list])
  3400. // from a single expression of class type U, conversion functions of
  3401. // U that convert to the non-reference type cv T are candidates.
  3402. // Explicit conversion functions are only candidates during
  3403. // direct-initialization.
  3404. //
  3405. // Note: SecondStepOfCopyInit is only ever true in this case when
  3406. // evaluating whether to produce a C++98 compatibility warning.
  3407. if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
  3408. !SecondStepOfCopyInit) {
  3409. Expr *Initializer = Args[0];
  3410. auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
  3411. if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
  3412. const auto &Conversions = SourceRD->getVisibleConversionFunctions();
  3413. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3414. NamedDecl *D = *I;
  3415. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3416. D = D->getUnderlyingDecl();
  3417. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3418. CXXConversionDecl *Conv;
  3419. if (ConvTemplate)
  3420. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3421. else
  3422. Conv = cast<CXXConversionDecl>(D);
  3423. if (AllowExplicit || !Conv->isExplicit()) {
  3424. if (ConvTemplate)
  3425. S.AddTemplateConversionCandidate(
  3426. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  3427. CandidateSet, AllowExplicit, AllowExplicit,
  3428. /*AllowResultConversion*/ false);
  3429. else
  3430. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  3431. DestType, CandidateSet, AllowExplicit,
  3432. AllowExplicit,
  3433. /*AllowResultConversion*/ false);
  3434. }
  3435. }
  3436. }
  3437. }
  3438. // Perform overload resolution and return the result.
  3439. return CandidateSet.BestViableFunction(S, DeclLoc, Best);
  3440. }
  3441. /// Attempt initialization by constructor (C++ [dcl.init]), which
  3442. /// enumerates the constructors of the initialized entity and performs overload
  3443. /// resolution to select the best.
  3444. /// \param DestType The destination class type.
  3445. /// \param DestArrayType The destination type, which is either DestType or
  3446. /// a (possibly multidimensional) array of DestType.
  3447. /// \param IsListInit Is this list-initialization?
  3448. /// \param IsInitListCopy Is this non-list-initialization resulting from a
  3449. /// list-initialization from {x} where x is the same
  3450. /// type as the entity?
  3451. static void TryConstructorInitialization(Sema &S,
  3452. const InitializedEntity &Entity,
  3453. const InitializationKind &Kind,
  3454. MultiExprArg Args, QualType DestType,
  3455. QualType DestArrayType,
  3456. InitializationSequence &Sequence,
  3457. bool IsListInit = false,
  3458. bool IsInitListCopy = false) {
  3459. assert(((!IsListInit && !IsInitListCopy) ||
  3460. (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
  3461. "IsListInit/IsInitListCopy must come with a single initializer list "
  3462. "argument.");
  3463. InitListExpr *ILE =
  3464. (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
  3465. MultiExprArg UnwrappedArgs =
  3466. ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
  3467. // The type we're constructing needs to be complete.
  3468. if (!S.isCompleteType(Kind.getLocation(), DestType)) {
  3469. Sequence.setIncompleteTypeFailure(DestType);
  3470. return;
  3471. }
  3472. // C++17 [dcl.init]p17:
  3473. // - If the initializer expression is a prvalue and the cv-unqualified
  3474. // version of the source type is the same class as the class of the
  3475. // destination, the initializer expression is used to initialize the
  3476. // destination object.
  3477. // Per DR (no number yet), this does not apply when initializing a base
  3478. // class or delegating to another constructor from a mem-initializer.
  3479. // ObjC++: Lambda captured by the block in the lambda to block conversion
  3480. // should avoid copy elision.
  3481. if (S.getLangOpts().CPlusPlus17 &&
  3482. Entity.getKind() != InitializedEntity::EK_Base &&
  3483. Entity.getKind() != InitializedEntity::EK_Delegating &&
  3484. Entity.getKind() !=
  3485. InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
  3486. UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
  3487. S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
  3488. // Convert qualifications if necessary.
  3489. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  3490. if (ILE)
  3491. Sequence.RewrapReferenceInitList(DestType, ILE);
  3492. return;
  3493. }
  3494. const RecordType *DestRecordType = DestType->getAs<RecordType>();
  3495. assert(DestRecordType && "Constructor initialization requires record type");
  3496. CXXRecordDecl *DestRecordDecl
  3497. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  3498. // Build the candidate set directly in the initialization sequence
  3499. // structure, so that it will persist if we fail.
  3500. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3501. // Determine whether we are allowed to call explicit constructors or
  3502. // explicit conversion operators.
  3503. bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
  3504. bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
  3505. // - Otherwise, if T is a class type, constructors are considered. The
  3506. // applicable constructors are enumerated, and the best one is chosen
  3507. // through overload resolution.
  3508. DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
  3509. OverloadingResult Result = OR_No_Viable_Function;
  3510. OverloadCandidateSet::iterator Best;
  3511. bool AsInitializerList = false;
  3512. // C++11 [over.match.list]p1, per DR1467:
  3513. // When objects of non-aggregate type T are list-initialized, such that
  3514. // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
  3515. // according to the rules in this section, overload resolution selects
  3516. // the constructor in two phases:
  3517. //
  3518. // - Initially, the candidate functions are the initializer-list
  3519. // constructors of the class T and the argument list consists of the
  3520. // initializer list as a single argument.
  3521. if (IsListInit) {
  3522. AsInitializerList = true;
  3523. // If the initializer list has no elements and T has a default constructor,
  3524. // the first phase is omitted.
  3525. if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
  3526. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
  3527. CandidateSet, DestType, Ctors, Best,
  3528. CopyInitialization, AllowExplicit,
  3529. /*OnlyListConstructors=*/true,
  3530. IsListInit);
  3531. }
  3532. // C++11 [over.match.list]p1:
  3533. // - If no viable initializer-list constructor is found, overload resolution
  3534. // is performed again, where the candidate functions are all the
  3535. // constructors of the class T and the argument list consists of the
  3536. // elements of the initializer list.
  3537. if (Result == OR_No_Viable_Function) {
  3538. AsInitializerList = false;
  3539. Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
  3540. CandidateSet, DestType, Ctors, Best,
  3541. CopyInitialization, AllowExplicit,
  3542. /*OnlyListConstructors=*/false,
  3543. IsListInit);
  3544. }
  3545. if (Result) {
  3546. Sequence.SetOverloadFailure(IsListInit ?
  3547. InitializationSequence::FK_ListConstructorOverloadFailed :
  3548. InitializationSequence::FK_ConstructorOverloadFailed,
  3549. Result);
  3550. return;
  3551. }
  3552. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3553. // In C++17, ResolveConstructorOverload can select a conversion function
  3554. // instead of a constructor.
  3555. if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
  3556. // Add the user-defined conversion step that calls the conversion function.
  3557. QualType ConvType = CD->getConversionType();
  3558. assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
  3559. "should not have selected this conversion function");
  3560. Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
  3561. HadMultipleCandidates);
  3562. if (!S.Context.hasSameType(ConvType, DestType))
  3563. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  3564. if (IsListInit)
  3565. Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
  3566. return;
  3567. }
  3568. // C++11 [dcl.init]p6:
  3569. // If a program calls for the default initialization of an object
  3570. // of a const-qualified type T, T shall be a class type with a
  3571. // user-provided default constructor.
  3572. // C++ core issue 253 proposal:
  3573. // If the implicit default constructor initializes all subobjects, no
  3574. // initializer should be required.
  3575. // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
  3576. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  3577. if (Kind.getKind() == InitializationKind::IK_Default &&
  3578. Entity.getType().isConstQualified()) {
  3579. if (!CtorDecl->getParent()->allowConstDefaultInit()) {
  3580. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  3581. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3582. return;
  3583. }
  3584. }
  3585. // C++11 [over.match.list]p1:
  3586. // In copy-list-initialization, if an explicit constructor is chosen, the
  3587. // initializer is ill-formed.
  3588. if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
  3589. Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
  3590. return;
  3591. }
  3592. // Add the constructor initialization step. Any cv-qualification conversion is
  3593. // subsumed by the initialization.
  3594. Sequence.AddConstructorInitializationStep(
  3595. Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
  3596. IsListInit | IsInitListCopy, AsInitializerList);
  3597. }
  3598. static bool
  3599. ResolveOverloadedFunctionForReferenceBinding(Sema &S,
  3600. Expr *Initializer,
  3601. QualType &SourceType,
  3602. QualType &UnqualifiedSourceType,
  3603. QualType UnqualifiedTargetType,
  3604. InitializationSequence &Sequence) {
  3605. if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
  3606. S.Context.OverloadTy) {
  3607. DeclAccessPair Found;
  3608. bool HadMultipleCandidates = false;
  3609. if (FunctionDecl *Fn
  3610. = S.ResolveAddressOfOverloadedFunction(Initializer,
  3611. UnqualifiedTargetType,
  3612. false, Found,
  3613. &HadMultipleCandidates)) {
  3614. Sequence.AddAddressOverloadResolutionStep(Fn, Found,
  3615. HadMultipleCandidates);
  3616. SourceType = Fn->getType();
  3617. UnqualifiedSourceType = SourceType.getUnqualifiedType();
  3618. } else if (!UnqualifiedTargetType->isRecordType()) {
  3619. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3620. return true;
  3621. }
  3622. }
  3623. return false;
  3624. }
  3625. static void TryReferenceInitializationCore(Sema &S,
  3626. const InitializedEntity &Entity,
  3627. const InitializationKind &Kind,
  3628. Expr *Initializer,
  3629. QualType cv1T1, QualType T1,
  3630. Qualifiers T1Quals,
  3631. QualType cv2T2, QualType T2,
  3632. Qualifiers T2Quals,
  3633. InitializationSequence &Sequence);
  3634. static void TryValueInitialization(Sema &S,
  3635. const InitializedEntity &Entity,
  3636. const InitializationKind &Kind,
  3637. InitializationSequence &Sequence,
  3638. InitListExpr *InitList = nullptr);
  3639. /// Attempt list initialization of a reference.
  3640. static void TryReferenceListInitialization(Sema &S,
  3641. const InitializedEntity &Entity,
  3642. const InitializationKind &Kind,
  3643. InitListExpr *InitList,
  3644. InitializationSequence &Sequence,
  3645. bool TreatUnavailableAsInvalid) {
  3646. // First, catch C++03 where this isn't possible.
  3647. if (!S.getLangOpts().CPlusPlus11) {
  3648. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3649. return;
  3650. }
  3651. // Can't reference initialize a compound literal.
  3652. if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
  3653. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3654. return;
  3655. }
  3656. QualType DestType = Entity.getType();
  3657. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3658. Qualifiers T1Quals;
  3659. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  3660. // Reference initialization via an initializer list works thus:
  3661. // If the initializer list consists of a single element that is
  3662. // reference-related to the referenced type, bind directly to that element
  3663. // (possibly creating temporaries).
  3664. // Otherwise, initialize a temporary with the initializer list and
  3665. // bind to that.
  3666. if (InitList->getNumInits() == 1) {
  3667. Expr *Initializer = InitList->getInit(0);
  3668. QualType cv2T2 = Initializer->getType();
  3669. Qualifiers T2Quals;
  3670. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  3671. // If this fails, creating a temporary wouldn't work either.
  3672. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  3673. T1, Sequence))
  3674. return;
  3675. SourceLocation DeclLoc = Initializer->getBeginLoc();
  3676. bool dummy1, dummy2, dummy3;
  3677. Sema::ReferenceCompareResult RefRelationship
  3678. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
  3679. dummy2, dummy3);
  3680. if (RefRelationship >= Sema::Ref_Related) {
  3681. // Try to bind the reference here.
  3682. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  3683. T1Quals, cv2T2, T2, T2Quals, Sequence);
  3684. if (Sequence)
  3685. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3686. return;
  3687. }
  3688. // Update the initializer if we've resolved an overloaded function.
  3689. if (Sequence.step_begin() != Sequence.step_end())
  3690. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3691. }
  3692. // Not reference-related. Create a temporary and bind to that.
  3693. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  3694. TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
  3695. TreatUnavailableAsInvalid);
  3696. if (Sequence) {
  3697. if (DestType->isRValueReferenceType() ||
  3698. (T1Quals.hasConst() && !T1Quals.hasVolatile()))
  3699. Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
  3700. else
  3701. Sequence.SetFailed(
  3702. InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3703. }
  3704. }
  3705. /// Attempt list initialization (C++0x [dcl.init.list])
  3706. static void TryListInitialization(Sema &S,
  3707. const InitializedEntity &Entity,
  3708. const InitializationKind &Kind,
  3709. InitListExpr *InitList,
  3710. InitializationSequence &Sequence,
  3711. bool TreatUnavailableAsInvalid) {
  3712. QualType DestType = Entity.getType();
  3713. // C++ doesn't allow scalar initialization with more than one argument.
  3714. // But C99 complex numbers are scalars and it makes sense there.
  3715. if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
  3716. !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
  3717. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
  3718. return;
  3719. }
  3720. if (DestType->isReferenceType()) {
  3721. TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
  3722. TreatUnavailableAsInvalid);
  3723. return;
  3724. }
  3725. if (DestType->isRecordType() &&
  3726. !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
  3727. Sequence.setIncompleteTypeFailure(DestType);
  3728. return;
  3729. }
  3730. // C++11 [dcl.init.list]p3, per DR1467:
  3731. // - If T is a class type and the initializer list has a single element of
  3732. // type cv U, where U is T or a class derived from T, the object is
  3733. // initialized from that element (by copy-initialization for
  3734. // copy-list-initialization, or by direct-initialization for
  3735. // direct-list-initialization).
  3736. // - Otherwise, if T is a character array and the initializer list has a
  3737. // single element that is an appropriately-typed string literal
  3738. // (8.5.2 [dcl.init.string]), initialization is performed as described
  3739. // in that section.
  3740. // - Otherwise, if T is an aggregate, [...] (continue below).
  3741. if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
  3742. if (DestType->isRecordType()) {
  3743. QualType InitType = InitList->getInit(0)->getType();
  3744. if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
  3745. S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
  3746. Expr *InitListAsExpr = InitList;
  3747. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  3748. DestType, Sequence,
  3749. /*InitListSyntax*/false,
  3750. /*IsInitListCopy*/true);
  3751. return;
  3752. }
  3753. }
  3754. if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
  3755. Expr *SubInit[1] = {InitList->getInit(0)};
  3756. if (!isa<VariableArrayType>(DestAT) &&
  3757. IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
  3758. InitializationKind SubKind =
  3759. Kind.getKind() == InitializationKind::IK_DirectList
  3760. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3761. InitList->getLBraceLoc(),
  3762. InitList->getRBraceLoc())
  3763. : Kind;
  3764. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3765. /*TopLevelOfInitList*/ true,
  3766. TreatUnavailableAsInvalid);
  3767. // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
  3768. // the element is not an appropriately-typed string literal, in which
  3769. // case we should proceed as in C++11 (below).
  3770. if (Sequence) {
  3771. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3772. return;
  3773. }
  3774. }
  3775. }
  3776. }
  3777. // C++11 [dcl.init.list]p3:
  3778. // - If T is an aggregate, aggregate initialization is performed.
  3779. if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
  3780. (S.getLangOpts().CPlusPlus11 &&
  3781. S.isStdInitializerList(DestType, nullptr))) {
  3782. if (S.getLangOpts().CPlusPlus11) {
  3783. // - Otherwise, if the initializer list has no elements and T is a
  3784. // class type with a default constructor, the object is
  3785. // value-initialized.
  3786. if (InitList->getNumInits() == 0) {
  3787. CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
  3788. if (RD->hasDefaultConstructor()) {
  3789. TryValueInitialization(S, Entity, Kind, Sequence, InitList);
  3790. return;
  3791. }
  3792. }
  3793. // - Otherwise, if T is a specialization of std::initializer_list<E>,
  3794. // an initializer_list object constructed [...]
  3795. if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
  3796. TreatUnavailableAsInvalid))
  3797. return;
  3798. // - Otherwise, if T is a class type, constructors are considered.
  3799. Expr *InitListAsExpr = InitList;
  3800. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  3801. DestType, Sequence, /*InitListSyntax*/true);
  3802. } else
  3803. Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
  3804. return;
  3805. }
  3806. if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
  3807. InitList->getNumInits() == 1) {
  3808. Expr *E = InitList->getInit(0);
  3809. // - Otherwise, if T is an enumeration with a fixed underlying type,
  3810. // the initializer-list has a single element v, and the initialization
  3811. // is direct-list-initialization, the object is initialized with the
  3812. // value T(v); if a narrowing conversion is required to convert v to
  3813. // the underlying type of T, the program is ill-formed.
  3814. auto *ET = DestType->getAs<EnumType>();
  3815. if (S.getLangOpts().CPlusPlus17 &&
  3816. Kind.getKind() == InitializationKind::IK_DirectList &&
  3817. ET && ET->getDecl()->isFixed() &&
  3818. !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
  3819. (E->getType()->isIntegralOrEnumerationType() ||
  3820. E->getType()->isFloatingType())) {
  3821. // There are two ways that T(v) can work when T is an enumeration type.
  3822. // If there is either an implicit conversion sequence from v to T or
  3823. // a conversion function that can convert from v to T, then we use that.
  3824. // Otherwise, if v is of integral, enumeration, or floating-point type,
  3825. // it is converted to the enumeration type via its underlying type.
  3826. // There is no overlap possible between these two cases (except when the
  3827. // source value is already of the destination type), and the first
  3828. // case is handled by the general case for single-element lists below.
  3829. ImplicitConversionSequence ICS;
  3830. ICS.setStandard();
  3831. ICS.Standard.setAsIdentityConversion();
  3832. if (!E->isRValue())
  3833. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  3834. // If E is of a floating-point type, then the conversion is ill-formed
  3835. // due to narrowing, but go through the motions in order to produce the
  3836. // right diagnostic.
  3837. ICS.Standard.Second = E->getType()->isFloatingType()
  3838. ? ICK_Floating_Integral
  3839. : ICK_Integral_Conversion;
  3840. ICS.Standard.setFromType(E->getType());
  3841. ICS.Standard.setToType(0, E->getType());
  3842. ICS.Standard.setToType(1, DestType);
  3843. ICS.Standard.setToType(2, DestType);
  3844. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
  3845. /*TopLevelOfInitList*/true);
  3846. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3847. return;
  3848. }
  3849. // - Otherwise, if the initializer list has a single element of type E
  3850. // [...references are handled above...], the object or reference is
  3851. // initialized from that element (by copy-initialization for
  3852. // copy-list-initialization, or by direct-initialization for
  3853. // direct-list-initialization); if a narrowing conversion is required
  3854. // to convert the element to T, the program is ill-formed.
  3855. //
  3856. // Per core-24034, this is direct-initialization if we were performing
  3857. // direct-list-initialization and copy-initialization otherwise.
  3858. // We can't use InitListChecker for this, because it always performs
  3859. // copy-initialization. This only matters if we might use an 'explicit'
  3860. // conversion operator, so we only need to handle the cases where the source
  3861. // is of record type.
  3862. if (InitList->getInit(0)->getType()->isRecordType()) {
  3863. InitializationKind SubKind =
  3864. Kind.getKind() == InitializationKind::IK_DirectList
  3865. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3866. InitList->getLBraceLoc(),
  3867. InitList->getRBraceLoc())
  3868. : Kind;
  3869. Expr *SubInit[1] = { InitList->getInit(0) };
  3870. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3871. /*TopLevelOfInitList*/true,
  3872. TreatUnavailableAsInvalid);
  3873. if (Sequence)
  3874. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3875. return;
  3876. }
  3877. }
  3878. InitListChecker CheckInitList(S, Entity, InitList,
  3879. DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
  3880. if (CheckInitList.HadError()) {
  3881. Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
  3882. return;
  3883. }
  3884. // Add the list initialization step with the built init list.
  3885. Sequence.AddListInitializationStep(DestType);
  3886. }
  3887. /// Try a reference initialization that involves calling a conversion
  3888. /// function.
  3889. static OverloadingResult TryRefInitWithConversionFunction(
  3890. Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
  3891. Expr *Initializer, bool AllowRValues, bool IsLValueRef,
  3892. InitializationSequence &Sequence) {
  3893. QualType DestType = Entity.getType();
  3894. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3895. QualType T1 = cv1T1.getUnqualifiedType();
  3896. QualType cv2T2 = Initializer->getType();
  3897. QualType T2 = cv2T2.getUnqualifiedType();
  3898. bool DerivedToBase;
  3899. bool ObjCConversion;
  3900. bool ObjCLifetimeConversion;
  3901. assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
  3902. DerivedToBase, ObjCConversion,
  3903. ObjCLifetimeConversion) &&
  3904. "Must have incompatible references when binding via conversion");
  3905. (void)DerivedToBase;
  3906. (void)ObjCConversion;
  3907. (void)ObjCLifetimeConversion;
  3908. // Build the candidate set directly in the initialization sequence
  3909. // structure, so that it will persist if we fail.
  3910. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3911. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  3912. // Determine whether we are allowed to call explicit conversion operators.
  3913. // Note that none of [over.match.copy], [over.match.conv], nor
  3914. // [over.match.ref] permit an explicit constructor to be chosen when
  3915. // initializing a reference, not even for direct-initialization.
  3916. bool AllowExplicitCtors = false;
  3917. bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
  3918. const RecordType *T1RecordType = nullptr;
  3919. if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
  3920. S.isCompleteType(Kind.getLocation(), T1)) {
  3921. // The type we're converting to is a class type. Enumerate its constructors
  3922. // to see if there is a suitable conversion.
  3923. CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
  3924. for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
  3925. auto Info = getConstructorInfo(D);
  3926. if (!Info.Constructor)
  3927. continue;
  3928. if (!Info.Constructor->isInvalidDecl() &&
  3929. Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
  3930. if (Info.ConstructorTmpl)
  3931. S.AddTemplateOverloadCandidate(
  3932. Info.ConstructorTmpl, Info.FoundDecl,
  3933. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  3934. /*SuppressUserConversions=*/true,
  3935. /*PartialOverloading*/ false, AllowExplicitCtors);
  3936. else
  3937. S.AddOverloadCandidate(
  3938. Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
  3939. /*SuppressUserConversions=*/true,
  3940. /*PartialOverloading*/ false, AllowExplicitCtors);
  3941. }
  3942. }
  3943. }
  3944. if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
  3945. return OR_No_Viable_Function;
  3946. const RecordType *T2RecordType = nullptr;
  3947. if ((T2RecordType = T2->getAs<RecordType>()) &&
  3948. S.isCompleteType(Kind.getLocation(), T2)) {
  3949. // The type we're converting from is a class type, enumerate its conversion
  3950. // functions.
  3951. CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
  3952. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3953. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3954. NamedDecl *D = *I;
  3955. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3956. if (isa<UsingShadowDecl>(D))
  3957. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3958. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3959. CXXConversionDecl *Conv;
  3960. if (ConvTemplate)
  3961. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3962. else
  3963. Conv = cast<CXXConversionDecl>(D);
  3964. // If the conversion function doesn't return a reference type,
  3965. // it can't be considered for this conversion unless we're allowed to
  3966. // consider rvalues.
  3967. // FIXME: Do we need to make sure that we only consider conversion
  3968. // candidates with reference-compatible results? That might be needed to
  3969. // break recursion.
  3970. if ((AllowExplicitConvs || !Conv->isExplicit()) &&
  3971. (AllowRValues ||
  3972. Conv->getConversionType()->isLValueReferenceType())) {
  3973. if (ConvTemplate)
  3974. S.AddTemplateConversionCandidate(
  3975. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  3976. CandidateSet,
  3977. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  3978. else
  3979. S.AddConversionCandidate(
  3980. Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
  3981. /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
  3982. }
  3983. }
  3984. }
  3985. if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
  3986. return OR_No_Viable_Function;
  3987. SourceLocation DeclLoc = Initializer->getBeginLoc();
  3988. // Perform overload resolution. If it fails, return the failed result.
  3989. OverloadCandidateSet::iterator Best;
  3990. if (OverloadingResult Result
  3991. = CandidateSet.BestViableFunction(S, DeclLoc, Best))
  3992. return Result;
  3993. FunctionDecl *Function = Best->Function;
  3994. // This is the overload that will be used for this initialization step if we
  3995. // use this initialization. Mark it as referenced.
  3996. Function->setReferenced();
  3997. // Compute the returned type and value kind of the conversion.
  3998. QualType cv3T3;
  3999. if (isa<CXXConversionDecl>(Function))
  4000. cv3T3 = Function->getReturnType();
  4001. else
  4002. cv3T3 = T1;
  4003. ExprValueKind VK = VK_RValue;
  4004. if (cv3T3->isLValueReferenceType())
  4005. VK = VK_LValue;
  4006. else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
  4007. VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
  4008. cv3T3 = cv3T3.getNonLValueExprType(S.Context);
  4009. // Add the user-defined conversion step.
  4010. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4011. Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
  4012. HadMultipleCandidates);
  4013. // Determine whether we'll need to perform derived-to-base adjustments or
  4014. // other conversions.
  4015. bool NewDerivedToBase = false;
  4016. bool NewObjCConversion = false;
  4017. bool NewObjCLifetimeConversion = false;
  4018. Sema::ReferenceCompareResult NewRefRelationship
  4019. = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
  4020. NewDerivedToBase, NewObjCConversion,
  4021. NewObjCLifetimeConversion);
  4022. // Add the final conversion sequence, if necessary.
  4023. if (NewRefRelationship == Sema::Ref_Incompatible) {
  4024. assert(!isa<CXXConstructorDecl>(Function) &&
  4025. "should not have conversion after constructor");
  4026. ImplicitConversionSequence ICS;
  4027. ICS.setStandard();
  4028. ICS.Standard = Best->FinalConversion;
  4029. Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
  4030. // Every implicit conversion results in a prvalue, except for a glvalue
  4031. // derived-to-base conversion, which we handle below.
  4032. cv3T3 = ICS.Standard.getToType(2);
  4033. VK = VK_RValue;
  4034. }
  4035. // If the converted initializer is a prvalue, its type T4 is adjusted to
  4036. // type "cv1 T4" and the temporary materialization conversion is applied.
  4037. //
  4038. // We adjust the cv-qualifications to match the reference regardless of
  4039. // whether we have a prvalue so that the AST records the change. In this
  4040. // case, T4 is "cv3 T3".
  4041. QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
  4042. if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
  4043. Sequence.AddQualificationConversionStep(cv1T4, VK);
  4044. Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
  4045. VK = IsLValueRef ? VK_LValue : VK_XValue;
  4046. if (NewDerivedToBase)
  4047. Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
  4048. else if (NewObjCConversion)
  4049. Sequence.AddObjCObjectConversionStep(cv1T1);
  4050. return OR_Success;
  4051. }
  4052. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  4053. const InitializedEntity &Entity,
  4054. Expr *CurInitExpr);
  4055. /// Attempt reference initialization (C++0x [dcl.init.ref])
  4056. static void TryReferenceInitialization(Sema &S,
  4057. const InitializedEntity &Entity,
  4058. const InitializationKind &Kind,
  4059. Expr *Initializer,
  4060. InitializationSequence &Sequence) {
  4061. QualType DestType = Entity.getType();
  4062. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  4063. Qualifiers T1Quals;
  4064. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  4065. QualType cv2T2 = Initializer->getType();
  4066. Qualifiers T2Quals;
  4067. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  4068. // If the initializer is the address of an overloaded function, try
  4069. // to resolve the overloaded function. If all goes well, T2 is the
  4070. // type of the resulting function.
  4071. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  4072. T1, Sequence))
  4073. return;
  4074. // Delegate everything else to a subfunction.
  4075. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  4076. T1Quals, cv2T2, T2, T2Quals, Sequence);
  4077. }
  4078. /// Determine whether an expression is a non-referenceable glvalue (one to
  4079. /// which a reference can never bind). Attempting to bind a reference to
  4080. /// such a glvalue will always create a temporary.
  4081. static bool isNonReferenceableGLValue(Expr *E) {
  4082. return E->refersToBitField() || E->refersToVectorElement();
  4083. }
  4084. /// Reference initialization without resolving overloaded functions.
  4085. static void TryReferenceInitializationCore(Sema &S,
  4086. const InitializedEntity &Entity,
  4087. const InitializationKind &Kind,
  4088. Expr *Initializer,
  4089. QualType cv1T1, QualType T1,
  4090. Qualifiers T1Quals,
  4091. QualType cv2T2, QualType T2,
  4092. Qualifiers T2Quals,
  4093. InitializationSequence &Sequence) {
  4094. QualType DestType = Entity.getType();
  4095. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4096. // Compute some basic properties of the types and the initializer.
  4097. bool isLValueRef = DestType->isLValueReferenceType();
  4098. bool isRValueRef = !isLValueRef;
  4099. bool DerivedToBase = false;
  4100. bool ObjCConversion = false;
  4101. bool ObjCLifetimeConversion = false;
  4102. Expr::Classification InitCategory = Initializer->Classify(S.Context);
  4103. Sema::ReferenceCompareResult RefRelationship
  4104. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
  4105. ObjCConversion, ObjCLifetimeConversion);
  4106. // C++0x [dcl.init.ref]p5:
  4107. // A reference to type "cv1 T1" is initialized by an expression of type
  4108. // "cv2 T2" as follows:
  4109. //
  4110. // - If the reference is an lvalue reference and the initializer
  4111. // expression
  4112. // Note the analogous bullet points for rvalue refs to functions. Because
  4113. // there are no function rvalues in C++, rvalue refs to functions are treated
  4114. // like lvalue refs.
  4115. OverloadingResult ConvOvlResult = OR_Success;
  4116. bool T1Function = T1->isFunctionType();
  4117. if (isLValueRef || T1Function) {
  4118. if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
  4119. (RefRelationship == Sema::Ref_Compatible ||
  4120. (Kind.isCStyleOrFunctionalCast() &&
  4121. RefRelationship == Sema::Ref_Related))) {
  4122. // - is an lvalue (but is not a bit-field), and "cv1 T1" is
  4123. // reference-compatible with "cv2 T2," or
  4124. if (T1Quals != T2Quals)
  4125. // Convert to cv1 T2. This should only add qualifiers unless this is a
  4126. // c-style cast. The removal of qualifiers in that case notionally
  4127. // happens after the reference binding, but that doesn't matter.
  4128. Sequence.AddQualificationConversionStep(
  4129. S.Context.getQualifiedType(T2, T1Quals),
  4130. Initializer->getValueKind());
  4131. if (DerivedToBase)
  4132. Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
  4133. else if (ObjCConversion)
  4134. Sequence.AddObjCObjectConversionStep(cv1T1);
  4135. // We only create a temporary here when binding a reference to a
  4136. // bit-field or vector element. Those cases are't supposed to be
  4137. // handled by this bullet, but the outcome is the same either way.
  4138. Sequence.AddReferenceBindingStep(cv1T1, false);
  4139. return;
  4140. }
  4141. // - has a class type (i.e., T2 is a class type), where T1 is not
  4142. // reference-related to T2, and can be implicitly converted to an
  4143. // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
  4144. // with "cv3 T3" (this conversion is selected by enumerating the
  4145. // applicable conversion functions (13.3.1.6) and choosing the best
  4146. // one through overload resolution (13.3)),
  4147. // If we have an rvalue ref to function type here, the rhs must be
  4148. // an rvalue. DR1287 removed the "implicitly" here.
  4149. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
  4150. (isLValueRef || InitCategory.isRValue())) {
  4151. ConvOvlResult = TryRefInitWithConversionFunction(
  4152. S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
  4153. /*IsLValueRef*/ isLValueRef, Sequence);
  4154. if (ConvOvlResult == OR_Success)
  4155. return;
  4156. if (ConvOvlResult != OR_No_Viable_Function)
  4157. Sequence.SetOverloadFailure(
  4158. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4159. ConvOvlResult);
  4160. }
  4161. }
  4162. // - Otherwise, the reference shall be an lvalue reference to a
  4163. // non-volatile const type (i.e., cv1 shall be const), or the reference
  4164. // shall be an rvalue reference.
  4165. // For address spaces, we interpret this to mean that an addr space
  4166. // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
  4167. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
  4168. T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
  4169. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4170. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4171. else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4172. Sequence.SetOverloadFailure(
  4173. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4174. ConvOvlResult);
  4175. else if (!InitCategory.isLValue())
  4176. Sequence.SetFailed(
  4177. T1Quals.isAddressSpaceSupersetOf(T2Quals)
  4178. ? InitializationSequence::
  4179. FK_NonConstLValueReferenceBindingToTemporary
  4180. : InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4181. else {
  4182. InitializationSequence::FailureKind FK;
  4183. switch (RefRelationship) {
  4184. case Sema::Ref_Compatible:
  4185. if (Initializer->refersToBitField())
  4186. FK = InitializationSequence::
  4187. FK_NonConstLValueReferenceBindingToBitfield;
  4188. else if (Initializer->refersToVectorElement())
  4189. FK = InitializationSequence::
  4190. FK_NonConstLValueReferenceBindingToVectorElement;
  4191. else
  4192. llvm_unreachable("unexpected kind of compatible initializer");
  4193. break;
  4194. case Sema::Ref_Related:
  4195. FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
  4196. break;
  4197. case Sema::Ref_Incompatible:
  4198. FK = InitializationSequence::
  4199. FK_NonConstLValueReferenceBindingToUnrelated;
  4200. break;
  4201. }
  4202. Sequence.SetFailed(FK);
  4203. }
  4204. return;
  4205. }
  4206. // - If the initializer expression
  4207. // - is an
  4208. // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
  4209. // [1z] rvalue (but not a bit-field) or
  4210. // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
  4211. //
  4212. // Note: functions are handled above and below rather than here...
  4213. if (!T1Function &&
  4214. (RefRelationship == Sema::Ref_Compatible ||
  4215. (Kind.isCStyleOrFunctionalCast() &&
  4216. RefRelationship == Sema::Ref_Related)) &&
  4217. ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
  4218. (InitCategory.isPRValue() &&
  4219. (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
  4220. T2->isArrayType())))) {
  4221. ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
  4222. if (InitCategory.isPRValue() && T2->isRecordType()) {
  4223. // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
  4224. // compiler the freedom to perform a copy here or bind to the
  4225. // object, while C++0x requires that we bind directly to the
  4226. // object. Hence, we always bind to the object without making an
  4227. // extra copy. However, in C++03 requires that we check for the
  4228. // presence of a suitable copy constructor:
  4229. //
  4230. // The constructor that would be used to make the copy shall
  4231. // be callable whether or not the copy is actually done.
  4232. if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
  4233. Sequence.AddExtraneousCopyToTemporary(cv2T2);
  4234. else if (S.getLangOpts().CPlusPlus11)
  4235. CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
  4236. }
  4237. // C++1z [dcl.init.ref]/5.2.1.2:
  4238. // If the converted initializer is a prvalue, its type T4 is adjusted
  4239. // to type "cv1 T4" and the temporary materialization conversion is
  4240. // applied.
  4241. // Postpone address space conversions to after the temporary materialization
  4242. // conversion to allow creating temporaries in the alloca address space.
  4243. auto T1QualsIgnoreAS = T1Quals;
  4244. auto T2QualsIgnoreAS = T2Quals;
  4245. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4246. T1QualsIgnoreAS.removeAddressSpace();
  4247. T2QualsIgnoreAS.removeAddressSpace();
  4248. }
  4249. QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
  4250. if (T1QualsIgnoreAS != T2QualsIgnoreAS)
  4251. Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
  4252. Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
  4253. ValueKind = isLValueRef ? VK_LValue : VK_XValue;
  4254. // Add addr space conversion if required.
  4255. if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
  4256. auto T4Quals = cv1T4.getQualifiers();
  4257. T4Quals.addAddressSpace(T1Quals.getAddressSpace());
  4258. QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
  4259. Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
  4260. }
  4261. // In any case, the reference is bound to the resulting glvalue (or to
  4262. // an appropriate base class subobject).
  4263. if (DerivedToBase)
  4264. Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
  4265. else if (ObjCConversion)
  4266. Sequence.AddObjCObjectConversionStep(cv1T1);
  4267. return;
  4268. }
  4269. // - has a class type (i.e., T2 is a class type), where T1 is not
  4270. // reference-related to T2, and can be implicitly converted to an
  4271. // xvalue, class prvalue, or function lvalue of type "cv3 T3",
  4272. // where "cv1 T1" is reference-compatible with "cv3 T3",
  4273. //
  4274. // DR1287 removes the "implicitly" here.
  4275. if (T2->isRecordType()) {
  4276. if (RefRelationship == Sema::Ref_Incompatible) {
  4277. ConvOvlResult = TryRefInitWithConversionFunction(
  4278. S, Entity, Kind, Initializer, /*AllowRValues*/ true,
  4279. /*IsLValueRef*/ isLValueRef, Sequence);
  4280. if (ConvOvlResult)
  4281. Sequence.SetOverloadFailure(
  4282. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4283. ConvOvlResult);
  4284. return;
  4285. }
  4286. if (RefRelationship == Sema::Ref_Compatible &&
  4287. isRValueRef && InitCategory.isLValue()) {
  4288. Sequence.SetFailed(
  4289. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4290. return;
  4291. }
  4292. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4293. return;
  4294. }
  4295. // - Otherwise, a temporary of type "cv1 T1" is created and initialized
  4296. // from the initializer expression using the rules for a non-reference
  4297. // copy-initialization (8.5). The reference is then bound to the
  4298. // temporary. [...]
  4299. // Ignore address space of reference type at this point and perform address
  4300. // space conversion after the reference binding step.
  4301. QualType cv1T1IgnoreAS =
  4302. T1Quals.hasAddressSpace()
  4303. ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
  4304. : cv1T1;
  4305. InitializedEntity TempEntity =
  4306. InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
  4307. // FIXME: Why do we use an implicit conversion here rather than trying
  4308. // copy-initialization?
  4309. ImplicitConversionSequence ICS
  4310. = S.TryImplicitConversion(Initializer, TempEntity.getType(),
  4311. /*SuppressUserConversions=*/false,
  4312. /*AllowExplicit=*/false,
  4313. /*FIXME:InOverloadResolution=*/false,
  4314. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  4315. /*AllowObjCWritebackConversion=*/false);
  4316. if (ICS.isBad()) {
  4317. // FIXME: Use the conversion function set stored in ICS to turn
  4318. // this into an overloading ambiguity diagnostic. However, we need
  4319. // to keep that set as an OverloadCandidateSet rather than as some
  4320. // other kind of set.
  4321. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  4322. Sequence.SetOverloadFailure(
  4323. InitializationSequence::FK_ReferenceInitOverloadFailed,
  4324. ConvOvlResult);
  4325. else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  4326. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4327. else
  4328. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
  4329. return;
  4330. } else {
  4331. Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
  4332. }
  4333. // [...] If T1 is reference-related to T2, cv1 must be the
  4334. // same cv-qualification as, or greater cv-qualification
  4335. // than, cv2; otherwise, the program is ill-formed.
  4336. unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
  4337. unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
  4338. if ((RefRelationship == Sema::Ref_Related &&
  4339. (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
  4340. !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
  4341. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  4342. return;
  4343. }
  4344. // [...] If T1 is reference-related to T2 and the reference is an rvalue
  4345. // reference, the initializer expression shall not be an lvalue.
  4346. if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
  4347. InitCategory.isLValue()) {
  4348. Sequence.SetFailed(
  4349. InitializationSequence::FK_RValueReferenceBindingToLValue);
  4350. return;
  4351. }
  4352. Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
  4353. if (T1Quals.hasAddressSpace()) {
  4354. if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
  4355. LangAS::Default)) {
  4356. Sequence.SetFailed(
  4357. InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
  4358. return;
  4359. }
  4360. Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
  4361. : VK_XValue);
  4362. }
  4363. }
  4364. /// Attempt character array initialization from a string literal
  4365. /// (C++ [dcl.init.string], C99 6.7.8).
  4366. static void TryStringLiteralInitialization(Sema &S,
  4367. const InitializedEntity &Entity,
  4368. const InitializationKind &Kind,
  4369. Expr *Initializer,
  4370. InitializationSequence &Sequence) {
  4371. Sequence.AddStringInitStep(Entity.getType());
  4372. }
  4373. /// Attempt value initialization (C++ [dcl.init]p7).
  4374. static void TryValueInitialization(Sema &S,
  4375. const InitializedEntity &Entity,
  4376. const InitializationKind &Kind,
  4377. InitializationSequence &Sequence,
  4378. InitListExpr *InitList) {
  4379. assert((!InitList || InitList->getNumInits() == 0) &&
  4380. "Shouldn't use value-init for non-empty init lists");
  4381. // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
  4382. //
  4383. // To value-initialize an object of type T means:
  4384. QualType T = Entity.getType();
  4385. // -- if T is an array type, then each element is value-initialized;
  4386. T = S.Context.getBaseElementType(T);
  4387. if (const RecordType *RT = T->getAs<RecordType>()) {
  4388. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  4389. bool NeedZeroInitialization = true;
  4390. // C++98:
  4391. // -- if T is a class type (clause 9) with a user-declared constructor
  4392. // (12.1), then the default constructor for T is called (and the
  4393. // initialization is ill-formed if T has no accessible default
  4394. // constructor);
  4395. // C++11:
  4396. // -- if T is a class type (clause 9) with either no default constructor
  4397. // (12.1 [class.ctor]) or a default constructor that is user-provided
  4398. // or deleted, then the object is default-initialized;
  4399. //
  4400. // Note that the C++11 rule is the same as the C++98 rule if there are no
  4401. // defaulted or deleted constructors, so we just use it unconditionally.
  4402. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
  4403. if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
  4404. NeedZeroInitialization = false;
  4405. // -- if T is a (possibly cv-qualified) non-union class type without a
  4406. // user-provided or deleted default constructor, then the object is
  4407. // zero-initialized and, if T has a non-trivial default constructor,
  4408. // default-initialized;
  4409. // The 'non-union' here was removed by DR1502. The 'non-trivial default
  4410. // constructor' part was removed by DR1507.
  4411. if (NeedZeroInitialization)
  4412. Sequence.AddZeroInitializationStep(Entity.getType());
  4413. // C++03:
  4414. // -- if T is a non-union class type without a user-declared constructor,
  4415. // then every non-static data member and base class component of T is
  4416. // value-initialized;
  4417. // [...] A program that calls for [...] value-initialization of an
  4418. // entity of reference type is ill-formed.
  4419. //
  4420. // C++11 doesn't need this handling, because value-initialization does not
  4421. // occur recursively there, and the implicit default constructor is
  4422. // defined as deleted in the problematic cases.
  4423. if (!S.getLangOpts().CPlusPlus11 &&
  4424. ClassDecl->hasUninitializedReferenceMember()) {
  4425. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
  4426. return;
  4427. }
  4428. // If this is list-value-initialization, pass the empty init list on when
  4429. // building the constructor call. This affects the semantics of a few
  4430. // things (such as whether an explicit default constructor can be called).
  4431. Expr *InitListAsExpr = InitList;
  4432. MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
  4433. bool InitListSyntax = InitList;
  4434. // FIXME: Instead of creating a CXXConstructExpr of array type here,
  4435. // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
  4436. return TryConstructorInitialization(
  4437. S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
  4438. }
  4439. }
  4440. Sequence.AddZeroInitializationStep(Entity.getType());
  4441. }
  4442. /// Attempt default initialization (C++ [dcl.init]p6).
  4443. static void TryDefaultInitialization(Sema &S,
  4444. const InitializedEntity &Entity,
  4445. const InitializationKind &Kind,
  4446. InitializationSequence &Sequence) {
  4447. assert(Kind.getKind() == InitializationKind::IK_Default);
  4448. // C++ [dcl.init]p6:
  4449. // To default-initialize an object of type T means:
  4450. // - if T is an array type, each element is default-initialized;
  4451. QualType DestType = S.Context.getBaseElementType(Entity.getType());
  4452. // - if T is a (possibly cv-qualified) class type (Clause 9), the default
  4453. // constructor for T is called (and the initialization is ill-formed if
  4454. // T has no accessible default constructor);
  4455. if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
  4456. TryConstructorInitialization(S, Entity, Kind, None, DestType,
  4457. Entity.getType(), Sequence);
  4458. return;
  4459. }
  4460. // - otherwise, no initialization is performed.
  4461. // If a program calls for the default initialization of an object of
  4462. // a const-qualified type T, T shall be a class type with a user-provided
  4463. // default constructor.
  4464. if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
  4465. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  4466. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  4467. return;
  4468. }
  4469. // If the destination type has a lifetime property, zero-initialize it.
  4470. if (DestType.getQualifiers().hasObjCLifetime()) {
  4471. Sequence.AddZeroInitializationStep(Entity.getType());
  4472. return;
  4473. }
  4474. }
  4475. /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
  4476. /// which enumerates all conversion functions and performs overload resolution
  4477. /// to select the best.
  4478. static void TryUserDefinedConversion(Sema &S,
  4479. QualType DestType,
  4480. const InitializationKind &Kind,
  4481. Expr *Initializer,
  4482. InitializationSequence &Sequence,
  4483. bool TopLevelOfInitList) {
  4484. assert(!DestType->isReferenceType() && "References are handled elsewhere");
  4485. QualType SourceType = Initializer->getType();
  4486. assert((DestType->isRecordType() || SourceType->isRecordType()) &&
  4487. "Must have a class type to perform a user-defined conversion");
  4488. // Build the candidate set directly in the initialization sequence
  4489. // structure, so that it will persist if we fail.
  4490. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  4491. CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
  4492. CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
  4493. // Determine whether we are allowed to call explicit constructors or
  4494. // explicit conversion operators.
  4495. bool AllowExplicit = Kind.AllowExplicit();
  4496. if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
  4497. // The type we're converting to is a class type. Enumerate its constructors
  4498. // to see if there is a suitable conversion.
  4499. CXXRecordDecl *DestRecordDecl
  4500. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  4501. // Try to complete the type we're converting to.
  4502. if (S.isCompleteType(Kind.getLocation(), DestType)) {
  4503. for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
  4504. auto Info = getConstructorInfo(D);
  4505. if (!Info.Constructor)
  4506. continue;
  4507. if (!Info.Constructor->isInvalidDecl() &&
  4508. Info.Constructor->isConvertingConstructor(AllowExplicit)) {
  4509. if (Info.ConstructorTmpl)
  4510. S.AddTemplateOverloadCandidate(
  4511. Info.ConstructorTmpl, Info.FoundDecl,
  4512. /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
  4513. /*SuppressUserConversions=*/true,
  4514. /*PartialOverloading*/ false, AllowExplicit);
  4515. else
  4516. S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
  4517. Initializer, CandidateSet,
  4518. /*SuppressUserConversions=*/true,
  4519. /*PartialOverloading*/ false, AllowExplicit);
  4520. }
  4521. }
  4522. }
  4523. }
  4524. SourceLocation DeclLoc = Initializer->getBeginLoc();
  4525. if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
  4526. // The type we're converting from is a class type, enumerate its conversion
  4527. // functions.
  4528. // We can only enumerate the conversion functions for a complete type; if
  4529. // the type isn't complete, simply skip this step.
  4530. if (S.isCompleteType(DeclLoc, SourceType)) {
  4531. CXXRecordDecl *SourceRecordDecl
  4532. = cast<CXXRecordDecl>(SourceRecordType->getDecl());
  4533. const auto &Conversions =
  4534. SourceRecordDecl->getVisibleConversionFunctions();
  4535. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4536. NamedDecl *D = *I;
  4537. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4538. if (isa<UsingShadowDecl>(D))
  4539. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4540. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4541. CXXConversionDecl *Conv;
  4542. if (ConvTemplate)
  4543. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4544. else
  4545. Conv = cast<CXXConversionDecl>(D);
  4546. if (AllowExplicit || !Conv->isExplicit()) {
  4547. if (ConvTemplate)
  4548. S.AddTemplateConversionCandidate(
  4549. ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
  4550. CandidateSet, AllowExplicit, AllowExplicit);
  4551. else
  4552. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
  4553. DestType, CandidateSet, AllowExplicit,
  4554. AllowExplicit);
  4555. }
  4556. }
  4557. }
  4558. }
  4559. // Perform overload resolution. If it fails, return the failed result.
  4560. OverloadCandidateSet::iterator Best;
  4561. if (OverloadingResult Result
  4562. = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
  4563. Sequence.SetOverloadFailure(
  4564. InitializationSequence::FK_UserConversionOverloadFailed,
  4565. Result);
  4566. return;
  4567. }
  4568. FunctionDecl *Function = Best->Function;
  4569. Function->setReferenced();
  4570. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4571. if (isa<CXXConstructorDecl>(Function)) {
  4572. // Add the user-defined conversion step. Any cv-qualification conversion is
  4573. // subsumed by the initialization. Per DR5, the created temporary is of the
  4574. // cv-unqualified type of the destination.
  4575. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  4576. DestType.getUnqualifiedType(),
  4577. HadMultipleCandidates);
  4578. // C++14 and before:
  4579. // - if the function is a constructor, the call initializes a temporary
  4580. // of the cv-unqualified version of the destination type. The [...]
  4581. // temporary [...] is then used to direct-initialize, according to the
  4582. // rules above, the object that is the destination of the
  4583. // copy-initialization.
  4584. // Note that this just performs a simple object copy from the temporary.
  4585. //
  4586. // C++17:
  4587. // - if the function is a constructor, the call is a prvalue of the
  4588. // cv-unqualified version of the destination type whose return object
  4589. // is initialized by the constructor. The call is used to
  4590. // direct-initialize, according to the rules above, the object that
  4591. // is the destination of the copy-initialization.
  4592. // Therefore we need to do nothing further.
  4593. //
  4594. // FIXME: Mark this copy as extraneous.
  4595. if (!S.getLangOpts().CPlusPlus17)
  4596. Sequence.AddFinalCopy(DestType);
  4597. else if (DestType.hasQualifiers())
  4598. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  4599. return;
  4600. }
  4601. // Add the user-defined conversion step that calls the conversion function.
  4602. QualType ConvType = Function->getCallResultType();
  4603. Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
  4604. HadMultipleCandidates);
  4605. if (ConvType->getAs<RecordType>()) {
  4606. // The call is used to direct-initialize [...] the object that is the
  4607. // destination of the copy-initialization.
  4608. //
  4609. // In C++17, this does not call a constructor if we enter /17.6.1:
  4610. // - If the initializer expression is a prvalue and the cv-unqualified
  4611. // version of the source type is the same as the class of the
  4612. // destination [... do not make an extra copy]
  4613. //
  4614. // FIXME: Mark this copy as extraneous.
  4615. if (!S.getLangOpts().CPlusPlus17 ||
  4616. Function->getReturnType()->isReferenceType() ||
  4617. !S.Context.hasSameUnqualifiedType(ConvType, DestType))
  4618. Sequence.AddFinalCopy(DestType);
  4619. else if (!S.Context.hasSameType(ConvType, DestType))
  4620. Sequence.AddQualificationConversionStep(DestType, VK_RValue);
  4621. return;
  4622. }
  4623. // If the conversion following the call to the conversion function
  4624. // is interesting, add it as a separate step.
  4625. if (Best->FinalConversion.First || Best->FinalConversion.Second ||
  4626. Best->FinalConversion.Third) {
  4627. ImplicitConversionSequence ICS;
  4628. ICS.setStandard();
  4629. ICS.Standard = Best->FinalConversion;
  4630. Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  4631. }
  4632. }
  4633. /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
  4634. /// a function with a pointer return type contains a 'return false;' statement.
  4635. /// In C++11, 'false' is not a null pointer, so this breaks the build of any
  4636. /// code using that header.
  4637. ///
  4638. /// Work around this by treating 'return false;' as zero-initializing the result
  4639. /// if it's used in a pointer-returning function in a system header.
  4640. static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
  4641. const InitializedEntity &Entity,
  4642. const Expr *Init) {
  4643. return S.getLangOpts().CPlusPlus11 &&
  4644. Entity.getKind() == InitializedEntity::EK_Result &&
  4645. Entity.getType()->isPointerType() &&
  4646. isa<CXXBoolLiteralExpr>(Init) &&
  4647. !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
  4648. S.getSourceManager().isInSystemHeader(Init->getExprLoc());
  4649. }
  4650. /// The non-zero enum values here are indexes into diagnostic alternatives.
  4651. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
  4652. /// Determines whether this expression is an acceptable ICR source.
  4653. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
  4654. bool isAddressOf, bool &isWeakAccess) {
  4655. // Skip parens.
  4656. e = e->IgnoreParens();
  4657. // Skip address-of nodes.
  4658. if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  4659. if (op->getOpcode() == UO_AddrOf)
  4660. return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
  4661. isWeakAccess);
  4662. // Skip certain casts.
  4663. } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
  4664. switch (ce->getCastKind()) {
  4665. case CK_Dependent:
  4666. case CK_BitCast:
  4667. case CK_LValueBitCast:
  4668. case CK_NoOp:
  4669. return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
  4670. case CK_ArrayToPointerDecay:
  4671. return IIK_nonscalar;
  4672. case CK_NullToPointer:
  4673. return IIK_okay;
  4674. default:
  4675. break;
  4676. }
  4677. // If we have a declaration reference, it had better be a local variable.
  4678. } else if (isa<DeclRefExpr>(e)) {
  4679. // set isWeakAccess to true, to mean that there will be an implicit
  4680. // load which requires a cleanup.
  4681. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  4682. isWeakAccess = true;
  4683. if (!isAddressOf) return IIK_nonlocal;
  4684. VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
  4685. if (!var) return IIK_nonlocal;
  4686. return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
  4687. // If we have a conditional operator, check both sides.
  4688. } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
  4689. if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
  4690. isWeakAccess))
  4691. return iik;
  4692. return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
  4693. // These are never scalar.
  4694. } else if (isa<ArraySubscriptExpr>(e)) {
  4695. return IIK_nonscalar;
  4696. // Otherwise, it needs to be a null pointer constant.
  4697. } else {
  4698. return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
  4699. ? IIK_okay : IIK_nonlocal);
  4700. }
  4701. return IIK_nonlocal;
  4702. }
  4703. /// Check whether the given expression is a valid operand for an
  4704. /// indirect copy/restore.
  4705. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
  4706. assert(src->isRValue());
  4707. bool isWeakAccess = false;
  4708. InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
  4709. // If isWeakAccess to true, there will be an implicit
  4710. // load which requires a cleanup.
  4711. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
  4712. S.Cleanup.setExprNeedsCleanups(true);
  4713. if (iik == IIK_okay) return;
  4714. S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
  4715. << ((unsigned) iik - 1) // shift index into diagnostic explanations
  4716. << src->getSourceRange();
  4717. }
  4718. /// Determine whether we have compatible array types for the
  4719. /// purposes of GNU by-copy array initialization.
  4720. static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
  4721. const ArrayType *Source) {
  4722. // If the source and destination array types are equivalent, we're
  4723. // done.
  4724. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
  4725. return true;
  4726. // Make sure that the element types are the same.
  4727. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
  4728. return false;
  4729. // The only mismatch we allow is when the destination is an
  4730. // incomplete array type and the source is a constant array type.
  4731. return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
  4732. }
  4733. static bool tryObjCWritebackConversion(Sema &S,
  4734. InitializationSequence &Sequence,
  4735. const InitializedEntity &Entity,
  4736. Expr *Initializer) {
  4737. bool ArrayDecay = false;
  4738. QualType ArgType = Initializer->getType();
  4739. QualType ArgPointee;
  4740. if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
  4741. ArrayDecay = true;
  4742. ArgPointee = ArgArrayType->getElementType();
  4743. ArgType = S.Context.getPointerType(ArgPointee);
  4744. }
  4745. // Handle write-back conversion.
  4746. QualType ConvertedArgType;
  4747. if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
  4748. ConvertedArgType))
  4749. return false;
  4750. // We should copy unless we're passing to an argument explicitly
  4751. // marked 'out'.
  4752. bool ShouldCopy = true;
  4753. if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  4754. ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  4755. // Do we need an lvalue conversion?
  4756. if (ArrayDecay || Initializer->isGLValue()) {
  4757. ImplicitConversionSequence ICS;
  4758. ICS.setStandard();
  4759. ICS.Standard.setAsIdentityConversion();
  4760. QualType ResultType;
  4761. if (ArrayDecay) {
  4762. ICS.Standard.First = ICK_Array_To_Pointer;
  4763. ResultType = S.Context.getPointerType(ArgPointee);
  4764. } else {
  4765. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  4766. ResultType = Initializer->getType().getNonLValueExprType(S.Context);
  4767. }
  4768. Sequence.AddConversionSequenceStep(ICS, ResultType);
  4769. }
  4770. Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  4771. return true;
  4772. }
  4773. static bool TryOCLSamplerInitialization(Sema &S,
  4774. InitializationSequence &Sequence,
  4775. QualType DestType,
  4776. Expr *Initializer) {
  4777. if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
  4778. (!Initializer->isIntegerConstantExpr(S.Context) &&
  4779. !Initializer->getType()->isSamplerT()))
  4780. return false;
  4781. Sequence.AddOCLSamplerInitStep(DestType);
  4782. return true;
  4783. }
  4784. static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
  4785. return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
  4786. (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
  4787. }
  4788. static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
  4789. InitializationSequence &Sequence,
  4790. QualType DestType,
  4791. Expr *Initializer) {
  4792. if (!S.getLangOpts().OpenCL)
  4793. return false;
  4794. //
  4795. // OpenCL 1.2 spec, s6.12.10
  4796. //
  4797. // The event argument can also be used to associate the
  4798. // async_work_group_copy with a previous async copy allowing
  4799. // an event to be shared by multiple async copies; otherwise
  4800. // event should be zero.
  4801. //
  4802. if (DestType->isEventT() || DestType->isQueueT()) {
  4803. if (!IsZeroInitializer(Initializer, S))
  4804. return false;
  4805. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  4806. return true;
  4807. }
  4808. // We should allow zero initialization for all types defined in the
  4809. // cl_intel_device_side_avc_motion_estimation extension, except
  4810. // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
  4811. if (S.getOpenCLOptions().isEnabled(
  4812. "cl_intel_device_side_avc_motion_estimation") &&
  4813. DestType->isOCLIntelSubgroupAVCType()) {
  4814. if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
  4815. DestType->isOCLIntelSubgroupAVCMceResultType())
  4816. return false;
  4817. if (!IsZeroInitializer(Initializer, S))
  4818. return false;
  4819. Sequence.AddOCLZeroOpaqueTypeStep(DestType);
  4820. return true;
  4821. }
  4822. return false;
  4823. }
  4824. InitializationSequence::InitializationSequence(Sema &S,
  4825. const InitializedEntity &Entity,
  4826. const InitializationKind &Kind,
  4827. MultiExprArg Args,
  4828. bool TopLevelOfInitList,
  4829. bool TreatUnavailableAsInvalid)
  4830. : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
  4831. InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
  4832. TreatUnavailableAsInvalid);
  4833. }
  4834. /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
  4835. /// address of that function, this returns true. Otherwise, it returns false.
  4836. static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
  4837. auto *DRE = dyn_cast<DeclRefExpr>(E);
  4838. if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
  4839. return false;
  4840. return !S.checkAddressOfFunctionIsAvailable(
  4841. cast<FunctionDecl>(DRE->getDecl()));
  4842. }
  4843. /// Determine whether we can perform an elementwise array copy for this kind
  4844. /// of entity.
  4845. static bool canPerformArrayCopy(const InitializedEntity &Entity) {
  4846. switch (Entity.getKind()) {
  4847. case InitializedEntity::EK_LambdaCapture:
  4848. // C++ [expr.prim.lambda]p24:
  4849. // For array members, the array elements are direct-initialized in
  4850. // increasing subscript order.
  4851. return true;
  4852. case InitializedEntity::EK_Variable:
  4853. // C++ [dcl.decomp]p1:
  4854. // [...] each element is copy-initialized or direct-initialized from the
  4855. // corresponding element of the assignment-expression [...]
  4856. return isa<DecompositionDecl>(Entity.getDecl());
  4857. case InitializedEntity::EK_Member:
  4858. // C++ [class.copy.ctor]p14:
  4859. // - if the member is an array, each element is direct-initialized with
  4860. // the corresponding subobject of x
  4861. return Entity.isImplicitMemberInitializer();
  4862. case InitializedEntity::EK_ArrayElement:
  4863. // All the above cases are intended to apply recursively, even though none
  4864. // of them actually say that.
  4865. if (auto *E = Entity.getParent())
  4866. return canPerformArrayCopy(*E);
  4867. break;
  4868. default:
  4869. break;
  4870. }
  4871. return false;
  4872. }
  4873. void InitializationSequence::InitializeFrom(Sema &S,
  4874. const InitializedEntity &Entity,
  4875. const InitializationKind &Kind,
  4876. MultiExprArg Args,
  4877. bool TopLevelOfInitList,
  4878. bool TreatUnavailableAsInvalid) {
  4879. ASTContext &Context = S.Context;
  4880. // Eliminate non-overload placeholder types in the arguments. We
  4881. // need to do this before checking whether types are dependent
  4882. // because lowering a pseudo-object expression might well give us
  4883. // something of dependent type.
  4884. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  4885. if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
  4886. // FIXME: should we be doing this here?
  4887. ExprResult result = S.CheckPlaceholderExpr(Args[I]);
  4888. if (result.isInvalid()) {
  4889. SetFailed(FK_PlaceholderType);
  4890. return;
  4891. }
  4892. Args[I] = result.get();
  4893. }
  4894. // C++0x [dcl.init]p16:
  4895. // The semantics of initializers are as follows. The destination type is
  4896. // the type of the object or reference being initialized and the source
  4897. // type is the type of the initializer expression. The source type is not
  4898. // defined when the initializer is a braced-init-list or when it is a
  4899. // parenthesized list of expressions.
  4900. QualType DestType = Entity.getType();
  4901. if (DestType->isDependentType() ||
  4902. Expr::hasAnyTypeDependentArguments(Args)) {
  4903. SequenceKind = DependentSequence;
  4904. return;
  4905. }
  4906. // Almost everything is a normal sequence.
  4907. setSequenceKind(NormalSequence);
  4908. QualType SourceType;
  4909. Expr *Initializer = nullptr;
  4910. if (Args.size() == 1) {
  4911. Initializer = Args[0];
  4912. if (S.getLangOpts().ObjC) {
  4913. if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
  4914. DestType, Initializer->getType(),
  4915. Initializer) ||
  4916. S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
  4917. Args[0] = Initializer;
  4918. }
  4919. if (!isa<InitListExpr>(Initializer))
  4920. SourceType = Initializer->getType();
  4921. }
  4922. // - If the initializer is a (non-parenthesized) braced-init-list, the
  4923. // object is list-initialized (8.5.4).
  4924. if (Kind.getKind() != InitializationKind::IK_Direct) {
  4925. if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
  4926. TryListInitialization(S, Entity, Kind, InitList, *this,
  4927. TreatUnavailableAsInvalid);
  4928. return;
  4929. }
  4930. }
  4931. // - If the destination type is a reference type, see 8.5.3.
  4932. if (DestType->isReferenceType()) {
  4933. // C++0x [dcl.init.ref]p1:
  4934. // A variable declared to be a T& or T&&, that is, "reference to type T"
  4935. // (8.3.2), shall be initialized by an object, or function, of type T or
  4936. // by an object that can be converted into a T.
  4937. // (Therefore, multiple arguments are not permitted.)
  4938. if (Args.size() != 1)
  4939. SetFailed(FK_TooManyInitsForReference);
  4940. // C++17 [dcl.init.ref]p5:
  4941. // A reference [...] is initialized by an expression [...] as follows:
  4942. // If the initializer is not an expression, presumably we should reject,
  4943. // but the standard fails to actually say so.
  4944. else if (isa<InitListExpr>(Args[0]))
  4945. SetFailed(FK_ParenthesizedListInitForReference);
  4946. else
  4947. TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
  4948. return;
  4949. }
  4950. // - If the initializer is (), the object is value-initialized.
  4951. if (Kind.getKind() == InitializationKind::IK_Value ||
  4952. (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
  4953. TryValueInitialization(S, Entity, Kind, *this);
  4954. return;
  4955. }
  4956. // Handle default initialization.
  4957. if (Kind.getKind() == InitializationKind::IK_Default) {
  4958. TryDefaultInitialization(S, Entity, Kind, *this);
  4959. return;
  4960. }
  4961. // - If the destination type is an array of characters, an array of
  4962. // char16_t, an array of char32_t, or an array of wchar_t, and the
  4963. // initializer is a string literal, see 8.5.2.
  4964. // - Otherwise, if the destination type is an array, the program is
  4965. // ill-formed.
  4966. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
  4967. if (Initializer && isa<VariableArrayType>(DestAT)) {
  4968. SetFailed(FK_VariableLengthArrayHasInitializer);
  4969. return;
  4970. }
  4971. if (Initializer) {
  4972. switch (IsStringInit(Initializer, DestAT, Context)) {
  4973. case SIF_None:
  4974. TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
  4975. return;
  4976. case SIF_NarrowStringIntoWideChar:
  4977. SetFailed(FK_NarrowStringIntoWideCharArray);
  4978. return;
  4979. case SIF_WideStringIntoChar:
  4980. SetFailed(FK_WideStringIntoCharArray);
  4981. return;
  4982. case SIF_IncompatWideStringIntoWideChar:
  4983. SetFailed(FK_IncompatWideStringIntoWideChar);
  4984. return;
  4985. case SIF_PlainStringIntoUTF8Char:
  4986. SetFailed(FK_PlainStringIntoUTF8Char);
  4987. return;
  4988. case SIF_UTF8StringIntoPlainChar:
  4989. SetFailed(FK_UTF8StringIntoPlainChar);
  4990. return;
  4991. case SIF_Other:
  4992. break;
  4993. }
  4994. }
  4995. // Some kinds of initialization permit an array to be initialized from
  4996. // another array of the same type, and perform elementwise initialization.
  4997. if (Initializer && isa<ConstantArrayType>(DestAT) &&
  4998. S.Context.hasSameUnqualifiedType(Initializer->getType(),
  4999. Entity.getType()) &&
  5000. canPerformArrayCopy(Entity)) {
  5001. // If source is a prvalue, use it directly.
  5002. if (Initializer->getValueKind() == VK_RValue) {
  5003. AddArrayInitStep(DestType, /*IsGNUExtension*/false);
  5004. return;
  5005. }
  5006. // Emit element-at-a-time copy loop.
  5007. InitializedEntity Element =
  5008. InitializedEntity::InitializeElement(S.Context, 0, Entity);
  5009. QualType InitEltT =
  5010. Context.getAsArrayType(Initializer->getType())->getElementType();
  5011. OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
  5012. Initializer->getValueKind(),
  5013. Initializer->getObjectKind());
  5014. Expr *OVEAsExpr = &OVE;
  5015. InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
  5016. TreatUnavailableAsInvalid);
  5017. if (!Failed())
  5018. AddArrayInitLoopStep(Entity.getType(), InitEltT);
  5019. return;
  5020. }
  5021. // Note: as an GNU C extension, we allow initialization of an
  5022. // array from a compound literal that creates an array of the same
  5023. // type, so long as the initializer has no side effects.
  5024. if (!S.getLangOpts().CPlusPlus && Initializer &&
  5025. isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
  5026. Initializer->getType()->isArrayType()) {
  5027. const ArrayType *SourceAT
  5028. = Context.getAsArrayType(Initializer->getType());
  5029. if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
  5030. SetFailed(FK_ArrayTypeMismatch);
  5031. else if (Initializer->HasSideEffects(S.Context))
  5032. SetFailed(FK_NonConstantArrayInit);
  5033. else {
  5034. AddArrayInitStep(DestType, /*IsGNUExtension*/true);
  5035. }
  5036. }
  5037. // Note: as a GNU C++ extension, we allow list-initialization of a
  5038. // class member of array type from a parenthesized initializer list.
  5039. else if (S.getLangOpts().CPlusPlus &&
  5040. Entity.getKind() == InitializedEntity::EK_Member &&
  5041. Initializer && isa<InitListExpr>(Initializer)) {
  5042. TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
  5043. *this, TreatUnavailableAsInvalid);
  5044. AddParenthesizedArrayInitStep(DestType);
  5045. } else if (DestAT->getElementType()->isCharType())
  5046. SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
  5047. else if (IsWideCharCompatible(DestAT->getElementType(), Context))
  5048. SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
  5049. else
  5050. SetFailed(FK_ArrayNeedsInitList);
  5051. return;
  5052. }
  5053. // Determine whether we should consider writeback conversions for
  5054. // Objective-C ARC.
  5055. bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
  5056. Entity.isParameterKind();
  5057. if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
  5058. return;
  5059. // We're at the end of the line for C: it's either a write-back conversion
  5060. // or it's a C assignment. There's no need to check anything else.
  5061. if (!S.getLangOpts().CPlusPlus) {
  5062. // If allowed, check whether this is an Objective-C writeback conversion.
  5063. if (allowObjCWritebackConversion &&
  5064. tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
  5065. return;
  5066. }
  5067. if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
  5068. return;
  5069. // Handle initialization in C
  5070. AddCAssignmentStep(DestType);
  5071. MaybeProduceObjCObject(S, *this, Entity);
  5072. return;
  5073. }
  5074. assert(S.getLangOpts().CPlusPlus);
  5075. // - If the destination type is a (possibly cv-qualified) class type:
  5076. if (DestType->isRecordType()) {
  5077. // - If the initialization is direct-initialization, or if it is
  5078. // copy-initialization where the cv-unqualified version of the
  5079. // source type is the same class as, or a derived class of, the
  5080. // class of the destination, constructors are considered. [...]
  5081. if (Kind.getKind() == InitializationKind::IK_Direct ||
  5082. (Kind.getKind() == InitializationKind::IK_Copy &&
  5083. (Context.hasSameUnqualifiedType(SourceType, DestType) ||
  5084. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
  5085. TryConstructorInitialization(S, Entity, Kind, Args,
  5086. DestType, DestType, *this);
  5087. // - Otherwise (i.e., for the remaining copy-initialization cases),
  5088. // user-defined conversion sequences that can convert from the source
  5089. // type to the destination type or (when a conversion function is
  5090. // used) to a derived class thereof are enumerated as described in
  5091. // 13.3.1.4, and the best one is chosen through overload resolution
  5092. // (13.3).
  5093. else
  5094. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5095. TopLevelOfInitList);
  5096. return;
  5097. }
  5098. assert(Args.size() >= 1 && "Zero-argument case handled above");
  5099. // The remaining cases all need a source type.
  5100. if (Args.size() > 1) {
  5101. SetFailed(FK_TooManyInitsForScalar);
  5102. return;
  5103. } else if (isa<InitListExpr>(Args[0])) {
  5104. SetFailed(FK_ParenthesizedListInitForScalar);
  5105. return;
  5106. }
  5107. // - Otherwise, if the source type is a (possibly cv-qualified) class
  5108. // type, conversion functions are considered.
  5109. if (!SourceType.isNull() && SourceType->isRecordType()) {
  5110. // For a conversion to _Atomic(T) from either T or a class type derived
  5111. // from T, initialize the T object then convert to _Atomic type.
  5112. bool NeedAtomicConversion = false;
  5113. if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
  5114. if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
  5115. S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
  5116. Atomic->getValueType())) {
  5117. DestType = Atomic->getValueType();
  5118. NeedAtomicConversion = true;
  5119. }
  5120. }
  5121. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  5122. TopLevelOfInitList);
  5123. MaybeProduceObjCObject(S, *this, Entity);
  5124. if (!Failed() && NeedAtomicConversion)
  5125. AddAtomicConversionStep(Entity.getType());
  5126. return;
  5127. }
  5128. // - Otherwise, the initial value of the object being initialized is the
  5129. // (possibly converted) value of the initializer expression. Standard
  5130. // conversions (Clause 4) will be used, if necessary, to convert the
  5131. // initializer expression to the cv-unqualified version of the
  5132. // destination type; no user-defined conversions are considered.
  5133. ImplicitConversionSequence ICS
  5134. = S.TryImplicitConversion(Initializer, DestType,
  5135. /*SuppressUserConversions*/true,
  5136. /*AllowExplicitConversions*/ false,
  5137. /*InOverloadResolution*/ false,
  5138. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  5139. allowObjCWritebackConversion);
  5140. if (ICS.isStandard() &&
  5141. ICS.Standard.Second == ICK_Writeback_Conversion) {
  5142. // Objective-C ARC writeback conversion.
  5143. // We should copy unless we're passing to an argument explicitly
  5144. // marked 'out'.
  5145. bool ShouldCopy = true;
  5146. if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  5147. ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  5148. // If there was an lvalue adjustment, add it as a separate conversion.
  5149. if (ICS.Standard.First == ICK_Array_To_Pointer ||
  5150. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5151. ImplicitConversionSequence LvalueICS;
  5152. LvalueICS.setStandard();
  5153. LvalueICS.Standard.setAsIdentityConversion();
  5154. LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
  5155. LvalueICS.Standard.First = ICS.Standard.First;
  5156. AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
  5157. }
  5158. AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
  5159. } else if (ICS.isBad()) {
  5160. DeclAccessPair dap;
  5161. if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
  5162. AddZeroInitializationStep(Entity.getType());
  5163. } else if (Initializer->getType() == Context.OverloadTy &&
  5164. !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
  5165. false, dap))
  5166. SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  5167. else if (Initializer->getType()->isFunctionType() &&
  5168. isExprAnUnaddressableFunction(S, Initializer))
  5169. SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
  5170. else
  5171. SetFailed(InitializationSequence::FK_ConversionFailed);
  5172. } else {
  5173. AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  5174. MaybeProduceObjCObject(S, *this, Entity);
  5175. }
  5176. }
  5177. InitializationSequence::~InitializationSequence() {
  5178. for (auto &S : Steps)
  5179. S.Destroy();
  5180. }
  5181. //===----------------------------------------------------------------------===//
  5182. // Perform initialization
  5183. //===----------------------------------------------------------------------===//
  5184. static Sema::AssignmentAction
  5185. getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
  5186. switch(Entity.getKind()) {
  5187. case InitializedEntity::EK_Variable:
  5188. case InitializedEntity::EK_New:
  5189. case InitializedEntity::EK_Exception:
  5190. case InitializedEntity::EK_Base:
  5191. case InitializedEntity::EK_Delegating:
  5192. return Sema::AA_Initializing;
  5193. case InitializedEntity::EK_Parameter:
  5194. if (Entity.getDecl() &&
  5195. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5196. return Sema::AA_Sending;
  5197. return Sema::AA_Passing;
  5198. case InitializedEntity::EK_Parameter_CF_Audited:
  5199. if (Entity.getDecl() &&
  5200. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  5201. return Sema::AA_Sending;
  5202. return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
  5203. case InitializedEntity::EK_Result:
  5204. case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
  5205. return Sema::AA_Returning;
  5206. case InitializedEntity::EK_Temporary:
  5207. case InitializedEntity::EK_RelatedResult:
  5208. // FIXME: Can we tell apart casting vs. converting?
  5209. return Sema::AA_Casting;
  5210. case InitializedEntity::EK_Member:
  5211. case InitializedEntity::EK_Binding:
  5212. case InitializedEntity::EK_ArrayElement:
  5213. case InitializedEntity::EK_VectorElement:
  5214. case InitializedEntity::EK_ComplexElement:
  5215. case InitializedEntity::EK_BlockElement:
  5216. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5217. case InitializedEntity::EK_LambdaCapture:
  5218. case InitializedEntity::EK_CompoundLiteralInit:
  5219. return Sema::AA_Initializing;
  5220. }
  5221. llvm_unreachable("Invalid EntityKind!");
  5222. }
  5223. /// Whether we should bind a created object as a temporary when
  5224. /// initializing the given entity.
  5225. static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
  5226. switch (Entity.getKind()) {
  5227. case InitializedEntity::EK_ArrayElement:
  5228. case InitializedEntity::EK_Member:
  5229. case InitializedEntity::EK_Result:
  5230. case InitializedEntity::EK_StmtExprResult:
  5231. case InitializedEntity::EK_New:
  5232. case InitializedEntity::EK_Variable:
  5233. case InitializedEntity::EK_Base:
  5234. case InitializedEntity::EK_Delegating:
  5235. case InitializedEntity::EK_VectorElement:
  5236. case InitializedEntity::EK_ComplexElement:
  5237. case InitializedEntity::EK_Exception:
  5238. case InitializedEntity::EK_BlockElement:
  5239. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5240. case InitializedEntity::EK_LambdaCapture:
  5241. case InitializedEntity::EK_CompoundLiteralInit:
  5242. return false;
  5243. case InitializedEntity::EK_Parameter:
  5244. case InitializedEntity::EK_Parameter_CF_Audited:
  5245. case InitializedEntity::EK_Temporary:
  5246. case InitializedEntity::EK_RelatedResult:
  5247. case InitializedEntity::EK_Binding:
  5248. return true;
  5249. }
  5250. llvm_unreachable("missed an InitializedEntity kind?");
  5251. }
  5252. /// Whether the given entity, when initialized with an object
  5253. /// created for that initialization, requires destruction.
  5254. static bool shouldDestroyEntity(const InitializedEntity &Entity) {
  5255. switch (Entity.getKind()) {
  5256. case InitializedEntity::EK_Result:
  5257. case InitializedEntity::EK_StmtExprResult:
  5258. case InitializedEntity::EK_New:
  5259. case InitializedEntity::EK_Base:
  5260. case InitializedEntity::EK_Delegating:
  5261. case InitializedEntity::EK_VectorElement:
  5262. case InitializedEntity::EK_ComplexElement:
  5263. case InitializedEntity::EK_BlockElement:
  5264. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5265. case InitializedEntity::EK_LambdaCapture:
  5266. return false;
  5267. case InitializedEntity::EK_Member:
  5268. case InitializedEntity::EK_Binding:
  5269. case InitializedEntity::EK_Variable:
  5270. case InitializedEntity::EK_Parameter:
  5271. case InitializedEntity::EK_Parameter_CF_Audited:
  5272. case InitializedEntity::EK_Temporary:
  5273. case InitializedEntity::EK_ArrayElement:
  5274. case InitializedEntity::EK_Exception:
  5275. case InitializedEntity::EK_CompoundLiteralInit:
  5276. case InitializedEntity::EK_RelatedResult:
  5277. return true;
  5278. }
  5279. llvm_unreachable("missed an InitializedEntity kind?");
  5280. }
  5281. /// Get the location at which initialization diagnostics should appear.
  5282. static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
  5283. Expr *Initializer) {
  5284. switch (Entity.getKind()) {
  5285. case InitializedEntity::EK_Result:
  5286. case InitializedEntity::EK_StmtExprResult:
  5287. return Entity.getReturnLoc();
  5288. case InitializedEntity::EK_Exception:
  5289. return Entity.getThrowLoc();
  5290. case InitializedEntity::EK_Variable:
  5291. case InitializedEntity::EK_Binding:
  5292. return Entity.getDecl()->getLocation();
  5293. case InitializedEntity::EK_LambdaCapture:
  5294. return Entity.getCaptureLoc();
  5295. case InitializedEntity::EK_ArrayElement:
  5296. case InitializedEntity::EK_Member:
  5297. case InitializedEntity::EK_Parameter:
  5298. case InitializedEntity::EK_Parameter_CF_Audited:
  5299. case InitializedEntity::EK_Temporary:
  5300. case InitializedEntity::EK_New:
  5301. case InitializedEntity::EK_Base:
  5302. case InitializedEntity::EK_Delegating:
  5303. case InitializedEntity::EK_VectorElement:
  5304. case InitializedEntity::EK_ComplexElement:
  5305. case InitializedEntity::EK_BlockElement:
  5306. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5307. case InitializedEntity::EK_CompoundLiteralInit:
  5308. case InitializedEntity::EK_RelatedResult:
  5309. return Initializer->getBeginLoc();
  5310. }
  5311. llvm_unreachable("missed an InitializedEntity kind?");
  5312. }
  5313. /// Make a (potentially elidable) temporary copy of the object
  5314. /// provided by the given initializer by calling the appropriate copy
  5315. /// constructor.
  5316. ///
  5317. /// \param S The Sema object used for type-checking.
  5318. ///
  5319. /// \param T The type of the temporary object, which must either be
  5320. /// the type of the initializer expression or a superclass thereof.
  5321. ///
  5322. /// \param Entity The entity being initialized.
  5323. ///
  5324. /// \param CurInit The initializer expression.
  5325. ///
  5326. /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
  5327. /// is permitted in C++03 (but not C++0x) when binding a reference to
  5328. /// an rvalue.
  5329. ///
  5330. /// \returns An expression that copies the initializer expression into
  5331. /// a temporary object, or an error expression if a copy could not be
  5332. /// created.
  5333. static ExprResult CopyObject(Sema &S,
  5334. QualType T,
  5335. const InitializedEntity &Entity,
  5336. ExprResult CurInit,
  5337. bool IsExtraneousCopy) {
  5338. if (CurInit.isInvalid())
  5339. return CurInit;
  5340. // Determine which class type we're copying to.
  5341. Expr *CurInitExpr = (Expr *)CurInit.get();
  5342. CXXRecordDecl *Class = nullptr;
  5343. if (const RecordType *Record = T->getAs<RecordType>())
  5344. Class = cast<CXXRecordDecl>(Record->getDecl());
  5345. if (!Class)
  5346. return CurInit;
  5347. SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
  5348. // Make sure that the type we are copying is complete.
  5349. if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
  5350. return CurInit;
  5351. // Perform overload resolution using the class's constructors. Per
  5352. // C++11 [dcl.init]p16, second bullet for class types, this initialization
  5353. // is direct-initialization.
  5354. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5355. DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
  5356. OverloadCandidateSet::iterator Best;
  5357. switch (ResolveConstructorOverload(
  5358. S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
  5359. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  5360. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  5361. /*SecondStepOfCopyInit=*/true)) {
  5362. case OR_Success:
  5363. break;
  5364. case OR_No_Viable_Function:
  5365. CandidateSet.NoteCandidates(
  5366. PartialDiagnosticAt(
  5367. Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
  5368. ? diag::ext_rvalue_to_reference_temp_copy_no_viable
  5369. : diag::err_temp_copy_no_viable)
  5370. << (int)Entity.getKind() << CurInitExpr->getType()
  5371. << CurInitExpr->getSourceRange()),
  5372. S, OCD_AllCandidates, CurInitExpr);
  5373. if (!IsExtraneousCopy || S.isSFINAEContext())
  5374. return ExprError();
  5375. return CurInit;
  5376. case OR_Ambiguous:
  5377. CandidateSet.NoteCandidates(
  5378. PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
  5379. << (int)Entity.getKind()
  5380. << CurInitExpr->getType()
  5381. << CurInitExpr->getSourceRange()),
  5382. S, OCD_ViableCandidates, CurInitExpr);
  5383. return ExprError();
  5384. case OR_Deleted:
  5385. S.Diag(Loc, diag::err_temp_copy_deleted)
  5386. << (int)Entity.getKind() << CurInitExpr->getType()
  5387. << CurInitExpr->getSourceRange();
  5388. S.NoteDeletedFunction(Best->Function);
  5389. return ExprError();
  5390. }
  5391. bool HadMultipleCandidates = CandidateSet.size() > 1;
  5392. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  5393. SmallVector<Expr*, 8> ConstructorArgs;
  5394. CurInit.get(); // Ownership transferred into MultiExprArg, below.
  5395. S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
  5396. IsExtraneousCopy);
  5397. if (IsExtraneousCopy) {
  5398. // If this is a totally extraneous copy for C++03 reference
  5399. // binding purposes, just return the original initialization
  5400. // expression. We don't generate an (elided) copy operation here
  5401. // because doing so would require us to pass down a flag to avoid
  5402. // infinite recursion, where each step adds another extraneous,
  5403. // elidable copy.
  5404. // Instantiate the default arguments of any extra parameters in
  5405. // the selected copy constructor, as if we were going to create a
  5406. // proper call to the copy constructor.
  5407. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
  5408. ParmVarDecl *Parm = Constructor->getParamDecl(I);
  5409. if (S.RequireCompleteType(Loc, Parm->getType(),
  5410. diag::err_call_incomplete_argument))
  5411. break;
  5412. // Build the default argument expression; we don't actually care
  5413. // if this succeeds or not, because this routine will complain
  5414. // if there was a problem.
  5415. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
  5416. }
  5417. return CurInitExpr;
  5418. }
  5419. // Determine the arguments required to actually perform the
  5420. // constructor call (we might have derived-to-base conversions, or
  5421. // the copy constructor may have default arguments).
  5422. if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
  5423. return ExprError();
  5424. // C++0x [class.copy]p32:
  5425. // When certain criteria are met, an implementation is allowed to
  5426. // omit the copy/move construction of a class object, even if the
  5427. // copy/move constructor and/or destructor for the object have
  5428. // side effects. [...]
  5429. // - when a temporary class object that has not been bound to a
  5430. // reference (12.2) would be copied/moved to a class object
  5431. // with the same cv-unqualified type, the copy/move operation
  5432. // can be omitted by constructing the temporary object
  5433. // directly into the target of the omitted copy/move
  5434. //
  5435. // Note that the other three bullets are handled elsewhere. Copy
  5436. // elision for return statements and throw expressions are handled as part
  5437. // of constructor initialization, while copy elision for exception handlers
  5438. // is handled by the run-time.
  5439. //
  5440. // FIXME: If the function parameter is not the same type as the temporary, we
  5441. // should still be able to elide the copy, but we don't have a way to
  5442. // represent in the AST how much should be elided in this case.
  5443. bool Elidable =
  5444. CurInitExpr->isTemporaryObject(S.Context, Class) &&
  5445. S.Context.hasSameUnqualifiedType(
  5446. Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
  5447. CurInitExpr->getType());
  5448. // Actually perform the constructor call.
  5449. CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
  5450. Elidable,
  5451. ConstructorArgs,
  5452. HadMultipleCandidates,
  5453. /*ListInit*/ false,
  5454. /*StdInitListInit*/ false,
  5455. /*ZeroInit*/ false,
  5456. CXXConstructExpr::CK_Complete,
  5457. SourceRange());
  5458. // If we're supposed to bind temporaries, do so.
  5459. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
  5460. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  5461. return CurInit;
  5462. }
  5463. /// Check whether elidable copy construction for binding a reference to
  5464. /// a temporary would have succeeded if we were building in C++98 mode, for
  5465. /// -Wc++98-compat.
  5466. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  5467. const InitializedEntity &Entity,
  5468. Expr *CurInitExpr) {
  5469. assert(S.getLangOpts().CPlusPlus11);
  5470. const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
  5471. if (!Record)
  5472. return;
  5473. SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
  5474. if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
  5475. return;
  5476. // Find constructors which would have been considered.
  5477. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5478. DeclContext::lookup_result Ctors =
  5479. S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
  5480. // Perform overload resolution.
  5481. OverloadCandidateSet::iterator Best;
  5482. OverloadingResult OR = ResolveConstructorOverload(
  5483. S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
  5484. /*CopyInitializing=*/false, /*AllowExplicit=*/true,
  5485. /*OnlyListConstructors=*/false, /*IsListInit=*/false,
  5486. /*SecondStepOfCopyInit=*/true);
  5487. PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
  5488. << OR << (int)Entity.getKind() << CurInitExpr->getType()
  5489. << CurInitExpr->getSourceRange();
  5490. switch (OR) {
  5491. case OR_Success:
  5492. S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
  5493. Best->FoundDecl, Entity, Diag);
  5494. // FIXME: Check default arguments as far as that's possible.
  5495. break;
  5496. case OR_No_Viable_Function:
  5497. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  5498. OCD_AllCandidates, CurInitExpr);
  5499. break;
  5500. case OR_Ambiguous:
  5501. CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
  5502. OCD_ViableCandidates, CurInitExpr);
  5503. break;
  5504. case OR_Deleted:
  5505. S.Diag(Loc, Diag);
  5506. S.NoteDeletedFunction(Best->Function);
  5507. break;
  5508. }
  5509. }
  5510. void InitializationSequence::PrintInitLocationNote(Sema &S,
  5511. const InitializedEntity &Entity) {
  5512. if (Entity.isParameterKind() && Entity.getDecl()) {
  5513. if (Entity.getDecl()->getLocation().isInvalid())
  5514. return;
  5515. if (Entity.getDecl()->getDeclName())
  5516. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
  5517. << Entity.getDecl()->getDeclName();
  5518. else
  5519. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
  5520. }
  5521. else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
  5522. Entity.getMethodDecl())
  5523. S.Diag(Entity.getMethodDecl()->getLocation(),
  5524. diag::note_method_return_type_change)
  5525. << Entity.getMethodDecl()->getDeclName();
  5526. }
  5527. /// Returns true if the parameters describe a constructor initialization of
  5528. /// an explicit temporary object, e.g. "Point(x, y)".
  5529. static bool isExplicitTemporary(const InitializedEntity &Entity,
  5530. const InitializationKind &Kind,
  5531. unsigned NumArgs) {
  5532. switch (Entity.getKind()) {
  5533. case InitializedEntity::EK_Temporary:
  5534. case InitializedEntity::EK_CompoundLiteralInit:
  5535. case InitializedEntity::EK_RelatedResult:
  5536. break;
  5537. default:
  5538. return false;
  5539. }
  5540. switch (Kind.getKind()) {
  5541. case InitializationKind::IK_DirectList:
  5542. return true;
  5543. // FIXME: Hack to work around cast weirdness.
  5544. case InitializationKind::IK_Direct:
  5545. case InitializationKind::IK_Value:
  5546. return NumArgs != 1;
  5547. default:
  5548. return false;
  5549. }
  5550. }
  5551. static ExprResult
  5552. PerformConstructorInitialization(Sema &S,
  5553. const InitializedEntity &Entity,
  5554. const InitializationKind &Kind,
  5555. MultiExprArg Args,
  5556. const InitializationSequence::Step& Step,
  5557. bool &ConstructorInitRequiresZeroInit,
  5558. bool IsListInitialization,
  5559. bool IsStdInitListInitialization,
  5560. SourceLocation LBraceLoc,
  5561. SourceLocation RBraceLoc) {
  5562. unsigned NumArgs = Args.size();
  5563. CXXConstructorDecl *Constructor
  5564. = cast<CXXConstructorDecl>(Step.Function.Function);
  5565. bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
  5566. // Build a call to the selected constructor.
  5567. SmallVector<Expr*, 8> ConstructorArgs;
  5568. SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
  5569. ? Kind.getEqualLoc()
  5570. : Kind.getLocation();
  5571. if (Kind.getKind() == InitializationKind::IK_Default) {
  5572. // Force even a trivial, implicit default constructor to be
  5573. // semantically checked. We do this explicitly because we don't build
  5574. // the definition for completely trivial constructors.
  5575. assert(Constructor->getParent() && "No parent class for constructor.");
  5576. if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  5577. Constructor->isTrivial() && !Constructor->isUsed(false)) {
  5578. S.runWithSufficientStackSpace(Loc, [&] {
  5579. S.DefineImplicitDefaultConstructor(Loc, Constructor);
  5580. });
  5581. }
  5582. }
  5583. ExprResult CurInit((Expr *)nullptr);
  5584. // C++ [over.match.copy]p1:
  5585. // - When initializing a temporary to be bound to the first parameter
  5586. // of a constructor that takes a reference to possibly cv-qualified
  5587. // T as its first argument, called with a single argument in the
  5588. // context of direct-initialization, explicit conversion functions
  5589. // are also considered.
  5590. bool AllowExplicitConv =
  5591. Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
  5592. hasCopyOrMoveCtorParam(S.Context,
  5593. getConstructorInfo(Step.Function.FoundDecl));
  5594. // Determine the arguments required to actually perform the constructor
  5595. // call.
  5596. if (S.CompleteConstructorCall(Constructor, Args,
  5597. Loc, ConstructorArgs,
  5598. AllowExplicitConv,
  5599. IsListInitialization))
  5600. return ExprError();
  5601. if (isExplicitTemporary(Entity, Kind, NumArgs)) {
  5602. // An explicitly-constructed temporary, e.g., X(1, 2).
  5603. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  5604. return ExprError();
  5605. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  5606. if (!TSInfo)
  5607. TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
  5608. SourceRange ParenOrBraceRange =
  5609. (Kind.getKind() == InitializationKind::IK_DirectList)
  5610. ? SourceRange(LBraceLoc, RBraceLoc)
  5611. : Kind.getParenOrBraceRange();
  5612. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
  5613. Step.Function.FoundDecl.getDecl())) {
  5614. Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
  5615. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  5616. return ExprError();
  5617. }
  5618. S.MarkFunctionReferenced(Loc, Constructor);
  5619. CurInit = CXXTemporaryObjectExpr::Create(
  5620. S.Context, Constructor,
  5621. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  5622. ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
  5623. IsListInitialization, IsStdInitListInitialization,
  5624. ConstructorInitRequiresZeroInit);
  5625. } else {
  5626. CXXConstructExpr::ConstructionKind ConstructKind =
  5627. CXXConstructExpr::CK_Complete;
  5628. if (Entity.getKind() == InitializedEntity::EK_Base) {
  5629. ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
  5630. CXXConstructExpr::CK_VirtualBase :
  5631. CXXConstructExpr::CK_NonVirtualBase;
  5632. } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
  5633. ConstructKind = CXXConstructExpr::CK_Delegating;
  5634. }
  5635. // Only get the parenthesis or brace range if it is a list initialization or
  5636. // direct construction.
  5637. SourceRange ParenOrBraceRange;
  5638. if (IsListInitialization)
  5639. ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
  5640. else if (Kind.getKind() == InitializationKind::IK_Direct)
  5641. ParenOrBraceRange = Kind.getParenOrBraceRange();
  5642. // If the entity allows NRVO, mark the construction as elidable
  5643. // unconditionally.
  5644. if (Entity.allowsNRVO())
  5645. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  5646. Step.Function.FoundDecl,
  5647. Constructor, /*Elidable=*/true,
  5648. ConstructorArgs,
  5649. HadMultipleCandidates,
  5650. IsListInitialization,
  5651. IsStdInitListInitialization,
  5652. ConstructorInitRequiresZeroInit,
  5653. ConstructKind,
  5654. ParenOrBraceRange);
  5655. else
  5656. CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
  5657. Step.Function.FoundDecl,
  5658. Constructor,
  5659. ConstructorArgs,
  5660. HadMultipleCandidates,
  5661. IsListInitialization,
  5662. IsStdInitListInitialization,
  5663. ConstructorInitRequiresZeroInit,
  5664. ConstructKind,
  5665. ParenOrBraceRange);
  5666. }
  5667. if (CurInit.isInvalid())
  5668. return ExprError();
  5669. // Only check access if all of that succeeded.
  5670. S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
  5671. if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
  5672. return ExprError();
  5673. if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
  5674. if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
  5675. return ExprError();
  5676. if (shouldBindAsTemporary(Entity))
  5677. CurInit = S.MaybeBindToTemporary(CurInit.get());
  5678. return CurInit;
  5679. }
  5680. namespace {
  5681. enum LifetimeKind {
  5682. /// The lifetime of a temporary bound to this entity ends at the end of the
  5683. /// full-expression, and that's (probably) fine.
  5684. LK_FullExpression,
  5685. /// The lifetime of a temporary bound to this entity is extended to the
  5686. /// lifeitme of the entity itself.
  5687. LK_Extended,
  5688. /// The lifetime of a temporary bound to this entity probably ends too soon,
  5689. /// because the entity is allocated in a new-expression.
  5690. LK_New,
  5691. /// The lifetime of a temporary bound to this entity ends too soon, because
  5692. /// the entity is a return object.
  5693. LK_Return,
  5694. /// The lifetime of a temporary bound to this entity ends too soon, because
  5695. /// the entity is the result of a statement expression.
  5696. LK_StmtExprResult,
  5697. /// This is a mem-initializer: if it would extend a temporary (other than via
  5698. /// a default member initializer), the program is ill-formed.
  5699. LK_MemInitializer,
  5700. };
  5701. using LifetimeResult =
  5702. llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
  5703. }
  5704. /// Determine the declaration which an initialized entity ultimately refers to,
  5705. /// for the purpose of lifetime-extending a temporary bound to a reference in
  5706. /// the initialization of \p Entity.
  5707. static LifetimeResult getEntityLifetime(
  5708. const InitializedEntity *Entity,
  5709. const InitializedEntity *InitField = nullptr) {
  5710. // C++11 [class.temporary]p5:
  5711. switch (Entity->getKind()) {
  5712. case InitializedEntity::EK_Variable:
  5713. // The temporary [...] persists for the lifetime of the reference
  5714. return {Entity, LK_Extended};
  5715. case InitializedEntity::EK_Member:
  5716. // For subobjects, we look at the complete object.
  5717. if (Entity->getParent())
  5718. return getEntityLifetime(Entity->getParent(), Entity);
  5719. // except:
  5720. // C++17 [class.base.init]p8:
  5721. // A temporary expression bound to a reference member in a
  5722. // mem-initializer is ill-formed.
  5723. // C++17 [class.base.init]p11:
  5724. // A temporary expression bound to a reference member from a
  5725. // default member initializer is ill-formed.
  5726. //
  5727. // The context of p11 and its example suggest that it's only the use of a
  5728. // default member initializer from a constructor that makes the program
  5729. // ill-formed, not its mere existence, and that it can even be used by
  5730. // aggregate initialization.
  5731. return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
  5732. : LK_MemInitializer};
  5733. case InitializedEntity::EK_Binding:
  5734. // Per [dcl.decomp]p3, the binding is treated as a variable of reference
  5735. // type.
  5736. return {Entity, LK_Extended};
  5737. case InitializedEntity::EK_Parameter:
  5738. case InitializedEntity::EK_Parameter_CF_Audited:
  5739. // -- A temporary bound to a reference parameter in a function call
  5740. // persists until the completion of the full-expression containing
  5741. // the call.
  5742. return {nullptr, LK_FullExpression};
  5743. case InitializedEntity::EK_Result:
  5744. // -- The lifetime of a temporary bound to the returned value in a
  5745. // function return statement is not extended; the temporary is
  5746. // destroyed at the end of the full-expression in the return statement.
  5747. return {nullptr, LK_Return};
  5748. case InitializedEntity::EK_StmtExprResult:
  5749. // FIXME: Should we lifetime-extend through the result of a statement
  5750. // expression?
  5751. return {nullptr, LK_StmtExprResult};
  5752. case InitializedEntity::EK_New:
  5753. // -- A temporary bound to a reference in a new-initializer persists
  5754. // until the completion of the full-expression containing the
  5755. // new-initializer.
  5756. return {nullptr, LK_New};
  5757. case InitializedEntity::EK_Temporary:
  5758. case InitializedEntity::EK_CompoundLiteralInit:
  5759. case InitializedEntity::EK_RelatedResult:
  5760. // We don't yet know the storage duration of the surrounding temporary.
  5761. // Assume it's got full-expression duration for now, it will patch up our
  5762. // storage duration if that's not correct.
  5763. return {nullptr, LK_FullExpression};
  5764. case InitializedEntity::EK_ArrayElement:
  5765. // For subobjects, we look at the complete object.
  5766. return getEntityLifetime(Entity->getParent(), InitField);
  5767. case InitializedEntity::EK_Base:
  5768. // For subobjects, we look at the complete object.
  5769. if (Entity->getParent())
  5770. return getEntityLifetime(Entity->getParent(), InitField);
  5771. return {InitField, LK_MemInitializer};
  5772. case InitializedEntity::EK_Delegating:
  5773. // We can reach this case for aggregate initialization in a constructor:
  5774. // struct A { int &&r; };
  5775. // struct B : A { B() : A{0} {} };
  5776. // In this case, use the outermost field decl as the context.
  5777. return {InitField, LK_MemInitializer};
  5778. case InitializedEntity::EK_BlockElement:
  5779. case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
  5780. case InitializedEntity::EK_LambdaCapture:
  5781. case InitializedEntity::EK_VectorElement:
  5782. case InitializedEntity::EK_ComplexElement:
  5783. return {nullptr, LK_FullExpression};
  5784. case InitializedEntity::EK_Exception:
  5785. // FIXME: Can we diagnose lifetime problems with exceptions?
  5786. return {nullptr, LK_FullExpression};
  5787. }
  5788. llvm_unreachable("unknown entity kind");
  5789. }
  5790. namespace {
  5791. enum ReferenceKind {
  5792. /// Lifetime would be extended by a reference binding to a temporary.
  5793. RK_ReferenceBinding,
  5794. /// Lifetime would be extended by a std::initializer_list object binding to
  5795. /// its backing array.
  5796. RK_StdInitializerList,
  5797. };
  5798. /// A temporary or local variable. This will be one of:
  5799. /// * A MaterializeTemporaryExpr.
  5800. /// * A DeclRefExpr whose declaration is a local.
  5801. /// * An AddrLabelExpr.
  5802. /// * A BlockExpr for a block with captures.
  5803. using Local = Expr*;
  5804. /// Expressions we stepped over when looking for the local state. Any steps
  5805. /// that would inhibit lifetime extension or take us out of subexpressions of
  5806. /// the initializer are included.
  5807. struct IndirectLocalPathEntry {
  5808. enum EntryKind {
  5809. DefaultInit,
  5810. AddressOf,
  5811. VarInit,
  5812. LValToRVal,
  5813. LifetimeBoundCall,
  5814. GslPointerInit
  5815. } Kind;
  5816. Expr *E;
  5817. const Decl *D = nullptr;
  5818. IndirectLocalPathEntry() {}
  5819. IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
  5820. IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
  5821. : Kind(K), E(E), D(D) {}
  5822. };
  5823. using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
  5824. struct RevertToOldSizeRAII {
  5825. IndirectLocalPath &Path;
  5826. unsigned OldSize = Path.size();
  5827. RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
  5828. ~RevertToOldSizeRAII() { Path.resize(OldSize); }
  5829. };
  5830. using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
  5831. ReferenceKind RK)>;
  5832. }
  5833. static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
  5834. for (auto E : Path)
  5835. if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
  5836. return true;
  5837. return false;
  5838. }
  5839. static bool pathContainsInit(IndirectLocalPath &Path) {
  5840. return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
  5841. return E.Kind == IndirectLocalPathEntry::DefaultInit ||
  5842. E.Kind == IndirectLocalPathEntry::VarInit;
  5843. });
  5844. }
  5845. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  5846. Expr *Init, LocalVisitor Visit,
  5847. bool RevisitSubinits,
  5848. bool EnableLifetimeWarnings);
  5849. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  5850. Expr *Init, ReferenceKind RK,
  5851. LocalVisitor Visit,
  5852. bool EnableLifetimeWarnings);
  5853. template <typename T> static bool isRecordWithAttr(QualType Type) {
  5854. if (auto *RD = Type->getAsCXXRecordDecl())
  5855. return RD->getCanonicalDecl()->hasAttr<T>();
  5856. return false;
  5857. }
  5858. // Decl::isInStdNamespace will return false for iterators in some STL
  5859. // implementations due to them being defined in a namespace outside of the std
  5860. // namespace.
  5861. static bool isInStlNamespace(const Decl *D) {
  5862. const DeclContext *DC = D->getDeclContext();
  5863. if (!DC)
  5864. return false;
  5865. if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
  5866. if (const IdentifierInfo *II = ND->getIdentifier()) {
  5867. StringRef Name = II->getName();
  5868. if (Name.size() >= 2 && Name.front() == '_' &&
  5869. (Name[1] == '_' || isUppercase(Name[1])))
  5870. return true;
  5871. }
  5872. return DC->isStdNamespace();
  5873. }
  5874. static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
  5875. if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
  5876. if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
  5877. return true;
  5878. if (!isInStlNamespace(Callee->getParent()))
  5879. return false;
  5880. if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
  5881. !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
  5882. return false;
  5883. if (Callee->getReturnType()->isPointerType() ||
  5884. isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
  5885. if (!Callee->getIdentifier())
  5886. return false;
  5887. return llvm::StringSwitch<bool>(Callee->getName())
  5888. .Cases("begin", "rbegin", "cbegin", "crbegin", true)
  5889. .Cases("end", "rend", "cend", "crend", true)
  5890. .Cases("c_str", "data", "get", true)
  5891. // Map and set types.
  5892. .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
  5893. .Default(false);
  5894. } else if (Callee->getReturnType()->isReferenceType()) {
  5895. if (!Callee->getIdentifier()) {
  5896. auto OO = Callee->getOverloadedOperator();
  5897. return OO == OverloadedOperatorKind::OO_Subscript ||
  5898. OO == OverloadedOperatorKind::OO_Star;
  5899. }
  5900. return llvm::StringSwitch<bool>(Callee->getName())
  5901. .Cases("front", "back", "at", "top", "value", true)
  5902. .Default(false);
  5903. }
  5904. return false;
  5905. }
  5906. static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
  5907. if (!FD->getIdentifier() || FD->getNumParams() != 1)
  5908. return false;
  5909. const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
  5910. if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
  5911. return false;
  5912. if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
  5913. !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
  5914. return false;
  5915. if (FD->getReturnType()->isPointerType() ||
  5916. isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
  5917. return llvm::StringSwitch<bool>(FD->getName())
  5918. .Cases("begin", "rbegin", "cbegin", "crbegin", true)
  5919. .Cases("end", "rend", "cend", "crend", true)
  5920. .Case("data", true)
  5921. .Default(false);
  5922. } else if (FD->getReturnType()->isReferenceType()) {
  5923. return llvm::StringSwitch<bool>(FD->getName())
  5924. .Cases("get", "any_cast", true)
  5925. .Default(false);
  5926. }
  5927. return false;
  5928. }
  5929. static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
  5930. LocalVisitor Visit) {
  5931. auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
  5932. Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
  5933. if (Arg->isGLValue())
  5934. visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
  5935. Visit,
  5936. /*EnableLifetimeWarnings=*/true);
  5937. else
  5938. visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
  5939. /*EnableLifetimeWarnings=*/true);
  5940. Path.pop_back();
  5941. };
  5942. if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
  5943. const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
  5944. if (MD && shouldTrackImplicitObjectArg(MD))
  5945. VisitPointerArg(MD, MCE->getImplicitObjectArgument());
  5946. return;
  5947. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
  5948. FunctionDecl *Callee = OCE->getDirectCallee();
  5949. if (Callee && Callee->isCXXInstanceMember() &&
  5950. shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
  5951. VisitPointerArg(Callee, OCE->getArg(0));
  5952. return;
  5953. } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
  5954. FunctionDecl *Callee = CE->getDirectCallee();
  5955. if (Callee && shouldTrackFirstArgument(Callee))
  5956. VisitPointerArg(Callee, CE->getArg(0));
  5957. return;
  5958. }
  5959. if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
  5960. const auto *Ctor = CCE->getConstructor();
  5961. const CXXRecordDecl *RD = Ctor->getParent()->getCanonicalDecl();
  5962. if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
  5963. VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
  5964. }
  5965. }
  5966. static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
  5967. const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
  5968. if (!TSI)
  5969. return false;
  5970. // Don't declare this variable in the second operand of the for-statement;
  5971. // GCC miscompiles that by ending its lifetime before evaluating the
  5972. // third operand. See gcc.gnu.org/PR86769.
  5973. AttributedTypeLoc ATL;
  5974. for (TypeLoc TL = TSI->getTypeLoc();
  5975. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5976. TL = ATL.getModifiedLoc()) {
  5977. if (ATL.getAttrAs<LifetimeBoundAttr>())
  5978. return true;
  5979. }
  5980. return false;
  5981. }
  5982. static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
  5983. LocalVisitor Visit) {
  5984. const FunctionDecl *Callee;
  5985. ArrayRef<Expr*> Args;
  5986. if (auto *CE = dyn_cast<CallExpr>(Call)) {
  5987. Callee = CE->getDirectCallee();
  5988. Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
  5989. } else {
  5990. auto *CCE = cast<CXXConstructExpr>(Call);
  5991. Callee = CCE->getConstructor();
  5992. Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
  5993. }
  5994. if (!Callee)
  5995. return;
  5996. Expr *ObjectArg = nullptr;
  5997. if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
  5998. ObjectArg = Args[0];
  5999. Args = Args.slice(1);
  6000. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
  6001. ObjectArg = MCE->getImplicitObjectArgument();
  6002. }
  6003. auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
  6004. Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
  6005. if (Arg->isGLValue())
  6006. visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
  6007. Visit,
  6008. /*EnableLifetimeWarnings=*/false);
  6009. else
  6010. visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
  6011. /*EnableLifetimeWarnings=*/false);
  6012. Path.pop_back();
  6013. };
  6014. if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
  6015. VisitLifetimeBoundArg(Callee, ObjectArg);
  6016. for (unsigned I = 0,
  6017. N = std::min<unsigned>(Callee->getNumParams(), Args.size());
  6018. I != N; ++I) {
  6019. if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
  6020. VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
  6021. }
  6022. }
  6023. /// Visit the locals that would be reachable through a reference bound to the
  6024. /// glvalue expression \c Init.
  6025. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
  6026. Expr *Init, ReferenceKind RK,
  6027. LocalVisitor Visit,
  6028. bool EnableLifetimeWarnings) {
  6029. RevertToOldSizeRAII RAII(Path);
  6030. // Walk past any constructs which we can lifetime-extend across.
  6031. Expr *Old;
  6032. do {
  6033. Old = Init;
  6034. if (auto *FE = dyn_cast<FullExpr>(Init))
  6035. Init = FE->getSubExpr();
  6036. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  6037. // If this is just redundant braces around an initializer, step over it.
  6038. if (ILE->isTransparent())
  6039. Init = ILE->getInit(0);
  6040. }
  6041. // Step over any subobject adjustments; we may have a materialized
  6042. // temporary inside them.
  6043. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  6044. // Per current approach for DR1376, look through casts to reference type
  6045. // when performing lifetime extension.
  6046. if (CastExpr *CE = dyn_cast<CastExpr>(Init))
  6047. if (CE->getSubExpr()->isGLValue())
  6048. Init = CE->getSubExpr();
  6049. // Per the current approach for DR1299, look through array element access
  6050. // on array glvalues when performing lifetime extension.
  6051. if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
  6052. Init = ASE->getBase();
  6053. auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
  6054. if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
  6055. Init = ICE->getSubExpr();
  6056. else
  6057. // We can't lifetime extend through this but we might still find some
  6058. // retained temporaries.
  6059. return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
  6060. EnableLifetimeWarnings);
  6061. }
  6062. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  6063. // constructor inherits one as an implicit mem-initializer.
  6064. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  6065. Path.push_back(
  6066. {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  6067. Init = DIE->getExpr();
  6068. }
  6069. } while (Init != Old);
  6070. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  6071. if (Visit(Path, Local(MTE), RK))
  6072. visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
  6073. true, EnableLifetimeWarnings);
  6074. }
  6075. if (isa<CallExpr>(Init)) {
  6076. if (EnableLifetimeWarnings)
  6077. handleGslAnnotatedTypes(Path, Init, Visit);
  6078. return visitLifetimeBoundArguments(Path, Init, Visit);
  6079. }
  6080. switch (Init->getStmtClass()) {
  6081. case Stmt::DeclRefExprClass: {
  6082. // If we find the name of a local non-reference parameter, we could have a
  6083. // lifetime problem.
  6084. auto *DRE = cast<DeclRefExpr>(Init);
  6085. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6086. if (VD && VD->hasLocalStorage() &&
  6087. !DRE->refersToEnclosingVariableOrCapture()) {
  6088. if (!VD->getType()->isReferenceType()) {
  6089. Visit(Path, Local(DRE), RK);
  6090. } else if (isa<ParmVarDecl>(DRE->getDecl())) {
  6091. // The lifetime of a reference parameter is unknown; assume it's OK
  6092. // for now.
  6093. break;
  6094. } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
  6095. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  6096. visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
  6097. RK_ReferenceBinding, Visit,
  6098. EnableLifetimeWarnings);
  6099. }
  6100. }
  6101. break;
  6102. }
  6103. case Stmt::UnaryOperatorClass: {
  6104. // The only unary operator that make sense to handle here
  6105. // is Deref. All others don't resolve to a "name." This includes
  6106. // handling all sorts of rvalues passed to a unary operator.
  6107. const UnaryOperator *U = cast<UnaryOperator>(Init);
  6108. if (U->getOpcode() == UO_Deref)
  6109. visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
  6110. EnableLifetimeWarnings);
  6111. break;
  6112. }
  6113. case Stmt::OMPArraySectionExprClass: {
  6114. visitLocalsRetainedByInitializer(Path,
  6115. cast<OMPArraySectionExpr>(Init)->getBase(),
  6116. Visit, true, EnableLifetimeWarnings);
  6117. break;
  6118. }
  6119. case Stmt::ConditionalOperatorClass:
  6120. case Stmt::BinaryConditionalOperatorClass: {
  6121. auto *C = cast<AbstractConditionalOperator>(Init);
  6122. if (!C->getTrueExpr()->getType()->isVoidType())
  6123. visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
  6124. EnableLifetimeWarnings);
  6125. if (!C->getFalseExpr()->getType()->isVoidType())
  6126. visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
  6127. EnableLifetimeWarnings);
  6128. break;
  6129. }
  6130. // FIXME: Visit the left-hand side of an -> or ->*.
  6131. default:
  6132. break;
  6133. }
  6134. }
  6135. /// Visit the locals that would be reachable through an object initialized by
  6136. /// the prvalue expression \c Init.
  6137. static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  6138. Expr *Init, LocalVisitor Visit,
  6139. bool RevisitSubinits,
  6140. bool EnableLifetimeWarnings) {
  6141. RevertToOldSizeRAII RAII(Path);
  6142. Expr *Old;
  6143. do {
  6144. Old = Init;
  6145. // Step into CXXDefaultInitExprs so we can diagnose cases where a
  6146. // constructor inherits one as an implicit mem-initializer.
  6147. if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
  6148. Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
  6149. Init = DIE->getExpr();
  6150. }
  6151. if (auto *FE = dyn_cast<FullExpr>(Init))
  6152. Init = FE->getSubExpr();
  6153. // Dig out the expression which constructs the extended temporary.
  6154. Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
  6155. if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
  6156. Init = BTE->getSubExpr();
  6157. Init = Init->IgnoreParens();
  6158. // Step over value-preserving rvalue casts.
  6159. if (auto *CE = dyn_cast<CastExpr>(Init)) {
  6160. switch (CE->getCastKind()) {
  6161. case CK_LValueToRValue:
  6162. // If we can match the lvalue to a const object, we can look at its
  6163. // initializer.
  6164. Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
  6165. return visitLocalsRetainedByReferenceBinding(
  6166. Path, Init, RK_ReferenceBinding,
  6167. [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
  6168. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  6169. auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6170. if (VD && VD->getType().isConstQualified() && VD->getInit() &&
  6171. !isVarOnPath(Path, VD)) {
  6172. Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
  6173. visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
  6174. EnableLifetimeWarnings);
  6175. }
  6176. } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
  6177. if (MTE->getType().isConstQualified())
  6178. visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
  6179. Visit, true,
  6180. EnableLifetimeWarnings);
  6181. }
  6182. return false;
  6183. }, EnableLifetimeWarnings);
  6184. // We assume that objects can be retained by pointers cast to integers,
  6185. // but not if the integer is cast to floating-point type or to _Complex.
  6186. // We assume that casts to 'bool' do not preserve enough information to
  6187. // retain a local object.
  6188. case CK_NoOp:
  6189. case CK_BitCast:
  6190. case CK_BaseToDerived:
  6191. case CK_DerivedToBase:
  6192. case CK_UncheckedDerivedToBase:
  6193. case CK_Dynamic:
  6194. case CK_ToUnion:
  6195. case CK_UserDefinedConversion:
  6196. case CK_ConstructorConversion:
  6197. case CK_IntegralToPointer:
  6198. case CK_PointerToIntegral:
  6199. case CK_VectorSplat:
  6200. case CK_IntegralCast:
  6201. case CK_CPointerToObjCPointerCast:
  6202. case CK_BlockPointerToObjCPointerCast:
  6203. case CK_AnyPointerToBlockPointerCast:
  6204. case CK_AddressSpaceConversion:
  6205. break;
  6206. case CK_ArrayToPointerDecay:
  6207. // Model array-to-pointer decay as taking the address of the array
  6208. // lvalue.
  6209. Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
  6210. return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
  6211. RK_ReferenceBinding, Visit,
  6212. EnableLifetimeWarnings);
  6213. default:
  6214. return;
  6215. }
  6216. Init = CE->getSubExpr();
  6217. }
  6218. } while (Old != Init);
  6219. // C++17 [dcl.init.list]p6:
  6220. // initializing an initializer_list object from the array extends the
  6221. // lifetime of the array exactly like binding a reference to a temporary.
  6222. if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
  6223. return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
  6224. RK_StdInitializerList, Visit,
  6225. EnableLifetimeWarnings);
  6226. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  6227. // We already visited the elements of this initializer list while
  6228. // performing the initialization. Don't visit them again unless we've
  6229. // changed the lifetime of the initialized entity.
  6230. if (!RevisitSubinits)
  6231. return;
  6232. if (ILE->isTransparent())
  6233. return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
  6234. RevisitSubinits,
  6235. EnableLifetimeWarnings);
  6236. if (ILE->getType()->isArrayType()) {
  6237. for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
  6238. visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
  6239. RevisitSubinits,
  6240. EnableLifetimeWarnings);
  6241. return;
  6242. }
  6243. if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
  6244. assert(RD->isAggregate() && "aggregate init on non-aggregate");
  6245. // If we lifetime-extend a braced initializer which is initializing an
  6246. // aggregate, and that aggregate contains reference members which are
  6247. // bound to temporaries, those temporaries are also lifetime-extended.
  6248. if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
  6249. ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
  6250. visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
  6251. RK_ReferenceBinding, Visit,
  6252. EnableLifetimeWarnings);
  6253. else {
  6254. unsigned Index = 0;
  6255. for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
  6256. visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
  6257. RevisitSubinits,
  6258. EnableLifetimeWarnings);
  6259. for (const auto *I : RD->fields()) {
  6260. if (Index >= ILE->getNumInits())
  6261. break;
  6262. if (I->isUnnamedBitfield())
  6263. continue;
  6264. Expr *SubInit = ILE->getInit(Index);
  6265. if (I->getType()->isReferenceType())
  6266. visitLocalsRetainedByReferenceBinding(Path, SubInit,
  6267. RK_ReferenceBinding, Visit,
  6268. EnableLifetimeWarnings);
  6269. else
  6270. // This might be either aggregate-initialization of a member or
  6271. // initialization of a std::initializer_list object. Regardless,
  6272. // we should recursively lifetime-extend that initializer.
  6273. visitLocalsRetainedByInitializer(Path, SubInit, Visit,
  6274. RevisitSubinits,
  6275. EnableLifetimeWarnings);
  6276. ++Index;
  6277. }
  6278. }
  6279. }
  6280. return;
  6281. }
  6282. // The lifetime of an init-capture is that of the closure object constructed
  6283. // by a lambda-expression.
  6284. if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
  6285. for (Expr *E : LE->capture_inits()) {
  6286. if (!E)
  6287. continue;
  6288. if (E->isGLValue())
  6289. visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
  6290. Visit, EnableLifetimeWarnings);
  6291. else
  6292. visitLocalsRetainedByInitializer(Path, E, Visit, true,
  6293. EnableLifetimeWarnings);
  6294. }
  6295. }
  6296. if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
  6297. if (EnableLifetimeWarnings)
  6298. handleGslAnnotatedTypes(Path, Init, Visit);
  6299. return visitLifetimeBoundArguments(Path, Init, Visit);
  6300. }
  6301. switch (Init->getStmtClass()) {
  6302. case Stmt::UnaryOperatorClass: {
  6303. auto *UO = cast<UnaryOperator>(Init);
  6304. // If the initializer is the address of a local, we could have a lifetime
  6305. // problem.
  6306. if (UO->getOpcode() == UO_AddrOf) {
  6307. // If this is &rvalue, then it's ill-formed and we have already diagnosed
  6308. // it. Don't produce a redundant warning about the lifetime of the
  6309. // temporary.
  6310. if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
  6311. return;
  6312. Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
  6313. visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
  6314. RK_ReferenceBinding, Visit,
  6315. EnableLifetimeWarnings);
  6316. }
  6317. break;
  6318. }
  6319. case Stmt::BinaryOperatorClass: {
  6320. // Handle pointer arithmetic.
  6321. auto *BO = cast<BinaryOperator>(Init);
  6322. BinaryOperatorKind BOK = BO->getOpcode();
  6323. if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
  6324. break;
  6325. if (BO->getLHS()->getType()->isPointerType())
  6326. visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
  6327. EnableLifetimeWarnings);
  6328. else if (BO->getRHS()->getType()->isPointerType())
  6329. visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
  6330. EnableLifetimeWarnings);
  6331. break;
  6332. }
  6333. case Stmt::ConditionalOperatorClass:
  6334. case Stmt::BinaryConditionalOperatorClass: {
  6335. auto *C = cast<AbstractConditionalOperator>(Init);
  6336. // In C++, we can have a throw-expression operand, which has 'void' type
  6337. // and isn't interesting from a lifetime perspective.
  6338. if (!C->getTrueExpr()->getType()->isVoidType())
  6339. visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
  6340. EnableLifetimeWarnings);
  6341. if (!C->getFalseExpr()->getType()->isVoidType())
  6342. visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
  6343. EnableLifetimeWarnings);
  6344. break;
  6345. }
  6346. case Stmt::BlockExprClass:
  6347. if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
  6348. // This is a local block, whose lifetime is that of the function.
  6349. Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
  6350. }
  6351. break;
  6352. case Stmt::AddrLabelExprClass:
  6353. // We want to warn if the address of a label would escape the function.
  6354. Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
  6355. break;
  6356. default:
  6357. break;
  6358. }
  6359. }
  6360. /// Determine whether this is an indirect path to a temporary that we are
  6361. /// supposed to lifetime-extend along (but don't).
  6362. static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
  6363. for (auto Elem : Path) {
  6364. if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
  6365. return false;
  6366. }
  6367. return true;
  6368. }
  6369. /// Find the range for the first interesting entry in the path at or after I.
  6370. static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
  6371. Expr *E) {
  6372. for (unsigned N = Path.size(); I != N; ++I) {
  6373. switch (Path[I].Kind) {
  6374. case IndirectLocalPathEntry::AddressOf:
  6375. case IndirectLocalPathEntry::LValToRVal:
  6376. case IndirectLocalPathEntry::LifetimeBoundCall:
  6377. case IndirectLocalPathEntry::GslPointerInit:
  6378. // These exist primarily to mark the path as not permitting or
  6379. // supporting lifetime extension.
  6380. break;
  6381. case IndirectLocalPathEntry::VarInit:
  6382. if (cast<VarDecl>(Path[I].D)->isImplicit())
  6383. return SourceRange();
  6384. LLVM_FALLTHROUGH;
  6385. case IndirectLocalPathEntry::DefaultInit:
  6386. return Path[I].E->getSourceRange();
  6387. }
  6388. }
  6389. return E->getSourceRange();
  6390. }
  6391. static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
  6392. for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
  6393. if (It->Kind == IndirectLocalPathEntry::VarInit)
  6394. continue;
  6395. return It->Kind == IndirectLocalPathEntry::GslPointerInit;
  6396. }
  6397. return false;
  6398. }
  6399. void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
  6400. Expr *Init) {
  6401. LifetimeResult LR = getEntityLifetime(&Entity);
  6402. LifetimeKind LK = LR.getInt();
  6403. const InitializedEntity *ExtendingEntity = LR.getPointer();
  6404. // If this entity doesn't have an interesting lifetime, don't bother looking
  6405. // for temporaries within its initializer.
  6406. if (LK == LK_FullExpression)
  6407. return;
  6408. auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
  6409. ReferenceKind RK) -> bool {
  6410. SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
  6411. SourceLocation DiagLoc = DiagRange.getBegin();
  6412. auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
  6413. bool IsGslPtrInitWithGslTempOwner = false;
  6414. bool IsLocalGslOwner = false;
  6415. if (pathOnlyInitializesGslPointer(Path)) {
  6416. if (isa<DeclRefExpr>(L)) {
  6417. // We do not want to follow the references when returning a pointer originating
  6418. // from a local owner to avoid the following false positive:
  6419. // int &p = *localUniquePtr;
  6420. // someContainer.add(std::move(localUniquePtr));
  6421. // return p;
  6422. IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
  6423. if (pathContainsInit(Path) || !IsLocalGslOwner)
  6424. return false;
  6425. } else {
  6426. IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
  6427. isRecordWithAttr<OwnerAttr>(MTE->getType());
  6428. // Skipping a chain of initializing gsl::Pointer annotated objects.
  6429. // We are looking only for the final source to find out if it was
  6430. // a local or temporary owner or the address of a local variable/param.
  6431. if (!IsGslPtrInitWithGslTempOwner)
  6432. return true;
  6433. }
  6434. }
  6435. switch (LK) {
  6436. case LK_FullExpression:
  6437. llvm_unreachable("already handled this");
  6438. case LK_Extended: {
  6439. if (!MTE) {
  6440. // The initialized entity has lifetime beyond the full-expression,
  6441. // and the local entity does too, so don't warn.
  6442. //
  6443. // FIXME: We should consider warning if a static / thread storage
  6444. // duration variable retains an automatic storage duration local.
  6445. return false;
  6446. }
  6447. if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
  6448. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
  6449. return false;
  6450. }
  6451. // Lifetime-extend the temporary.
  6452. if (Path.empty()) {
  6453. // Update the storage duration of the materialized temporary.
  6454. // FIXME: Rebuild the expression instead of mutating it.
  6455. MTE->setExtendingDecl(ExtendingEntity->getDecl(),
  6456. ExtendingEntity->allocateManglingNumber());
  6457. // Also visit the temporaries lifetime-extended by this initializer.
  6458. return true;
  6459. }
  6460. if (shouldLifetimeExtendThroughPath(Path)) {
  6461. // We're supposed to lifetime-extend the temporary along this path (per
  6462. // the resolution of DR1815), but we don't support that yet.
  6463. //
  6464. // FIXME: Properly handle this situation. Perhaps the easiest approach
  6465. // would be to clone the initializer expression on each use that would
  6466. // lifetime extend its temporaries.
  6467. Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
  6468. << RK << DiagRange;
  6469. } else {
  6470. // If the path goes through the initialization of a variable or field,
  6471. // it can't possibly reach a temporary created in this full-expression.
  6472. // We will have already diagnosed any problems with the initializer.
  6473. if (pathContainsInit(Path))
  6474. return false;
  6475. Diag(DiagLoc, diag::warn_dangling_variable)
  6476. << RK << !Entity.getParent()
  6477. << ExtendingEntity->getDecl()->isImplicit()
  6478. << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
  6479. }
  6480. break;
  6481. }
  6482. case LK_MemInitializer: {
  6483. if (isa<MaterializeTemporaryExpr>(L)) {
  6484. // Under C++ DR1696, if a mem-initializer (or a default member
  6485. // initializer used by the absence of one) would lifetime-extend a
  6486. // temporary, the program is ill-formed.
  6487. if (auto *ExtendingDecl =
  6488. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  6489. if (IsGslPtrInitWithGslTempOwner) {
  6490. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
  6491. << ExtendingDecl << DiagRange;
  6492. Diag(ExtendingDecl->getLocation(),
  6493. diag::note_ref_or_ptr_member_declared_here)
  6494. << true;
  6495. return false;
  6496. }
  6497. bool IsSubobjectMember = ExtendingEntity != &Entity;
  6498. Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
  6499. ? diag::err_dangling_member
  6500. : diag::warn_dangling_member)
  6501. << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
  6502. // Don't bother adding a note pointing to the field if we're inside
  6503. // its default member initializer; our primary diagnostic points to
  6504. // the same place in that case.
  6505. if (Path.empty() ||
  6506. Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
  6507. Diag(ExtendingDecl->getLocation(),
  6508. diag::note_lifetime_extending_member_declared_here)
  6509. << RK << IsSubobjectMember;
  6510. }
  6511. } else {
  6512. // We have a mem-initializer but no particular field within it; this
  6513. // is either a base class or a delegating initializer directly
  6514. // initializing the base-class from something that doesn't live long
  6515. // enough.
  6516. //
  6517. // FIXME: Warn on this.
  6518. return false;
  6519. }
  6520. } else {
  6521. // Paths via a default initializer can only occur during error recovery
  6522. // (there's no other way that a default initializer can refer to a
  6523. // local). Don't produce a bogus warning on those cases.
  6524. if (pathContainsInit(Path))
  6525. return false;
  6526. // Suppress false positives for code like the one below:
  6527. // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
  6528. if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
  6529. return false;
  6530. auto *DRE = dyn_cast<DeclRefExpr>(L);
  6531. auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
  6532. if (!VD) {
  6533. // A member was initialized to a local block.
  6534. // FIXME: Warn on this.
  6535. return false;
  6536. }
  6537. if (auto *Member =
  6538. ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
  6539. bool IsPointer = !Member->getType()->isReferenceType();
  6540. Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  6541. : diag::warn_bind_ref_member_to_parameter)
  6542. << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
  6543. Diag(Member->getLocation(),
  6544. diag::note_ref_or_ptr_member_declared_here)
  6545. << (unsigned)IsPointer;
  6546. }
  6547. }
  6548. break;
  6549. }
  6550. case LK_New:
  6551. if (isa<MaterializeTemporaryExpr>(L)) {
  6552. if (IsGslPtrInitWithGslTempOwner)
  6553. Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
  6554. else
  6555. Diag(DiagLoc, RK == RK_ReferenceBinding
  6556. ? diag::warn_new_dangling_reference
  6557. : diag::warn_new_dangling_initializer_list)
  6558. << !Entity.getParent() << DiagRange;
  6559. } else {
  6560. // We can't determine if the allocation outlives the local declaration.
  6561. return false;
  6562. }
  6563. break;
  6564. case LK_Return:
  6565. case LK_StmtExprResult:
  6566. if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
  6567. // We can't determine if the local variable outlives the statement
  6568. // expression.
  6569. if (LK == LK_StmtExprResult)
  6570. return false;
  6571. Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
  6572. << Entity.getType()->isReferenceType() << DRE->getDecl()
  6573. << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
  6574. } else if (isa<BlockExpr>(L)) {
  6575. Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
  6576. } else if (isa<AddrLabelExpr>(L)) {
  6577. // Don't warn when returning a label from a statement expression.
  6578. // Leaving the scope doesn't end its lifetime.
  6579. if (LK == LK_StmtExprResult)
  6580. return false;
  6581. Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
  6582. } else {
  6583. Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
  6584. << Entity.getType()->isReferenceType() << DiagRange;
  6585. }
  6586. break;
  6587. }
  6588. for (unsigned I = 0; I != Path.size(); ++I) {
  6589. auto Elem = Path[I];
  6590. switch (Elem.Kind) {
  6591. case IndirectLocalPathEntry::AddressOf:
  6592. case IndirectLocalPathEntry::LValToRVal:
  6593. // These exist primarily to mark the path as not permitting or
  6594. // supporting lifetime extension.
  6595. break;
  6596. case IndirectLocalPathEntry::LifetimeBoundCall:
  6597. case IndirectLocalPathEntry::GslPointerInit:
  6598. // FIXME: Consider adding a note for these.
  6599. break;
  6600. case IndirectLocalPathEntry::DefaultInit: {
  6601. auto *FD = cast<FieldDecl>(Elem.D);
  6602. Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
  6603. << FD << nextPathEntryRange(Path, I + 1, L);
  6604. break;
  6605. }
  6606. case IndirectLocalPathEntry::VarInit:
  6607. const VarDecl *VD = cast<VarDecl>(Elem.D);
  6608. Diag(VD->getLocation(), diag::note_local_var_initializer)
  6609. << VD->getType()->isReferenceType()
  6610. << VD->isImplicit() << VD->getDeclName()
  6611. << nextPathEntryRange(Path, I + 1, L);
  6612. break;
  6613. }
  6614. }
  6615. // We didn't lifetime-extend, so don't go any further; we don't need more
  6616. // warnings or errors on inner temporaries within this one's initializer.
  6617. return false;
  6618. };
  6619. bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
  6620. diag::warn_dangling_lifetime_pointer, SourceLocation());
  6621. llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
  6622. if (Init->isGLValue())
  6623. visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
  6624. TemporaryVisitor,
  6625. EnableLifetimeWarnings);
  6626. else
  6627. visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
  6628. EnableLifetimeWarnings);
  6629. }
  6630. static void DiagnoseNarrowingInInitList(Sema &S,
  6631. const ImplicitConversionSequence &ICS,
  6632. QualType PreNarrowingType,
  6633. QualType EntityType,
  6634. const Expr *PostInit);
  6635. /// Provide warnings when std::move is used on construction.
  6636. static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
  6637. bool IsReturnStmt) {
  6638. if (!InitExpr)
  6639. return;
  6640. if (S.inTemplateInstantiation())
  6641. return;
  6642. QualType DestType = InitExpr->getType();
  6643. if (!DestType->isRecordType())
  6644. return;
  6645. const CXXConstructExpr *CCE =
  6646. dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
  6647. if (!CCE || CCE->getNumArgs() != 1)
  6648. return;
  6649. if (!CCE->getConstructor()->isCopyOrMoveConstructor())
  6650. return;
  6651. InitExpr = CCE->getArg(0)->IgnoreImpCasts();
  6652. // Find the std::move call and get the argument.
  6653. const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
  6654. if (!CE || !CE->isCallToStdMove())
  6655. return;
  6656. const Expr *Arg = CE->getArg(0);
  6657. unsigned DiagID = 0;
  6658. if (!IsReturnStmt && !isa<MaterializeTemporaryExpr>(Arg))
  6659. return;
  6660. if (isa<MaterializeTemporaryExpr>(Arg)) {
  6661. DiagID = diag::warn_pessimizing_move_on_initialization;
  6662. const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
  6663. if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
  6664. return;
  6665. } else { // IsReturnStmt
  6666. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
  6667. if (!DRE || DRE->refersToEnclosingVariableOrCapture())
  6668. return;
  6669. const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
  6670. if (!VD || !VD->hasLocalStorage())
  6671. return;
  6672. // __block variables are not moved implicitly.
  6673. if (VD->hasAttr<BlocksAttr>())
  6674. return;
  6675. QualType SourceType = VD->getType();
  6676. if (!SourceType->isRecordType())
  6677. return;
  6678. if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
  6679. return;
  6680. }
  6681. // If we're returning a function parameter, copy elision
  6682. // is not possible.
  6683. if (isa<ParmVarDecl>(VD))
  6684. DiagID = diag::warn_redundant_move_on_return;
  6685. else
  6686. DiagID = diag::warn_pessimizing_move_on_return;
  6687. }
  6688. S.Diag(CE->getBeginLoc(), DiagID);
  6689. // Get all the locations for a fix-it. Don't emit the fix-it if any location
  6690. // is within a macro.
  6691. SourceLocation BeginLoc = CCE->getBeginLoc();
  6692. if (BeginLoc.isMacroID())
  6693. return;
  6694. SourceLocation RParen = CE->getRParenLoc();
  6695. if (RParen.isMacroID())
  6696. return;
  6697. SourceLocation ArgLoc = Arg->getBeginLoc();
  6698. // Special testing for the argument location. Since the fix-it needs the
  6699. // location right before the argument, the argument location can be in a
  6700. // macro only if it is at the beginning of the macro.
  6701. while (ArgLoc.isMacroID() &&
  6702. S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
  6703. ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
  6704. }
  6705. SourceLocation LParen = ArgLoc.getLocWithOffset(-1);
  6706. if (LParen.isMacroID())
  6707. return;
  6708. SourceLocation EndLoc = CCE->getEndLoc();
  6709. if (EndLoc.isMacroID())
  6710. return;
  6711. S.Diag(CE->getBeginLoc(), diag::note_remove_move)
  6712. << FixItHint::CreateRemoval(SourceRange(BeginLoc, LParen))
  6713. << FixItHint::CreateRemoval(SourceRange(RParen, EndLoc));
  6714. }
  6715. static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
  6716. // Check to see if we are dereferencing a null pointer. If so, this is
  6717. // undefined behavior, so warn about it. This only handles the pattern
  6718. // "*null", which is a very syntactic check.
  6719. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  6720. if (UO->getOpcode() == UO_Deref &&
  6721. UO->getSubExpr()->IgnoreParenCasts()->
  6722. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
  6723. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  6724. S.PDiag(diag::warn_binding_null_to_reference)
  6725. << UO->getSubExpr()->getSourceRange());
  6726. }
  6727. }
  6728. MaterializeTemporaryExpr *
  6729. Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
  6730. bool BoundToLvalueReference) {
  6731. auto MTE = new (Context)
  6732. MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
  6733. // Order an ExprWithCleanups for lifetime marks.
  6734. //
  6735. // TODO: It'll be good to have a single place to check the access of the
  6736. // destructor and generate ExprWithCleanups for various uses. Currently these
  6737. // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
  6738. // but there may be a chance to merge them.
  6739. Cleanup.setExprNeedsCleanups(false);
  6740. return MTE;
  6741. }
  6742. ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
  6743. // In C++98, we don't want to implicitly create an xvalue.
  6744. // FIXME: This means that AST consumers need to deal with "prvalues" that
  6745. // denote materialized temporaries. Maybe we should add another ValueKind
  6746. // for "xvalue pretending to be a prvalue" for C++98 support.
  6747. if (!E->isRValue() || !getLangOpts().CPlusPlus11)
  6748. return E;
  6749. // C++1z [conv.rval]/1: T shall be a complete type.
  6750. // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
  6751. // If so, we should check for a non-abstract class type here too.
  6752. QualType T = E->getType();
  6753. if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
  6754. return ExprError();
  6755. return CreateMaterializeTemporaryExpr(E->getType(), E, false);
  6756. }
  6757. ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
  6758. ExprValueKind VK,
  6759. CheckedConversionKind CCK) {
  6760. CastKind CK = CK_NoOp;
  6761. if (VK == VK_RValue) {
  6762. auto PointeeTy = Ty->getPointeeType();
  6763. auto ExprPointeeTy = E->getType()->getPointeeType();
  6764. if (!PointeeTy.isNull() &&
  6765. PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
  6766. CK = CK_AddressSpaceConversion;
  6767. } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
  6768. CK = CK_AddressSpaceConversion;
  6769. }
  6770. return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
  6771. }
  6772. ExprResult InitializationSequence::Perform(Sema &S,
  6773. const InitializedEntity &Entity,
  6774. const InitializationKind &Kind,
  6775. MultiExprArg Args,
  6776. QualType *ResultType) {
  6777. if (Failed()) {
  6778. Diagnose(S, Entity, Kind, Args);
  6779. return ExprError();
  6780. }
  6781. if (!ZeroInitializationFixit.empty()) {
  6782. unsigned DiagID = diag::err_default_init_const;
  6783. if (Decl *D = Entity.getDecl())
  6784. if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
  6785. DiagID = diag::ext_default_init_const;
  6786. // The initialization would have succeeded with this fixit. Since the fixit
  6787. // is on the error, we need to build a valid AST in this case, so this isn't
  6788. // handled in the Failed() branch above.
  6789. QualType DestType = Entity.getType();
  6790. S.Diag(Kind.getLocation(), DiagID)
  6791. << DestType << (bool)DestType->getAs<RecordType>()
  6792. << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
  6793. ZeroInitializationFixit);
  6794. }
  6795. if (getKind() == DependentSequence) {
  6796. // If the declaration is a non-dependent, incomplete array type
  6797. // that has an initializer, then its type will be completed once
  6798. // the initializer is instantiated.
  6799. if (ResultType && !Entity.getType()->isDependentType() &&
  6800. Args.size() == 1) {
  6801. QualType DeclType = Entity.getType();
  6802. if (const IncompleteArrayType *ArrayT
  6803. = S.Context.getAsIncompleteArrayType(DeclType)) {
  6804. // FIXME: We don't currently have the ability to accurately
  6805. // compute the length of an initializer list without
  6806. // performing full type-checking of the initializer list
  6807. // (since we have to determine where braces are implicitly
  6808. // introduced and such). So, we fall back to making the array
  6809. // type a dependently-sized array type with no specified
  6810. // bound.
  6811. if (isa<InitListExpr>((Expr *)Args[0])) {
  6812. SourceRange Brackets;
  6813. // Scavange the location of the brackets from the entity, if we can.
  6814. if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
  6815. if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
  6816. TypeLoc TL = TInfo->getTypeLoc();
  6817. if (IncompleteArrayTypeLoc ArrayLoc =
  6818. TL.getAs<IncompleteArrayTypeLoc>())
  6819. Brackets = ArrayLoc.getBracketsRange();
  6820. }
  6821. }
  6822. *ResultType
  6823. = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
  6824. /*NumElts=*/nullptr,
  6825. ArrayT->getSizeModifier(),
  6826. ArrayT->getIndexTypeCVRQualifiers(),
  6827. Brackets);
  6828. }
  6829. }
  6830. }
  6831. if (Kind.getKind() == InitializationKind::IK_Direct &&
  6832. !Kind.isExplicitCast()) {
  6833. // Rebuild the ParenListExpr.
  6834. SourceRange ParenRange = Kind.getParenOrBraceRange();
  6835. return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
  6836. Args);
  6837. }
  6838. assert(Kind.getKind() == InitializationKind::IK_Copy ||
  6839. Kind.isExplicitCast() ||
  6840. Kind.getKind() == InitializationKind::IK_DirectList);
  6841. return ExprResult(Args[0]);
  6842. }
  6843. // No steps means no initialization.
  6844. if (Steps.empty())
  6845. return ExprResult((Expr *)nullptr);
  6846. if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
  6847. Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  6848. !Entity.isParameterKind()) {
  6849. // Produce a C++98 compatibility warning if we are initializing a reference
  6850. // from an initializer list. For parameters, we produce a better warning
  6851. // elsewhere.
  6852. Expr *Init = Args[0];
  6853. S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
  6854. << Init->getSourceRange();
  6855. }
  6856. // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
  6857. QualType ETy = Entity.getType();
  6858. Qualifiers TyQualifiers = ETy.getQualifiers();
  6859. bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
  6860. TyQualifiers.getAddressSpace() == LangAS::opencl_global;
  6861. if (S.getLangOpts().OpenCLVersion >= 200 &&
  6862. ETy->isAtomicType() && !HasGlobalAS &&
  6863. Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
  6864. S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
  6865. << 1
  6866. << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
  6867. return ExprError();
  6868. }
  6869. QualType DestType = Entity.getType().getNonReferenceType();
  6870. // FIXME: Ugly hack around the fact that Entity.getType() is not
  6871. // the same as Entity.getDecl()->getType() in cases involving type merging,
  6872. // and we want latter when it makes sense.
  6873. if (ResultType)
  6874. *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
  6875. Entity.getType();
  6876. ExprResult CurInit((Expr *)nullptr);
  6877. SmallVector<Expr*, 4> ArrayLoopCommonExprs;
  6878. // For initialization steps that start with a single initializer,
  6879. // grab the only argument out the Args and place it into the "current"
  6880. // initializer.
  6881. switch (Steps.front().Kind) {
  6882. case SK_ResolveAddressOfOverloadedFunction:
  6883. case SK_CastDerivedToBaseRValue:
  6884. case SK_CastDerivedToBaseXValue:
  6885. case SK_CastDerivedToBaseLValue:
  6886. case SK_BindReference:
  6887. case SK_BindReferenceToTemporary:
  6888. case SK_FinalCopy:
  6889. case SK_ExtraneousCopyToTemporary:
  6890. case SK_UserConversion:
  6891. case SK_QualificationConversionLValue:
  6892. case SK_QualificationConversionXValue:
  6893. case SK_QualificationConversionRValue:
  6894. case SK_AtomicConversion:
  6895. case SK_ConversionSequence:
  6896. case SK_ConversionSequenceNoNarrowing:
  6897. case SK_ListInitialization:
  6898. case SK_UnwrapInitList:
  6899. case SK_RewrapInitList:
  6900. case SK_CAssignment:
  6901. case SK_StringInit:
  6902. case SK_ObjCObjectConversion:
  6903. case SK_ArrayLoopIndex:
  6904. case SK_ArrayLoopInit:
  6905. case SK_ArrayInit:
  6906. case SK_GNUArrayInit:
  6907. case SK_ParenthesizedArrayInit:
  6908. case SK_PassByIndirectCopyRestore:
  6909. case SK_PassByIndirectRestore:
  6910. case SK_ProduceObjCObject:
  6911. case SK_StdInitializerList:
  6912. case SK_OCLSamplerInit:
  6913. case SK_OCLZeroOpaqueType: {
  6914. assert(Args.size() == 1);
  6915. CurInit = Args[0];
  6916. if (!CurInit.get()) return ExprError();
  6917. break;
  6918. }
  6919. case SK_ConstructorInitialization:
  6920. case SK_ConstructorInitializationFromList:
  6921. case SK_StdInitializerListConstructorCall:
  6922. case SK_ZeroInitialization:
  6923. break;
  6924. }
  6925. // Promote from an unevaluated context to an unevaluated list context in
  6926. // C++11 list-initialization; we need to instantiate entities usable in
  6927. // constant expressions here in order to perform narrowing checks =(
  6928. EnterExpressionEvaluationContext Evaluated(
  6929. S, EnterExpressionEvaluationContext::InitList,
  6930. CurInit.get() && isa<InitListExpr>(CurInit.get()));
  6931. // C++ [class.abstract]p2:
  6932. // no objects of an abstract class can be created except as subobjects
  6933. // of a class derived from it
  6934. auto checkAbstractType = [&](QualType T) -> bool {
  6935. if (Entity.getKind() == InitializedEntity::EK_Base ||
  6936. Entity.getKind() == InitializedEntity::EK_Delegating)
  6937. return false;
  6938. return S.RequireNonAbstractType(Kind.getLocation(), T,
  6939. diag::err_allocation_of_abstract_type);
  6940. };
  6941. // Walk through the computed steps for the initialization sequence,
  6942. // performing the specified conversions along the way.
  6943. bool ConstructorInitRequiresZeroInit = false;
  6944. for (step_iterator Step = step_begin(), StepEnd = step_end();
  6945. Step != StepEnd; ++Step) {
  6946. if (CurInit.isInvalid())
  6947. return ExprError();
  6948. QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
  6949. switch (Step->Kind) {
  6950. case SK_ResolveAddressOfOverloadedFunction:
  6951. // Overload resolution determined which function invoke; update the
  6952. // initializer to reflect that choice.
  6953. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
  6954. if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
  6955. return ExprError();
  6956. CurInit = S.FixOverloadedFunctionReference(CurInit,
  6957. Step->Function.FoundDecl,
  6958. Step->Function.Function);
  6959. break;
  6960. case SK_CastDerivedToBaseRValue:
  6961. case SK_CastDerivedToBaseXValue:
  6962. case SK_CastDerivedToBaseLValue: {
  6963. // We have a derived-to-base cast that produces either an rvalue or an
  6964. // lvalue. Perform that cast.
  6965. CXXCastPath BasePath;
  6966. // Casts to inaccessible base classes are allowed with C-style casts.
  6967. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
  6968. if (S.CheckDerivedToBaseConversion(
  6969. SourceType, Step->Type, CurInit.get()->getBeginLoc(),
  6970. CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
  6971. return ExprError();
  6972. ExprValueKind VK =
  6973. Step->Kind == SK_CastDerivedToBaseLValue ?
  6974. VK_LValue :
  6975. (Step->Kind == SK_CastDerivedToBaseXValue ?
  6976. VK_XValue :
  6977. VK_RValue);
  6978. CurInit =
  6979. ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
  6980. CurInit.get(), &BasePath, VK);
  6981. break;
  6982. }
  6983. case SK_BindReference:
  6984. // Reference binding does not have any corresponding ASTs.
  6985. // Check exception specifications
  6986. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  6987. return ExprError();
  6988. // We don't check for e.g. function pointers here, since address
  6989. // availability checks should only occur when the function first decays
  6990. // into a pointer or reference.
  6991. if (CurInit.get()->getType()->isFunctionProtoType()) {
  6992. if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
  6993. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  6994. if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  6995. DRE->getBeginLoc()))
  6996. return ExprError();
  6997. }
  6998. }
  6999. }
  7000. CheckForNullPointerDereference(S, CurInit.get());
  7001. break;
  7002. case SK_BindReferenceToTemporary: {
  7003. // Make sure the "temporary" is actually an rvalue.
  7004. assert(CurInit.get()->isRValue() && "not a temporary");
  7005. // Check exception specifications
  7006. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  7007. return ExprError();
  7008. // Materialize the temporary into memory.
  7009. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  7010. Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
  7011. CurInit = MTE;
  7012. // If we're extending this temporary to automatic storage duration -- we
  7013. // need to register its cleanup during the full-expression's cleanups.
  7014. if (MTE->getStorageDuration() == SD_Automatic &&
  7015. MTE->getType().isDestructedType())
  7016. S.Cleanup.setExprNeedsCleanups(true);
  7017. break;
  7018. }
  7019. case SK_FinalCopy:
  7020. if (checkAbstractType(Step->Type))
  7021. return ExprError();
  7022. // If the overall initialization is initializing a temporary, we already
  7023. // bound our argument if it was necessary to do so. If not (if we're
  7024. // ultimately initializing a non-temporary), our argument needs to be
  7025. // bound since it's initializing a function parameter.
  7026. // FIXME: This is a mess. Rationalize temporary destruction.
  7027. if (!shouldBindAsTemporary(Entity))
  7028. CurInit = S.MaybeBindToTemporary(CurInit.get());
  7029. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  7030. /*IsExtraneousCopy=*/false);
  7031. break;
  7032. case SK_ExtraneousCopyToTemporary:
  7033. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  7034. /*IsExtraneousCopy=*/true);
  7035. break;
  7036. case SK_UserConversion: {
  7037. // We have a user-defined conversion that invokes either a constructor
  7038. // or a conversion function.
  7039. CastKind CastKind;
  7040. FunctionDecl *Fn = Step->Function.Function;
  7041. DeclAccessPair FoundFn = Step->Function.FoundDecl;
  7042. bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
  7043. bool CreatedObject = false;
  7044. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7045. // Build a call to the selected constructor.
  7046. SmallVector<Expr*, 8> ConstructorArgs;
  7047. SourceLocation Loc = CurInit.get()->getBeginLoc();
  7048. // Determine the arguments required to actually perform the constructor
  7049. // call.
  7050. Expr *Arg = CurInit.get();
  7051. if (S.CompleteConstructorCall(Constructor,
  7052. MultiExprArg(&Arg, 1),
  7053. Loc, ConstructorArgs))
  7054. return ExprError();
  7055. // Build an expression that constructs a temporary.
  7056. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
  7057. FoundFn, Constructor,
  7058. ConstructorArgs,
  7059. HadMultipleCandidates,
  7060. /*ListInit*/ false,
  7061. /*StdInitListInit*/ false,
  7062. /*ZeroInit*/ false,
  7063. CXXConstructExpr::CK_Complete,
  7064. SourceRange());
  7065. if (CurInit.isInvalid())
  7066. return ExprError();
  7067. S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
  7068. Entity);
  7069. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  7070. return ExprError();
  7071. CastKind = CK_ConstructorConversion;
  7072. CreatedObject = true;
  7073. } else {
  7074. // Build a call to the conversion function.
  7075. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
  7076. S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
  7077. FoundFn);
  7078. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  7079. return ExprError();
  7080. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
  7081. HadMultipleCandidates);
  7082. if (CurInit.isInvalid())
  7083. return ExprError();
  7084. CastKind = CK_UserDefinedConversion;
  7085. CreatedObject = Conversion->getReturnType()->isRecordType();
  7086. }
  7087. if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
  7088. return ExprError();
  7089. CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
  7090. CastKind, CurInit.get(), nullptr,
  7091. CurInit.get()->getValueKind());
  7092. if (shouldBindAsTemporary(Entity))
  7093. // The overall entity is temporary, so this expression should be
  7094. // destroyed at the end of its full-expression.
  7095. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  7096. else if (CreatedObject && shouldDestroyEntity(Entity)) {
  7097. // The object outlasts the full-expression, but we need to prepare for
  7098. // a destructor being run on it.
  7099. // FIXME: It makes no sense to do this here. This should happen
  7100. // regardless of how we initialized the entity.
  7101. QualType T = CurInit.get()->getType();
  7102. if (const RecordType *Record = T->getAs<RecordType>()) {
  7103. CXXDestructorDecl *Destructor
  7104. = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
  7105. S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
  7106. S.PDiag(diag::err_access_dtor_temp) << T);
  7107. S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
  7108. if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
  7109. return ExprError();
  7110. }
  7111. }
  7112. break;
  7113. }
  7114. case SK_QualificationConversionLValue:
  7115. case SK_QualificationConversionXValue:
  7116. case SK_QualificationConversionRValue: {
  7117. // Perform a qualification conversion; these can never go wrong.
  7118. ExprValueKind VK =
  7119. Step->Kind == SK_QualificationConversionLValue
  7120. ? VK_LValue
  7121. : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
  7122. : VK_RValue);
  7123. CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
  7124. break;
  7125. }
  7126. case SK_AtomicConversion: {
  7127. assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
  7128. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7129. CK_NonAtomicToAtomic, VK_RValue);
  7130. break;
  7131. }
  7132. case SK_ConversionSequence:
  7133. case SK_ConversionSequenceNoNarrowing: {
  7134. if (const auto *FromPtrType =
  7135. CurInit.get()->getType()->getAs<PointerType>()) {
  7136. if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
  7137. if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7138. !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7139. S.Diag(CurInit.get()->getExprLoc(),
  7140. diag::warn_noderef_to_dereferenceable_pointer)
  7141. << CurInit.get()->getSourceRange();
  7142. }
  7143. }
  7144. }
  7145. Sema::CheckedConversionKind CCK
  7146. = Kind.isCStyleCast()? Sema::CCK_CStyleCast
  7147. : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
  7148. : Kind.isExplicitCast()? Sema::CCK_OtherCast
  7149. : Sema::CCK_ImplicitConversion;
  7150. ExprResult CurInitExprRes =
  7151. S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
  7152. getAssignmentAction(Entity), CCK);
  7153. if (CurInitExprRes.isInvalid())
  7154. return ExprError();
  7155. S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
  7156. CurInit = CurInitExprRes;
  7157. if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
  7158. S.getLangOpts().CPlusPlus)
  7159. DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
  7160. CurInit.get());
  7161. break;
  7162. }
  7163. case SK_ListInitialization: {
  7164. if (checkAbstractType(Step->Type))
  7165. return ExprError();
  7166. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  7167. // If we're not initializing the top-level entity, we need to create an
  7168. // InitializeTemporary entity for our target type.
  7169. QualType Ty = Step->Type;
  7170. bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
  7171. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
  7172. InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
  7173. InitListChecker PerformInitList(S, InitEntity,
  7174. InitList, Ty, /*VerifyOnly=*/false,
  7175. /*TreatUnavailableAsInvalid=*/false);
  7176. if (PerformInitList.HadError())
  7177. return ExprError();
  7178. // Hack: We must update *ResultType if available in order to set the
  7179. // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  7180. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  7181. if (ResultType &&
  7182. ResultType->getNonReferenceType()->isIncompleteArrayType()) {
  7183. if ((*ResultType)->isRValueReferenceType())
  7184. Ty = S.Context.getRValueReferenceType(Ty);
  7185. else if ((*ResultType)->isLValueReferenceType())
  7186. Ty = S.Context.getLValueReferenceType(Ty,
  7187. (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
  7188. *ResultType = Ty;
  7189. }
  7190. InitListExpr *StructuredInitList =
  7191. PerformInitList.getFullyStructuredList();
  7192. CurInit.get();
  7193. CurInit = shouldBindAsTemporary(InitEntity)
  7194. ? S.MaybeBindToTemporary(StructuredInitList)
  7195. : StructuredInitList;
  7196. break;
  7197. }
  7198. case SK_ConstructorInitializationFromList: {
  7199. if (checkAbstractType(Step->Type))
  7200. return ExprError();
  7201. // When an initializer list is passed for a parameter of type "reference
  7202. // to object", we don't get an EK_Temporary entity, but instead an
  7203. // EK_Parameter entity with reference type.
  7204. // FIXME: This is a hack. What we really should do is create a user
  7205. // conversion step for this case, but this makes it considerably more
  7206. // complicated. For now, this will do.
  7207. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  7208. Entity.getType().getNonReferenceType());
  7209. bool UseTemporary = Entity.getType()->isReferenceType();
  7210. assert(Args.size() == 1 && "expected a single argument for list init");
  7211. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  7212. S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
  7213. << InitList->getSourceRange();
  7214. MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
  7215. CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
  7216. Entity,
  7217. Kind, Arg, *Step,
  7218. ConstructorInitRequiresZeroInit,
  7219. /*IsListInitialization*/true,
  7220. /*IsStdInitListInit*/false,
  7221. InitList->getLBraceLoc(),
  7222. InitList->getRBraceLoc());
  7223. break;
  7224. }
  7225. case SK_UnwrapInitList:
  7226. CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
  7227. break;
  7228. case SK_RewrapInitList: {
  7229. Expr *E = CurInit.get();
  7230. InitListExpr *Syntactic = Step->WrappingSyntacticList;
  7231. InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
  7232. Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
  7233. ILE->setSyntacticForm(Syntactic);
  7234. ILE->setType(E->getType());
  7235. ILE->setValueKind(E->getValueKind());
  7236. CurInit = ILE;
  7237. break;
  7238. }
  7239. case SK_ConstructorInitialization:
  7240. case SK_StdInitializerListConstructorCall: {
  7241. if (checkAbstractType(Step->Type))
  7242. return ExprError();
  7243. // When an initializer list is passed for a parameter of type "reference
  7244. // to object", we don't get an EK_Temporary entity, but instead an
  7245. // EK_Parameter entity with reference type.
  7246. // FIXME: This is a hack. What we really should do is create a user
  7247. // conversion step for this case, but this makes it considerably more
  7248. // complicated. For now, this will do.
  7249. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  7250. Entity.getType().getNonReferenceType());
  7251. bool UseTemporary = Entity.getType()->isReferenceType();
  7252. bool IsStdInitListInit =
  7253. Step->Kind == SK_StdInitializerListConstructorCall;
  7254. Expr *Source = CurInit.get();
  7255. SourceRange Range = Kind.hasParenOrBraceRange()
  7256. ? Kind.getParenOrBraceRange()
  7257. : SourceRange();
  7258. CurInit = PerformConstructorInitialization(
  7259. S, UseTemporary ? TempEntity : Entity, Kind,
  7260. Source ? MultiExprArg(Source) : Args, *Step,
  7261. ConstructorInitRequiresZeroInit,
  7262. /*IsListInitialization*/ IsStdInitListInit,
  7263. /*IsStdInitListInitialization*/ IsStdInitListInit,
  7264. /*LBraceLoc*/ Range.getBegin(),
  7265. /*RBraceLoc*/ Range.getEnd());
  7266. break;
  7267. }
  7268. case SK_ZeroInitialization: {
  7269. step_iterator NextStep = Step;
  7270. ++NextStep;
  7271. if (NextStep != StepEnd &&
  7272. (NextStep->Kind == SK_ConstructorInitialization ||
  7273. NextStep->Kind == SK_ConstructorInitializationFromList)) {
  7274. // The need for zero-initialization is recorded directly into
  7275. // the call to the object's constructor within the next step.
  7276. ConstructorInitRequiresZeroInit = true;
  7277. } else if (Kind.getKind() == InitializationKind::IK_Value &&
  7278. S.getLangOpts().CPlusPlus &&
  7279. !Kind.isImplicitValueInit()) {
  7280. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  7281. if (!TSInfo)
  7282. TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
  7283. Kind.getRange().getBegin());
  7284. CurInit = new (S.Context) CXXScalarValueInitExpr(
  7285. Entity.getType().getNonLValueExprType(S.Context), TSInfo,
  7286. Kind.getRange().getEnd());
  7287. } else {
  7288. CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
  7289. }
  7290. break;
  7291. }
  7292. case SK_CAssignment: {
  7293. QualType SourceType = CurInit.get()->getType();
  7294. // Save off the initial CurInit in case we need to emit a diagnostic
  7295. ExprResult InitialCurInit = CurInit;
  7296. ExprResult Result = CurInit;
  7297. Sema::AssignConvertType ConvTy =
  7298. S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
  7299. Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
  7300. if (Result.isInvalid())
  7301. return ExprError();
  7302. CurInit = Result;
  7303. // If this is a call, allow conversion to a transparent union.
  7304. ExprResult CurInitExprRes = CurInit;
  7305. if (ConvTy != Sema::Compatible &&
  7306. Entity.isParameterKind() &&
  7307. S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
  7308. == Sema::Compatible)
  7309. ConvTy = Sema::Compatible;
  7310. if (CurInitExprRes.isInvalid())
  7311. return ExprError();
  7312. CurInit = CurInitExprRes;
  7313. bool Complained;
  7314. if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
  7315. Step->Type, SourceType,
  7316. InitialCurInit.get(),
  7317. getAssignmentAction(Entity, true),
  7318. &Complained)) {
  7319. PrintInitLocationNote(S, Entity);
  7320. return ExprError();
  7321. } else if (Complained)
  7322. PrintInitLocationNote(S, Entity);
  7323. break;
  7324. }
  7325. case SK_StringInit: {
  7326. QualType Ty = Step->Type;
  7327. CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
  7328. S.Context.getAsArrayType(Ty), S);
  7329. break;
  7330. }
  7331. case SK_ObjCObjectConversion:
  7332. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7333. CK_ObjCObjectLValueCast,
  7334. CurInit.get()->getValueKind());
  7335. break;
  7336. case SK_ArrayLoopIndex: {
  7337. Expr *Cur = CurInit.get();
  7338. Expr *BaseExpr = new (S.Context)
  7339. OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
  7340. Cur->getValueKind(), Cur->getObjectKind(), Cur);
  7341. Expr *IndexExpr =
  7342. new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
  7343. CurInit = S.CreateBuiltinArraySubscriptExpr(
  7344. BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
  7345. ArrayLoopCommonExprs.push_back(BaseExpr);
  7346. break;
  7347. }
  7348. case SK_ArrayLoopInit: {
  7349. assert(!ArrayLoopCommonExprs.empty() &&
  7350. "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
  7351. Expr *Common = ArrayLoopCommonExprs.pop_back_val();
  7352. CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
  7353. CurInit.get());
  7354. break;
  7355. }
  7356. case SK_GNUArrayInit:
  7357. // Okay: we checked everything before creating this step. Note that
  7358. // this is a GNU extension.
  7359. S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
  7360. << Step->Type << CurInit.get()->getType()
  7361. << CurInit.get()->getSourceRange();
  7362. updateGNUCompoundLiteralRValue(CurInit.get());
  7363. LLVM_FALLTHROUGH;
  7364. case SK_ArrayInit:
  7365. // If the destination type is an incomplete array type, update the
  7366. // type accordingly.
  7367. if (ResultType) {
  7368. if (const IncompleteArrayType *IncompleteDest
  7369. = S.Context.getAsIncompleteArrayType(Step->Type)) {
  7370. if (const ConstantArrayType *ConstantSource
  7371. = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
  7372. *ResultType = S.Context.getConstantArrayType(
  7373. IncompleteDest->getElementType(),
  7374. ConstantSource->getSize(),
  7375. ArrayType::Normal, 0);
  7376. }
  7377. }
  7378. }
  7379. break;
  7380. case SK_ParenthesizedArrayInit:
  7381. // Okay: we checked everything before creating this step. Note that
  7382. // this is a GNU extension.
  7383. S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
  7384. << CurInit.get()->getSourceRange();
  7385. break;
  7386. case SK_PassByIndirectCopyRestore:
  7387. case SK_PassByIndirectRestore:
  7388. checkIndirectCopyRestoreSource(S, CurInit.get());
  7389. CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
  7390. CurInit.get(), Step->Type,
  7391. Step->Kind == SK_PassByIndirectCopyRestore);
  7392. break;
  7393. case SK_ProduceObjCObject:
  7394. CurInit =
  7395. ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
  7396. CurInit.get(), nullptr, VK_RValue);
  7397. break;
  7398. case SK_StdInitializerList: {
  7399. S.Diag(CurInit.get()->getExprLoc(),
  7400. diag::warn_cxx98_compat_initializer_list_init)
  7401. << CurInit.get()->getSourceRange();
  7402. // Materialize the temporary into memory.
  7403. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
  7404. CurInit.get()->getType(), CurInit.get(),
  7405. /*BoundToLvalueReference=*/false);
  7406. // Wrap it in a construction of a std::initializer_list<T>.
  7407. CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
  7408. // Bind the result, in case the library has given initializer_list a
  7409. // non-trivial destructor.
  7410. if (shouldBindAsTemporary(Entity))
  7411. CurInit = S.MaybeBindToTemporary(CurInit.get());
  7412. break;
  7413. }
  7414. case SK_OCLSamplerInit: {
  7415. // Sampler initialization have 5 cases:
  7416. // 1. function argument passing
  7417. // 1a. argument is a file-scope variable
  7418. // 1b. argument is a function-scope variable
  7419. // 1c. argument is one of caller function's parameters
  7420. // 2. variable initialization
  7421. // 2a. initializing a file-scope variable
  7422. // 2b. initializing a function-scope variable
  7423. //
  7424. // For file-scope variables, since they cannot be initialized by function
  7425. // call of __translate_sampler_initializer in LLVM IR, their references
  7426. // need to be replaced by a cast from their literal initializers to
  7427. // sampler type. Since sampler variables can only be used in function
  7428. // calls as arguments, we only need to replace them when handling the
  7429. // argument passing.
  7430. assert(Step->Type->isSamplerT() &&
  7431. "Sampler initialization on non-sampler type.");
  7432. Expr *Init = CurInit.get()->IgnoreParens();
  7433. QualType SourceType = Init->getType();
  7434. // Case 1
  7435. if (Entity.isParameterKind()) {
  7436. if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
  7437. S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
  7438. << SourceType;
  7439. break;
  7440. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
  7441. auto Var = cast<VarDecl>(DRE->getDecl());
  7442. // Case 1b and 1c
  7443. // No cast from integer to sampler is needed.
  7444. if (!Var->hasGlobalStorage()) {
  7445. CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
  7446. CK_LValueToRValue, Init,
  7447. /*BasePath=*/nullptr, VK_RValue);
  7448. break;
  7449. }
  7450. // Case 1a
  7451. // For function call with a file-scope sampler variable as argument,
  7452. // get the integer literal.
  7453. // Do not diagnose if the file-scope variable does not have initializer
  7454. // since this has already been diagnosed when parsing the variable
  7455. // declaration.
  7456. if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
  7457. break;
  7458. Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
  7459. Var->getInit()))->getSubExpr();
  7460. SourceType = Init->getType();
  7461. }
  7462. } else {
  7463. // Case 2
  7464. // Check initializer is 32 bit integer constant.
  7465. // If the initializer is taken from global variable, do not diagnose since
  7466. // this has already been done when parsing the variable declaration.
  7467. if (!Init->isConstantInitializer(S.Context, false))
  7468. break;
  7469. if (!SourceType->isIntegerType() ||
  7470. 32 != S.Context.getIntWidth(SourceType)) {
  7471. S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
  7472. << SourceType;
  7473. break;
  7474. }
  7475. Expr::EvalResult EVResult;
  7476. Init->EvaluateAsInt(EVResult, S.Context);
  7477. llvm::APSInt Result = EVResult.Val.getInt();
  7478. const uint64_t SamplerValue = Result.getLimitedValue();
  7479. // 32-bit value of sampler's initializer is interpreted as
  7480. // bit-field with the following structure:
  7481. // |unspecified|Filter|Addressing Mode| Normalized Coords|
  7482. // |31 6|5 4|3 1| 0|
  7483. // This structure corresponds to enum values of sampler properties
  7484. // defined in SPIR spec v1.2 and also opencl-c.h
  7485. unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
  7486. unsigned FilterMode = (0x30 & SamplerValue) >> 4;
  7487. if (FilterMode != 1 && FilterMode != 2 &&
  7488. !S.getOpenCLOptions().isEnabled(
  7489. "cl_intel_device_side_avc_motion_estimation"))
  7490. S.Diag(Kind.getLocation(),
  7491. diag::warn_sampler_initializer_invalid_bits)
  7492. << "Filter Mode";
  7493. if (AddressingMode > 4)
  7494. S.Diag(Kind.getLocation(),
  7495. diag::warn_sampler_initializer_invalid_bits)
  7496. << "Addressing Mode";
  7497. }
  7498. // Cases 1a, 2a and 2b
  7499. // Insert cast from integer to sampler.
  7500. CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
  7501. CK_IntToOCLSampler);
  7502. break;
  7503. }
  7504. case SK_OCLZeroOpaqueType: {
  7505. assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
  7506. Step->Type->isOCLIntelSubgroupAVCType()) &&
  7507. "Wrong type for initialization of OpenCL opaque type.");
  7508. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  7509. CK_ZeroToOCLOpaqueType,
  7510. CurInit.get()->getValueKind());
  7511. break;
  7512. }
  7513. }
  7514. }
  7515. // Check whether the initializer has a shorter lifetime than the initialized
  7516. // entity, and if not, either lifetime-extend or warn as appropriate.
  7517. if (auto *Init = CurInit.get())
  7518. S.checkInitializerLifetime(Entity, Init);
  7519. // Diagnose non-fatal problems with the completed initialization.
  7520. if (Entity.getKind() == InitializedEntity::EK_Member &&
  7521. cast<FieldDecl>(Entity.getDecl())->isBitField())
  7522. S.CheckBitFieldInitialization(Kind.getLocation(),
  7523. cast<FieldDecl>(Entity.getDecl()),
  7524. CurInit.get());
  7525. // Check for std::move on construction.
  7526. if (const Expr *E = CurInit.get()) {
  7527. CheckMoveOnConstruction(S, E,
  7528. Entity.getKind() == InitializedEntity::EK_Result);
  7529. }
  7530. return CurInit;
  7531. }
  7532. /// Somewhere within T there is an uninitialized reference subobject.
  7533. /// Dig it out and diagnose it.
  7534. static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
  7535. QualType T) {
  7536. if (T->isReferenceType()) {
  7537. S.Diag(Loc, diag::err_reference_without_init)
  7538. << T.getNonReferenceType();
  7539. return true;
  7540. }
  7541. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  7542. if (!RD || !RD->hasUninitializedReferenceMember())
  7543. return false;
  7544. for (const auto *FI : RD->fields()) {
  7545. if (FI->isUnnamedBitfield())
  7546. continue;
  7547. if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
  7548. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  7549. return true;
  7550. }
  7551. }
  7552. for (const auto &BI : RD->bases()) {
  7553. if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
  7554. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  7555. return true;
  7556. }
  7557. }
  7558. return false;
  7559. }
  7560. //===----------------------------------------------------------------------===//
  7561. // Diagnose initialization failures
  7562. //===----------------------------------------------------------------------===//
  7563. /// Emit notes associated with an initialization that failed due to a
  7564. /// "simple" conversion failure.
  7565. static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
  7566. Expr *op) {
  7567. QualType destType = entity.getType();
  7568. if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
  7569. op->getType()->isObjCObjectPointerType()) {
  7570. // Emit a possible note about the conversion failing because the
  7571. // operand is a message send with a related result type.
  7572. S.EmitRelatedResultTypeNote(op);
  7573. // Emit a possible note about a return failing because we're
  7574. // expecting a related result type.
  7575. if (entity.getKind() == InitializedEntity::EK_Result)
  7576. S.EmitRelatedResultTypeNoteForReturn(destType);
  7577. }
  7578. }
  7579. static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
  7580. InitListExpr *InitList) {
  7581. QualType DestType = Entity.getType();
  7582. QualType E;
  7583. if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
  7584. QualType ArrayType = S.Context.getConstantArrayType(
  7585. E.withConst(),
  7586. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  7587. InitList->getNumInits()),
  7588. clang::ArrayType::Normal, 0);
  7589. InitializedEntity HiddenArray =
  7590. InitializedEntity::InitializeTemporary(ArrayType);
  7591. return diagnoseListInit(S, HiddenArray, InitList);
  7592. }
  7593. if (DestType->isReferenceType()) {
  7594. // A list-initialization failure for a reference means that we tried to
  7595. // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
  7596. // inner initialization failed.
  7597. QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
  7598. diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
  7599. SourceLocation Loc = InitList->getBeginLoc();
  7600. if (auto *D = Entity.getDecl())
  7601. Loc = D->getLocation();
  7602. S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
  7603. return;
  7604. }
  7605. InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
  7606. /*VerifyOnly=*/false,
  7607. /*TreatUnavailableAsInvalid=*/false);
  7608. assert(DiagnoseInitList.HadError() &&
  7609. "Inconsistent init list check result.");
  7610. }
  7611. bool InitializationSequence::Diagnose(Sema &S,
  7612. const InitializedEntity &Entity,
  7613. const InitializationKind &Kind,
  7614. ArrayRef<Expr *> Args) {
  7615. if (!Failed())
  7616. return false;
  7617. // When we want to diagnose only one element of a braced-init-list,
  7618. // we need to factor it out.
  7619. Expr *OnlyArg;
  7620. if (Args.size() == 1) {
  7621. auto *List = dyn_cast<InitListExpr>(Args[0]);
  7622. if (List && List->getNumInits() == 1)
  7623. OnlyArg = List->getInit(0);
  7624. else
  7625. OnlyArg = Args[0];
  7626. }
  7627. else
  7628. OnlyArg = nullptr;
  7629. QualType DestType = Entity.getType();
  7630. switch (Failure) {
  7631. case FK_TooManyInitsForReference:
  7632. // FIXME: Customize for the initialized entity?
  7633. if (Args.empty()) {
  7634. // Dig out the reference subobject which is uninitialized and diagnose it.
  7635. // If this is value-initialization, this could be nested some way within
  7636. // the target type.
  7637. assert(Kind.getKind() == InitializationKind::IK_Value ||
  7638. DestType->isReferenceType());
  7639. bool Diagnosed =
  7640. DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
  7641. assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
  7642. (void)Diagnosed;
  7643. } else // FIXME: diagnostic below could be better!
  7644. S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
  7645. << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  7646. break;
  7647. case FK_ParenthesizedListInitForReference:
  7648. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  7649. << 1 << Entity.getType() << Args[0]->getSourceRange();
  7650. break;
  7651. case FK_ArrayNeedsInitList:
  7652. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
  7653. break;
  7654. case FK_ArrayNeedsInitListOrStringLiteral:
  7655. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
  7656. break;
  7657. case FK_ArrayNeedsInitListOrWideStringLiteral:
  7658. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
  7659. break;
  7660. case FK_NarrowStringIntoWideCharArray:
  7661. S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
  7662. break;
  7663. case FK_WideStringIntoCharArray:
  7664. S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
  7665. break;
  7666. case FK_IncompatWideStringIntoWideChar:
  7667. S.Diag(Kind.getLocation(),
  7668. diag::err_array_init_incompat_wide_string_into_wchar);
  7669. break;
  7670. case FK_PlainStringIntoUTF8Char:
  7671. S.Diag(Kind.getLocation(),
  7672. diag::err_array_init_plain_string_into_char8_t);
  7673. S.Diag(Args.front()->getBeginLoc(),
  7674. diag::note_array_init_plain_string_into_char8_t)
  7675. << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
  7676. break;
  7677. case FK_UTF8StringIntoPlainChar:
  7678. S.Diag(Kind.getLocation(),
  7679. diag::err_array_init_utf8_string_into_char)
  7680. << S.getLangOpts().CPlusPlus2a;
  7681. break;
  7682. case FK_ArrayTypeMismatch:
  7683. case FK_NonConstantArrayInit:
  7684. S.Diag(Kind.getLocation(),
  7685. (Failure == FK_ArrayTypeMismatch
  7686. ? diag::err_array_init_different_type
  7687. : diag::err_array_init_non_constant_array))
  7688. << DestType.getNonReferenceType()
  7689. << OnlyArg->getType()
  7690. << Args[0]->getSourceRange();
  7691. break;
  7692. case FK_VariableLengthArrayHasInitializer:
  7693. S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
  7694. << Args[0]->getSourceRange();
  7695. break;
  7696. case FK_AddressOfOverloadFailed: {
  7697. DeclAccessPair Found;
  7698. S.ResolveAddressOfOverloadedFunction(OnlyArg,
  7699. DestType.getNonReferenceType(),
  7700. true,
  7701. Found);
  7702. break;
  7703. }
  7704. case FK_AddressOfUnaddressableFunction: {
  7705. auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
  7706. S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  7707. OnlyArg->getBeginLoc());
  7708. break;
  7709. }
  7710. case FK_ReferenceInitOverloadFailed:
  7711. case FK_UserConversionOverloadFailed:
  7712. switch (FailedOverloadResult) {
  7713. case OR_Ambiguous:
  7714. FailedCandidateSet.NoteCandidates(
  7715. PartialDiagnosticAt(
  7716. Kind.getLocation(),
  7717. Failure == FK_UserConversionOverloadFailed
  7718. ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
  7719. << OnlyArg->getType() << DestType
  7720. << Args[0]->getSourceRange())
  7721. : (S.PDiag(diag::err_ref_init_ambiguous)
  7722. << DestType << OnlyArg->getType()
  7723. << Args[0]->getSourceRange())),
  7724. S, OCD_ViableCandidates, Args);
  7725. break;
  7726. case OR_No_Viable_Function: {
  7727. auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
  7728. if (!S.RequireCompleteType(Kind.getLocation(),
  7729. DestType.getNonReferenceType(),
  7730. diag::err_typecheck_nonviable_condition_incomplete,
  7731. OnlyArg->getType(), Args[0]->getSourceRange()))
  7732. S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
  7733. << (Entity.getKind() == InitializedEntity::EK_Result)
  7734. << OnlyArg->getType() << Args[0]->getSourceRange()
  7735. << DestType.getNonReferenceType();
  7736. FailedCandidateSet.NoteCandidates(S, Args, Cands);
  7737. break;
  7738. }
  7739. case OR_Deleted: {
  7740. S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
  7741. << OnlyArg->getType() << DestType.getNonReferenceType()
  7742. << Args[0]->getSourceRange();
  7743. OverloadCandidateSet::iterator Best;
  7744. OverloadingResult Ovl
  7745. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  7746. if (Ovl == OR_Deleted) {
  7747. S.NoteDeletedFunction(Best->Function);
  7748. } else {
  7749. llvm_unreachable("Inconsistent overload resolution?");
  7750. }
  7751. break;
  7752. }
  7753. case OR_Success:
  7754. llvm_unreachable("Conversion did not fail!");
  7755. }
  7756. break;
  7757. case FK_NonConstLValueReferenceBindingToTemporary:
  7758. if (isa<InitListExpr>(Args[0])) {
  7759. S.Diag(Kind.getLocation(),
  7760. diag::err_lvalue_reference_bind_to_initlist)
  7761. << DestType.getNonReferenceType().isVolatileQualified()
  7762. << DestType.getNonReferenceType()
  7763. << Args[0]->getSourceRange();
  7764. break;
  7765. }
  7766. LLVM_FALLTHROUGH;
  7767. case FK_NonConstLValueReferenceBindingToUnrelated:
  7768. S.Diag(Kind.getLocation(),
  7769. Failure == FK_NonConstLValueReferenceBindingToTemporary
  7770. ? diag::err_lvalue_reference_bind_to_temporary
  7771. : diag::err_lvalue_reference_bind_to_unrelated)
  7772. << DestType.getNonReferenceType().isVolatileQualified()
  7773. << DestType.getNonReferenceType()
  7774. << OnlyArg->getType()
  7775. << Args[0]->getSourceRange();
  7776. break;
  7777. case FK_NonConstLValueReferenceBindingToBitfield: {
  7778. // We don't necessarily have an unambiguous source bit-field.
  7779. FieldDecl *BitField = Args[0]->getSourceBitField();
  7780. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
  7781. << DestType.isVolatileQualified()
  7782. << (BitField ? BitField->getDeclName() : DeclarationName())
  7783. << (BitField != nullptr)
  7784. << Args[0]->getSourceRange();
  7785. if (BitField)
  7786. S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
  7787. break;
  7788. }
  7789. case FK_NonConstLValueReferenceBindingToVectorElement:
  7790. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
  7791. << DestType.isVolatileQualified()
  7792. << Args[0]->getSourceRange();
  7793. break;
  7794. case FK_RValueReferenceBindingToLValue:
  7795. S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
  7796. << DestType.getNonReferenceType() << OnlyArg->getType()
  7797. << Args[0]->getSourceRange();
  7798. break;
  7799. case FK_ReferenceAddrspaceMismatchTemporary:
  7800. S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
  7801. << DestType << Args[0]->getSourceRange();
  7802. break;
  7803. case FK_ReferenceInitDropsQualifiers: {
  7804. QualType SourceType = OnlyArg->getType();
  7805. QualType NonRefType = DestType.getNonReferenceType();
  7806. Qualifiers DroppedQualifiers =
  7807. SourceType.getQualifiers() - NonRefType.getQualifiers();
  7808. if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
  7809. SourceType.getQualifiers()))
  7810. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  7811. << NonRefType << SourceType << 1 /*addr space*/
  7812. << Args[0]->getSourceRange();
  7813. else
  7814. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  7815. << NonRefType << SourceType << 0 /*cv quals*/
  7816. << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
  7817. << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
  7818. break;
  7819. }
  7820. case FK_ReferenceInitFailed:
  7821. S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
  7822. << DestType.getNonReferenceType()
  7823. << DestType.getNonReferenceType()->isIncompleteType()
  7824. << OnlyArg->isLValue()
  7825. << OnlyArg->getType()
  7826. << Args[0]->getSourceRange();
  7827. emitBadConversionNotes(S, Entity, Args[0]);
  7828. break;
  7829. case FK_ConversionFailed: {
  7830. QualType FromType = OnlyArg->getType();
  7831. PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
  7832. << (int)Entity.getKind()
  7833. << DestType
  7834. << OnlyArg->isLValue()
  7835. << FromType
  7836. << Args[0]->getSourceRange();
  7837. S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
  7838. S.Diag(Kind.getLocation(), PDiag);
  7839. emitBadConversionNotes(S, Entity, Args[0]);
  7840. break;
  7841. }
  7842. case FK_ConversionFromPropertyFailed:
  7843. // No-op. This error has already been reported.
  7844. break;
  7845. case FK_TooManyInitsForScalar: {
  7846. SourceRange R;
  7847. auto *InitList = dyn_cast<InitListExpr>(Args[0]);
  7848. if (InitList && InitList->getNumInits() >= 1) {
  7849. R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
  7850. } else {
  7851. assert(Args.size() > 1 && "Expected multiple initializers!");
  7852. R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
  7853. }
  7854. R.setBegin(S.getLocForEndOfToken(R.getBegin()));
  7855. if (Kind.isCStyleOrFunctionalCast())
  7856. S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
  7857. << R;
  7858. else
  7859. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  7860. << /*scalar=*/2 << R;
  7861. break;
  7862. }
  7863. case FK_ParenthesizedListInitForScalar:
  7864. S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
  7865. << 0 << Entity.getType() << Args[0]->getSourceRange();
  7866. break;
  7867. case FK_ReferenceBindingToInitList:
  7868. S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
  7869. << DestType.getNonReferenceType() << Args[0]->getSourceRange();
  7870. break;
  7871. case FK_InitListBadDestinationType:
  7872. S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
  7873. << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
  7874. break;
  7875. case FK_ListConstructorOverloadFailed:
  7876. case FK_ConstructorOverloadFailed: {
  7877. SourceRange ArgsRange;
  7878. if (Args.size())
  7879. ArgsRange =
  7880. SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
  7881. if (Failure == FK_ListConstructorOverloadFailed) {
  7882. assert(Args.size() == 1 &&
  7883. "List construction from other than 1 argument.");
  7884. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  7885. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  7886. }
  7887. // FIXME: Using "DestType" for the entity we're printing is probably
  7888. // bad.
  7889. switch (FailedOverloadResult) {
  7890. case OR_Ambiguous:
  7891. FailedCandidateSet.NoteCandidates(
  7892. PartialDiagnosticAt(Kind.getLocation(),
  7893. S.PDiag(diag::err_ovl_ambiguous_init)
  7894. << DestType << ArgsRange),
  7895. S, OCD_ViableCandidates, Args);
  7896. break;
  7897. case OR_No_Viable_Function:
  7898. if (Kind.getKind() == InitializationKind::IK_Default &&
  7899. (Entity.getKind() == InitializedEntity::EK_Base ||
  7900. Entity.getKind() == InitializedEntity::EK_Member) &&
  7901. isa<CXXConstructorDecl>(S.CurContext)) {
  7902. // This is implicit default initialization of a member or
  7903. // base within a constructor. If no viable function was
  7904. // found, notify the user that they need to explicitly
  7905. // initialize this base/member.
  7906. CXXConstructorDecl *Constructor
  7907. = cast<CXXConstructorDecl>(S.CurContext);
  7908. const CXXRecordDecl *InheritedFrom = nullptr;
  7909. if (auto Inherited = Constructor->getInheritedConstructor())
  7910. InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
  7911. if (Entity.getKind() == InitializedEntity::EK_Base) {
  7912. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  7913. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  7914. << S.Context.getTypeDeclType(Constructor->getParent())
  7915. << /*base=*/0
  7916. << Entity.getType()
  7917. << InheritedFrom;
  7918. RecordDecl *BaseDecl
  7919. = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
  7920. ->getDecl();
  7921. S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  7922. << S.Context.getTagDeclType(BaseDecl);
  7923. } else {
  7924. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  7925. << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
  7926. << S.Context.getTypeDeclType(Constructor->getParent())
  7927. << /*member=*/1
  7928. << Entity.getName()
  7929. << InheritedFrom;
  7930. S.Diag(Entity.getDecl()->getLocation(),
  7931. diag::note_member_declared_at);
  7932. if (const RecordType *Record
  7933. = Entity.getType()->getAs<RecordType>())
  7934. S.Diag(Record->getDecl()->getLocation(),
  7935. diag::note_previous_decl)
  7936. << S.Context.getTagDeclType(Record->getDecl());
  7937. }
  7938. break;
  7939. }
  7940. FailedCandidateSet.NoteCandidates(
  7941. PartialDiagnosticAt(
  7942. Kind.getLocation(),
  7943. S.PDiag(diag::err_ovl_no_viable_function_in_init)
  7944. << DestType << ArgsRange),
  7945. S, OCD_AllCandidates, Args);
  7946. break;
  7947. case OR_Deleted: {
  7948. OverloadCandidateSet::iterator Best;
  7949. OverloadingResult Ovl
  7950. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  7951. if (Ovl != OR_Deleted) {
  7952. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  7953. << DestType << ArgsRange;
  7954. llvm_unreachable("Inconsistent overload resolution?");
  7955. break;
  7956. }
  7957. // If this is a defaulted or implicitly-declared function, then
  7958. // it was implicitly deleted. Make it clear that the deletion was
  7959. // implicit.
  7960. if (S.isImplicitlyDeleted(Best->Function))
  7961. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
  7962. << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
  7963. << DestType << ArgsRange;
  7964. else
  7965. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  7966. << DestType << ArgsRange;
  7967. S.NoteDeletedFunction(Best->Function);
  7968. break;
  7969. }
  7970. case OR_Success:
  7971. llvm_unreachable("Conversion did not fail!");
  7972. }
  7973. }
  7974. break;
  7975. case FK_DefaultInitOfConst:
  7976. if (Entity.getKind() == InitializedEntity::EK_Member &&
  7977. isa<CXXConstructorDecl>(S.CurContext)) {
  7978. // This is implicit default-initialization of a const member in
  7979. // a constructor. Complain that it needs to be explicitly
  7980. // initialized.
  7981. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
  7982. S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
  7983. << (Constructor->getInheritedConstructor() ? 2 :
  7984. Constructor->isImplicit() ? 1 : 0)
  7985. << S.Context.getTypeDeclType(Constructor->getParent())
  7986. << /*const=*/1
  7987. << Entity.getName();
  7988. S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
  7989. << Entity.getName();
  7990. } else {
  7991. S.Diag(Kind.getLocation(), diag::err_default_init_const)
  7992. << DestType << (bool)DestType->getAs<RecordType>();
  7993. }
  7994. break;
  7995. case FK_Incomplete:
  7996. S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
  7997. diag::err_init_incomplete_type);
  7998. break;
  7999. case FK_ListInitializationFailed: {
  8000. // Run the init list checker again to emit diagnostics.
  8001. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  8002. diagnoseListInit(S, Entity, InitList);
  8003. break;
  8004. }
  8005. case FK_PlaceholderType: {
  8006. // FIXME: Already diagnosed!
  8007. break;
  8008. }
  8009. case FK_ExplicitConstructor: {
  8010. S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
  8011. << Args[0]->getSourceRange();
  8012. OverloadCandidateSet::iterator Best;
  8013. OverloadingResult Ovl
  8014. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  8015. (void)Ovl;
  8016. assert(Ovl == OR_Success && "Inconsistent overload resolution");
  8017. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  8018. S.Diag(CtorDecl->getLocation(),
  8019. diag::note_explicit_ctor_deduction_guide_here) << false;
  8020. break;
  8021. }
  8022. }
  8023. PrintInitLocationNote(S, Entity);
  8024. return true;
  8025. }
  8026. void InitializationSequence::dump(raw_ostream &OS) const {
  8027. switch (SequenceKind) {
  8028. case FailedSequence: {
  8029. OS << "Failed sequence: ";
  8030. switch (Failure) {
  8031. case FK_TooManyInitsForReference:
  8032. OS << "too many initializers for reference";
  8033. break;
  8034. case FK_ParenthesizedListInitForReference:
  8035. OS << "parenthesized list init for reference";
  8036. break;
  8037. case FK_ArrayNeedsInitList:
  8038. OS << "array requires initializer list";
  8039. break;
  8040. case FK_AddressOfUnaddressableFunction:
  8041. OS << "address of unaddressable function was taken";
  8042. break;
  8043. case FK_ArrayNeedsInitListOrStringLiteral:
  8044. OS << "array requires initializer list or string literal";
  8045. break;
  8046. case FK_ArrayNeedsInitListOrWideStringLiteral:
  8047. OS << "array requires initializer list or wide string literal";
  8048. break;
  8049. case FK_NarrowStringIntoWideCharArray:
  8050. OS << "narrow string into wide char array";
  8051. break;
  8052. case FK_WideStringIntoCharArray:
  8053. OS << "wide string into char array";
  8054. break;
  8055. case FK_IncompatWideStringIntoWideChar:
  8056. OS << "incompatible wide string into wide char array";
  8057. break;
  8058. case FK_PlainStringIntoUTF8Char:
  8059. OS << "plain string literal into char8_t array";
  8060. break;
  8061. case FK_UTF8StringIntoPlainChar:
  8062. OS << "u8 string literal into char array";
  8063. break;
  8064. case FK_ArrayTypeMismatch:
  8065. OS << "array type mismatch";
  8066. break;
  8067. case FK_NonConstantArrayInit:
  8068. OS << "non-constant array initializer";
  8069. break;
  8070. case FK_AddressOfOverloadFailed:
  8071. OS << "address of overloaded function failed";
  8072. break;
  8073. case FK_ReferenceInitOverloadFailed:
  8074. OS << "overload resolution for reference initialization failed";
  8075. break;
  8076. case FK_NonConstLValueReferenceBindingToTemporary:
  8077. OS << "non-const lvalue reference bound to temporary";
  8078. break;
  8079. case FK_NonConstLValueReferenceBindingToBitfield:
  8080. OS << "non-const lvalue reference bound to bit-field";
  8081. break;
  8082. case FK_NonConstLValueReferenceBindingToVectorElement:
  8083. OS << "non-const lvalue reference bound to vector element";
  8084. break;
  8085. case FK_NonConstLValueReferenceBindingToUnrelated:
  8086. OS << "non-const lvalue reference bound to unrelated type";
  8087. break;
  8088. case FK_RValueReferenceBindingToLValue:
  8089. OS << "rvalue reference bound to an lvalue";
  8090. break;
  8091. case FK_ReferenceInitDropsQualifiers:
  8092. OS << "reference initialization drops qualifiers";
  8093. break;
  8094. case FK_ReferenceAddrspaceMismatchTemporary:
  8095. OS << "reference with mismatching address space bound to temporary";
  8096. break;
  8097. case FK_ReferenceInitFailed:
  8098. OS << "reference initialization failed";
  8099. break;
  8100. case FK_ConversionFailed:
  8101. OS << "conversion failed";
  8102. break;
  8103. case FK_ConversionFromPropertyFailed:
  8104. OS << "conversion from property failed";
  8105. break;
  8106. case FK_TooManyInitsForScalar:
  8107. OS << "too many initializers for scalar";
  8108. break;
  8109. case FK_ParenthesizedListInitForScalar:
  8110. OS << "parenthesized list init for reference";
  8111. break;
  8112. case FK_ReferenceBindingToInitList:
  8113. OS << "referencing binding to initializer list";
  8114. break;
  8115. case FK_InitListBadDestinationType:
  8116. OS << "initializer list for non-aggregate, non-scalar type";
  8117. break;
  8118. case FK_UserConversionOverloadFailed:
  8119. OS << "overloading failed for user-defined conversion";
  8120. break;
  8121. case FK_ConstructorOverloadFailed:
  8122. OS << "constructor overloading failed";
  8123. break;
  8124. case FK_DefaultInitOfConst:
  8125. OS << "default initialization of a const variable";
  8126. break;
  8127. case FK_Incomplete:
  8128. OS << "initialization of incomplete type";
  8129. break;
  8130. case FK_ListInitializationFailed:
  8131. OS << "list initialization checker failure";
  8132. break;
  8133. case FK_VariableLengthArrayHasInitializer:
  8134. OS << "variable length array has an initializer";
  8135. break;
  8136. case FK_PlaceholderType:
  8137. OS << "initializer expression isn't contextually valid";
  8138. break;
  8139. case FK_ListConstructorOverloadFailed:
  8140. OS << "list constructor overloading failed";
  8141. break;
  8142. case FK_ExplicitConstructor:
  8143. OS << "list copy initialization chose explicit constructor";
  8144. break;
  8145. }
  8146. OS << '\n';
  8147. return;
  8148. }
  8149. case DependentSequence:
  8150. OS << "Dependent sequence\n";
  8151. return;
  8152. case NormalSequence:
  8153. OS << "Normal sequence: ";
  8154. break;
  8155. }
  8156. for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
  8157. if (S != step_begin()) {
  8158. OS << " -> ";
  8159. }
  8160. switch (S->Kind) {
  8161. case SK_ResolveAddressOfOverloadedFunction:
  8162. OS << "resolve address of overloaded function";
  8163. break;
  8164. case SK_CastDerivedToBaseRValue:
  8165. OS << "derived-to-base (rvalue)";
  8166. break;
  8167. case SK_CastDerivedToBaseXValue:
  8168. OS << "derived-to-base (xvalue)";
  8169. break;
  8170. case SK_CastDerivedToBaseLValue:
  8171. OS << "derived-to-base (lvalue)";
  8172. break;
  8173. case SK_BindReference:
  8174. OS << "bind reference to lvalue";
  8175. break;
  8176. case SK_BindReferenceToTemporary:
  8177. OS << "bind reference to a temporary";
  8178. break;
  8179. case SK_FinalCopy:
  8180. OS << "final copy in class direct-initialization";
  8181. break;
  8182. case SK_ExtraneousCopyToTemporary:
  8183. OS << "extraneous C++03 copy to temporary";
  8184. break;
  8185. case SK_UserConversion:
  8186. OS << "user-defined conversion via " << *S->Function.Function;
  8187. break;
  8188. case SK_QualificationConversionRValue:
  8189. OS << "qualification conversion (rvalue)";
  8190. break;
  8191. case SK_QualificationConversionXValue:
  8192. OS << "qualification conversion (xvalue)";
  8193. break;
  8194. case SK_QualificationConversionLValue:
  8195. OS << "qualification conversion (lvalue)";
  8196. break;
  8197. case SK_AtomicConversion:
  8198. OS << "non-atomic-to-atomic conversion";
  8199. break;
  8200. case SK_ConversionSequence:
  8201. OS << "implicit conversion sequence (";
  8202. S->ICS->dump(); // FIXME: use OS
  8203. OS << ")";
  8204. break;
  8205. case SK_ConversionSequenceNoNarrowing:
  8206. OS << "implicit conversion sequence with narrowing prohibited (";
  8207. S->ICS->dump(); // FIXME: use OS
  8208. OS << ")";
  8209. break;
  8210. case SK_ListInitialization:
  8211. OS << "list aggregate initialization";
  8212. break;
  8213. case SK_UnwrapInitList:
  8214. OS << "unwrap reference initializer list";
  8215. break;
  8216. case SK_RewrapInitList:
  8217. OS << "rewrap reference initializer list";
  8218. break;
  8219. case SK_ConstructorInitialization:
  8220. OS << "constructor initialization";
  8221. break;
  8222. case SK_ConstructorInitializationFromList:
  8223. OS << "list initialization via constructor";
  8224. break;
  8225. case SK_ZeroInitialization:
  8226. OS << "zero initialization";
  8227. break;
  8228. case SK_CAssignment:
  8229. OS << "C assignment";
  8230. break;
  8231. case SK_StringInit:
  8232. OS << "string initialization";
  8233. break;
  8234. case SK_ObjCObjectConversion:
  8235. OS << "Objective-C object conversion";
  8236. break;
  8237. case SK_ArrayLoopIndex:
  8238. OS << "indexing for array initialization loop";
  8239. break;
  8240. case SK_ArrayLoopInit:
  8241. OS << "array initialization loop";
  8242. break;
  8243. case SK_ArrayInit:
  8244. OS << "array initialization";
  8245. break;
  8246. case SK_GNUArrayInit:
  8247. OS << "array initialization (GNU extension)";
  8248. break;
  8249. case SK_ParenthesizedArrayInit:
  8250. OS << "parenthesized array initialization";
  8251. break;
  8252. case SK_PassByIndirectCopyRestore:
  8253. OS << "pass by indirect copy and restore";
  8254. break;
  8255. case SK_PassByIndirectRestore:
  8256. OS << "pass by indirect restore";
  8257. break;
  8258. case SK_ProduceObjCObject:
  8259. OS << "Objective-C object retension";
  8260. break;
  8261. case SK_StdInitializerList:
  8262. OS << "std::initializer_list from initializer list";
  8263. break;
  8264. case SK_StdInitializerListConstructorCall:
  8265. OS << "list initialization from std::initializer_list";
  8266. break;
  8267. case SK_OCLSamplerInit:
  8268. OS << "OpenCL sampler_t from integer constant";
  8269. break;
  8270. case SK_OCLZeroOpaqueType:
  8271. OS << "OpenCL opaque type from zero";
  8272. break;
  8273. }
  8274. OS << " [" << S->Type.getAsString() << ']';
  8275. }
  8276. OS << '\n';
  8277. }
  8278. void InitializationSequence::dump() const {
  8279. dump(llvm::errs());
  8280. }
  8281. static bool NarrowingErrs(const LangOptions &L) {
  8282. return L.CPlusPlus11 &&
  8283. (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
  8284. }
  8285. static void DiagnoseNarrowingInInitList(Sema &S,
  8286. const ImplicitConversionSequence &ICS,
  8287. QualType PreNarrowingType,
  8288. QualType EntityType,
  8289. const Expr *PostInit) {
  8290. const StandardConversionSequence *SCS = nullptr;
  8291. switch (ICS.getKind()) {
  8292. case ImplicitConversionSequence::StandardConversion:
  8293. SCS = &ICS.Standard;
  8294. break;
  8295. case ImplicitConversionSequence::UserDefinedConversion:
  8296. SCS = &ICS.UserDefined.After;
  8297. break;
  8298. case ImplicitConversionSequence::AmbiguousConversion:
  8299. case ImplicitConversionSequence::EllipsisConversion:
  8300. case ImplicitConversionSequence::BadConversion:
  8301. return;
  8302. }
  8303. // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
  8304. APValue ConstantValue;
  8305. QualType ConstantType;
  8306. switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
  8307. ConstantType)) {
  8308. case NK_Not_Narrowing:
  8309. case NK_Dependent_Narrowing:
  8310. // No narrowing occurred.
  8311. return;
  8312. case NK_Type_Narrowing:
  8313. // This was a floating-to-integer conversion, which is always considered a
  8314. // narrowing conversion even if the value is a constant and can be
  8315. // represented exactly as an integer.
  8316. S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
  8317. ? diag::ext_init_list_type_narrowing
  8318. : diag::warn_init_list_type_narrowing)
  8319. << PostInit->getSourceRange()
  8320. << PreNarrowingType.getLocalUnqualifiedType()
  8321. << EntityType.getLocalUnqualifiedType();
  8322. break;
  8323. case NK_Constant_Narrowing:
  8324. // A constant value was narrowed.
  8325. S.Diag(PostInit->getBeginLoc(),
  8326. NarrowingErrs(S.getLangOpts())
  8327. ? diag::ext_init_list_constant_narrowing
  8328. : diag::warn_init_list_constant_narrowing)
  8329. << PostInit->getSourceRange()
  8330. << ConstantValue.getAsString(S.getASTContext(), ConstantType)
  8331. << EntityType.getLocalUnqualifiedType();
  8332. break;
  8333. case NK_Variable_Narrowing:
  8334. // A variable's value may have been narrowed.
  8335. S.Diag(PostInit->getBeginLoc(),
  8336. NarrowingErrs(S.getLangOpts())
  8337. ? diag::ext_init_list_variable_narrowing
  8338. : diag::warn_init_list_variable_narrowing)
  8339. << PostInit->getSourceRange()
  8340. << PreNarrowingType.getLocalUnqualifiedType()
  8341. << EntityType.getLocalUnqualifiedType();
  8342. break;
  8343. }
  8344. SmallString<128> StaticCast;
  8345. llvm::raw_svector_ostream OS(StaticCast);
  8346. OS << "static_cast<";
  8347. if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
  8348. // It's important to use the typedef's name if there is one so that the
  8349. // fixit doesn't break code using types like int64_t.
  8350. //
  8351. // FIXME: This will break if the typedef requires qualification. But
  8352. // getQualifiedNameAsString() includes non-machine-parsable components.
  8353. OS << *TT->getDecl();
  8354. } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
  8355. OS << BT->getName(S.getLangOpts());
  8356. else {
  8357. // Oops, we didn't find the actual type of the variable. Don't emit a fixit
  8358. // with a broken cast.
  8359. return;
  8360. }
  8361. OS << ">(";
  8362. S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
  8363. << PostInit->getSourceRange()
  8364. << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
  8365. << FixItHint::CreateInsertion(
  8366. S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
  8367. }
  8368. //===----------------------------------------------------------------------===//
  8369. // Initialization helper functions
  8370. //===----------------------------------------------------------------------===//
  8371. bool
  8372. Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
  8373. ExprResult Init) {
  8374. if (Init.isInvalid())
  8375. return false;
  8376. Expr *InitE = Init.get();
  8377. assert(InitE && "No initialization expression");
  8378. InitializationKind Kind =
  8379. InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
  8380. InitializationSequence Seq(*this, Entity, Kind, InitE);
  8381. return !Seq.Failed();
  8382. }
  8383. ExprResult
  8384. Sema::PerformCopyInitialization(const InitializedEntity &Entity,
  8385. SourceLocation EqualLoc,
  8386. ExprResult Init,
  8387. bool TopLevelOfInitList,
  8388. bool AllowExplicit) {
  8389. if (Init.isInvalid())
  8390. return ExprError();
  8391. Expr *InitE = Init.get();
  8392. assert(InitE && "No initialization expression?");
  8393. if (EqualLoc.isInvalid())
  8394. EqualLoc = InitE->getBeginLoc();
  8395. InitializationKind Kind = InitializationKind::CreateCopy(
  8396. InitE->getBeginLoc(), EqualLoc, AllowExplicit);
  8397. InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
  8398. // Prevent infinite recursion when performing parameter copy-initialization.
  8399. const bool ShouldTrackCopy =
  8400. Entity.isParameterKind() && Seq.isConstructorInitialization();
  8401. if (ShouldTrackCopy) {
  8402. if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
  8403. CurrentParameterCopyTypes.end()) {
  8404. Seq.SetOverloadFailure(
  8405. InitializationSequence::FK_ConstructorOverloadFailed,
  8406. OR_No_Viable_Function);
  8407. // Try to give a meaningful diagnostic note for the problematic
  8408. // constructor.
  8409. const auto LastStep = Seq.step_end() - 1;
  8410. assert(LastStep->Kind ==
  8411. InitializationSequence::SK_ConstructorInitialization);
  8412. const FunctionDecl *Function = LastStep->Function.Function;
  8413. auto Candidate =
  8414. llvm::find_if(Seq.getFailedCandidateSet(),
  8415. [Function](const OverloadCandidate &Candidate) -> bool {
  8416. return Candidate.Viable &&
  8417. Candidate.Function == Function &&
  8418. Candidate.Conversions.size() > 0;
  8419. });
  8420. if (Candidate != Seq.getFailedCandidateSet().end() &&
  8421. Function->getNumParams() > 0) {
  8422. Candidate->Viable = false;
  8423. Candidate->FailureKind = ovl_fail_bad_conversion;
  8424. Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
  8425. InitE,
  8426. Function->getParamDecl(0)->getType());
  8427. }
  8428. }
  8429. CurrentParameterCopyTypes.push_back(Entity.getType());
  8430. }
  8431. ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
  8432. if (ShouldTrackCopy)
  8433. CurrentParameterCopyTypes.pop_back();
  8434. return Result;
  8435. }
  8436. /// Determine whether RD is, or is derived from, a specialization of CTD.
  8437. static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
  8438. ClassTemplateDecl *CTD) {
  8439. auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
  8440. auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
  8441. return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
  8442. };
  8443. return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
  8444. }
  8445. QualType Sema::DeduceTemplateSpecializationFromInitializer(
  8446. TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
  8447. const InitializationKind &Kind, MultiExprArg Inits) {
  8448. auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
  8449. TSInfo->getType()->getContainedDeducedType());
  8450. assert(DeducedTST && "not a deduced template specialization type");
  8451. auto TemplateName = DeducedTST->getTemplateName();
  8452. if (TemplateName.isDependent())
  8453. return Context.DependentTy;
  8454. // We can only perform deduction for class templates.
  8455. auto *Template =
  8456. dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
  8457. if (!Template) {
  8458. Diag(Kind.getLocation(),
  8459. diag::err_deduced_non_class_template_specialization_type)
  8460. << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
  8461. if (auto *TD = TemplateName.getAsTemplateDecl())
  8462. Diag(TD->getLocation(), diag::note_template_decl_here);
  8463. return QualType();
  8464. }
  8465. // Can't deduce from dependent arguments.
  8466. if (Expr::hasAnyTypeDependentArguments(Inits)) {
  8467. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8468. diag::warn_cxx14_compat_class_template_argument_deduction)
  8469. << TSInfo->getTypeLoc().getSourceRange() << 0;
  8470. return Context.DependentTy;
  8471. }
  8472. // FIXME: Perform "exact type" matching first, per CWG discussion?
  8473. // Or implement this via an implied 'T(T) -> T' deduction guide?
  8474. // FIXME: Do we need/want a std::initializer_list<T> special case?
  8475. // Look up deduction guides, including those synthesized from constructors.
  8476. //
  8477. // C++1z [over.match.class.deduct]p1:
  8478. // A set of functions and function templates is formed comprising:
  8479. // - For each constructor of the class template designated by the
  8480. // template-name, a function template [...]
  8481. // - For each deduction-guide, a function or function template [...]
  8482. DeclarationNameInfo NameInfo(
  8483. Context.DeclarationNames.getCXXDeductionGuideName(Template),
  8484. TSInfo->getTypeLoc().getEndLoc());
  8485. LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
  8486. LookupQualifiedName(Guides, Template->getDeclContext());
  8487. // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
  8488. // clear on this, but they're not found by name so access does not apply.
  8489. Guides.suppressDiagnostics();
  8490. // Figure out if this is list-initialization.
  8491. InitListExpr *ListInit =
  8492. (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
  8493. ? dyn_cast<InitListExpr>(Inits[0])
  8494. : nullptr;
  8495. // C++1z [over.match.class.deduct]p1:
  8496. // Initialization and overload resolution are performed as described in
  8497. // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
  8498. // (as appropriate for the type of initialization performed) for an object
  8499. // of a hypothetical class type, where the selected functions and function
  8500. // templates are considered to be the constructors of that class type
  8501. //
  8502. // Since we know we're initializing a class type of a type unrelated to that
  8503. // of the initializer, this reduces to something fairly reasonable.
  8504. OverloadCandidateSet Candidates(Kind.getLocation(),
  8505. OverloadCandidateSet::CSK_Normal);
  8506. OverloadCandidateSet::iterator Best;
  8507. bool HasAnyDeductionGuide = false;
  8508. bool AllowExplicit = !Kind.isCopyInit() || ListInit;
  8509. auto tryToResolveOverload =
  8510. [&](bool OnlyListConstructors) -> OverloadingResult {
  8511. Candidates.clear(OverloadCandidateSet::CSK_Normal);
  8512. HasAnyDeductionGuide = false;
  8513. for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
  8514. NamedDecl *D = (*I)->getUnderlyingDecl();
  8515. if (D->isInvalidDecl())
  8516. continue;
  8517. auto *TD = dyn_cast<FunctionTemplateDecl>(D);
  8518. auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
  8519. TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
  8520. if (!GD)
  8521. continue;
  8522. if (!GD->isImplicit())
  8523. HasAnyDeductionGuide = true;
  8524. // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
  8525. // For copy-initialization, the candidate functions are all the
  8526. // converting constructors (12.3.1) of that class.
  8527. // C++ [over.match.copy]p1: (non-list copy-initialization from class)
  8528. // The converting constructors of T are candidate functions.
  8529. if (!AllowExplicit) {
  8530. // Only consider converting constructors.
  8531. if (GD->isExplicit())
  8532. continue;
  8533. // When looking for a converting constructor, deduction guides that
  8534. // could never be called with one argument are not interesting to
  8535. // check or note.
  8536. if (GD->getMinRequiredArguments() > 1 ||
  8537. (GD->getNumParams() == 0 && !GD->isVariadic()))
  8538. continue;
  8539. }
  8540. // C++ [over.match.list]p1.1: (first phase list initialization)
  8541. // Initially, the candidate functions are the initializer-list
  8542. // constructors of the class T
  8543. if (OnlyListConstructors && !isInitListConstructor(GD))
  8544. continue;
  8545. // C++ [over.match.list]p1.2: (second phase list initialization)
  8546. // the candidate functions are all the constructors of the class T
  8547. // C++ [over.match.ctor]p1: (all other cases)
  8548. // the candidate functions are all the constructors of the class of
  8549. // the object being initialized
  8550. // C++ [over.best.ics]p4:
  8551. // When [...] the constructor [...] is a candidate by
  8552. // - [over.match.copy] (in all cases)
  8553. // FIXME: The "second phase of [over.match.list] case can also
  8554. // theoretically happen here, but it's not clear whether we can
  8555. // ever have a parameter of the right type.
  8556. bool SuppressUserConversions = Kind.isCopyInit();
  8557. if (TD)
  8558. AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
  8559. Inits, Candidates, SuppressUserConversions,
  8560. /*PartialOverloading*/ false,
  8561. AllowExplicit);
  8562. else
  8563. AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
  8564. SuppressUserConversions,
  8565. /*PartialOverloading*/ false, AllowExplicit);
  8566. }
  8567. return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
  8568. };
  8569. OverloadingResult Result = OR_No_Viable_Function;
  8570. // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
  8571. // try initializer-list constructors.
  8572. if (ListInit) {
  8573. bool TryListConstructors = true;
  8574. // Try list constructors unless the list is empty and the class has one or
  8575. // more default constructors, in which case those constructors win.
  8576. if (!ListInit->getNumInits()) {
  8577. for (NamedDecl *D : Guides) {
  8578. auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
  8579. if (FD && FD->getMinRequiredArguments() == 0) {
  8580. TryListConstructors = false;
  8581. break;
  8582. }
  8583. }
  8584. } else if (ListInit->getNumInits() == 1) {
  8585. // C++ [over.match.class.deduct]:
  8586. // As an exception, the first phase in [over.match.list] (considering
  8587. // initializer-list constructors) is omitted if the initializer list
  8588. // consists of a single expression of type cv U, where U is a
  8589. // specialization of C or a class derived from a specialization of C.
  8590. Expr *E = ListInit->getInit(0);
  8591. auto *RD = E->getType()->getAsCXXRecordDecl();
  8592. if (!isa<InitListExpr>(E) && RD &&
  8593. isCompleteType(Kind.getLocation(), E->getType()) &&
  8594. isOrIsDerivedFromSpecializationOf(RD, Template))
  8595. TryListConstructors = false;
  8596. }
  8597. if (TryListConstructors)
  8598. Result = tryToResolveOverload(/*OnlyListConstructor*/true);
  8599. // Then unwrap the initializer list and try again considering all
  8600. // constructors.
  8601. Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
  8602. }
  8603. // If list-initialization fails, or if we're doing any other kind of
  8604. // initialization, we (eventually) consider constructors.
  8605. if (Result == OR_No_Viable_Function)
  8606. Result = tryToResolveOverload(/*OnlyListConstructor*/false);
  8607. switch (Result) {
  8608. case OR_Ambiguous:
  8609. // FIXME: For list-initialization candidates, it'd usually be better to
  8610. // list why they were not viable when given the initializer list itself as
  8611. // an argument.
  8612. Candidates.NoteCandidates(
  8613. PartialDiagnosticAt(
  8614. Kind.getLocation(),
  8615. PDiag(diag::err_deduced_class_template_ctor_ambiguous)
  8616. << TemplateName),
  8617. *this, OCD_ViableCandidates, Inits);
  8618. return QualType();
  8619. case OR_No_Viable_Function: {
  8620. CXXRecordDecl *Primary =
  8621. cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
  8622. bool Complete =
  8623. isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
  8624. Candidates.NoteCandidates(
  8625. PartialDiagnosticAt(
  8626. Kind.getLocation(),
  8627. PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
  8628. : diag::err_deduced_class_template_incomplete)
  8629. << TemplateName << !Guides.empty()),
  8630. *this, OCD_AllCandidates, Inits);
  8631. return QualType();
  8632. }
  8633. case OR_Deleted: {
  8634. Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
  8635. << TemplateName;
  8636. NoteDeletedFunction(Best->Function);
  8637. return QualType();
  8638. }
  8639. case OR_Success:
  8640. // C++ [over.match.list]p1:
  8641. // In copy-list-initialization, if an explicit constructor is chosen, the
  8642. // initialization is ill-formed.
  8643. if (Kind.isCopyInit() && ListInit &&
  8644. cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
  8645. bool IsDeductionGuide = !Best->Function->isImplicit();
  8646. Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
  8647. << TemplateName << IsDeductionGuide;
  8648. Diag(Best->Function->getLocation(),
  8649. diag::note_explicit_ctor_deduction_guide_here)
  8650. << IsDeductionGuide;
  8651. return QualType();
  8652. }
  8653. // Make sure we didn't select an unusable deduction guide, and mark it
  8654. // as referenced.
  8655. DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
  8656. MarkFunctionReferenced(Kind.getLocation(), Best->Function);
  8657. break;
  8658. }
  8659. // C++ [dcl.type.class.deduct]p1:
  8660. // The placeholder is replaced by the return type of the function selected
  8661. // by overload resolution for class template deduction.
  8662. QualType DeducedType =
  8663. SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
  8664. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8665. diag::warn_cxx14_compat_class_template_argument_deduction)
  8666. << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
  8667. // Warn if CTAD was used on a type that does not have any user-defined
  8668. // deduction guides.
  8669. if (!HasAnyDeductionGuide) {
  8670. Diag(TSInfo->getTypeLoc().getBeginLoc(),
  8671. diag::warn_ctad_maybe_unsupported)
  8672. << TemplateName;
  8673. Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
  8674. }
  8675. return DeducedType;
  8676. }