SemaInit.cpp 388 KB

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