SemaInit.cpp 300 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737
  1. //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for initializers.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Initialization.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/TypeLoc.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/Sema/Designator.h"
  21. #include "clang/Sema/Lookup.h"
  22. #include "clang/Sema/SemaInternal.h"
  23. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  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. #include <map>
  29. using namespace clang;
  30. //===----------------------------------------------------------------------===//
  31. // Sema Initialization Checking
  32. //===----------------------------------------------------------------------===//
  33. /// \brief Check whether T is compatible with a wide character type (wchar_t,
  34. /// char16_t or char32_t).
  35. static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
  36. if (Context.typesAreCompatible(Context.getWideCharType(), T))
  37. return true;
  38. if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
  39. return Context.typesAreCompatible(Context.Char16Ty, T) ||
  40. Context.typesAreCompatible(Context.Char32Ty, T);
  41. }
  42. return false;
  43. }
  44. enum StringInitFailureKind {
  45. SIF_None,
  46. SIF_NarrowStringIntoWideChar,
  47. SIF_WideStringIntoChar,
  48. SIF_IncompatWideStringIntoWideChar,
  49. SIF_Other
  50. };
  51. /// \brief Check whether the array of type AT can be initialized by the Init
  52. /// expression by means of string initialization. Returns SIF_None if so,
  53. /// otherwise returns a StringInitFailureKind that describes why the
  54. /// initialization would not work.
  55. static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
  56. ASTContext &Context) {
  57. if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
  58. return SIF_Other;
  59. // See if this is a string literal or @encode.
  60. Init = Init->IgnoreParens();
  61. // Handle @encode, which is a narrow string.
  62. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
  63. return SIF_None;
  64. // Otherwise we can only handle string literals.
  65. StringLiteral *SL = dyn_cast<StringLiteral>(Init);
  66. if (!SL)
  67. return SIF_Other;
  68. const QualType ElemTy =
  69. Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
  70. switch (SL->getKind()) {
  71. case StringLiteral::Ascii:
  72. case StringLiteral::UTF8:
  73. // char array can be initialized with a narrow string.
  74. // Only allow char x[] = "foo"; not char x[] = L"foo";
  75. if (ElemTy->isCharType())
  76. return SIF_None;
  77. if (IsWideCharCompatible(ElemTy, Context))
  78. return SIF_NarrowStringIntoWideChar;
  79. return SIF_Other;
  80. // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
  81. // "An array with element type compatible with a qualified or unqualified
  82. // version of wchar_t, char16_t, or char32_t may be initialized by a wide
  83. // string literal with the corresponding encoding prefix (L, u, or U,
  84. // respectively), optionally enclosed in braces.
  85. case StringLiteral::UTF16:
  86. if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
  87. return SIF_None;
  88. if (ElemTy->isCharType())
  89. return SIF_WideStringIntoChar;
  90. if (IsWideCharCompatible(ElemTy, Context))
  91. return SIF_IncompatWideStringIntoWideChar;
  92. return SIF_Other;
  93. case StringLiteral::UTF32:
  94. if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
  95. return SIF_None;
  96. if (ElemTy->isCharType())
  97. return SIF_WideStringIntoChar;
  98. if (IsWideCharCompatible(ElemTy, Context))
  99. return SIF_IncompatWideStringIntoWideChar;
  100. return SIF_Other;
  101. case StringLiteral::Wide:
  102. if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
  103. return SIF_None;
  104. if (ElemTy->isCharType())
  105. return SIF_WideStringIntoChar;
  106. if (IsWideCharCompatible(ElemTy, Context))
  107. return SIF_IncompatWideStringIntoWideChar;
  108. return SIF_Other;
  109. }
  110. llvm_unreachable("missed a StringLiteral kind?");
  111. }
  112. static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
  113. ASTContext &Context) {
  114. const ArrayType *arrayType = Context.getAsArrayType(declType);
  115. if (!arrayType)
  116. return SIF_Other;
  117. return IsStringInit(init, arrayType, Context);
  118. }
  119. /// Update the type of a string literal, including any surrounding parentheses,
  120. /// to match the type of the object which it is initializing.
  121. static void updateStringLiteralType(Expr *E, QualType Ty) {
  122. while (true) {
  123. E->setType(Ty);
  124. if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
  125. break;
  126. else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
  127. E = PE->getSubExpr();
  128. else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
  129. E = UO->getSubExpr();
  130. else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
  131. E = GSE->getResultExpr();
  132. else
  133. llvm_unreachable("unexpected expr in string literal init");
  134. }
  135. }
  136. static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
  137. Sema &S) {
  138. // Get the length of the string as parsed.
  139. auto *ConstantArrayTy =
  140. cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
  141. uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
  142. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  143. // C99 6.7.8p14. We have an array of character type with unknown size
  144. // being initialized to a string literal.
  145. llvm::APInt ConstVal(32, StrLength);
  146. // Return a new array type (C99 6.7.8p22).
  147. DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
  148. ConstVal,
  149. ArrayType::Normal, 0);
  150. updateStringLiteralType(Str, DeclT);
  151. return;
  152. }
  153. const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
  154. // We have an array of character type with known size. However,
  155. // the size may be smaller or larger than the string we are initializing.
  156. // FIXME: Avoid truncation for 64-bit length strings.
  157. if (S.getLangOpts().CPlusPlus) {
  158. if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
  159. // For Pascal strings it's OK to strip off the terminating null character,
  160. // so the example below is valid:
  161. //
  162. // unsigned char a[2] = "\pa";
  163. if (SL->isPascal())
  164. StrLength--;
  165. }
  166. // [dcl.init.string]p2
  167. if (StrLength > CAT->getSize().getZExtValue())
  168. S.Diag(Str->getLocStart(),
  169. diag::err_initializer_string_for_char_array_too_long)
  170. << Str->getSourceRange();
  171. } else {
  172. // C99 6.7.8p14.
  173. if (StrLength-1 > CAT->getSize().getZExtValue())
  174. S.Diag(Str->getLocStart(),
  175. diag::ext_initializer_string_for_char_array_too_long)
  176. << Str->getSourceRange();
  177. }
  178. // Set the type to the actual size that we are initializing. If we have
  179. // something like:
  180. // char x[1] = "foo";
  181. // then this will set the string literal's type to char[1].
  182. updateStringLiteralType(Str, DeclT);
  183. }
  184. //===----------------------------------------------------------------------===//
  185. // Semantic checking for initializer lists.
  186. //===----------------------------------------------------------------------===//
  187. /// @brief Semantic checking for initializer lists.
  188. ///
  189. /// The InitListChecker class contains a set of routines that each
  190. /// handle the initialization of a certain kind of entity, e.g.,
  191. /// arrays, vectors, struct/union types, scalars, etc. The
  192. /// InitListChecker itself performs a recursive walk of the subobject
  193. /// structure of the type to be initialized, while stepping through
  194. /// the initializer list one element at a time. The IList and Index
  195. /// parameters to each of the Check* routines contain the active
  196. /// (syntactic) initializer list and the index into that initializer
  197. /// list that represents the current initializer. Each routine is
  198. /// responsible for moving that Index forward as it consumes elements.
  199. ///
  200. /// Each Check* routine also has a StructuredList/StructuredIndex
  201. /// arguments, which contains the current "structured" (semantic)
  202. /// initializer list and the index into that initializer list where we
  203. /// are copying initializers as we map them over to the semantic
  204. /// list. Once we have completed our recursive walk of the subobject
  205. /// structure, we will have constructed a full semantic initializer
  206. /// list.
  207. ///
  208. /// C99 designators cause changes in the initializer list traversal,
  209. /// because they make the initialization "jump" into a specific
  210. /// subobject and then continue the initialization from that
  211. /// point. CheckDesignatedInitializer() recursively steps into the
  212. /// designated subobject and manages backing out the recursion to
  213. /// initialize the subobjects after the one designated.
  214. namespace {
  215. class InitListChecker {
  216. Sema &SemaRef;
  217. const InitializationKind &Kind; // HLSL Change: provide access to the initialization kind
  218. bool hadError;
  219. bool VerifyOnly; // no diagnostics, no structure building
  220. llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
  221. InitListExpr *FullyStructuredList;
  222. void CheckImplicitInitList(const InitializedEntity &Entity,
  223. InitListExpr *ParentIList, QualType T,
  224. unsigned &Index, InitListExpr *StructuredList,
  225. unsigned &StructuredIndex);
  226. void CheckExplicitInitList(const InitializedEntity &Entity,
  227. InitListExpr *IList, QualType &T,
  228. InitListExpr *StructuredList,
  229. bool TopLevelObject = false);
  230. void CheckListElementTypes(const InitializedEntity &Entity,
  231. InitListExpr *IList, QualType &DeclType,
  232. bool SubobjectIsDesignatorContext,
  233. unsigned &Index,
  234. InitListExpr *StructuredList,
  235. unsigned &StructuredIndex,
  236. bool TopLevelObject = false);
  237. void CheckSubElementType(const InitializedEntity &Entity,
  238. InitListExpr *IList, QualType ElemType,
  239. unsigned &Index,
  240. InitListExpr *StructuredList,
  241. unsigned &StructuredIndex);
  242. void CheckComplexType(const InitializedEntity &Entity,
  243. InitListExpr *IList, QualType DeclType,
  244. unsigned &Index,
  245. InitListExpr *StructuredList,
  246. unsigned &StructuredIndex);
  247. void CheckScalarType(const InitializedEntity &Entity,
  248. InitListExpr *IList, QualType DeclType,
  249. unsigned &Index,
  250. InitListExpr *StructuredList,
  251. unsigned &StructuredIndex);
  252. void CheckReferenceType(const InitializedEntity &Entity,
  253. InitListExpr *IList, QualType DeclType,
  254. unsigned &Index,
  255. InitListExpr *StructuredList,
  256. unsigned &StructuredIndex);
  257. void CheckVectorType(const InitializedEntity &Entity,
  258. InitListExpr *IList, QualType DeclType, unsigned &Index,
  259. InitListExpr *StructuredList,
  260. unsigned &StructuredIndex);
  261. void CheckStructUnionTypes(const InitializedEntity &Entity,
  262. InitListExpr *IList, QualType DeclType,
  263. RecordDecl::field_iterator Field,
  264. bool SubobjectIsDesignatorContext, unsigned &Index,
  265. InitListExpr *StructuredList,
  266. unsigned &StructuredIndex,
  267. bool TopLevelObject = false);
  268. void CheckArrayType(const InitializedEntity &Entity,
  269. InitListExpr *IList, QualType &DeclType,
  270. llvm::APSInt elementIndex,
  271. bool SubobjectIsDesignatorContext, unsigned &Index,
  272. InitListExpr *StructuredList,
  273. unsigned &StructuredIndex);
  274. bool CheckDesignatedInitializer(const InitializedEntity &Entity,
  275. InitListExpr *IList, DesignatedInitExpr *DIE,
  276. unsigned DesigIdx,
  277. QualType &CurrentObjectType,
  278. RecordDecl::field_iterator *NextField,
  279. llvm::APSInt *NextElementIndex,
  280. unsigned &Index,
  281. InitListExpr *StructuredList,
  282. unsigned &StructuredIndex,
  283. bool FinishSubobjectInit,
  284. bool TopLevelObject);
  285. InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  286. QualType CurrentObjectType,
  287. InitListExpr *StructuredList,
  288. unsigned StructuredIndex,
  289. SourceRange InitRange,
  290. bool IsFullyOverwritten = false);
  291. void UpdateStructuredListElement(InitListExpr *StructuredList,
  292. unsigned &StructuredIndex,
  293. Expr *expr);
  294. int numArrayElements(QualType DeclType);
  295. int numStructUnionElements(QualType DeclType);
  296. static ExprResult PerformEmptyInit(Sema &SemaRef,
  297. SourceLocation Loc,
  298. const InitializedEntity &Entity,
  299. bool VerifyOnly);
  300. // Explanation on the "FillWithNoInit" mode:
  301. //
  302. // Assume we have the following definitions (Case#1):
  303. // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
  304. // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
  305. //
  306. // l.lp.x[1][0..1] should not be filled with implicit initializers because the
  307. // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
  308. //
  309. // But if we have (Case#2):
  310. // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
  311. //
  312. // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
  313. // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
  314. //
  315. // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
  316. // in the InitListExpr, the "holes" in Case#1 are filled not with empty
  317. // initializers but with special "NoInitExpr" place holders, which tells the
  318. // CodeGen not to generate any initializers for these parts.
  319. void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  320. const InitializedEntity &ParentEntity,
  321. InitListExpr *ILE, bool &RequiresSecondPass,
  322. bool FillWithNoInit = false);
  323. void FillInEmptyInitializations(const InitializedEntity &Entity,
  324. InitListExpr *ILE, bool &RequiresSecondPass,
  325. bool FillWithNoInit = false);
  326. bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
  327. Expr *InitExpr, FieldDecl *Field,
  328. bool TopLevelObject);
  329. void CheckEmptyInitializable(const InitializedEntity &Entity,
  330. SourceLocation Loc);
  331. public:
  332. InitListChecker(Sema &S, const InitializedEntity &Entity, const InitializationKind &K, // HLSL Change - add Kind
  333. InitListExpr *IL, QualType &T, bool VerifyOnly);
  334. bool HadError() { return hadError; }
  335. // @brief Retrieves the fully-structured initializer list used for
  336. // semantic analysis and code generation.
  337. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
  338. };
  339. } // end anonymous namespace
  340. ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
  341. SourceLocation Loc,
  342. const InitializedEntity &Entity,
  343. bool VerifyOnly) {
  344. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  345. true);
  346. MultiExprArg SubInit;
  347. Expr *InitExpr;
  348. InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
  349. // C++ [dcl.init.aggr]p7:
  350. // If there are fewer initializer-clauses in the list than there are
  351. // members in the aggregate, then each member not explicitly initialized
  352. // ...
  353. bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
  354. Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
  355. if (EmptyInitList) {
  356. // C++1y / DR1070:
  357. // shall be initialized [...] from an empty initializer list.
  358. //
  359. // We apply the resolution of this DR to C++11 but not C++98, since C++98
  360. // does not have useful semantics for initialization from an init list.
  361. // We treat this as copy-initialization, because aggregate initialization
  362. // always performs copy-initialization on its elements.
  363. //
  364. // Only do this if we're initializing a class type, to avoid filling in
  365. // the initializer list where possible.
  366. InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
  367. InitListExpr(SemaRef.Context, Loc, None, Loc);
  368. InitExpr->setType(SemaRef.Context.VoidTy);
  369. SubInit = InitExpr;
  370. Kind = InitializationKind::CreateCopy(Loc, Loc);
  371. } else {
  372. // C++03:
  373. // shall be value-initialized.
  374. }
  375. InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
  376. // libstdc++4.6 marks the vector default constructor as explicit in
  377. // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
  378. // stlport does so too. Look for std::__debug for libstdc++, and for
  379. // std:: for stlport. This is effectively a compiler-side implementation of
  380. // LWG2193.
  381. if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
  382. InitializationSequence::FK_ExplicitConstructor) {
  383. OverloadCandidateSet::iterator Best;
  384. OverloadingResult O =
  385. InitSeq.getFailedCandidateSet()
  386. .BestViableFunction(SemaRef, Kind.getLocation(), Best);
  387. (void)O;
  388. assert(O == OR_Success && "Inconsistent overload resolution");
  389. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  390. CXXRecordDecl *R = CtorDecl->getParent();
  391. if (CtorDecl->getMinRequiredArguments() == 0 &&
  392. CtorDecl->isExplicit() && R->getDeclName() &&
  393. SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
  394. bool IsInStd = false;
  395. for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
  396. ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
  397. if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
  398. IsInStd = true;
  399. }
  400. if (IsInStd && llvm::StringSwitch<bool>(R->getName())
  401. .Cases("basic_string", "deque", "forward_list", true)
  402. .Cases("list", "map", "multimap", "multiset", true)
  403. .Cases("priority_queue", "queue", "set", "stack", true)
  404. .Cases("unordered_map", "unordered_set", "vector", true)
  405. .Default(false)) {
  406. InitSeq.InitializeFrom(
  407. SemaRef, Entity,
  408. InitializationKind::CreateValue(Loc, Loc, Loc, true),
  409. MultiExprArg(), /*TopLevelOfInitList=*/false);
  410. // Emit a warning for this. System header warnings aren't shown
  411. // by default, but people working on system headers should see it.
  412. if (!VerifyOnly) {
  413. SemaRef.Diag(CtorDecl->getLocation(),
  414. diag::warn_invalid_initializer_from_system_header);
  415. SemaRef.Diag(Entity.getDecl()->getLocation(),
  416. diag::note_used_in_initialization_here);
  417. }
  418. }
  419. }
  420. }
  421. if (!InitSeq) {
  422. if (!VerifyOnly) {
  423. InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
  424. if (Entity.getKind() == InitializedEntity::EK_Member)
  425. SemaRef.Diag(Entity.getDecl()->getLocation(),
  426. diag::note_in_omitted_aggregate_initializer)
  427. << /*field*/1 << Entity.getDecl();
  428. else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
  429. SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
  430. << /*array element*/0 << Entity.getElementIndex();
  431. }
  432. return ExprError();
  433. }
  434. return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
  435. : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
  436. }
  437. void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
  438. SourceLocation Loc) {
  439. assert(VerifyOnly &&
  440. "CheckEmptyInitializable is only inteded for verification mode.");
  441. if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
  442. hadError = true;
  443. }
  444. void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
  445. const InitializedEntity &ParentEntity,
  446. InitListExpr *ILE,
  447. bool &RequiresSecondPass,
  448. bool FillWithNoInit) {
  449. SourceLocation Loc = ILE->getLocEnd();
  450. unsigned NumInits = ILE->getNumInits();
  451. InitializedEntity MemberEntity
  452. = InitializedEntity::InitializeMember(Field, &ParentEntity);
  453. if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
  454. if (!RType->getDecl()->isUnion())
  455. assert(Init < NumInits && "This ILE should have been expanded");
  456. if (Init >= NumInits || !ILE->getInit(Init)) {
  457. if (FillWithNoInit) {
  458. Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
  459. if (Init < NumInits)
  460. ILE->setInit(Init, Filler);
  461. else
  462. ILE->updateInit(SemaRef.Context, Init, Filler);
  463. return;
  464. }
  465. // C++1y [dcl.init.aggr]p7:
  466. // If there are fewer initializer-clauses in the list than there are
  467. // members in the aggregate, then each member not explicitly initialized
  468. // shall be initialized from its brace-or-equal-initializer [...]
  469. if (Field->hasInClassInitializer()) {
  470. ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
  471. if (DIE.isInvalid()) {
  472. hadError = true;
  473. return;
  474. }
  475. if (Init < NumInits)
  476. ILE->setInit(Init, DIE.get());
  477. else {
  478. ILE->updateInit(SemaRef.Context, Init, DIE.get());
  479. RequiresSecondPass = true;
  480. }
  481. return;
  482. }
  483. if (Field->getType()->isReferenceType()) {
  484. // C++ [dcl.init.aggr]p9:
  485. // If an incomplete or empty initializer-list leaves a
  486. // member of reference type uninitialized, the program is
  487. // ill-formed.
  488. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
  489. << Field->getType()
  490. << ILE->getSyntacticForm()->getSourceRange();
  491. SemaRef.Diag(Field->getLocation(),
  492. diag::note_uninit_reference_member);
  493. hadError = true;
  494. return;
  495. }
  496. ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
  497. /*VerifyOnly*/false);
  498. if (MemberInit.isInvalid()) {
  499. hadError = true;
  500. return;
  501. }
  502. if (hadError) {
  503. // Do nothing
  504. } else if (Init < NumInits) {
  505. ILE->setInit(Init, MemberInit.getAs<Expr>());
  506. } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
  507. // Empty initialization requires a constructor call, so
  508. // extend the initializer list to include the constructor
  509. // call and make a note that we'll need to take another pass
  510. // through the initializer list.
  511. ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
  512. RequiresSecondPass = true;
  513. }
  514. } else if (InitListExpr *InnerILE
  515. = dyn_cast<InitListExpr>(ILE->getInit(Init)))
  516. FillInEmptyInitializations(MemberEntity, InnerILE,
  517. RequiresSecondPass, FillWithNoInit);
  518. else if (DesignatedInitUpdateExpr *InnerDIUE
  519. = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
  520. FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
  521. RequiresSecondPass, /*FillWithNoInit =*/ true);
  522. }
  523. /// Recursively replaces NULL values within the given initializer list
  524. /// with expressions that perform value-initialization of the
  525. /// appropriate type.
  526. void
  527. InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
  528. InitListExpr *ILE,
  529. bool &RequiresSecondPass,
  530. bool FillWithNoInit) {
  531. assert((ILE->getType() != SemaRef.Context.VoidTy) &&
  532. "Should not have void type");
  533. if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
  534. const RecordDecl *RDecl = RType->getDecl();
  535. if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
  536. FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
  537. Entity, ILE, RequiresSecondPass, FillWithNoInit);
  538. else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
  539. cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
  540. for (auto *Field : RDecl->fields()) {
  541. if (Field->hasInClassInitializer()) {
  542. FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
  543. FillWithNoInit);
  544. break;
  545. }
  546. }
  547. } else {
  548. // The fields beyond ILE->getNumInits() are default initialized, so in
  549. // order to leave them uninitialized, the ILE is expanded and the extra
  550. // fields are then filled with NoInitExpr.
  551. unsigned NumFields = 0;
  552. for (auto *Field : RDecl->fields())
  553. if (!Field->isUnnamedBitfield())
  554. ++NumFields;
  555. if (ILE->getNumInits() < NumFields)
  556. ILE->resizeInits(SemaRef.Context, NumFields);
  557. unsigned Init = 0;
  558. for (auto *Field : RDecl->fields()) {
  559. if (Field->isUnnamedBitfield())
  560. continue;
  561. if (hadError)
  562. return;
  563. FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
  564. FillWithNoInit);
  565. if (hadError)
  566. return;
  567. ++Init;
  568. // Only look at the first initialization of a union.
  569. if (RDecl->isUnion())
  570. break;
  571. }
  572. }
  573. return;
  574. }
  575. QualType ElementType;
  576. InitializedEntity ElementEntity = Entity;
  577. unsigned NumInits = ILE->getNumInits();
  578. unsigned NumElements = NumInits;
  579. if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
  580. ElementType = AType->getElementType();
  581. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
  582. NumElements = CAType->getSize().getZExtValue();
  583. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  584. 0, Entity);
  585. } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
  586. ElementType = VType->getElementType();
  587. NumElements = VType->getNumElements();
  588. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  589. 0, Entity);
  590. } else
  591. ElementType = ILE->getType();
  592. for (unsigned Init = 0; Init != NumElements; ++Init) {
  593. if (hadError)
  594. return;
  595. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
  596. ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
  597. ElementEntity.setElementIndex(Init);
  598. Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
  599. if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
  600. ILE->setInit(Init, ILE->getArrayFiller());
  601. else if (!InitExpr && !ILE->hasArrayFiller()) {
  602. Expr *Filler = nullptr;
  603. if (FillWithNoInit)
  604. Filler = new (SemaRef.Context) NoInitExpr(ElementType);
  605. else {
  606. ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
  607. ElementEntity,
  608. /*VerifyOnly*/false);
  609. if (ElementInit.isInvalid()) {
  610. hadError = true;
  611. return;
  612. }
  613. Filler = ElementInit.getAs<Expr>();
  614. }
  615. if (hadError) {
  616. // Do nothing
  617. } else if (Init < NumInits) {
  618. // For arrays, just set the expression used for value-initialization
  619. // of the "holes" in the array.
  620. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
  621. ILE->setArrayFiller(Filler);
  622. else
  623. ILE->setInit(Init, Filler);
  624. } else {
  625. // For arrays, just set the expression used for value-initialization
  626. // of the rest of elements and exit.
  627. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  628. ILE->setArrayFiller(Filler);
  629. return;
  630. }
  631. if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
  632. // Empty initialization requires a constructor call, so
  633. // extend the initializer list to include the constructor
  634. // call and make a note that we'll need to take another pass
  635. // through the initializer list.
  636. ILE->updateInit(SemaRef.Context, Init, Filler);
  637. RequiresSecondPass = true;
  638. }
  639. }
  640. } else if (InitListExpr *InnerILE
  641. = dyn_cast_or_null<InitListExpr>(InitExpr))
  642. FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
  643. FillWithNoInit);
  644. else if (DesignatedInitUpdateExpr *InnerDIUE
  645. = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
  646. FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
  647. RequiresSecondPass, /*FillWithNoInit =*/ true);
  648. }
  649. }
  650. InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
  651. const InitializationKind &K, // HLSL Change - add K
  652. InitListExpr *IL, QualType &T,
  653. bool VerifyOnly)
  654. : SemaRef(S), Kind(K), VerifyOnly(VerifyOnly) { // HLSL Change - add Kind
  655. // FIXME: Check that IL isn't already the semantic form of some other
  656. // InitListExpr. If it is, we'd create a broken AST.
  657. hadError = false;
  658. FullyStructuredList =
  659. getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
  660. CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
  661. /*TopLevelObject=*/true);
  662. if (!hadError && !VerifyOnly) {
  663. bool RequiresSecondPass = false;
  664. FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
  665. if (RequiresSecondPass && !hadError)
  666. FillInEmptyInitializations(Entity, FullyStructuredList,
  667. RequiresSecondPass);
  668. }
  669. }
  670. int InitListChecker::numArrayElements(QualType DeclType) {
  671. // FIXME: use a proper constant
  672. int maxElements = 0x7FFFFFFF;
  673. if (const ConstantArrayType *CAT =
  674. SemaRef.Context.getAsConstantArrayType(DeclType)) {
  675. maxElements = static_cast<int>(CAT->getSize().getZExtValue());
  676. }
  677. return maxElements;
  678. }
  679. int InitListChecker::numStructUnionElements(QualType DeclType) {
  680. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  681. int InitializableMembers = 0;
  682. for (const auto *Field : structDecl->fields())
  683. if (!Field->isUnnamedBitfield())
  684. ++InitializableMembers;
  685. if (structDecl->isUnion())
  686. return std::min(InitializableMembers, 1);
  687. return InitializableMembers - structDecl->hasFlexibleArrayMember();
  688. }
  689. /// Check whether the range of the initializer \p ParentIList from element
  690. /// \p Index onwards can be used to initialize an object of type \p T. Update
  691. /// \p Index to indicate how many elements of the list were consumed.
  692. ///
  693. /// This also fills in \p StructuredList, from element \p StructuredIndex
  694. /// onwards, with the fully-braced, desugared form of the initialization.
  695. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
  696. InitListExpr *ParentIList,
  697. QualType T, unsigned &Index,
  698. InitListExpr *StructuredList,
  699. unsigned &StructuredIndex) {
  700. int maxElements = 0;
  701. if (T->isArrayType())
  702. maxElements = numArrayElements(T);
  703. else if (T->isRecordType())
  704. maxElements = numStructUnionElements(T);
  705. else if (T->isVectorType())
  706. maxElements = T->getAs<VectorType>()->getNumElements();
  707. else
  708. llvm_unreachable("CheckImplicitInitList(): Illegal type");
  709. if (maxElements == 0) {
  710. if (!VerifyOnly)
  711. SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
  712. diag::err_implicit_empty_initializer);
  713. ++Index;
  714. hadError = true;
  715. return;
  716. }
  717. // Build a structured initializer list corresponding to this subobject.
  718. InitListExpr *StructuredSubobjectInitList
  719. = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
  720. StructuredIndex,
  721. SourceRange(ParentIList->getInit(Index)->getLocStart(),
  722. ParentIList->getSourceRange().getEnd()));
  723. unsigned StructuredSubobjectInitIndex = 0;
  724. // Check the element types and build the structural subobject.
  725. unsigned StartIndex = Index;
  726. CheckListElementTypes(Entity, ParentIList, T,
  727. /*SubobjectIsDesignatorContext=*/false, Index,
  728. StructuredSubobjectInitList,
  729. StructuredSubobjectInitIndex);
  730. if (!VerifyOnly) {
  731. StructuredSubobjectInitList->setType(T);
  732. unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
  733. // Update the structured sub-object initializer so that it's ending
  734. // range corresponds with the end of the last initializer it used.
  735. if (EndIndex < ParentIList->getNumInits()) {
  736. SourceLocation EndLoc
  737. = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
  738. StructuredSubobjectInitList->setRBraceLoc(EndLoc);
  739. }
  740. // Complain about missing braces.
  741. if (T->isArrayType() || T->isRecordType()) {
  742. SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
  743. diag::warn_missing_braces)
  744. << StructuredSubobjectInitList->getSourceRange()
  745. << FixItHint::CreateInsertion(
  746. StructuredSubobjectInitList->getLocStart(), "{")
  747. << FixItHint::CreateInsertion(
  748. SemaRef.getLocForEndOfToken(
  749. StructuredSubobjectInitList->getLocEnd()),
  750. "}");
  751. }
  752. }
  753. }
  754. /// Warn that \p Entity was of scalar type and was initialized by a
  755. /// single-element braced initializer list.
  756. static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
  757. SourceRange Braces) {
  758. // Don't warn during template instantiation. If the initialization was
  759. // non-dependent, we warned during the initial parse; otherwise, the
  760. // type might not be scalar in some uses of the template.
  761. if (!S.ActiveTemplateInstantiations.empty())
  762. return;
  763. unsigned DiagID = 0;
  764. switch (Entity.getKind()) {
  765. case InitializedEntity::EK_VectorElement:
  766. case InitializedEntity::EK_ComplexElement:
  767. case InitializedEntity::EK_ArrayElement:
  768. case InitializedEntity::EK_Parameter:
  769. case InitializedEntity::EK_Parameter_CF_Audited:
  770. case InitializedEntity::EK_Result:
  771. // Extra braces here are suspicious.
  772. DiagID = diag::warn_braces_around_scalar_init;
  773. break;
  774. case InitializedEntity::EK_Member:
  775. // Warn on aggregate initialization but not on ctor init list or
  776. // default member initializer.
  777. if (Entity.getParent())
  778. DiagID = diag::warn_braces_around_scalar_init;
  779. break;
  780. case InitializedEntity::EK_Variable:
  781. case InitializedEntity::EK_LambdaCapture:
  782. // No warning, might be direct-list-initialization.
  783. // FIXME: Should we warn for copy-list-initialization in these cases?
  784. break;
  785. case InitializedEntity::EK_New:
  786. case InitializedEntity::EK_Temporary:
  787. case InitializedEntity::EK_CompoundLiteralInit:
  788. // No warning, braces are part of the syntax of the underlying construct.
  789. break;
  790. case InitializedEntity::EK_RelatedResult:
  791. // No warning, we already warned when initializing the result.
  792. break;
  793. case InitializedEntity::EK_Exception:
  794. case InitializedEntity::EK_Base:
  795. case InitializedEntity::EK_Delegating:
  796. case InitializedEntity::EK_BlockElement:
  797. llvm_unreachable("unexpected braced scalar init");
  798. }
  799. if (DiagID) {
  800. S.Diag(Braces.getBegin(), DiagID)
  801. << Braces
  802. << FixItHint::CreateRemoval(Braces.getBegin())
  803. << FixItHint::CreateRemoval(Braces.getEnd());
  804. }
  805. }
  806. /// Check whether the initializer \p IList (that was written with explicit
  807. /// braces) can be used to initialize an object of type \p T.
  808. ///
  809. /// This also fills in \p StructuredList with the fully-braced, desugared
  810. /// form of the initialization.
  811. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
  812. InitListExpr *IList, QualType &T,
  813. InitListExpr *StructuredList,
  814. bool TopLevelObject) {
  815. assert((IList->isExplicit() || SemaRef.getLangOpts().HLSL) && "Illegal Implicit InitListExpr"); // HLSL Change: reuse in context of constructors for vectors
  816. if (!VerifyOnly) {
  817. SyntacticToSemantic[IList] = StructuredList;
  818. StructuredList->setSyntacticForm(IList);
  819. }
  820. unsigned Index = 0, StructuredIndex = 0;
  821. CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
  822. Index, StructuredList, StructuredIndex, TopLevelObject);
  823. if (!VerifyOnly) {
  824. QualType ExprTy = T;
  825. if (!ExprTy->isArrayType())
  826. ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
  827. IList->setType(ExprTy);
  828. StructuredList->setType(ExprTy);
  829. }
  830. if (hadError)
  831. return;
  832. if (Index < IList->getNumInits()) {
  833. // We have leftover initializers
  834. if (VerifyOnly) {
  835. if (SemaRef.getLangOpts().CPlusPlus ||
  836. (SemaRef.getLangOpts().OpenCL &&
  837. IList->getType()->isVectorType())) {
  838. hadError = true;
  839. }
  840. return;
  841. }
  842. if (StructuredIndex == 1 &&
  843. IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
  844. SIF_None) {
  845. unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
  846. if (SemaRef.getLangOpts().CPlusPlus) {
  847. DK = diag::err_excess_initializers_in_char_array_initializer;
  848. hadError = true;
  849. }
  850. // Special-case
  851. SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
  852. << IList->getInit(Index)->getSourceRange();
  853. } else if (!T->isIncompleteType()) {
  854. // Don't complain for incomplete types, since we'll get an error
  855. // elsewhere
  856. QualType CurrentObjectType = StructuredList->getType();
  857. int initKind =
  858. CurrentObjectType->isArrayType()? 0 :
  859. CurrentObjectType->isVectorType()? 1 :
  860. CurrentObjectType->isScalarType()? 2 :
  861. CurrentObjectType->isUnionType()? 3 :
  862. 4;
  863. unsigned DK = diag::ext_excess_initializers;
  864. if (SemaRef.getLangOpts().CPlusPlus) {
  865. DK = diag::err_excess_initializers;
  866. hadError = true;
  867. }
  868. if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
  869. DK = diag::err_excess_initializers;
  870. hadError = true;
  871. }
  872. SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
  873. << initKind << IList->getInit(Index)->getSourceRange();
  874. }
  875. }
  876. if (!VerifyOnly && T->isScalarType() &&
  877. IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
  878. warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
  879. }
  880. void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
  881. InitListExpr *IList,
  882. QualType &DeclType,
  883. bool SubobjectIsDesignatorContext,
  884. unsigned &Index,
  885. InitListExpr *StructuredList,
  886. unsigned &StructuredIndex,
  887. bool TopLevelObject) {
  888. if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
  889. // Explicitly braced initializer for complex type can be real+imaginary
  890. // parts.
  891. CheckComplexType(Entity, IList, DeclType, Index,
  892. StructuredList, StructuredIndex);
  893. } else if (DeclType->isScalarType()) {
  894. CheckScalarType(Entity, IList, DeclType, Index,
  895. StructuredList, StructuredIndex);
  896. } else if (DeclType->isVectorType()) {
  897. CheckVectorType(Entity, IList, DeclType, Index,
  898. StructuredList, StructuredIndex);
  899. } else if (DeclType->isRecordType()) {
  900. assert(DeclType->isAggregateType() &&
  901. "non-aggregate records should be handed in CheckSubElementType");
  902. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  903. CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
  904. SubobjectIsDesignatorContext, Index,
  905. StructuredList, StructuredIndex,
  906. TopLevelObject);
  907. } else if (DeclType->isArrayType()) {
  908. llvm::APSInt Zero(
  909. SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
  910. false);
  911. CheckArrayType(Entity, IList, DeclType, Zero,
  912. SubobjectIsDesignatorContext, Index,
  913. StructuredList, StructuredIndex);
  914. } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
  915. // This type is invalid, issue a diagnostic.
  916. ++Index;
  917. if (!VerifyOnly)
  918. SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
  919. << DeclType;
  920. hadError = true;
  921. } else if (DeclType->isReferenceType()) {
  922. CheckReferenceType(Entity, IList, DeclType, Index,
  923. StructuredList, StructuredIndex);
  924. } else if (DeclType->isObjCObjectType()) {
  925. if (!VerifyOnly)
  926. SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
  927. << DeclType;
  928. hadError = true;
  929. } else {
  930. if (!VerifyOnly)
  931. SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
  932. << DeclType;
  933. hadError = true;
  934. }
  935. }
  936. void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
  937. InitListExpr *IList,
  938. QualType ElemType,
  939. unsigned &Index,
  940. InitListExpr *StructuredList,
  941. unsigned &StructuredIndex) {
  942. Expr *expr = IList->getInit(Index);
  943. if (ElemType->isReferenceType())
  944. return CheckReferenceType(Entity, IList, ElemType, Index,
  945. StructuredList, StructuredIndex);
  946. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
  947. if (SubInitList->getNumInits() == 1 &&
  948. IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
  949. SIF_None) {
  950. expr = SubInitList->getInit(0);
  951. } else if (!SemaRef.getLangOpts().CPlusPlus) {
  952. InitListExpr *InnerStructuredList
  953. = getStructuredSubobjectInit(IList, Index, ElemType,
  954. StructuredList, StructuredIndex,
  955. SubInitList->getSourceRange(), true);
  956. CheckExplicitInitList(Entity, SubInitList, ElemType,
  957. InnerStructuredList);
  958. if (!hadError && !VerifyOnly) {
  959. bool RequiresSecondPass = false;
  960. FillInEmptyInitializations(Entity, InnerStructuredList,
  961. RequiresSecondPass);
  962. if (RequiresSecondPass && !hadError)
  963. FillInEmptyInitializations(Entity, InnerStructuredList,
  964. RequiresSecondPass);
  965. }
  966. ++StructuredIndex;
  967. ++Index;
  968. return;
  969. }
  970. // C++ initialization is handled later.
  971. } else if (isa<ImplicitValueInitExpr>(expr)) {
  972. // This happens during template instantiation when we see an InitListExpr
  973. // that we've already checked once.
  974. assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
  975. "found implicit initialization for the wrong type");
  976. if (!VerifyOnly)
  977. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  978. ++Index;
  979. return;
  980. }
  981. if (SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().HLSL) { // HLSL Change: use OpenCL-style rules
  982. // C++ [dcl.init.aggr]p2:
  983. // Each member is copy-initialized from the corresponding
  984. // initializer-clause.
  985. // FIXME: Better EqualLoc?
  986. InitializationKind Kind =
  987. InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
  988. InitializationSequence Seq(SemaRef, Entity, Kind, expr,
  989. /*TopLevelOfInitList*/ true);
  990. // C++14 [dcl.init.aggr]p13:
  991. // If the assignment-expression can initialize a member, the member is
  992. // initialized. Otherwise [...] brace elision is assumed
  993. //
  994. // Brace elision is never performed if the element is not an
  995. // assignment-expression.
  996. if (Seq || isa<InitListExpr>(expr)) {
  997. if (!VerifyOnly) {
  998. ExprResult Result =
  999. Seq.Perform(SemaRef, Entity, Kind, expr);
  1000. if (Result.isInvalid())
  1001. hadError = true;
  1002. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1003. Result.getAs<Expr>());
  1004. } else if (!Seq)
  1005. hadError = true;
  1006. ++Index;
  1007. return;
  1008. }
  1009. // Fall through for subaggregate initialization
  1010. } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
  1011. // FIXME: Need to handle atomic aggregate types with implicit init lists.
  1012. return CheckScalarType(Entity, IList, ElemType, Index,
  1013. StructuredList, StructuredIndex);
  1014. } else if (const ArrayType *arrayType =
  1015. SemaRef.Context.getAsArrayType(ElemType)) {
  1016. // arrayType can be incomplete if we're initializing a flexible
  1017. // array member. There's nothing we can do with the completed
  1018. // type here, though.
  1019. if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
  1020. if (!VerifyOnly) {
  1021. CheckStringInit(expr, ElemType, arrayType, SemaRef);
  1022. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1023. }
  1024. ++Index;
  1025. return;
  1026. }
  1027. // Fall through for subaggregate initialization.
  1028. } else {
  1029. assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
  1030. "Unexpected type");
  1031. // C99 6.7.8p13:
  1032. //
  1033. // The initializer for a structure or union object that has
  1034. // automatic storage duration shall be either an initializer
  1035. // list as described below, or a single expression that has
  1036. // compatible structure or union type. In the latter case, the
  1037. // initial value of the object, including unnamed members, is
  1038. // that of the expression.
  1039. ExprResult ExprRes = expr;
  1040. if (SemaRef.CheckSingleAssignmentConstraints(
  1041. ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
  1042. if (ExprRes.isInvalid())
  1043. hadError = true;
  1044. else {
  1045. ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
  1046. if (ExprRes.isInvalid())
  1047. hadError = true;
  1048. }
  1049. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1050. ExprRes.getAs<Expr>());
  1051. ++Index;
  1052. return;
  1053. }
  1054. ExprRes.get();
  1055. // Fall through for subaggregate initialization
  1056. }
  1057. // C++ [dcl.init.aggr]p12:
  1058. //
  1059. // [...] Otherwise, if the member is itself a non-empty
  1060. // subaggregate, brace elision is assumed and the initializer is
  1061. // considered for the initialization of the first member of
  1062. // the subaggregate.
  1063. if (!SemaRef.getLangOpts().OpenCL &&
  1064. (ElemType->isAggregateType() || ElemType->isVectorType())) {
  1065. CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
  1066. StructuredIndex);
  1067. ++StructuredIndex;
  1068. } else {
  1069. if (!VerifyOnly) {
  1070. // We cannot initialize this element, so let
  1071. // PerformCopyInitialization produce the appropriate diagnostic.
  1072. SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
  1073. /*TopLevelOfInitList=*/true);
  1074. }
  1075. hadError = true;
  1076. ++Index;
  1077. ++StructuredIndex;
  1078. }
  1079. }
  1080. void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
  1081. InitListExpr *IList, QualType DeclType,
  1082. unsigned &Index,
  1083. InitListExpr *StructuredList,
  1084. unsigned &StructuredIndex) {
  1085. assert(Index == 0 && "Index in explicit init list must be zero");
  1086. // As an extension, clang supports complex initializers, which initialize
  1087. // a complex number component-wise. When an explicit initializer list for
  1088. // a complex number contains two two initializers, this extension kicks in:
  1089. // it exepcts the initializer list to contain two elements convertible to
  1090. // the element type of the complex type. The first element initializes
  1091. // the real part, and the second element intitializes the imaginary part.
  1092. if (IList->getNumInits() != 2)
  1093. return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  1094. StructuredIndex);
  1095. // This is an extension in C. (The builtin _Complex type does not exist
  1096. // in the C++ standard.)
  1097. if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
  1098. SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
  1099. << IList->getSourceRange();
  1100. // Initialize the complex number.
  1101. QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
  1102. InitializedEntity ElementEntity =
  1103. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1104. for (unsigned i = 0; i < 2; ++i) {
  1105. ElementEntity.setElementIndex(Index);
  1106. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1107. StructuredList, StructuredIndex);
  1108. }
  1109. }
  1110. void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
  1111. InitListExpr *IList, QualType DeclType,
  1112. unsigned &Index,
  1113. InitListExpr *StructuredList,
  1114. unsigned &StructuredIndex) {
  1115. if (Index >= IList->getNumInits()) {
  1116. if (!VerifyOnly)
  1117. SemaRef.Diag(IList->getLocStart(),
  1118. SemaRef.getLangOpts().CPlusPlus11 ?
  1119. diag::warn_cxx98_compat_empty_scalar_initializer :
  1120. diag::err_empty_scalar_initializer)
  1121. << IList->getSourceRange();
  1122. hadError = !SemaRef.getLangOpts().CPlusPlus11;
  1123. ++Index;
  1124. ++StructuredIndex;
  1125. return;
  1126. }
  1127. Expr *expr = IList->getInit(Index);
  1128. if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
  1129. // FIXME: This is invalid, and accepting it causes overload resolution
  1130. // to pick the wrong overload in some corner cases.
  1131. if (!VerifyOnly)
  1132. SemaRef.Diag(SubIList->getLocStart(),
  1133. diag::ext_many_braces_around_scalar_init)
  1134. << SubIList->getSourceRange();
  1135. CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
  1136. StructuredIndex);
  1137. return;
  1138. } else if (isa<DesignatedInitExpr>(expr)) {
  1139. if (!VerifyOnly)
  1140. SemaRef.Diag(expr->getLocStart(),
  1141. diag::err_designator_for_scalar_init)
  1142. << DeclType << expr->getSourceRange();
  1143. hadError = true;
  1144. ++Index;
  1145. ++StructuredIndex;
  1146. return;
  1147. }
  1148. if (VerifyOnly) {
  1149. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1150. hadError = true;
  1151. ++Index;
  1152. return;
  1153. }
  1154. ExprResult Result =
  1155. SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
  1156. /*TopLevelOfInitList=*/true);
  1157. Expr *ResultExpr = nullptr;
  1158. if (Result.isInvalid())
  1159. hadError = true; // types weren't compatible.
  1160. else {
  1161. ResultExpr = Result.getAs<Expr>();
  1162. if (ResultExpr != expr) {
  1163. // The type was promoted, update initializer list.
  1164. IList->setInit(Index, ResultExpr);
  1165. }
  1166. }
  1167. if (hadError)
  1168. ++StructuredIndex;
  1169. else
  1170. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  1171. ++Index;
  1172. }
  1173. void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
  1174. InitListExpr *IList, QualType DeclType,
  1175. unsigned &Index,
  1176. InitListExpr *StructuredList,
  1177. unsigned &StructuredIndex) {
  1178. if (Index >= IList->getNumInits()) {
  1179. // FIXME: It would be wonderful if we could point at the actual member. In
  1180. // general, it would be useful to pass location information down the stack,
  1181. // so that we know the location (or decl) of the "current object" being
  1182. // initialized.
  1183. if (!VerifyOnly)
  1184. SemaRef.Diag(IList->getLocStart(),
  1185. diag::err_init_reference_member_uninitialized)
  1186. << DeclType
  1187. << IList->getSourceRange();
  1188. hadError = true;
  1189. ++Index;
  1190. ++StructuredIndex;
  1191. return;
  1192. }
  1193. Expr *expr = IList->getInit(Index);
  1194. if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
  1195. if (!VerifyOnly)
  1196. SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
  1197. << DeclType << IList->getSourceRange();
  1198. hadError = true;
  1199. ++Index;
  1200. ++StructuredIndex;
  1201. return;
  1202. }
  1203. if (VerifyOnly) {
  1204. if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
  1205. hadError = true;
  1206. ++Index;
  1207. return;
  1208. }
  1209. ExprResult Result =
  1210. SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
  1211. /*TopLevelOfInitList=*/true);
  1212. if (Result.isInvalid())
  1213. hadError = true;
  1214. expr = Result.getAs<Expr>();
  1215. IList->setInit(Index, expr);
  1216. if (hadError)
  1217. ++StructuredIndex;
  1218. else
  1219. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  1220. ++Index;
  1221. }
  1222. void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
  1223. InitListExpr *IList, QualType DeclType,
  1224. unsigned &Index,
  1225. InitListExpr *StructuredList,
  1226. unsigned &StructuredIndex) {
  1227. const VectorType *VT = DeclType->getAs<VectorType>();
  1228. unsigned maxElements = VT->getNumElements();
  1229. unsigned numEltsInit = 0;
  1230. QualType elementType = VT->getElementType();
  1231. if (Index >= IList->getNumInits()) {
  1232. // Make sure the element type can be value-initialized.
  1233. if (VerifyOnly)
  1234. CheckEmptyInitializable(
  1235. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
  1236. IList->getLocEnd());
  1237. return;
  1238. }
  1239. // HLSL Change - HLSL is more similar to OpenCL than C/C++
  1240. if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL) {
  1241. // If the initializing element is a vector, try to copy-initialize
  1242. // instead of breaking it apart (which is doomed to failure anyway).
  1243. Expr *Init = IList->getInit(Index);
  1244. if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
  1245. if (VerifyOnly) {
  1246. if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
  1247. hadError = true;
  1248. ++Index;
  1249. return;
  1250. }
  1251. ExprResult Result =
  1252. SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
  1253. /*TopLevelOfInitList=*/true);
  1254. Expr *ResultExpr = nullptr;
  1255. if (Result.isInvalid())
  1256. hadError = true; // types weren't compatible.
  1257. else {
  1258. ResultExpr = Result.getAs<Expr>();
  1259. if (ResultExpr != Init) {
  1260. // The type was promoted, update initializer list.
  1261. IList->setInit(Index, ResultExpr);
  1262. }
  1263. }
  1264. if (hadError)
  1265. ++StructuredIndex;
  1266. else
  1267. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1268. ResultExpr);
  1269. ++Index;
  1270. return;
  1271. }
  1272. InitializedEntity ElementEntity =
  1273. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1274. for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
  1275. // Don't attempt to go past the end of the init list
  1276. if (Index >= IList->getNumInits()) {
  1277. if (VerifyOnly)
  1278. CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
  1279. break;
  1280. }
  1281. ElementEntity.setElementIndex(Index);
  1282. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1283. StructuredList, StructuredIndex);
  1284. }
  1285. if (VerifyOnly)
  1286. return;
  1287. bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
  1288. const VectorType *T = Entity.getType()->getAs<VectorType>();
  1289. if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
  1290. T->getVectorKind() == VectorType::NeonPolyVector)) {
  1291. // The ability to use vector initializer lists is a GNU vector extension
  1292. // and is unrelated to the NEON intrinsics in arm_neon.h. On little
  1293. // endian machines it works fine, however on big endian machines it
  1294. // exhibits surprising behaviour:
  1295. //
  1296. // uint32x2_t x = {42, 64};
  1297. // return vget_lane_u32(x, 0); // Will return 64.
  1298. //
  1299. // Because of this, explicitly call out that it is non-portable.
  1300. //
  1301. SemaRef.Diag(IList->getLocStart(),
  1302. diag::warn_neon_vector_initializer_non_portable);
  1303. const char *typeCode;
  1304. unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
  1305. if (elementType->isFloatingType())
  1306. typeCode = "f";
  1307. else if (elementType->isSignedIntegerType())
  1308. typeCode = "s";
  1309. else if (elementType->isUnsignedIntegerType())
  1310. typeCode = "u";
  1311. else
  1312. llvm_unreachable("Invalid element type!");
  1313. SemaRef.Diag(IList->getLocStart(),
  1314. SemaRef.Context.getTypeSize(VT) > 64 ?
  1315. diag::note_neon_vector_initializer_non_portable_q :
  1316. diag::note_neon_vector_initializer_non_portable)
  1317. << typeCode << typeSize;
  1318. }
  1319. return;
  1320. }
  1321. InitializedEntity ElementEntity =
  1322. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1323. // OpenCL initializers allows vectors to be constructed from vectors.
  1324. for (unsigned i = 0; i < maxElements; ++i) {
  1325. // Don't attempt to go past the end of the init list
  1326. if (Index >= IList->getNumInits())
  1327. break;
  1328. ElementEntity.setElementIndex(Index);
  1329. QualType IType = IList->getInit(Index)->getType();
  1330. if (!IType->isVectorType()) {
  1331. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1332. StructuredList, StructuredIndex);
  1333. ++numEltsInit;
  1334. } else {
  1335. QualType VecType;
  1336. const VectorType *IVT = IType->getAs<VectorType>();
  1337. unsigned numIElts = IVT->getNumElements();
  1338. if (IType->isExtVectorType())
  1339. VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
  1340. else
  1341. VecType = SemaRef.Context.getVectorType(elementType, numIElts,
  1342. IVT->getVectorKind());
  1343. CheckSubElementType(ElementEntity, IList, VecType, Index,
  1344. StructuredList, StructuredIndex);
  1345. numEltsInit += numIElts;
  1346. }
  1347. }
  1348. // HLSL Change Starts
  1349. // For copy assignments that aren't explicit initialization lists, allow extra elements (emit a warning though).
  1350. bool extraElementsAllowed = false;
  1351. if (SemaRef.getLangOpts().HLSL && IList->getLBraceLoc().isInvalid()) {
  1352. extraElementsAllowed = numEltsInit > maxElements;
  1353. if (extraElementsAllowed && !VerifyOnly) {
  1354. SemaRef.Diag(Kind.getLocation(), diag::warn_hlsl_implicit_vector_truncation);
  1355. }
  1356. }
  1357. // HLSL Change Ends
  1358. // OpenCL requires all elements to be initialized.
  1359. if (numEltsInit != maxElements && !extraElementsAllowed) { // HLSL Change
  1360. if (!VerifyOnly) {
  1361. static const unsigned selectVectorIdx = 0;
  1362. SemaRef.Diag(IList->getLocStart(),
  1363. diag::err_incorrect_num_initializers)
  1364. << (numEltsInit < maxElements) << selectVectorIdx << maxElements << numEltsInit;
  1365. }
  1366. hadError = true;
  1367. }
  1368. }
  1369. void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
  1370. InitListExpr *IList, QualType &DeclType,
  1371. llvm::APSInt elementIndex,
  1372. bool SubobjectIsDesignatorContext,
  1373. unsigned &Index,
  1374. InitListExpr *StructuredList,
  1375. unsigned &StructuredIndex) {
  1376. const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
  1377. // Check for the special-case of initializing an array with a string.
  1378. if (Index < IList->getNumInits()) {
  1379. if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
  1380. SIF_None) {
  1381. // We place the string literal directly into the resulting
  1382. // initializer list. This is the only place where the structure
  1383. // of the structured initializer list doesn't match exactly,
  1384. // because doing so would involve allocating one character
  1385. // constant for each string.
  1386. if (!VerifyOnly) {
  1387. CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
  1388. UpdateStructuredListElement(StructuredList, StructuredIndex,
  1389. IList->getInit(Index));
  1390. StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
  1391. }
  1392. ++Index;
  1393. return;
  1394. }
  1395. }
  1396. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
  1397. // Check for VLAs; in standard C it would be possible to check this
  1398. // earlier, but I don't know where clang accepts VLAs (gcc accepts
  1399. // them in all sorts of strange places).
  1400. if (!VerifyOnly)
  1401. SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
  1402. diag::err_variable_object_no_init)
  1403. << VAT->getSizeExpr()->getSourceRange();
  1404. hadError = true;
  1405. ++Index;
  1406. ++StructuredIndex;
  1407. return;
  1408. }
  1409. // We might know the maximum number of elements in advance.
  1410. llvm::APSInt maxElements(elementIndex.getBitWidth(),
  1411. elementIndex.isUnsigned());
  1412. bool maxElementsKnown = false;
  1413. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
  1414. maxElements = CAT->getSize();
  1415. elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
  1416. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1417. maxElementsKnown = true;
  1418. }
  1419. QualType elementType = arrayType->getElementType();
  1420. while (Index < IList->getNumInits()) {
  1421. Expr *Init = IList->getInit(Index);
  1422. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1423. // If we're not the subobject that matches up with the '{' for
  1424. // the designator, we shouldn't be handling the
  1425. // designator. Return immediately.
  1426. if (!SubobjectIsDesignatorContext)
  1427. return;
  1428. // Handle this designated initializer. elementIndex will be
  1429. // updated to be the next array element we'll initialize.
  1430. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1431. DeclType, nullptr, &elementIndex, Index,
  1432. StructuredList, StructuredIndex, true,
  1433. false)) {
  1434. hadError = true;
  1435. continue;
  1436. }
  1437. if (elementIndex.getBitWidth() > maxElements.getBitWidth())
  1438. maxElements = maxElements.extend(elementIndex.getBitWidth());
  1439. else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
  1440. elementIndex = elementIndex.extend(maxElements.getBitWidth());
  1441. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1442. // If the array is of incomplete type, keep track of the number of
  1443. // elements in the initializer.
  1444. if (!maxElementsKnown && elementIndex > maxElements)
  1445. maxElements = elementIndex;
  1446. continue;
  1447. }
  1448. // If we know the maximum number of elements, and we've already
  1449. // hit it, stop consuming elements in the initializer list.
  1450. if (maxElementsKnown && elementIndex == maxElements)
  1451. break;
  1452. InitializedEntity ElementEntity =
  1453. InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
  1454. Entity);
  1455. // Check this element.
  1456. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1457. StructuredList, StructuredIndex);
  1458. ++elementIndex;
  1459. // If the array is of incomplete type, keep track of the number of
  1460. // elements in the initializer.
  1461. if (!maxElementsKnown && elementIndex > maxElements)
  1462. maxElements = elementIndex;
  1463. }
  1464. if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
  1465. // If this is an incomplete array type, the actual type needs to
  1466. // be calculated here.
  1467. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
  1468. if (maxElements == Zero) {
  1469. // Sizing an array implicitly to zero is not allowed by ISO C,
  1470. // but is supported by GNU.
  1471. SemaRef.Diag(IList->getLocStart(),
  1472. diag::ext_typecheck_zero_array_size);
  1473. }
  1474. DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
  1475. ArrayType::Normal, 0);
  1476. }
  1477. if (!hadError && VerifyOnly) {
  1478. // Check if there are any members of the array that get value-initialized.
  1479. // If so, check if doing that is possible.
  1480. // FIXME: This needs to detect holes left by designated initializers too.
  1481. if (maxElementsKnown && elementIndex < maxElements)
  1482. CheckEmptyInitializable(InitializedEntity::InitializeElement(
  1483. SemaRef.Context, 0, Entity),
  1484. IList->getLocEnd());
  1485. }
  1486. }
  1487. bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
  1488. Expr *InitExpr,
  1489. FieldDecl *Field,
  1490. bool TopLevelObject) {
  1491. // Handle GNU flexible array initializers.
  1492. unsigned FlexArrayDiag;
  1493. if (isa<InitListExpr>(InitExpr) &&
  1494. cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
  1495. // Empty flexible array init always allowed as an extension
  1496. FlexArrayDiag = diag::ext_flexible_array_init;
  1497. } else if (SemaRef.getLangOpts().CPlusPlus) {
  1498. // Disallow flexible array init in C++; it is not required for gcc
  1499. // compatibility, and it needs work to IRGen correctly in general.
  1500. FlexArrayDiag = diag::err_flexible_array_init;
  1501. } else if (!TopLevelObject) {
  1502. // Disallow flexible array init on non-top-level object
  1503. FlexArrayDiag = diag::err_flexible_array_init;
  1504. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  1505. // Disallow flexible array init on anything which is not a variable.
  1506. FlexArrayDiag = diag::err_flexible_array_init;
  1507. } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
  1508. // Disallow flexible array init on local variables.
  1509. FlexArrayDiag = diag::err_flexible_array_init;
  1510. } else {
  1511. // Allow other cases.
  1512. FlexArrayDiag = diag::ext_flexible_array_init;
  1513. }
  1514. if (!VerifyOnly) {
  1515. SemaRef.Diag(InitExpr->getLocStart(),
  1516. FlexArrayDiag)
  1517. << InitExpr->getLocStart();
  1518. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1519. << Field;
  1520. }
  1521. return FlexArrayDiag != diag::ext_flexible_array_init;
  1522. }
  1523. void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
  1524. InitListExpr *IList,
  1525. QualType DeclType,
  1526. RecordDecl::field_iterator Field,
  1527. bool SubobjectIsDesignatorContext,
  1528. unsigned &Index,
  1529. InitListExpr *StructuredList,
  1530. unsigned &StructuredIndex,
  1531. bool TopLevelObject) {
  1532. RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
  1533. // If the record is invalid, some of it's members are invalid. To avoid
  1534. // confusion, we forgo checking the intializer for the entire record.
  1535. if (structDecl->isInvalidDecl()) {
  1536. // Assume it was supposed to consume a single initializer.
  1537. ++Index;
  1538. hadError = true;
  1539. return;
  1540. }
  1541. if (DeclType->isUnionType() && IList->getNumInits() == 0) {
  1542. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1543. // If there's a default initializer, use it.
  1544. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
  1545. if (VerifyOnly)
  1546. return;
  1547. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1548. Field != FieldEnd; ++Field) {
  1549. if (Field->hasInClassInitializer()) {
  1550. StructuredList->setInitializedFieldInUnion(*Field);
  1551. // FIXME: Actually build a CXXDefaultInitExpr?
  1552. return;
  1553. }
  1554. }
  1555. }
  1556. // Value-initialize the first member of the union that isn't an unnamed
  1557. // bitfield.
  1558. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1559. Field != FieldEnd; ++Field) {
  1560. if (!Field->isUnnamedBitfield()) {
  1561. if (VerifyOnly)
  1562. CheckEmptyInitializable(
  1563. InitializedEntity::InitializeMember(*Field, &Entity),
  1564. IList->getLocEnd());
  1565. else
  1566. StructuredList->setInitializedFieldInUnion(*Field);
  1567. break;
  1568. }
  1569. }
  1570. return;
  1571. }
  1572. // If structDecl is a forward declaration, this loop won't do
  1573. // anything except look at designated initializers; That's okay,
  1574. // because an error should get printed out elsewhere. It might be
  1575. // worthwhile to skip over the rest of the initializer, though.
  1576. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1577. RecordDecl::field_iterator FieldEnd = RD->field_end();
  1578. bool InitializedSomething = false;
  1579. bool CheckForMissingFields = true;
  1580. while (Index < IList->getNumInits()) {
  1581. Expr *Init = IList->getInit(Index);
  1582. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1583. // If we're not the subobject that matches up with the '{' for
  1584. // the designator, we shouldn't be handling the
  1585. // designator. Return immediately.
  1586. if (!SubobjectIsDesignatorContext)
  1587. return;
  1588. // Handle this designated initializer. Field will be updated to
  1589. // the next field that we'll be initializing.
  1590. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1591. DeclType, &Field, nullptr, Index,
  1592. StructuredList, StructuredIndex,
  1593. true, TopLevelObject))
  1594. hadError = true;
  1595. InitializedSomething = true;
  1596. // Disable check for missing fields when designators are used.
  1597. // This matches gcc behaviour.
  1598. CheckForMissingFields = false;
  1599. continue;
  1600. }
  1601. if (Field == FieldEnd) {
  1602. // We've run out of fields. We're done.
  1603. break;
  1604. }
  1605. // We've already initialized a member of a union. We're done.
  1606. if (InitializedSomething && DeclType->isUnionType())
  1607. break;
  1608. // If we've hit the flexible array member at the end, we're done.
  1609. if (Field->getType()->isIncompleteArrayType())
  1610. break;
  1611. if (Field->isUnnamedBitfield()) {
  1612. // Don't initialize unnamed bitfields, e.g. "int : 20;"
  1613. ++Field;
  1614. continue;
  1615. }
  1616. // Make sure we can use this declaration.
  1617. bool InvalidUse;
  1618. if (VerifyOnly)
  1619. InvalidUse = !SemaRef.CanUseDecl(*Field);
  1620. else
  1621. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
  1622. IList->getInit(Index)->getLocStart());
  1623. if (InvalidUse) {
  1624. ++Index;
  1625. ++Field;
  1626. hadError = true;
  1627. continue;
  1628. }
  1629. InitializedEntity MemberEntity =
  1630. InitializedEntity::InitializeMember(*Field, &Entity);
  1631. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1632. StructuredList, StructuredIndex);
  1633. InitializedSomething = true;
  1634. if (DeclType->isUnionType() && !VerifyOnly) {
  1635. // Initialize the first field within the union.
  1636. StructuredList->setInitializedFieldInUnion(*Field);
  1637. }
  1638. ++Field;
  1639. }
  1640. // Emit warnings for missing struct field initializers.
  1641. if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
  1642. Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
  1643. !DeclType->isUnionType()) {
  1644. // It is possible we have one or more unnamed bitfields remaining.
  1645. // Find first (if any) named field and emit warning.
  1646. for (RecordDecl::field_iterator it = Field, end = RD->field_end();
  1647. it != end; ++it) {
  1648. if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
  1649. SemaRef.Diag(IList->getSourceRange().getEnd(),
  1650. diag::warn_missing_field_initializers) << *it;
  1651. break;
  1652. }
  1653. }
  1654. }
  1655. // Check that any remaining fields can be value-initialized.
  1656. if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
  1657. !Field->getType()->isIncompleteArrayType()) {
  1658. // FIXME: Should check for holes left by designated initializers too.
  1659. for (; Field != FieldEnd && !hadError; ++Field) {
  1660. if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
  1661. CheckEmptyInitializable(
  1662. InitializedEntity::InitializeMember(*Field, &Entity),
  1663. IList->getLocEnd());
  1664. }
  1665. }
  1666. if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
  1667. Index >= IList->getNumInits())
  1668. return;
  1669. if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
  1670. TopLevelObject)) {
  1671. hadError = true;
  1672. ++Index;
  1673. return;
  1674. }
  1675. InitializedEntity MemberEntity =
  1676. InitializedEntity::InitializeMember(*Field, &Entity);
  1677. if (isa<InitListExpr>(IList->getInit(Index)))
  1678. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1679. StructuredList, StructuredIndex);
  1680. else
  1681. CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
  1682. StructuredList, StructuredIndex);
  1683. }
  1684. /// \brief Expand a field designator that refers to a member of an
  1685. /// anonymous struct or union into a series of field designators that
  1686. /// refers to the field within the appropriate subobject.
  1687. ///
  1688. static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
  1689. DesignatedInitExpr *DIE,
  1690. unsigned DesigIdx,
  1691. IndirectFieldDecl *IndirectField) {
  1692. typedef DesignatedInitExpr::Designator Designator;
  1693. // Build the replacement designators.
  1694. SmallVector<Designator, 4> Replacements;
  1695. for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
  1696. PE = IndirectField->chain_end(); PI != PE; ++PI) {
  1697. if (PI + 1 == PE)
  1698. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1699. DIE->getDesignator(DesigIdx)->getDotLoc(),
  1700. DIE->getDesignator(DesigIdx)->getFieldLoc()));
  1701. else
  1702. Replacements.push_back(Designator((IdentifierInfo *)nullptr,
  1703. SourceLocation(), SourceLocation()));
  1704. assert(isa<FieldDecl>(*PI));
  1705. Replacements.back().setField(cast<FieldDecl>(*PI));
  1706. }
  1707. // Expand the current designator into the set of replacement
  1708. // designators, so we have a full subobject path down to where the
  1709. // member of the anonymous struct/union is actually stored.
  1710. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
  1711. &Replacements[0] + Replacements.size());
  1712. }
  1713. static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
  1714. DesignatedInitExpr *DIE) {
  1715. unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
  1716. SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
  1717. for (unsigned I = 0; I < NumIndexExprs; ++I)
  1718. IndexExprs[I] = DIE->getSubExpr(I + 1);
  1719. return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
  1720. DIE->size(), IndexExprs,
  1721. DIE->getEqualOrColonLoc(),
  1722. DIE->usesGNUSyntax(), DIE->getInit());
  1723. }
  1724. namespace {
  1725. // Callback to only accept typo corrections that are for field members of
  1726. // the given struct or union.
  1727. class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
  1728. public:
  1729. explicit FieldInitializerValidatorCCC(RecordDecl *RD)
  1730. : Record(RD) {}
  1731. bool ValidateCandidate(const TypoCorrection &candidate) override {
  1732. FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
  1733. return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
  1734. }
  1735. private:
  1736. RecordDecl *Record;
  1737. };
  1738. }
  1739. /// @brief Check the well-formedness of a C99 designated initializer.
  1740. ///
  1741. /// Determines whether the designated initializer @p DIE, which
  1742. /// resides at the given @p Index within the initializer list @p
  1743. /// IList, is well-formed for a current object of type @p DeclType
  1744. /// (C99 6.7.8). The actual subobject that this designator refers to
  1745. /// within the current subobject is returned in either
  1746. /// @p NextField or @p NextElementIndex (whichever is appropriate).
  1747. ///
  1748. /// @param IList The initializer list in which this designated
  1749. /// initializer occurs.
  1750. ///
  1751. /// @param DIE The designated initializer expression.
  1752. ///
  1753. /// @param DesigIdx The index of the current designator.
  1754. ///
  1755. /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
  1756. /// into which the designation in @p DIE should refer.
  1757. ///
  1758. /// @param NextField If non-NULL and the first designator in @p DIE is
  1759. /// a field, this will be set to the field declaration corresponding
  1760. /// to the field named by the designator.
  1761. ///
  1762. /// @param NextElementIndex If non-NULL and the first designator in @p
  1763. /// DIE is an array designator or GNU array-range designator, this
  1764. /// will be set to the last index initialized by this designator.
  1765. ///
  1766. /// @param Index Index into @p IList where the designated initializer
  1767. /// @p DIE occurs.
  1768. ///
  1769. /// @param StructuredList The initializer list expression that
  1770. /// describes all of the subobject initializers in the order they'll
  1771. /// actually be initialized.
  1772. ///
  1773. /// @returns true if there was an error, false otherwise.
  1774. bool
  1775. InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
  1776. InitListExpr *IList,
  1777. DesignatedInitExpr *DIE,
  1778. unsigned DesigIdx,
  1779. QualType &CurrentObjectType,
  1780. RecordDecl::field_iterator *NextField,
  1781. llvm::APSInt *NextElementIndex,
  1782. unsigned &Index,
  1783. InitListExpr *StructuredList,
  1784. unsigned &StructuredIndex,
  1785. bool FinishSubobjectInit,
  1786. bool TopLevelObject) {
  1787. if (DesigIdx == DIE->size()) {
  1788. // Check the actual initialization for the designated object type.
  1789. bool prevHadError = hadError;
  1790. // Temporarily remove the designator expression from the
  1791. // initializer list that the child calls see, so that we don't try
  1792. // to re-process the designator.
  1793. unsigned OldIndex = Index;
  1794. IList->setInit(OldIndex, DIE->getInit());
  1795. CheckSubElementType(Entity, IList, CurrentObjectType, Index,
  1796. StructuredList, StructuredIndex);
  1797. // Restore the designated initializer expression in the syntactic
  1798. // form of the initializer list.
  1799. if (IList->getInit(OldIndex) != DIE->getInit())
  1800. DIE->setInit(IList->getInit(OldIndex));
  1801. IList->setInit(OldIndex, DIE);
  1802. return hadError && !prevHadError;
  1803. }
  1804. DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
  1805. bool IsFirstDesignator = (DesigIdx == 0);
  1806. if (!VerifyOnly) {
  1807. assert((IsFirstDesignator || StructuredList) &&
  1808. "Need a non-designated initializer list to start from");
  1809. // Determine the structural initializer list that corresponds to the
  1810. // current subobject.
  1811. if (IsFirstDesignator)
  1812. StructuredList = SyntacticToSemantic.lookup(IList);
  1813. else {
  1814. Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
  1815. StructuredList->getInit(StructuredIndex) : nullptr;
  1816. if (!ExistingInit && StructuredList->hasArrayFiller())
  1817. ExistingInit = StructuredList->getArrayFiller();
  1818. if (!ExistingInit)
  1819. StructuredList =
  1820. getStructuredSubobjectInit(IList, Index, CurrentObjectType,
  1821. StructuredList, StructuredIndex,
  1822. SourceRange(D->getLocStart(),
  1823. DIE->getLocEnd()));
  1824. else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
  1825. StructuredList = Result;
  1826. else {
  1827. if (DesignatedInitUpdateExpr *E =
  1828. dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
  1829. StructuredList = E->getUpdater();
  1830. else {
  1831. DesignatedInitUpdateExpr *DIUE =
  1832. new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
  1833. D->getLocStart(), ExistingInit,
  1834. DIE->getLocEnd());
  1835. StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
  1836. StructuredList = DIUE->getUpdater();
  1837. }
  1838. // We need to check on source range validity because the previous
  1839. // initializer does not have to be an explicit initializer. e.g.,
  1840. //
  1841. // struct P { int a, b; };
  1842. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  1843. //
  1844. // There is an overwrite taking place because the first braced initializer
  1845. // list "{ .a = 2 }" already provides value for .p.b (which is zero).
  1846. if (ExistingInit->getSourceRange().isValid()) {
  1847. // We are creating an initializer list that initializes the
  1848. // subobjects of the current object, but there was already an
  1849. // initialization that completely initialized the current
  1850. // subobject, e.g., by a compound literal:
  1851. //
  1852. // struct X { int a, b; };
  1853. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  1854. //
  1855. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  1856. // designated initializer re-initializes the whole
  1857. // subobject [0], overwriting previous initializers.
  1858. SemaRef.Diag(D->getLocStart(),
  1859. diag::warn_subobject_initializer_overrides)
  1860. << SourceRange(D->getLocStart(), DIE->getLocEnd());
  1861. SemaRef.Diag(ExistingInit->getLocStart(),
  1862. diag::note_previous_initializer)
  1863. << /*FIXME:has side effects=*/0
  1864. << ExistingInit->getSourceRange();
  1865. }
  1866. }
  1867. }
  1868. assert(StructuredList && "Expected a structured initializer list");
  1869. }
  1870. if (D->isFieldDesignator()) {
  1871. // C99 6.7.8p7:
  1872. //
  1873. // If a designator has the form
  1874. //
  1875. // . identifier
  1876. //
  1877. // then the current object (defined below) shall have
  1878. // structure or union type and the identifier shall be the
  1879. // name of a member of that type.
  1880. const RecordType *RT = CurrentObjectType->getAs<RecordType>();
  1881. if (!RT) {
  1882. SourceLocation Loc = D->getDotLoc();
  1883. if (Loc.isInvalid())
  1884. Loc = D->getFieldLoc();
  1885. if (!VerifyOnly)
  1886. SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
  1887. << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
  1888. ++Index;
  1889. return true;
  1890. }
  1891. FieldDecl *KnownField = D->getField();
  1892. if (!KnownField) {
  1893. IdentifierInfo *FieldName = D->getFieldName();
  1894. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
  1895. for (NamedDecl *ND : Lookup) {
  1896. if (auto *FD = dyn_cast<FieldDecl>(ND)) {
  1897. KnownField = FD;
  1898. break;
  1899. }
  1900. if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
  1901. // In verify mode, don't modify the original.
  1902. if (VerifyOnly)
  1903. DIE = CloneDesignatedInitExpr(SemaRef, DIE);
  1904. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
  1905. D = DIE->getDesignator(DesigIdx);
  1906. KnownField = cast<FieldDecl>(*IFD->chain_begin());
  1907. break;
  1908. }
  1909. }
  1910. if (!KnownField) {
  1911. if (VerifyOnly) {
  1912. ++Index;
  1913. return true; // No typo correction when just trying this out.
  1914. }
  1915. // Name lookup found something, but it wasn't a field.
  1916. if (!Lookup.empty()) {
  1917. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
  1918. << FieldName;
  1919. SemaRef.Diag(Lookup.front()->getLocation(),
  1920. diag::note_field_designator_found);
  1921. ++Index;
  1922. return true;
  1923. }
  1924. // Name lookup didn't find anything.
  1925. // Determine whether this was a typo for another field name.
  1926. if (TypoCorrection Corrected = SemaRef.CorrectTypo(
  1927. DeclarationNameInfo(FieldName, D->getFieldLoc()),
  1928. Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
  1929. llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
  1930. Sema::CTK_ErrorRecovery, RT->getDecl())) {
  1931. SemaRef.diagnoseTypo(
  1932. Corrected,
  1933. SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
  1934. << FieldName << CurrentObjectType);
  1935. KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
  1936. hadError = true;
  1937. } else {
  1938. // Typo correction didn't find anything.
  1939. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
  1940. << FieldName << CurrentObjectType;
  1941. ++Index;
  1942. return true;
  1943. }
  1944. }
  1945. }
  1946. unsigned FieldIndex = 0;
  1947. for (auto *FI : RT->getDecl()->fields()) {
  1948. if (FI->isUnnamedBitfield())
  1949. continue;
  1950. if (KnownField == FI)
  1951. break;
  1952. ++FieldIndex;
  1953. }
  1954. RecordDecl::field_iterator Field =
  1955. RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
  1956. // All of the fields of a union are located at the same place in
  1957. // the initializer list.
  1958. if (RT->getDecl()->isUnion()) {
  1959. FieldIndex = 0;
  1960. if (!VerifyOnly) {
  1961. FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
  1962. if (CurrentField && CurrentField != *Field) {
  1963. assert(StructuredList->getNumInits() == 1
  1964. && "A union should never have more than one initializer!");
  1965. // we're about to throw away an initializer, emit warning
  1966. SemaRef.Diag(D->getFieldLoc(),
  1967. diag::warn_initializer_overrides)
  1968. << D->getSourceRange();
  1969. Expr *ExistingInit = StructuredList->getInit(0);
  1970. SemaRef.Diag(ExistingInit->getLocStart(),
  1971. diag::note_previous_initializer)
  1972. << /*FIXME:has side effects=*/0
  1973. << ExistingInit->getSourceRange();
  1974. // remove existing initializer
  1975. StructuredList->resizeInits(SemaRef.Context, 0);
  1976. StructuredList->setInitializedFieldInUnion(nullptr);
  1977. }
  1978. StructuredList->setInitializedFieldInUnion(*Field);
  1979. }
  1980. }
  1981. // Make sure we can use this declaration.
  1982. bool InvalidUse;
  1983. if (VerifyOnly)
  1984. InvalidUse = !SemaRef.CanUseDecl(*Field);
  1985. else
  1986. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
  1987. if (InvalidUse) {
  1988. ++Index;
  1989. return true;
  1990. }
  1991. if (!VerifyOnly) {
  1992. // Update the designator with the field declaration.
  1993. D->setField(*Field);
  1994. // Make sure that our non-designated initializer list has space
  1995. // for a subobject corresponding to this field.
  1996. if (FieldIndex >= StructuredList->getNumInits())
  1997. StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
  1998. }
  1999. // This designator names a flexible array member.
  2000. if (Field->getType()->isIncompleteArrayType()) {
  2001. bool Invalid = false;
  2002. if ((DesigIdx + 1) != DIE->size()) {
  2003. // We can't designate an object within the flexible array
  2004. // member (because GCC doesn't allow it).
  2005. if (!VerifyOnly) {
  2006. DesignatedInitExpr::Designator *NextD
  2007. = DIE->getDesignator(DesigIdx + 1);
  2008. SemaRef.Diag(NextD->getLocStart(),
  2009. diag::err_designator_into_flexible_array_member)
  2010. << SourceRange(NextD->getLocStart(),
  2011. DIE->getLocEnd());
  2012. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2013. << *Field;
  2014. }
  2015. Invalid = true;
  2016. }
  2017. if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
  2018. !isa<StringLiteral>(DIE->getInit())) {
  2019. // The initializer is not an initializer list.
  2020. if (!VerifyOnly) {
  2021. SemaRef.Diag(DIE->getInit()->getLocStart(),
  2022. diag::err_flexible_array_init_needs_braces)
  2023. << DIE->getInit()->getSourceRange();
  2024. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  2025. << *Field;
  2026. }
  2027. Invalid = true;
  2028. }
  2029. // Check GNU flexible array initializer.
  2030. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
  2031. TopLevelObject))
  2032. Invalid = true;
  2033. if (Invalid) {
  2034. ++Index;
  2035. return true;
  2036. }
  2037. // Initialize the array.
  2038. bool prevHadError = hadError;
  2039. unsigned newStructuredIndex = FieldIndex;
  2040. unsigned OldIndex = Index;
  2041. IList->setInit(Index, DIE->getInit());
  2042. InitializedEntity MemberEntity =
  2043. InitializedEntity::InitializeMember(*Field, &Entity);
  2044. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  2045. StructuredList, newStructuredIndex);
  2046. IList->setInit(OldIndex, DIE);
  2047. if (hadError && !prevHadError) {
  2048. ++Field;
  2049. ++FieldIndex;
  2050. if (NextField)
  2051. *NextField = Field;
  2052. StructuredIndex = FieldIndex;
  2053. return true;
  2054. }
  2055. } else {
  2056. // Recurse to check later designated subobjects.
  2057. QualType FieldType = Field->getType();
  2058. unsigned newStructuredIndex = FieldIndex;
  2059. InitializedEntity MemberEntity =
  2060. InitializedEntity::InitializeMember(*Field, &Entity);
  2061. if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
  2062. FieldType, nullptr, nullptr, Index,
  2063. StructuredList, newStructuredIndex,
  2064. true, false))
  2065. return true;
  2066. }
  2067. // Find the position of the next field to be initialized in this
  2068. // subobject.
  2069. ++Field;
  2070. ++FieldIndex;
  2071. // If this the first designator, our caller will continue checking
  2072. // the rest of this struct/class/union subobject.
  2073. if (IsFirstDesignator) {
  2074. if (NextField)
  2075. *NextField = Field;
  2076. StructuredIndex = FieldIndex;
  2077. return false;
  2078. }
  2079. if (!FinishSubobjectInit)
  2080. return false;
  2081. // We've already initialized something in the union; we're done.
  2082. if (RT->getDecl()->isUnion())
  2083. return hadError;
  2084. // Check the remaining fields within this class/struct/union subobject.
  2085. bool prevHadError = hadError;
  2086. CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
  2087. StructuredList, FieldIndex);
  2088. return hadError && !prevHadError;
  2089. }
  2090. // C99 6.7.8p6:
  2091. //
  2092. // If a designator has the form
  2093. //
  2094. // [ constant-expression ]
  2095. //
  2096. // then the current object (defined below) shall have array
  2097. // type and the expression shall be an integer constant
  2098. // expression. If the array is of unknown size, any
  2099. // nonnegative value is valid.
  2100. //
  2101. // Additionally, cope with the GNU extension that permits
  2102. // designators of the form
  2103. //
  2104. // [ constant-expression ... constant-expression ]
  2105. const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
  2106. if (!AT) {
  2107. if (!VerifyOnly)
  2108. SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
  2109. << CurrentObjectType;
  2110. ++Index;
  2111. return true;
  2112. }
  2113. Expr *IndexExpr = nullptr;
  2114. llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
  2115. if (D->isArrayDesignator()) {
  2116. IndexExpr = DIE->getArrayIndex(*D);
  2117. DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
  2118. DesignatedEndIndex = DesignatedStartIndex;
  2119. } else {
  2120. assert(D->isArrayRangeDesignator() && "Need array-range designator");
  2121. DesignatedStartIndex =
  2122. DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2123. DesignatedEndIndex =
  2124. DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
  2125. IndexExpr = DIE->getArrayRangeEnd(*D);
  2126. // Codegen can't handle evaluating array range designators that have side
  2127. // effects, because we replicate the AST value for each initialized element.
  2128. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
  2129. // elements with something that has a side effect, so codegen can emit an
  2130. // "error unsupported" error instead of miscompiling the app.
  2131. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
  2132. DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
  2133. FullyStructuredList->sawArrayRangeDesignator();
  2134. }
  2135. if (isa<ConstantArrayType>(AT)) {
  2136. llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
  2137. DesignatedStartIndex
  2138. = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
  2139. DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
  2140. DesignatedEndIndex
  2141. = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
  2142. DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
  2143. if (DesignatedEndIndex >= MaxElements) {
  2144. if (!VerifyOnly)
  2145. SemaRef.Diag(IndexExpr->getLocStart(),
  2146. diag::err_array_designator_too_large)
  2147. << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
  2148. << IndexExpr->getSourceRange();
  2149. ++Index;
  2150. return true;
  2151. }
  2152. } else {
  2153. unsigned DesignatedIndexBitWidth =
  2154. ConstantArrayType::getMaxSizeBits(SemaRef.Context);
  2155. DesignatedStartIndex =
  2156. DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
  2157. DesignatedEndIndex =
  2158. DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
  2159. DesignatedStartIndex.setIsUnsigned(true);
  2160. DesignatedEndIndex.setIsUnsigned(true);
  2161. }
  2162. if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
  2163. // We're modifying a string literal init; we have to decompose the string
  2164. // so we can modify the individual characters.
  2165. ASTContext &Context = SemaRef.Context;
  2166. Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
  2167. // Compute the character type
  2168. QualType CharTy = AT->getElementType();
  2169. // Compute the type of the integer literals.
  2170. QualType PromotedCharTy = CharTy;
  2171. if (CharTy->isPromotableIntegerType())
  2172. PromotedCharTy = Context.getPromotedIntegerType(CharTy);
  2173. unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
  2174. if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
  2175. // Get the length of the string.
  2176. uint64_t StrLen = SL->getLength();
  2177. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2178. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2179. StructuredList->resizeInits(Context, StrLen);
  2180. // Build a literal for each character in the string, and put them into
  2181. // the init list.
  2182. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2183. llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
  2184. Expr *Init = new (Context) IntegerLiteral(
  2185. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2186. if (CharTy != PromotedCharTy)
  2187. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2188. Init, nullptr, VK_RValue);
  2189. StructuredList->updateInit(Context, i, Init);
  2190. }
  2191. } else {
  2192. ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
  2193. std::string Str;
  2194. Context.getObjCEncodingForType(E->getEncodedType(), Str);
  2195. // Get the length of the string.
  2196. uint64_t StrLen = Str.size();
  2197. if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
  2198. StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
  2199. StructuredList->resizeInits(Context, StrLen);
  2200. // Build a literal for each character in the string, and put them into
  2201. // the init list.
  2202. for (unsigned i = 0, e = StrLen; i != e; ++i) {
  2203. llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
  2204. Expr *Init = new (Context) IntegerLiteral(
  2205. Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
  2206. if (CharTy != PromotedCharTy)
  2207. Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
  2208. Init, nullptr, VK_RValue);
  2209. StructuredList->updateInit(Context, i, Init);
  2210. }
  2211. }
  2212. }
  2213. // Make sure that our non-designated initializer list has space
  2214. // for a subobject corresponding to this array element.
  2215. if (!VerifyOnly &&
  2216. DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
  2217. StructuredList->resizeInits(SemaRef.Context,
  2218. DesignatedEndIndex.getZExtValue() + 1);
  2219. // Repeatedly perform subobject initializations in the range
  2220. // [DesignatedStartIndex, DesignatedEndIndex].
  2221. // Move to the next designator
  2222. unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
  2223. unsigned OldIndex = Index;
  2224. InitializedEntity ElementEntity =
  2225. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  2226. while (DesignatedStartIndex <= DesignatedEndIndex) {
  2227. // Recurse to check later designated subobjects.
  2228. QualType ElementType = AT->getElementType();
  2229. Index = OldIndex;
  2230. ElementEntity.setElementIndex(ElementIndex);
  2231. if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
  2232. ElementType, nullptr, nullptr, Index,
  2233. StructuredList, ElementIndex,
  2234. (DesignatedStartIndex == DesignatedEndIndex),
  2235. false))
  2236. return true;
  2237. // Move to the next index in the array that we'll be initializing.
  2238. ++DesignatedStartIndex;
  2239. ElementIndex = DesignatedStartIndex.getZExtValue();
  2240. }
  2241. // If this the first designator, our caller will continue checking
  2242. // the rest of this array subobject.
  2243. if (IsFirstDesignator) {
  2244. if (NextElementIndex)
  2245. *NextElementIndex = DesignatedStartIndex;
  2246. StructuredIndex = ElementIndex;
  2247. return false;
  2248. }
  2249. if (!FinishSubobjectInit)
  2250. return false;
  2251. // Check the remaining elements within this array subobject.
  2252. bool prevHadError = hadError;
  2253. CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
  2254. /*SubobjectIsDesignatorContext=*/false, Index,
  2255. StructuredList, ElementIndex);
  2256. return hadError && !prevHadError;
  2257. }
  2258. // Get the structured initializer list for a subobject of type
  2259. // @p CurrentObjectType.
  2260. InitListExpr *
  2261. InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  2262. QualType CurrentObjectType,
  2263. InitListExpr *StructuredList,
  2264. unsigned StructuredIndex,
  2265. SourceRange InitRange,
  2266. bool IsFullyOverwritten) {
  2267. if (VerifyOnly)
  2268. return nullptr; // No structured list in verification-only mode.
  2269. Expr *ExistingInit = nullptr;
  2270. if (!StructuredList)
  2271. ExistingInit = SyntacticToSemantic.lookup(IList);
  2272. else if (StructuredIndex < StructuredList->getNumInits())
  2273. ExistingInit = StructuredList->getInit(StructuredIndex);
  2274. if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
  2275. // There might have already been initializers for subobjects of the current
  2276. // object, but a subsequent initializer list will overwrite the entirety
  2277. // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
  2278. //
  2279. // struct P { char x[6]; };
  2280. // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
  2281. //
  2282. // The first designated initializer is ignored, and l.x is just "f".
  2283. if (!IsFullyOverwritten)
  2284. return Result;
  2285. if (ExistingInit) {
  2286. // We are creating an initializer list that initializes the
  2287. // subobjects of the current object, but there was already an
  2288. // initialization that completely initialized the current
  2289. // subobject, e.g., by a compound literal:
  2290. //
  2291. // struct X { int a, b; };
  2292. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  2293. //
  2294. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  2295. // designated initializer re-initializes the whole
  2296. // subobject [0], overwriting previous initializers.
  2297. SemaRef.Diag(InitRange.getBegin(),
  2298. diag::warn_subobject_initializer_overrides)
  2299. << InitRange;
  2300. SemaRef.Diag(ExistingInit->getLocStart(),
  2301. diag::note_previous_initializer)
  2302. << /*FIXME:has side effects=*/0
  2303. << ExistingInit->getSourceRange();
  2304. }
  2305. InitListExpr *Result
  2306. = new (SemaRef.Context) InitListExpr(SemaRef.Context,
  2307. InitRange.getBegin(), None,
  2308. InitRange.getEnd());
  2309. QualType ResultType = CurrentObjectType;
  2310. if (!ResultType->isArrayType())
  2311. ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
  2312. Result->setType(ResultType);
  2313. // Pre-allocate storage for the structured initializer list.
  2314. unsigned NumElements = 0;
  2315. unsigned NumInits = 0;
  2316. bool GotNumInits = false;
  2317. if (!StructuredList) {
  2318. NumInits = IList->getNumInits();
  2319. GotNumInits = true;
  2320. } else if (Index < IList->getNumInits()) {
  2321. if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
  2322. NumInits = SubList->getNumInits();
  2323. GotNumInits = true;
  2324. }
  2325. }
  2326. if (const ArrayType *AType
  2327. = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
  2328. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
  2329. NumElements = CAType->getSize().getZExtValue();
  2330. // Simple heuristic so that we don't allocate a very large
  2331. // initializer with many empty entries at the end.
  2332. if (GotNumInits && NumElements > NumInits)
  2333. NumElements = 0;
  2334. }
  2335. } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
  2336. NumElements = VType->getNumElements();
  2337. else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
  2338. RecordDecl *RDecl = RType->getDecl();
  2339. if (RDecl->isUnion())
  2340. NumElements = 1;
  2341. else
  2342. NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
  2343. }
  2344. Result->reserveInits(SemaRef.Context, NumElements);
  2345. // Link this new initializer list into the structured initializer
  2346. // lists.
  2347. if (StructuredList)
  2348. StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
  2349. else {
  2350. Result->setSyntacticForm(IList);
  2351. SyntacticToSemantic[IList] = Result;
  2352. }
  2353. return Result;
  2354. }
  2355. /// Update the initializer at index @p StructuredIndex within the
  2356. /// structured initializer list to the value @p expr.
  2357. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
  2358. unsigned &StructuredIndex,
  2359. Expr *expr) {
  2360. // No structured initializer list to update
  2361. if (!StructuredList)
  2362. return;
  2363. if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
  2364. StructuredIndex, expr)) {
  2365. // This initializer overwrites a previous initializer. Warn.
  2366. // We need to check on source range validity because the previous
  2367. // initializer does not have to be an explicit initializer.
  2368. // struct P { int a, b; };
  2369. // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
  2370. // There is an overwrite taking place because the first braced initializer
  2371. // list "{ .a = 2 }' already provides value for .p.b (which is zero).
  2372. if (PrevInit->getSourceRange().isValid()) {
  2373. SemaRef.Diag(expr->getLocStart(),
  2374. diag::warn_initializer_overrides)
  2375. << expr->getSourceRange();
  2376. SemaRef.Diag(PrevInit->getLocStart(),
  2377. diag::note_previous_initializer)
  2378. << /*FIXME:has side effects=*/0
  2379. << PrevInit->getSourceRange();
  2380. }
  2381. }
  2382. ++StructuredIndex;
  2383. }
  2384. /// Check that the given Index expression is a valid array designator
  2385. /// value. This is essentially just a wrapper around
  2386. /// VerifyIntegerConstantExpression that also checks for negative values
  2387. /// and produces a reasonable diagnostic if there is a
  2388. /// failure. Returns the index expression, possibly with an implicit cast
  2389. /// added, on success. If everything went okay, Value will receive the
  2390. /// value of the constant expression.
  2391. static ExprResult
  2392. CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
  2393. SourceLocation Loc = Index->getLocStart();
  2394. // Make sure this is an integer constant expression.
  2395. ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
  2396. if (Result.isInvalid())
  2397. return Result;
  2398. if (Value.isSigned() && Value.isNegative())
  2399. return S.Diag(Loc, diag::err_array_designator_negative)
  2400. << Value.toString(10) << Index->getSourceRange();
  2401. Value.setIsUnsigned(true);
  2402. return Result;
  2403. }
  2404. ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
  2405. SourceLocation Loc,
  2406. bool GNUSyntax,
  2407. ExprResult Init) {
  2408. typedef DesignatedInitExpr::Designator ASTDesignator;
  2409. bool Invalid = false;
  2410. SmallVector<ASTDesignator, 32> Designators;
  2411. SmallVector<Expr *, 32> InitExpressions;
  2412. // Build designators and check array designator expressions.
  2413. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
  2414. const Designator &D = Desig.getDesignator(Idx);
  2415. switch (D.getKind()) {
  2416. case Designator::FieldDesignator:
  2417. Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
  2418. D.getFieldLoc()));
  2419. break;
  2420. case Designator::ArrayDesignator: {
  2421. Expr *Index = static_cast<Expr *>(D.getArrayIndex());
  2422. llvm::APSInt IndexValue;
  2423. if (!Index->isTypeDependent() && !Index->isValueDependent())
  2424. Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
  2425. if (!Index)
  2426. Invalid = true;
  2427. else {
  2428. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2429. D.getLBracketLoc(),
  2430. D.getRBracketLoc()));
  2431. InitExpressions.push_back(Index);
  2432. }
  2433. break;
  2434. }
  2435. case Designator::ArrayRangeDesignator: {
  2436. Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
  2437. Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
  2438. llvm::APSInt StartValue;
  2439. llvm::APSInt EndValue;
  2440. bool StartDependent = StartIndex->isTypeDependent() ||
  2441. StartIndex->isValueDependent();
  2442. bool EndDependent = EndIndex->isTypeDependent() ||
  2443. EndIndex->isValueDependent();
  2444. if (!StartDependent)
  2445. StartIndex =
  2446. CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
  2447. if (!EndDependent)
  2448. EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
  2449. if (!StartIndex || !EndIndex)
  2450. Invalid = true;
  2451. else {
  2452. // Make sure we're comparing values with the same bit width.
  2453. if (StartDependent || EndDependent) {
  2454. // Nothing to compute.
  2455. } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
  2456. EndValue = EndValue.extend(StartValue.getBitWidth());
  2457. else if (StartValue.getBitWidth() < EndValue.getBitWidth())
  2458. StartValue = StartValue.extend(EndValue.getBitWidth());
  2459. if (!StartDependent && !EndDependent && EndValue < StartValue) {
  2460. Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
  2461. << StartValue.toString(10) << EndValue.toString(10)
  2462. << StartIndex->getSourceRange() << EndIndex->getSourceRange();
  2463. Invalid = true;
  2464. } else {
  2465. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2466. D.getLBracketLoc(),
  2467. D.getEllipsisLoc(),
  2468. D.getRBracketLoc()));
  2469. InitExpressions.push_back(StartIndex);
  2470. InitExpressions.push_back(EndIndex);
  2471. }
  2472. }
  2473. break;
  2474. }
  2475. }
  2476. }
  2477. if (Invalid || Init.isInvalid())
  2478. return ExprError();
  2479. // Clear out the expressions within the designation.
  2480. Desig.ClearExprs(*this);
  2481. DesignatedInitExpr *DIE
  2482. = DesignatedInitExpr::Create(Context,
  2483. Designators.data(), Designators.size(),
  2484. InitExpressions, Loc, GNUSyntax,
  2485. Init.getAs<Expr>());
  2486. if (!getLangOpts().C99)
  2487. Diag(DIE->getLocStart(), diag::ext_designated_init)
  2488. << DIE->getSourceRange();
  2489. return DIE;
  2490. }
  2491. //===----------------------------------------------------------------------===//
  2492. // Initialization entity
  2493. //===----------------------------------------------------------------------===//
  2494. InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
  2495. const InitializedEntity &Parent)
  2496. : Parent(&Parent), Index(Index)
  2497. {
  2498. if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
  2499. Kind = EK_ArrayElement;
  2500. Type = AT->getElementType();
  2501. } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
  2502. Kind = EK_VectorElement;
  2503. Type = VT->getElementType();
  2504. } else {
  2505. const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
  2506. assert(CT && "Unexpected type");
  2507. Kind = EK_ComplexElement;
  2508. Type = CT->getElementType();
  2509. }
  2510. }
  2511. InitializedEntity
  2512. InitializedEntity::InitializeBase(ASTContext &Context,
  2513. const CXXBaseSpecifier *Base,
  2514. bool IsInheritedVirtualBase) {
  2515. InitializedEntity Result;
  2516. Result.Kind = EK_Base;
  2517. Result.Parent = nullptr;
  2518. Result.Base = reinterpret_cast<uintptr_t>(Base);
  2519. if (IsInheritedVirtualBase)
  2520. Result.Base |= 0x01;
  2521. Result.Type = Base->getType();
  2522. return Result;
  2523. }
  2524. DeclarationName InitializedEntity::getName() const {
  2525. switch (getKind()) {
  2526. case EK_Parameter:
  2527. case EK_Parameter_CF_Audited: {
  2528. ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2529. return (D ? D->getDeclName() : DeclarationName());
  2530. }
  2531. case EK_Variable:
  2532. case EK_Member:
  2533. return VariableOrMember->getDeclName();
  2534. case EK_LambdaCapture:
  2535. return DeclarationName(Capture.VarID);
  2536. case EK_Result:
  2537. case EK_Exception:
  2538. case EK_New:
  2539. case EK_Temporary:
  2540. case EK_Base:
  2541. case EK_Delegating:
  2542. case EK_ArrayElement:
  2543. case EK_VectorElement:
  2544. case EK_ComplexElement:
  2545. case EK_BlockElement:
  2546. case EK_CompoundLiteralInit:
  2547. case EK_RelatedResult:
  2548. return DeclarationName();
  2549. }
  2550. llvm_unreachable("Invalid EntityKind!");
  2551. }
  2552. DeclaratorDecl *InitializedEntity::getDecl() const {
  2553. switch (getKind()) {
  2554. case EK_Variable:
  2555. case EK_Member:
  2556. return VariableOrMember;
  2557. case EK_Parameter:
  2558. case EK_Parameter_CF_Audited:
  2559. return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2560. case EK_Result:
  2561. case EK_Exception:
  2562. case EK_New:
  2563. case EK_Temporary:
  2564. case EK_Base:
  2565. case EK_Delegating:
  2566. case EK_ArrayElement:
  2567. case EK_VectorElement:
  2568. case EK_ComplexElement:
  2569. case EK_BlockElement:
  2570. case EK_LambdaCapture:
  2571. case EK_CompoundLiteralInit:
  2572. case EK_RelatedResult:
  2573. return nullptr;
  2574. }
  2575. llvm_unreachable("Invalid EntityKind!");
  2576. }
  2577. bool InitializedEntity::allowsNRVO() const {
  2578. switch (getKind()) {
  2579. case EK_Result:
  2580. case EK_Exception:
  2581. return LocAndNRVO.NRVO;
  2582. case EK_Variable:
  2583. case EK_Parameter:
  2584. case EK_Parameter_CF_Audited:
  2585. case EK_Member:
  2586. case EK_New:
  2587. case EK_Temporary:
  2588. case EK_CompoundLiteralInit:
  2589. case EK_Base:
  2590. case EK_Delegating:
  2591. case EK_ArrayElement:
  2592. case EK_VectorElement:
  2593. case EK_ComplexElement:
  2594. case EK_BlockElement:
  2595. case EK_LambdaCapture:
  2596. case EK_RelatedResult:
  2597. break;
  2598. }
  2599. return false;
  2600. }
  2601. unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
  2602. assert(getParent() != this);
  2603. unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
  2604. for (unsigned I = 0; I != Depth; ++I)
  2605. OS << "`-";
  2606. switch (getKind()) {
  2607. case EK_Variable: OS << "Variable"; break;
  2608. case EK_Parameter: OS << "Parameter"; break;
  2609. case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
  2610. break;
  2611. case EK_Result: OS << "Result"; break;
  2612. case EK_Exception: OS << "Exception"; break;
  2613. case EK_Member: OS << "Member"; break;
  2614. case EK_New: OS << "New"; break;
  2615. case EK_Temporary: OS << "Temporary"; break;
  2616. case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
  2617. case EK_RelatedResult: OS << "RelatedResult"; break;
  2618. case EK_Base: OS << "Base"; break;
  2619. case EK_Delegating: OS << "Delegating"; break;
  2620. case EK_ArrayElement: OS << "ArrayElement " << Index; break;
  2621. case EK_VectorElement: OS << "VectorElement " << Index; break;
  2622. case EK_ComplexElement: OS << "ComplexElement " << Index; break;
  2623. case EK_BlockElement: OS << "Block"; break;
  2624. case EK_LambdaCapture:
  2625. OS << "LambdaCapture ";
  2626. OS << DeclarationName(Capture.VarID);
  2627. break;
  2628. }
  2629. if (Decl *D = getDecl()) {
  2630. OS << " ";
  2631. cast<NamedDecl>(D)->printQualifiedName(OS);
  2632. }
  2633. OS << " '" << getType().getAsString() << "'\n";
  2634. return Depth + 1;
  2635. }
  2636. void InitializedEntity::dump() const {
  2637. dumpImpl(llvm::errs());
  2638. }
  2639. //===----------------------------------------------------------------------===//
  2640. // Initialization sequence
  2641. //===----------------------------------------------------------------------===//
  2642. void InitializationSequence::Step::Destroy() {
  2643. switch (Kind) {
  2644. case SK_ResolveAddressOfOverloadedFunction:
  2645. case SK_CastDerivedToBaseRValue:
  2646. case SK_CastDerivedToBaseXValue:
  2647. case SK_CastDerivedToBaseLValue:
  2648. case SK_BindReference:
  2649. case SK_BindReferenceToTemporary:
  2650. case SK_ExtraneousCopyToTemporary:
  2651. case SK_UserConversion:
  2652. case SK_QualificationConversionRValue:
  2653. case SK_QualificationConversionXValue:
  2654. case SK_QualificationConversionLValue:
  2655. case SK_AtomicConversion:
  2656. case SK_LValueToRValue:
  2657. case SK_ListInitialization:
  2658. case SK_UnwrapInitList:
  2659. case SK_RewrapInitList:
  2660. case SK_ConstructorInitialization:
  2661. case SK_ConstructorInitializationFromList:
  2662. case SK_ZeroInitialization:
  2663. case SK_CAssignment:
  2664. case SK_StringInit:
  2665. case SK_ObjCObjectConversion:
  2666. case SK_ArrayInit:
  2667. case SK_ParenthesizedArrayInit:
  2668. case SK_PassByIndirectCopyRestore:
  2669. case SK_PassByIndirectRestore:
  2670. case SK_ProduceObjCObject:
  2671. case SK_StdInitializerList:
  2672. case SK_StdInitializerListConstructorCall:
  2673. case SK_OCLSamplerInit:
  2674. case SK_OCLZeroEvent:
  2675. break;
  2676. case SK_ConversionSequence:
  2677. case SK_ConversionSequenceNoNarrowing:
  2678. delete ICS;
  2679. }
  2680. }
  2681. bool InitializationSequence::isDirectReferenceBinding() const {
  2682. return !Steps.empty() && Steps.back().Kind == SK_BindReference;
  2683. }
  2684. bool InitializationSequence::isAmbiguous() const {
  2685. if (!Failed())
  2686. return false;
  2687. switch (getFailureKind()) {
  2688. case FK_TooManyInitsForReference:
  2689. case FK_ArrayNeedsInitList:
  2690. case FK_ArrayNeedsInitListOrStringLiteral:
  2691. case FK_ArrayNeedsInitListOrWideStringLiteral:
  2692. case FK_NarrowStringIntoWideCharArray:
  2693. case FK_WideStringIntoCharArray:
  2694. case FK_IncompatWideStringIntoWideChar:
  2695. case FK_AddressOfOverloadFailed: // FIXME: Could do better
  2696. case FK_NonConstLValueReferenceBindingToTemporary:
  2697. case FK_NonConstLValueReferenceBindingToUnrelated:
  2698. case FK_RValueReferenceBindingToLValue:
  2699. case FK_ReferenceInitDropsQualifiers:
  2700. case FK_ReferenceInitFailed:
  2701. case FK_ConversionFailed:
  2702. case FK_ConversionFromPropertyFailed:
  2703. case FK_TooManyInitsForScalar:
  2704. case FK_ReferenceBindingToInitList:
  2705. case FK_InitListBadDestinationType:
  2706. case FK_DefaultInitOfConst:
  2707. case FK_Incomplete:
  2708. case FK_ArrayTypeMismatch:
  2709. case FK_NonConstantArrayInit:
  2710. case FK_ListInitializationFailed:
  2711. case FK_VariableLengthArrayHasInitializer:
  2712. case FK_PlaceholderType:
  2713. case FK_ExplicitConstructor:
  2714. return false;
  2715. case FK_ReferenceInitOverloadFailed:
  2716. case FK_UserConversionOverloadFailed:
  2717. case FK_ConstructorOverloadFailed:
  2718. case FK_ListConstructorOverloadFailed:
  2719. return FailedOverloadResult == OR_Ambiguous;
  2720. }
  2721. llvm_unreachable("Invalid EntityKind!");
  2722. }
  2723. bool InitializationSequence::isConstructorInitialization() const {
  2724. return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
  2725. }
  2726. void
  2727. InitializationSequence
  2728. ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
  2729. DeclAccessPair Found,
  2730. bool HadMultipleCandidates) {
  2731. Step S;
  2732. S.Kind = SK_ResolveAddressOfOverloadedFunction;
  2733. S.Type = Function->getType();
  2734. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2735. S.Function.Function = Function;
  2736. S.Function.FoundDecl = Found;
  2737. Steps.push_back(S);
  2738. }
  2739. void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
  2740. ExprValueKind VK) {
  2741. Step S;
  2742. switch (VK) {
  2743. case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
  2744. case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
  2745. case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
  2746. }
  2747. S.Type = BaseType;
  2748. Steps.push_back(S);
  2749. }
  2750. void InitializationSequence::AddReferenceBindingStep(QualType T,
  2751. bool BindingTemporary) {
  2752. Step S;
  2753. S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
  2754. S.Type = T;
  2755. Steps.push_back(S);
  2756. }
  2757. void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
  2758. Step S;
  2759. S.Kind = SK_ExtraneousCopyToTemporary;
  2760. S.Type = T;
  2761. Steps.push_back(S);
  2762. }
  2763. void
  2764. InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
  2765. DeclAccessPair FoundDecl,
  2766. QualType T,
  2767. bool HadMultipleCandidates) {
  2768. Step S;
  2769. S.Kind = SK_UserConversion;
  2770. S.Type = T;
  2771. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2772. S.Function.Function = Function;
  2773. S.Function.FoundDecl = FoundDecl;
  2774. Steps.push_back(S);
  2775. }
  2776. void InitializationSequence::AddQualificationConversionStep(QualType Ty,
  2777. ExprValueKind VK) {
  2778. Step S;
  2779. S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
  2780. switch (VK) {
  2781. case VK_RValue:
  2782. S.Kind = SK_QualificationConversionRValue;
  2783. break;
  2784. case VK_XValue:
  2785. S.Kind = SK_QualificationConversionXValue;
  2786. break;
  2787. case VK_LValue:
  2788. S.Kind = SK_QualificationConversionLValue;
  2789. break;
  2790. }
  2791. S.Type = Ty;
  2792. Steps.push_back(S);
  2793. }
  2794. void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
  2795. Step S;
  2796. S.Kind = SK_AtomicConversion;
  2797. S.Type = Ty;
  2798. Steps.push_back(S);
  2799. }
  2800. void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
  2801. assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
  2802. Step S;
  2803. S.Kind = SK_LValueToRValue;
  2804. S.Type = Ty;
  2805. Steps.push_back(S);
  2806. }
  2807. void InitializationSequence::AddConversionSequenceStep(
  2808. const ImplicitConversionSequence &ICS, QualType T,
  2809. bool TopLevelOfInitList) {
  2810. Step S;
  2811. S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
  2812. : SK_ConversionSequence;
  2813. S.Type = T;
  2814. S.ICS = new ImplicitConversionSequence(ICS);
  2815. Steps.push_back(S);
  2816. }
  2817. void InitializationSequence::AddListInitializationStep(QualType T) {
  2818. Step S;
  2819. S.Kind = SK_ListInitialization;
  2820. S.Type = T;
  2821. Steps.push_back(S);
  2822. }
  2823. void
  2824. InitializationSequence
  2825. ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
  2826. AccessSpecifier Access,
  2827. QualType T,
  2828. bool HadMultipleCandidates,
  2829. bool FromInitList, bool AsInitList) {
  2830. Step S;
  2831. S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
  2832. : SK_ConstructorInitializationFromList
  2833. : SK_ConstructorInitialization;
  2834. S.Type = T;
  2835. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2836. S.Function.Function = Constructor;
  2837. S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
  2838. Steps.push_back(S);
  2839. }
  2840. void InitializationSequence::AddZeroInitializationStep(QualType T) {
  2841. Step S;
  2842. S.Kind = SK_ZeroInitialization;
  2843. S.Type = T;
  2844. Steps.push_back(S);
  2845. }
  2846. void InitializationSequence::AddCAssignmentStep(QualType T) {
  2847. Step S;
  2848. S.Kind = SK_CAssignment;
  2849. S.Type = T;
  2850. Steps.push_back(S);
  2851. }
  2852. void InitializationSequence::AddStringInitStep(QualType T) {
  2853. Step S;
  2854. S.Kind = SK_StringInit;
  2855. S.Type = T;
  2856. Steps.push_back(S);
  2857. }
  2858. void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
  2859. Step S;
  2860. S.Kind = SK_ObjCObjectConversion;
  2861. S.Type = T;
  2862. Steps.push_back(S);
  2863. }
  2864. void InitializationSequence::AddArrayInitStep(QualType T) {
  2865. Step S;
  2866. S.Kind = SK_ArrayInit;
  2867. S.Type = T;
  2868. Steps.push_back(S);
  2869. }
  2870. void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
  2871. Step S;
  2872. S.Kind = SK_ParenthesizedArrayInit;
  2873. S.Type = T;
  2874. Steps.push_back(S);
  2875. }
  2876. void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
  2877. bool shouldCopy) {
  2878. Step s;
  2879. s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
  2880. : SK_PassByIndirectRestore);
  2881. s.Type = type;
  2882. Steps.push_back(s);
  2883. }
  2884. void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
  2885. Step S;
  2886. S.Kind = SK_ProduceObjCObject;
  2887. S.Type = T;
  2888. Steps.push_back(S);
  2889. }
  2890. void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
  2891. Step S;
  2892. S.Kind = SK_StdInitializerList;
  2893. S.Type = T;
  2894. Steps.push_back(S);
  2895. }
  2896. void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
  2897. Step S;
  2898. S.Kind = SK_OCLSamplerInit;
  2899. S.Type = T;
  2900. Steps.push_back(S);
  2901. }
  2902. void InitializationSequence::AddOCLZeroEventStep(QualType T) {
  2903. Step S;
  2904. S.Kind = SK_OCLZeroEvent;
  2905. S.Type = T;
  2906. Steps.push_back(S);
  2907. }
  2908. void InitializationSequence::RewrapReferenceInitList(QualType T,
  2909. InitListExpr *Syntactic) {
  2910. assert(Syntactic->getNumInits() == 1 &&
  2911. "Can only rewrap trivial init lists.");
  2912. Step S;
  2913. S.Kind = SK_UnwrapInitList;
  2914. S.Type = Syntactic->getInit(0)->getType();
  2915. Steps.insert(Steps.begin(), S);
  2916. S.Kind = SK_RewrapInitList;
  2917. S.Type = T;
  2918. S.WrappingSyntacticList = Syntactic;
  2919. Steps.push_back(S);
  2920. }
  2921. void InitializationSequence::SetOverloadFailure(FailureKind Failure,
  2922. OverloadingResult Result) {
  2923. setSequenceKind(FailedSequence);
  2924. this->Failure = Failure;
  2925. this->FailedOverloadResult = Result;
  2926. }
  2927. //===----------------------------------------------------------------------===//
  2928. // Attempt initialization
  2929. //===----------------------------------------------------------------------===//
  2930. /// Tries to add a zero initializer. Returns true if that worked.
  2931. static bool
  2932. maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
  2933. const InitializedEntity &Entity) {
  2934. if (Entity.getKind() != InitializedEntity::EK_Variable)
  2935. return false;
  2936. VarDecl *VD = cast<VarDecl>(Entity.getDecl());
  2937. if (VD->getInit() || VD->getLocEnd().isMacroID())
  2938. return false;
  2939. QualType VariableTy = VD->getType().getCanonicalType();
  2940. SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
  2941. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  2942. if (!Init.empty()) {
  2943. Sequence.AddZeroInitializationStep(Entity.getType());
  2944. Sequence.SetZeroInitializationFixit(Init, Loc);
  2945. return true;
  2946. }
  2947. return false;
  2948. }
  2949. static void MaybeProduceObjCObject(Sema &S,
  2950. InitializationSequence &Sequence,
  2951. const InitializedEntity &Entity) {
  2952. if (!S.getLangOpts().ObjCAutoRefCount) return;
  2953. /// When initializing a parameter, produce the value if it's marked
  2954. /// __attribute__((ns_consumed)).
  2955. if (Entity.isParameterKind()) {
  2956. if (!Entity.isParameterConsumed())
  2957. return;
  2958. assert(Entity.getType()->isObjCRetainableType() &&
  2959. "consuming an object of unretainable type?");
  2960. Sequence.AddProduceObjCObjectStep(Entity.getType());
  2961. /// When initializing a return value, if the return type is a
  2962. /// retainable type, then returns need to immediately retain the
  2963. /// object. If an autorelease is required, it will be done at the
  2964. /// last instant.
  2965. } else if (Entity.getKind() == InitializedEntity::EK_Result) {
  2966. if (!Entity.getType()->isObjCRetainableType())
  2967. return;
  2968. Sequence.AddProduceObjCObjectStep(Entity.getType());
  2969. }
  2970. }
  2971. static void TryListInitialization(Sema &S,
  2972. const InitializedEntity &Entity,
  2973. const InitializationKind &Kind,
  2974. InitListExpr *InitList,
  2975. InitializationSequence &Sequence);
  2976. /// \brief When initializing from init list via constructor, handle
  2977. /// initialization of an object of type std::initializer_list<T>.
  2978. ///
  2979. /// \return true if we have handled initialization of an object of type
  2980. /// std::initializer_list<T>, false otherwise.
  2981. static bool TryInitializerListConstruction(Sema &S,
  2982. InitListExpr *List,
  2983. QualType DestType,
  2984. InitializationSequence &Sequence) {
  2985. QualType E;
  2986. if (!S.isStdInitializerList(DestType, &E))
  2987. return false;
  2988. if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
  2989. Sequence.setIncompleteTypeFailure(E);
  2990. return true;
  2991. }
  2992. // Try initializing a temporary array from the init list.
  2993. QualType ArrayType = S.Context.getConstantArrayType(
  2994. E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  2995. List->getNumInits()),
  2996. clang::ArrayType::Normal, 0);
  2997. InitializedEntity HiddenArray =
  2998. InitializedEntity::InitializeTemporary(ArrayType);
  2999. InitializationKind Kind =
  3000. InitializationKind::CreateDirectList(List->getExprLoc());
  3001. TryListInitialization(S, HiddenArray, Kind, List, Sequence);
  3002. if (Sequence)
  3003. Sequence.AddStdInitializerListConstructionStep(DestType);
  3004. return true;
  3005. }
  3006. static OverloadingResult
  3007. ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
  3008. MultiExprArg Args,
  3009. OverloadCandidateSet &CandidateSet,
  3010. DeclContext::lookup_result Ctors,
  3011. OverloadCandidateSet::iterator &Best,
  3012. bool CopyInitializing, bool AllowExplicit,
  3013. bool OnlyListConstructors, bool IsListInit) {
  3014. CandidateSet.clear();
  3015. for (NamedDecl *D : Ctors) {
  3016. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  3017. bool SuppressUserConversions = false;
  3018. // Find the constructor (which may be a template).
  3019. CXXConstructorDecl *Constructor = nullptr;
  3020. FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
  3021. if (ConstructorTmpl)
  3022. Constructor = cast<CXXConstructorDecl>(
  3023. ConstructorTmpl->getTemplatedDecl());
  3024. else {
  3025. Constructor = cast<CXXConstructorDecl>(D);
  3026. // C++11 [over.best.ics]p4:
  3027. // ... and the constructor or user-defined conversion function is a
  3028. // candidate by
  3029. // - 13.3.1.3, when the argument is the temporary in the second step
  3030. // of a class copy-initialization, or
  3031. // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
  3032. // user-defined conversion sequences are not considered.
  3033. // FIXME: This breaks backward compatibility, e.g. PR12117. As a
  3034. // temporary fix, let's re-instate the third bullet above until
  3035. // there is a resolution in the standard, i.e.,
  3036. // - 13.3.1.7 when the initializer list has exactly one element that is
  3037. // itself an initializer list and a conversion to some class X or
  3038. // reference to (possibly cv-qualified) X is considered for the first
  3039. // parameter of a constructor of X.
  3040. if ((CopyInitializing ||
  3041. (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
  3042. Constructor->isCopyOrMoveConstructor())
  3043. SuppressUserConversions = true;
  3044. }
  3045. if (!Constructor->isInvalidDecl() &&
  3046. (AllowExplicit || !Constructor->isExplicit()) &&
  3047. (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
  3048. if (ConstructorTmpl)
  3049. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  3050. /*ExplicitArgs*/ nullptr, Args,
  3051. CandidateSet, SuppressUserConversions);
  3052. else {
  3053. // C++ [over.match.copy]p1:
  3054. // - When initializing a temporary to be bound to the first parameter
  3055. // of a constructor that takes a reference to possibly cv-qualified
  3056. // T as its first argument, called with a single argument in the
  3057. // context of direct-initialization, explicit conversion functions
  3058. // are also considered.
  3059. bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
  3060. Args.size() == 1 &&
  3061. Constructor->isCopyOrMoveConstructor();
  3062. S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
  3063. SuppressUserConversions,
  3064. /*PartialOverloading=*/false,
  3065. /*AllowExplicit=*/AllowExplicitConv);
  3066. }
  3067. }
  3068. }
  3069. // Perform overload resolution and return the result.
  3070. return CandidateSet.BestViableFunction(S, DeclLoc, Best);
  3071. }
  3072. /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
  3073. /// enumerates the constructors of the initialized entity and performs overload
  3074. /// resolution to select the best.
  3075. /// \param IsListInit Is this list-initialization?
  3076. /// \param IsInitListCopy Is this non-list-initialization resulting from a
  3077. /// list-initialization from {x} where x is the same
  3078. /// type as the entity?
  3079. static void TryConstructorInitialization(Sema &S,
  3080. const InitializedEntity &Entity,
  3081. const InitializationKind &Kind,
  3082. MultiExprArg Args, QualType DestType,
  3083. InitializationSequence &Sequence,
  3084. bool IsListInit = false,
  3085. bool IsInitListCopy = false) {
  3086. assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
  3087. "IsListInit must come with a single initializer list argument.");
  3088. // The type we're constructing needs to be complete.
  3089. if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
  3090. Sequence.setIncompleteTypeFailure(DestType);
  3091. return;
  3092. }
  3093. const RecordType *DestRecordType = DestType->getAs<RecordType>();
  3094. assert(DestRecordType && "Constructor initialization requires record type");
  3095. CXXRecordDecl *DestRecordDecl
  3096. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  3097. // Build the candidate set directly in the initialization sequence
  3098. // structure, so that it will persist if we fail.
  3099. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3100. // Determine whether we are allowed to call explicit constructors or
  3101. // explicit conversion operators.
  3102. bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
  3103. bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
  3104. // - Otherwise, if T is a class type, constructors are considered. The
  3105. // applicable constructors are enumerated, and the best one is chosen
  3106. // through overload resolution.
  3107. DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
  3108. OverloadingResult Result = OR_No_Viable_Function;
  3109. OverloadCandidateSet::iterator Best;
  3110. bool AsInitializerList = false;
  3111. // C++11 [over.match.list]p1, per DR1467:
  3112. // When objects of non-aggregate type T are list-initialized, such that
  3113. // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
  3114. // according to the rules in this section, overload resolution selects
  3115. // the constructor in two phases:
  3116. //
  3117. // - Initially, the candidate functions are the initializer-list
  3118. // constructors of the class T and the argument list consists of the
  3119. // initializer list as a single argument.
  3120. if (IsListInit) {
  3121. InitListExpr *ILE = cast<InitListExpr>(Args[0]);
  3122. AsInitializerList = true;
  3123. // If the initializer list has no elements and T has a default constructor,
  3124. // the first phase is omitted.
  3125. if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
  3126. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
  3127. CandidateSet, Ctors, Best,
  3128. CopyInitialization, AllowExplicit,
  3129. /*OnlyListConstructor=*/true,
  3130. IsListInit);
  3131. // Time to unwrap the init list.
  3132. Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
  3133. }
  3134. // C++11 [over.match.list]p1:
  3135. // - If no viable initializer-list constructor is found, overload resolution
  3136. // is performed again, where the candidate functions are all the
  3137. // constructors of the class T and the argument list consists of the
  3138. // elements of the initializer list.
  3139. if (Result == OR_No_Viable_Function) {
  3140. AsInitializerList = false;
  3141. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
  3142. CandidateSet, Ctors, Best,
  3143. CopyInitialization, AllowExplicit,
  3144. /*OnlyListConstructors=*/false,
  3145. IsListInit);
  3146. }
  3147. if (Result) {
  3148. Sequence.SetOverloadFailure(IsListInit ?
  3149. InitializationSequence::FK_ListConstructorOverloadFailed :
  3150. InitializationSequence::FK_ConstructorOverloadFailed,
  3151. Result);
  3152. return;
  3153. }
  3154. // C++11 [dcl.init]p6:
  3155. // If a program calls for the default initialization of an object
  3156. // of a const-qualified type T, T shall be a class type with a
  3157. // user-provided default constructor.
  3158. if (Kind.getKind() == InitializationKind::IK_Default &&
  3159. Entity.getType().isConstQualified() &&
  3160. !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
  3161. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  3162. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3163. return;
  3164. }
  3165. // C++11 [over.match.list]p1:
  3166. // In copy-list-initialization, if an explicit constructor is chosen, the
  3167. // initializer is ill-formed.
  3168. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  3169. if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
  3170. Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
  3171. return;
  3172. }
  3173. // Add the constructor initialization step. Any cv-qualification conversion is
  3174. // subsumed by the initialization.
  3175. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3176. Sequence.AddConstructorInitializationStep(
  3177. CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
  3178. IsListInit | IsInitListCopy, AsInitializerList);
  3179. }
  3180. static bool
  3181. ResolveOverloadedFunctionForReferenceBinding(Sema &S,
  3182. Expr *Initializer,
  3183. QualType &SourceType,
  3184. QualType &UnqualifiedSourceType,
  3185. QualType UnqualifiedTargetType,
  3186. InitializationSequence &Sequence) {
  3187. if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
  3188. S.Context.OverloadTy) {
  3189. DeclAccessPair Found;
  3190. bool HadMultipleCandidates = false;
  3191. if (FunctionDecl *Fn
  3192. = S.ResolveAddressOfOverloadedFunction(Initializer,
  3193. UnqualifiedTargetType,
  3194. false, Found,
  3195. &HadMultipleCandidates)) {
  3196. Sequence.AddAddressOverloadResolutionStep(Fn, Found,
  3197. HadMultipleCandidates);
  3198. SourceType = Fn->getType();
  3199. UnqualifiedSourceType = SourceType.getUnqualifiedType();
  3200. } else if (!UnqualifiedTargetType->isRecordType()) {
  3201. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3202. return true;
  3203. }
  3204. }
  3205. return false;
  3206. }
  3207. static void TryReferenceInitializationCore(Sema &S,
  3208. const InitializedEntity &Entity,
  3209. const InitializationKind &Kind,
  3210. Expr *Initializer,
  3211. QualType cv1T1, QualType T1,
  3212. Qualifiers T1Quals,
  3213. QualType cv2T2, QualType T2,
  3214. Qualifiers T2Quals,
  3215. InitializationSequence &Sequence);
  3216. static void TryValueInitialization(Sema &S,
  3217. const InitializedEntity &Entity,
  3218. const InitializationKind &Kind,
  3219. InitializationSequence &Sequence,
  3220. InitListExpr *InitList = nullptr);
  3221. /// \brief Attempt list initialization of a reference.
  3222. static void TryReferenceListInitialization(Sema &S,
  3223. const InitializedEntity &Entity,
  3224. const InitializationKind &Kind,
  3225. InitListExpr *InitList,
  3226. InitializationSequence &Sequence) {
  3227. // First, catch C++03 where this isn't possible.
  3228. if (!S.getLangOpts().CPlusPlus11) {
  3229. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3230. return;
  3231. }
  3232. // Can't reference initialize a compound literal.
  3233. if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
  3234. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  3235. return;
  3236. }
  3237. QualType DestType = Entity.getType();
  3238. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3239. Qualifiers T1Quals;
  3240. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  3241. // Reference initialization via an initializer list works thus:
  3242. // If the initializer list consists of a single element that is
  3243. // reference-related to the referenced type, bind directly to that element
  3244. // (possibly creating temporaries).
  3245. // Otherwise, initialize a temporary with the initializer list and
  3246. // bind to that.
  3247. if (InitList->getNumInits() == 1) {
  3248. Expr *Initializer = InitList->getInit(0);
  3249. QualType cv2T2 = Initializer->getType();
  3250. Qualifiers T2Quals;
  3251. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  3252. // If this fails, creating a temporary wouldn't work either.
  3253. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  3254. T1, Sequence))
  3255. return;
  3256. SourceLocation DeclLoc = Initializer->getLocStart();
  3257. bool dummy1, dummy2, dummy3;
  3258. Sema::ReferenceCompareResult RefRelationship
  3259. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
  3260. dummy2, dummy3);
  3261. if (RefRelationship >= Sema::Ref_Related) {
  3262. // Try to bind the reference here.
  3263. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  3264. T1Quals, cv2T2, T2, T2Quals, Sequence);
  3265. if (Sequence)
  3266. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3267. return;
  3268. }
  3269. // Update the initializer if we've resolved an overloaded function.
  3270. if (Sequence.step_begin() != Sequence.step_end())
  3271. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  3272. }
  3273. // Not reference-related. Create a temporary and bind to that.
  3274. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  3275. TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
  3276. if (Sequence) {
  3277. if (DestType->isRValueReferenceType() ||
  3278. (T1Quals.hasConst() && !T1Quals.hasVolatile()))
  3279. Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
  3280. else
  3281. Sequence.SetFailed(
  3282. InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3283. }
  3284. }
  3285. /// \brief Attempt list initialization (C++0x [dcl.init.list])
  3286. static void TryListInitialization(Sema &S,
  3287. const InitializedEntity &Entity,
  3288. const InitializationKind &Kind,
  3289. InitListExpr *InitList,
  3290. InitializationSequence &Sequence) {
  3291. QualType DestType = Entity.getType();
  3292. // C++ doesn't allow scalar initialization with more than one argument.
  3293. // But C99 complex numbers are scalars and it makes sense there.
  3294. if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
  3295. !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
  3296. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
  3297. return;
  3298. }
  3299. if (DestType->isReferenceType()) {
  3300. TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
  3301. return;
  3302. }
  3303. if (DestType->isRecordType() &&
  3304. S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
  3305. Sequence.setIncompleteTypeFailure(DestType);
  3306. return;
  3307. }
  3308. // C++11 [dcl.init.list]p3, per DR1467:
  3309. // - If T is a class type and the initializer list has a single element of
  3310. // type cv U, where U is T or a class derived from T, the object is
  3311. // initialized from that element (by copy-initialization for
  3312. // copy-list-initialization, or by direct-initialization for
  3313. // direct-list-initialization).
  3314. // - Otherwise, if T is a character array and the initializer list has a
  3315. // single element that is an appropriately-typed string literal
  3316. // (8.5.2 [dcl.init.string]), initialization is performed as described
  3317. // in that section.
  3318. // - Otherwise, if T is an aggregate, [...] (continue below).
  3319. if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
  3320. if (DestType->isRecordType()) {
  3321. QualType InitType = InitList->getInit(0)->getType();
  3322. if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
  3323. S.IsDerivedFrom(InitType, DestType)) {
  3324. Expr *InitAsExpr = InitList->getInit(0);
  3325. TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
  3326. Sequence, /*InitListSyntax*/ false,
  3327. /*IsInitListCopy*/ true);
  3328. return;
  3329. }
  3330. }
  3331. if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
  3332. Expr *SubInit[1] = {InitList->getInit(0)};
  3333. if (!isa<VariableArrayType>(DestAT) &&
  3334. IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
  3335. InitializationKind SubKind =
  3336. Kind.getKind() == InitializationKind::IK_DirectList
  3337. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3338. InitList->getLBraceLoc(),
  3339. InitList->getRBraceLoc())
  3340. : Kind;
  3341. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3342. /*TopLevelOfInitList*/ true);
  3343. // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
  3344. // the element is not an appropriately-typed string literal, in which
  3345. // case we should proceed as in C++11 (below).
  3346. if (Sequence) {
  3347. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3348. return;
  3349. }
  3350. }
  3351. }
  3352. }
  3353. // C++11 [dcl.init.list]p3:
  3354. // - If T is an aggregate, aggregate initialization is performed.
  3355. if (DestType->isRecordType() && !DestType->isAggregateType()) {
  3356. if (S.getLangOpts().CPlusPlus11) {
  3357. // - Otherwise, if the initializer list has no elements and T is a
  3358. // class type with a default constructor, the object is
  3359. // value-initialized.
  3360. if (InitList->getNumInits() == 0) {
  3361. CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
  3362. if (RD->hasDefaultConstructor()) {
  3363. TryValueInitialization(S, Entity, Kind, Sequence, InitList);
  3364. return;
  3365. }
  3366. }
  3367. // - Otherwise, if T is a specialization of std::initializer_list<E>,
  3368. // an initializer_list object constructed [...]
  3369. if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
  3370. return;
  3371. // - Otherwise, if T is a class type, constructors are considered.
  3372. Expr *InitListAsExpr = InitList;
  3373. TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
  3374. Sequence, /*InitListSyntax*/ true);
  3375. } else
  3376. Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
  3377. return;
  3378. }
  3379. if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
  3380. InitList->getNumInits() == 1 &&
  3381. InitList->getInit(0)->getType()->isRecordType()) {
  3382. // - Otherwise, if the initializer list has a single element of type E
  3383. // [...references are handled above...], the object or reference is
  3384. // initialized from that element (by copy-initialization for
  3385. // copy-list-initialization, or by direct-initialization for
  3386. // direct-list-initialization); if a narrowing conversion is required
  3387. // to convert the element to T, the program is ill-formed.
  3388. //
  3389. // Per core-24034, this is direct-initialization if we were performing
  3390. // direct-list-initialization and copy-initialization otherwise.
  3391. // We can't use InitListChecker for this, because it always performs
  3392. // copy-initialization. This only matters if we might use an 'explicit'
  3393. // conversion operator, so we only need to handle the cases where the source
  3394. // is of record type.
  3395. InitializationKind SubKind =
  3396. Kind.getKind() == InitializationKind::IK_DirectList
  3397. ? InitializationKind::CreateDirect(Kind.getLocation(),
  3398. InitList->getLBraceLoc(),
  3399. InitList->getRBraceLoc())
  3400. : Kind;
  3401. Expr *SubInit[1] = { InitList->getInit(0) };
  3402. Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
  3403. /*TopLevelOfInitList*/true);
  3404. if (Sequence)
  3405. Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
  3406. return;
  3407. }
  3408. InitListChecker CheckInitList(S, Entity, Kind, InitList, // HLSL Change - add Kind
  3409. DestType, /*VerifyOnly=*/true);
  3410. if (CheckInitList.HadError()) {
  3411. Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
  3412. return;
  3413. }
  3414. // Add the list initialization step with the built init list.
  3415. Sequence.AddListInitializationStep(DestType);
  3416. }
  3417. /// \brief Try a reference initialization that involves calling a conversion
  3418. /// function.
  3419. static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
  3420. const InitializedEntity &Entity,
  3421. const InitializationKind &Kind,
  3422. Expr *Initializer,
  3423. bool AllowRValues,
  3424. InitializationSequence &Sequence) {
  3425. QualType DestType = Entity.getType();
  3426. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3427. QualType T1 = cv1T1.getUnqualifiedType();
  3428. QualType cv2T2 = Initializer->getType();
  3429. QualType T2 = cv2T2.getUnqualifiedType();
  3430. bool DerivedToBase;
  3431. bool ObjCConversion;
  3432. bool ObjCLifetimeConversion;
  3433. assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
  3434. T1, T2, DerivedToBase,
  3435. ObjCConversion,
  3436. ObjCLifetimeConversion) &&
  3437. "Must have incompatible references when binding via conversion");
  3438. (void)DerivedToBase;
  3439. (void)ObjCConversion;
  3440. (void)ObjCLifetimeConversion;
  3441. // Build the candidate set directly in the initialization sequence
  3442. // structure, so that it will persist if we fail.
  3443. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3444. CandidateSet.clear();
  3445. // Determine whether we are allowed to call explicit constructors or
  3446. // explicit conversion operators.
  3447. bool AllowExplicit = Kind.AllowExplicit();
  3448. bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
  3449. const RecordType *T1RecordType = nullptr;
  3450. if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
  3451. !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
  3452. // The type we're converting to is a class type. Enumerate its constructors
  3453. // to see if there is a suitable conversion.
  3454. CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
  3455. for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
  3456. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  3457. // Find the constructor (which may be a template).
  3458. CXXConstructorDecl *Constructor = nullptr;
  3459. FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
  3460. if (ConstructorTmpl)
  3461. Constructor = cast<CXXConstructorDecl>(
  3462. ConstructorTmpl->getTemplatedDecl());
  3463. else
  3464. Constructor = cast<CXXConstructorDecl>(D);
  3465. if (!Constructor->isInvalidDecl() &&
  3466. Constructor->isConvertingConstructor(AllowExplicit)) {
  3467. if (ConstructorTmpl)
  3468. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  3469. /*ExplicitArgs*/ nullptr,
  3470. Initializer, CandidateSet,
  3471. /*SuppressUserConversions=*/true);
  3472. else
  3473. S.AddOverloadCandidate(Constructor, FoundDecl,
  3474. Initializer, CandidateSet,
  3475. /*SuppressUserConversions=*/true);
  3476. }
  3477. }
  3478. }
  3479. if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
  3480. return OR_No_Viable_Function;
  3481. const RecordType *T2RecordType = nullptr;
  3482. if ((T2RecordType = T2->getAs<RecordType>()) &&
  3483. !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
  3484. // The type we're converting from is a class type, enumerate its conversion
  3485. // functions.
  3486. CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
  3487. const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
  3488. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  3489. NamedDecl *D = *I;
  3490. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3491. if (isa<UsingShadowDecl>(D))
  3492. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3493. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3494. CXXConversionDecl *Conv;
  3495. if (ConvTemplate)
  3496. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3497. else
  3498. Conv = cast<CXXConversionDecl>(D);
  3499. // If the conversion function doesn't return a reference type,
  3500. // it can't be considered for this conversion unless we're allowed to
  3501. // consider rvalues.
  3502. // FIXME: Do we need to make sure that we only consider conversion
  3503. // candidates with reference-compatible results? That might be needed to
  3504. // break recursion.
  3505. if ((AllowExplicitConvs || !Conv->isExplicit()) &&
  3506. (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
  3507. if (ConvTemplate)
  3508. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
  3509. ActingDC, Initializer,
  3510. DestType, CandidateSet,
  3511. /*AllowObjCConversionOnExplicit=*/
  3512. false);
  3513. else
  3514. S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
  3515. Initializer, DestType, CandidateSet,
  3516. /*AllowObjCConversionOnExplicit=*/false);
  3517. }
  3518. }
  3519. }
  3520. if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
  3521. return OR_No_Viable_Function;
  3522. SourceLocation DeclLoc = Initializer->getLocStart();
  3523. // Perform overload resolution. If it fails, return the failed result.
  3524. OverloadCandidateSet::iterator Best;
  3525. if (OverloadingResult Result
  3526. = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
  3527. return Result;
  3528. FunctionDecl *Function = Best->Function;
  3529. // This is the overload that will be used for this initialization step if we
  3530. // use this initialization. Mark it as referenced.
  3531. Function->setReferenced();
  3532. // Compute the returned type of the conversion.
  3533. if (isa<CXXConversionDecl>(Function))
  3534. T2 = Function->getReturnType();
  3535. else
  3536. T2 = cv1T1;
  3537. // Add the user-defined conversion step.
  3538. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3539. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  3540. T2.getNonLValueExprType(S.Context),
  3541. HadMultipleCandidates);
  3542. // Determine whether we need to perform derived-to-base or
  3543. // cv-qualification adjustments.
  3544. ExprValueKind VK = VK_RValue;
  3545. if (T2->isLValueReferenceType())
  3546. VK = VK_LValue;
  3547. else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
  3548. VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
  3549. bool NewDerivedToBase = false;
  3550. bool NewObjCConversion = false;
  3551. bool NewObjCLifetimeConversion = false;
  3552. Sema::ReferenceCompareResult NewRefRelationship
  3553. = S.CompareReferenceRelationship(DeclLoc, T1,
  3554. T2.getNonLValueExprType(S.Context),
  3555. NewDerivedToBase, NewObjCConversion,
  3556. NewObjCLifetimeConversion);
  3557. if (NewRefRelationship == Sema::Ref_Incompatible) {
  3558. // If the type we've converted to is not reference-related to the
  3559. // type we're looking for, then there is another conversion step
  3560. // we need to perform to produce a temporary of the right type
  3561. // that we'll be binding to.
  3562. ImplicitConversionSequence ICS;
  3563. ICS.setStandard();
  3564. ICS.Standard = Best->FinalConversion;
  3565. T2 = ICS.Standard.getToType(2);
  3566. Sequence.AddConversionSequenceStep(ICS, T2);
  3567. } else if (NewDerivedToBase)
  3568. Sequence.AddDerivedToBaseCastStep(
  3569. S.Context.getQualifiedType(T1,
  3570. T2.getNonReferenceType().getQualifiers()),
  3571. VK);
  3572. else if (NewObjCConversion)
  3573. Sequence.AddObjCObjectConversionStep(
  3574. S.Context.getQualifiedType(T1,
  3575. T2.getNonReferenceType().getQualifiers()));
  3576. if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
  3577. Sequence.AddQualificationConversionStep(cv1T1, VK);
  3578. Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
  3579. return OR_Success;
  3580. }
  3581. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  3582. const InitializedEntity &Entity,
  3583. Expr *CurInitExpr);
  3584. /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
  3585. static void TryReferenceInitialization(Sema &S,
  3586. const InitializedEntity &Entity,
  3587. const InitializationKind &Kind,
  3588. Expr *Initializer,
  3589. InitializationSequence &Sequence) {
  3590. QualType DestType = Entity.getType();
  3591. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  3592. Qualifiers T1Quals;
  3593. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  3594. QualType cv2T2 = Initializer->getType();
  3595. Qualifiers T2Quals;
  3596. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  3597. // If the initializer is the address of an overloaded function, try
  3598. // to resolve the overloaded function. If all goes well, T2 is the
  3599. // type of the resulting function.
  3600. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  3601. T1, Sequence))
  3602. return;
  3603. // Delegate everything else to a subfunction.
  3604. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  3605. T1Quals, cv2T2, T2, T2Quals, Sequence);
  3606. }
  3607. /// Converts the target of reference initialization so that it has the
  3608. /// appropriate qualifiers and value kind.
  3609. ///
  3610. /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
  3611. /// \code
  3612. /// int x;
  3613. /// const int &r = x;
  3614. /// \endcode
  3615. ///
  3616. /// In this case the reference is binding to a bitfield lvalue, which isn't
  3617. /// valid. Perform a load to create a lifetime-extended temporary instead.
  3618. /// \code
  3619. /// const int &r = someStruct.bitfield;
  3620. /// \endcode
  3621. static ExprValueKind
  3622. convertQualifiersAndValueKindIfNecessary(Sema &S,
  3623. InitializationSequence &Sequence,
  3624. Expr *Initializer,
  3625. QualType cv1T1,
  3626. Qualifiers T1Quals,
  3627. Qualifiers T2Quals,
  3628. bool IsLValueRef) {
  3629. bool IsNonAddressableType = Initializer->refersToBitField() ||
  3630. Initializer->refersToVectorElement();
  3631. if (IsNonAddressableType) {
  3632. // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
  3633. // lvalue reference to a non-volatile const type, or the reference shall be
  3634. // an rvalue reference.
  3635. //
  3636. // If not, we can't make a temporary and bind to that. Give up and allow the
  3637. // error to be diagnosed later.
  3638. if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
  3639. assert(Initializer->isGLValue());
  3640. return Initializer->getValueKind();
  3641. }
  3642. // Force a load so we can materialize a temporary.
  3643. Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
  3644. return VK_RValue;
  3645. }
  3646. if (T1Quals != T2Quals) {
  3647. Sequence.AddQualificationConversionStep(cv1T1,
  3648. Initializer->getValueKind());
  3649. }
  3650. return Initializer->getValueKind();
  3651. }
  3652. /// \brief Reference initialization without resolving overloaded functions.
  3653. static void TryReferenceInitializationCore(Sema &S,
  3654. const InitializedEntity &Entity,
  3655. const InitializationKind &Kind,
  3656. Expr *Initializer,
  3657. QualType cv1T1, QualType T1,
  3658. Qualifiers T1Quals,
  3659. QualType cv2T2, QualType T2,
  3660. Qualifiers T2Quals,
  3661. InitializationSequence &Sequence) {
  3662. QualType DestType = Entity.getType();
  3663. SourceLocation DeclLoc = Initializer->getLocStart();
  3664. // Compute some basic properties of the types and the initializer.
  3665. bool isLValueRef = DestType->isLValueReferenceType();
  3666. bool isRValueRef = !isLValueRef;
  3667. bool DerivedToBase = false;
  3668. bool ObjCConversion = false;
  3669. bool ObjCLifetimeConversion = false;
  3670. Expr::Classification InitCategory = Initializer->Classify(S.Context);
  3671. Sema::ReferenceCompareResult RefRelationship
  3672. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
  3673. ObjCConversion, ObjCLifetimeConversion);
  3674. // C++0x [dcl.init.ref]p5:
  3675. // A reference to type "cv1 T1" is initialized by an expression of type
  3676. // "cv2 T2" as follows:
  3677. //
  3678. // - If the reference is an lvalue reference and the initializer
  3679. // expression
  3680. // Note the analogous bullet points for rvalue refs to functions. Because
  3681. // there are no function rvalues in C++, rvalue refs to functions are treated
  3682. // like lvalue refs.
  3683. OverloadingResult ConvOvlResult = OR_Success;
  3684. bool T1Function = T1->isFunctionType();
  3685. if (isLValueRef || T1Function) {
  3686. if (InitCategory.isLValue() &&
  3687. (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
  3688. (Kind.isCStyleOrFunctionalCast() &&
  3689. RefRelationship == Sema::Ref_Related))) {
  3690. // - is an lvalue (but is not a bit-field), and "cv1 T1" is
  3691. // reference-compatible with "cv2 T2," or
  3692. //
  3693. // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
  3694. // bit-field when we're determining whether the reference initialization
  3695. // can occur. However, we do pay attention to whether it is a bit-field
  3696. // to decide whether we're actually binding to a temporary created from
  3697. // the bit-field.
  3698. if (DerivedToBase)
  3699. Sequence.AddDerivedToBaseCastStep(
  3700. S.Context.getQualifiedType(T1, T2Quals),
  3701. VK_LValue);
  3702. else if (ObjCConversion)
  3703. Sequence.AddObjCObjectConversionStep(
  3704. S.Context.getQualifiedType(T1, T2Quals));
  3705. ExprValueKind ValueKind =
  3706. convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
  3707. cv1T1, T1Quals, T2Quals,
  3708. isLValueRef);
  3709. Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
  3710. return;
  3711. }
  3712. // - has a class type (i.e., T2 is a class type), where T1 is not
  3713. // reference-related to T2, and can be implicitly converted to an
  3714. // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
  3715. // with "cv3 T3" (this conversion is selected by enumerating the
  3716. // applicable conversion functions (13.3.1.6) and choosing the best
  3717. // one through overload resolution (13.3)),
  3718. // If we have an rvalue ref to function type here, the rhs must be
  3719. // an rvalue. DR1287 removed the "implicitly" here.
  3720. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
  3721. (isLValueRef || InitCategory.isRValue())) {
  3722. ConvOvlResult = TryRefInitWithConversionFunction(
  3723. S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
  3724. if (ConvOvlResult == OR_Success)
  3725. return;
  3726. if (ConvOvlResult != OR_No_Viable_Function)
  3727. Sequence.SetOverloadFailure(
  3728. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3729. ConvOvlResult);
  3730. }
  3731. }
  3732. // - Otherwise, the reference shall be an lvalue reference to a
  3733. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3734. // shall be an rvalue reference.
  3735. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
  3736. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  3737. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3738. else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  3739. Sequence.SetOverloadFailure(
  3740. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3741. ConvOvlResult);
  3742. else
  3743. Sequence.SetFailed(InitCategory.isLValue()
  3744. ? (RefRelationship == Sema::Ref_Related
  3745. ? InitializationSequence::FK_ReferenceInitDropsQualifiers
  3746. : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
  3747. : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3748. return;
  3749. }
  3750. // - If the initializer expression
  3751. // - is an xvalue, class prvalue, array prvalue, or function lvalue and
  3752. // "cv1 T1" is reference-compatible with "cv2 T2"
  3753. // Note: functions are handled below.
  3754. if (!T1Function &&
  3755. (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
  3756. (Kind.isCStyleOrFunctionalCast() &&
  3757. RefRelationship == Sema::Ref_Related)) &&
  3758. (InitCategory.isXValue() ||
  3759. (InitCategory.isPRValue() && T2->isRecordType()) ||
  3760. (InitCategory.isPRValue() && T2->isArrayType()))) {
  3761. ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
  3762. if (InitCategory.isPRValue() && T2->isRecordType()) {
  3763. // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
  3764. // compiler the freedom to perform a copy here or bind to the
  3765. // object, while C++0x requires that we bind directly to the
  3766. // object. Hence, we always bind to the object without making an
  3767. // extra copy. However, in C++03 requires that we check for the
  3768. // presence of a suitable copy constructor:
  3769. //
  3770. // The constructor that would be used to make the copy shall
  3771. // be callable whether or not the copy is actually done.
  3772. if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
  3773. Sequence.AddExtraneousCopyToTemporary(cv2T2);
  3774. else if (S.getLangOpts().CPlusPlus11)
  3775. CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
  3776. }
  3777. if (DerivedToBase)
  3778. Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
  3779. ValueKind);
  3780. else if (ObjCConversion)
  3781. Sequence.AddObjCObjectConversionStep(
  3782. S.Context.getQualifiedType(T1, T2Quals));
  3783. ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
  3784. Initializer, cv1T1,
  3785. T1Quals, T2Quals,
  3786. isLValueRef);
  3787. Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
  3788. return;
  3789. }
  3790. // - has a class type (i.e., T2 is a class type), where T1 is not
  3791. // reference-related to T2, and can be implicitly converted to an
  3792. // xvalue, class prvalue, or function lvalue of type "cv3 T3",
  3793. // where "cv1 T1" is reference-compatible with "cv3 T3",
  3794. //
  3795. // DR1287 removes the "implicitly" here.
  3796. if (T2->isRecordType()) {
  3797. if (RefRelationship == Sema::Ref_Incompatible) {
  3798. ConvOvlResult = TryRefInitWithConversionFunction(
  3799. S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
  3800. if (ConvOvlResult)
  3801. Sequence.SetOverloadFailure(
  3802. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3803. ConvOvlResult);
  3804. return;
  3805. }
  3806. if ((RefRelationship == Sema::Ref_Compatible ||
  3807. RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
  3808. isRValueRef && InitCategory.isLValue()) {
  3809. Sequence.SetFailed(
  3810. InitializationSequence::FK_RValueReferenceBindingToLValue);
  3811. return;
  3812. }
  3813. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  3814. return;
  3815. }
  3816. // - Otherwise, a temporary of type "cv1 T1" is created and initialized
  3817. // from the initializer expression using the rules for a non-reference
  3818. // copy-initialization (8.5). The reference is then bound to the
  3819. // temporary. [...]
  3820. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  3821. // FIXME: Why do we use an implicit conversion here rather than trying
  3822. // copy-initialization?
  3823. ImplicitConversionSequence ICS
  3824. = S.TryImplicitConversion(Initializer, TempEntity.getType(),
  3825. /*SuppressUserConversions=*/false,
  3826. /*AllowExplicit=*/false,
  3827. /*FIXME:InOverloadResolution=*/false,
  3828. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  3829. /*AllowObjCWritebackConversion=*/false);
  3830. if (ICS.isBad()) {
  3831. // FIXME: Use the conversion function set stored in ICS to turn
  3832. // this into an overloading ambiguity diagnostic. However, we need
  3833. // to keep that set as an OverloadCandidateSet rather than as some
  3834. // other kind of set.
  3835. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  3836. Sequence.SetOverloadFailure(
  3837. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3838. ConvOvlResult);
  3839. else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  3840. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3841. else
  3842. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
  3843. return;
  3844. } else {
  3845. Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
  3846. }
  3847. // [...] If T1 is reference-related to T2, cv1 must be the
  3848. // same cv-qualification as, or greater cv-qualification
  3849. // than, cv2; otherwise, the program is ill-formed.
  3850. unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
  3851. unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
  3852. if (RefRelationship == Sema::Ref_Related &&
  3853. (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
  3854. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  3855. return;
  3856. }
  3857. // [...] If T1 is reference-related to T2 and the reference is an rvalue
  3858. // reference, the initializer expression shall not be an lvalue.
  3859. if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
  3860. InitCategory.isLValue()) {
  3861. Sequence.SetFailed(
  3862. InitializationSequence::FK_RValueReferenceBindingToLValue);
  3863. return;
  3864. }
  3865. Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
  3866. return;
  3867. }
  3868. /// \brief Attempt character array initialization from a string literal
  3869. /// (C++ [dcl.init.string], C99 6.7.8).
  3870. static void TryStringLiteralInitialization(Sema &S,
  3871. const InitializedEntity &Entity,
  3872. const InitializationKind &Kind,
  3873. Expr *Initializer,
  3874. InitializationSequence &Sequence) {
  3875. Sequence.AddStringInitStep(Entity.getType());
  3876. }
  3877. /// \brief Attempt value initialization (C++ [dcl.init]p7).
  3878. static void TryValueInitialization(Sema &S,
  3879. const InitializedEntity &Entity,
  3880. const InitializationKind &Kind,
  3881. InitializationSequence &Sequence,
  3882. InitListExpr *InitList) {
  3883. assert((!InitList || InitList->getNumInits() == 0) &&
  3884. "Shouldn't use value-init for non-empty init lists");
  3885. // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
  3886. //
  3887. // To value-initialize an object of type T means:
  3888. QualType T = Entity.getType();
  3889. // -- if T is an array type, then each element is value-initialized;
  3890. T = S.Context.getBaseElementType(T);
  3891. if (const RecordType *RT = T->getAs<RecordType>()) {
  3892. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  3893. bool NeedZeroInitialization = true;
  3894. if (!S.getLangOpts().CPlusPlus11) {
  3895. // C++98:
  3896. // -- if T is a class type (clause 9) with a user-declared constructor
  3897. // (12.1), then the default constructor for T is called (and the
  3898. // initialization is ill-formed if T has no accessible default
  3899. // constructor);
  3900. if (ClassDecl->hasUserDeclaredConstructor())
  3901. NeedZeroInitialization = false;
  3902. } else {
  3903. // C++11:
  3904. // -- if T is a class type (clause 9) with either no default constructor
  3905. // (12.1 [class.ctor]) or a default constructor that is user-provided
  3906. // or deleted, then the object is default-initialized;
  3907. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
  3908. if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
  3909. NeedZeroInitialization = false;
  3910. }
  3911. // -- if T is a (possibly cv-qualified) non-union class type without a
  3912. // user-provided or deleted default constructor, then the object is
  3913. // zero-initialized and, if T has a non-trivial default constructor,
  3914. // default-initialized;
  3915. // The 'non-union' here was removed by DR1502. The 'non-trivial default
  3916. // constructor' part was removed by DR1507.
  3917. if (NeedZeroInitialization)
  3918. Sequence.AddZeroInitializationStep(Entity.getType());
  3919. // C++03:
  3920. // -- if T is a non-union class type without a user-declared constructor,
  3921. // then every non-static data member and base class component of T is
  3922. // value-initialized;
  3923. // [...] A program that calls for [...] value-initialization of an
  3924. // entity of reference type is ill-formed.
  3925. //
  3926. // C++11 doesn't need this handling, because value-initialization does not
  3927. // occur recursively there, and the implicit default constructor is
  3928. // defined as deleted in the problematic cases.
  3929. if (!S.getLangOpts().CPlusPlus11 &&
  3930. ClassDecl->hasUninitializedReferenceMember()) {
  3931. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
  3932. return;
  3933. }
  3934. // If this is list-value-initialization, pass the empty init list on when
  3935. // building the constructor call. This affects the semantics of a few
  3936. // things (such as whether an explicit default constructor can be called).
  3937. Expr *InitListAsExpr = InitList;
  3938. MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
  3939. bool InitListSyntax = InitList;
  3940. return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
  3941. InitListSyntax);
  3942. }
  3943. }
  3944. Sequence.AddZeroInitializationStep(Entity.getType());
  3945. }
  3946. /// \brief Attempt default initialization (C++ [dcl.init]p6).
  3947. static void TryDefaultInitialization(Sema &S,
  3948. const InitializedEntity &Entity,
  3949. const InitializationKind &Kind,
  3950. InitializationSequence &Sequence) {
  3951. assert(Kind.getKind() == InitializationKind::IK_Default);
  3952. // C++ [dcl.init]p6:
  3953. // To default-initialize an object of type T means:
  3954. // - if T is an array type, each element is default-initialized;
  3955. QualType DestType = S.Context.getBaseElementType(Entity.getType());
  3956. // - if T is a (possibly cv-qualified) class type (Clause 9), the default
  3957. // constructor for T is called (and the initialization is ill-formed if
  3958. // T has no accessible default constructor);
  3959. if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
  3960. TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
  3961. return;
  3962. }
  3963. // - otherwise, no initialization is performed.
  3964. // If a program calls for the default initialization of an object of
  3965. // a const-qualified type T, T shall be a class type with a user-provided
  3966. // default constructor.
  3967. if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
  3968. if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
  3969. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3970. return;
  3971. }
  3972. // If the destination type has a lifetime property, zero-initialize it.
  3973. if (DestType.getQualifiers().hasObjCLifetime()) {
  3974. Sequence.AddZeroInitializationStep(Entity.getType());
  3975. return;
  3976. }
  3977. }
  3978. /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
  3979. /// which enumerates all conversion functions and performs overload resolution
  3980. /// to select the best.
  3981. static void TryUserDefinedConversion(Sema &S,
  3982. QualType DestType,
  3983. const InitializationKind &Kind,
  3984. Expr *Initializer,
  3985. InitializationSequence &Sequence,
  3986. bool TopLevelOfInitList) {
  3987. assert(!DestType->isReferenceType() && "References are handled elsewhere");
  3988. QualType SourceType = Initializer->getType();
  3989. assert((DestType->isRecordType() || SourceType->isRecordType()) &&
  3990. "Must have a class type to perform a user-defined conversion");
  3991. // Build the candidate set directly in the initialization sequence
  3992. // structure, so that it will persist if we fail.
  3993. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3994. CandidateSet.clear();
  3995. // Determine whether we are allowed to call explicit constructors or
  3996. // explicit conversion operators.
  3997. bool AllowExplicit = Kind.AllowExplicit();
  3998. if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
  3999. // The type we're converting to is a class type. Enumerate its constructors
  4000. // to see if there is a suitable conversion.
  4001. CXXRecordDecl *DestRecordDecl
  4002. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  4003. // Try to complete the type we're converting to.
  4004. if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
  4005. DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
  4006. // The container holding the constructors can under certain conditions
  4007. // be changed while iterating. To be safe we copy the lookup results
  4008. // to a new container.
  4009. SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
  4010. for (SmallVectorImpl<NamedDecl *>::iterator
  4011. Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
  4012. Con != ConEnd; ++Con) {
  4013. NamedDecl *D = *Con;
  4014. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  4015. // Find the constructor (which may be a template).
  4016. CXXConstructorDecl *Constructor = nullptr;
  4017. FunctionTemplateDecl *ConstructorTmpl
  4018. = dyn_cast<FunctionTemplateDecl>(D);
  4019. if (ConstructorTmpl)
  4020. Constructor = cast<CXXConstructorDecl>(
  4021. ConstructorTmpl->getTemplatedDecl());
  4022. else
  4023. Constructor = cast<CXXConstructorDecl>(D);
  4024. if (!Constructor->isInvalidDecl() &&
  4025. Constructor->isConvertingConstructor(AllowExplicit)) {
  4026. if (ConstructorTmpl)
  4027. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  4028. /*ExplicitArgs*/ nullptr,
  4029. Initializer, CandidateSet,
  4030. /*SuppressUserConversions=*/true);
  4031. else
  4032. S.AddOverloadCandidate(Constructor, FoundDecl,
  4033. Initializer, CandidateSet,
  4034. /*SuppressUserConversions=*/true);
  4035. }
  4036. }
  4037. }
  4038. }
  4039. SourceLocation DeclLoc = Initializer->getLocStart();
  4040. if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
  4041. // The type we're converting from is a class type, enumerate its conversion
  4042. // functions.
  4043. // We can only enumerate the conversion functions for a complete type; if
  4044. // the type isn't complete, simply skip this step.
  4045. if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
  4046. CXXRecordDecl *SourceRecordDecl
  4047. = cast<CXXRecordDecl>(SourceRecordType->getDecl());
  4048. const auto &Conversions =
  4049. SourceRecordDecl->getVisibleConversionFunctions();
  4050. for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
  4051. NamedDecl *D = *I;
  4052. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  4053. if (isa<UsingShadowDecl>(D))
  4054. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  4055. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  4056. CXXConversionDecl *Conv;
  4057. if (ConvTemplate)
  4058. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  4059. else
  4060. Conv = cast<CXXConversionDecl>(D);
  4061. if (AllowExplicit || !Conv->isExplicit()) {
  4062. if (ConvTemplate)
  4063. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
  4064. ActingDC, Initializer, DestType,
  4065. CandidateSet, AllowExplicit);
  4066. else
  4067. S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
  4068. Initializer, DestType, CandidateSet,
  4069. AllowExplicit);
  4070. }
  4071. }
  4072. }
  4073. }
  4074. // Perform overload resolution. If it fails, return the failed result.
  4075. OverloadCandidateSet::iterator Best;
  4076. if (OverloadingResult Result
  4077. = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  4078. Sequence.SetOverloadFailure(
  4079. InitializationSequence::FK_UserConversionOverloadFailed,
  4080. Result);
  4081. return;
  4082. }
  4083. FunctionDecl *Function = Best->Function;
  4084. Function->setReferenced();
  4085. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4086. if (isa<CXXConstructorDecl>(Function)) {
  4087. // Add the user-defined conversion step. Any cv-qualification conversion is
  4088. // subsumed by the initialization. Per DR5, the created temporary is of the
  4089. // cv-unqualified type of the destination.
  4090. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  4091. DestType.getUnqualifiedType(),
  4092. HadMultipleCandidates);
  4093. return;
  4094. }
  4095. // Add the user-defined conversion step that calls the conversion function.
  4096. QualType ConvType = Function->getCallResultType();
  4097. if (ConvType->getAs<RecordType>()) {
  4098. // If we're converting to a class type, there may be an copy of
  4099. // the resulting temporary object (possible to create an object of
  4100. // a base class type). That copy is not a separate conversion, so
  4101. // we just make a note of the actual destination type (possibly a
  4102. // base class of the type returned by the conversion function) and
  4103. // let the user-defined conversion step handle the conversion.
  4104. Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
  4105. HadMultipleCandidates);
  4106. return;
  4107. }
  4108. Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
  4109. HadMultipleCandidates);
  4110. // If the conversion following the call to the conversion function
  4111. // is interesting, add it as a separate step.
  4112. if (Best->FinalConversion.First || Best->FinalConversion.Second ||
  4113. Best->FinalConversion.Third) {
  4114. ImplicitConversionSequence ICS;
  4115. ICS.setStandard();
  4116. ICS.Standard = Best->FinalConversion;
  4117. Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  4118. }
  4119. }
  4120. /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
  4121. /// a function with a pointer return type contains a 'return false;' statement.
  4122. /// In C++11, 'false' is not a null pointer, so this breaks the build of any
  4123. /// code using that header.
  4124. ///
  4125. /// Work around this by treating 'return false;' as zero-initializing the result
  4126. /// if it's used in a pointer-returning function in a system header.
  4127. static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
  4128. const InitializedEntity &Entity,
  4129. const Expr *Init) {
  4130. return S.getLangOpts().CPlusPlus11 &&
  4131. Entity.getKind() == InitializedEntity::EK_Result &&
  4132. Entity.getType()->isPointerType() &&
  4133. isa<CXXBoolLiteralExpr>(Init) &&
  4134. !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
  4135. S.getSourceManager().isInSystemHeader(Init->getExprLoc());
  4136. }
  4137. /// The non-zero enum values here are indexes into diagnostic alternatives.
  4138. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
  4139. /// Determines whether this expression is an acceptable ICR source.
  4140. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
  4141. bool isAddressOf, bool &isWeakAccess) {
  4142. // Skip parens.
  4143. e = e->IgnoreParens();
  4144. // Skip address-of nodes.
  4145. if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  4146. if (op->getOpcode() == UO_AddrOf)
  4147. return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
  4148. isWeakAccess);
  4149. // Skip certain casts.
  4150. } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
  4151. switch (ce->getCastKind()) {
  4152. case CK_Dependent:
  4153. case CK_BitCast:
  4154. case CK_LValueBitCast:
  4155. case CK_NoOp:
  4156. return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
  4157. case CK_ArrayToPointerDecay:
  4158. return IIK_nonscalar;
  4159. case CK_NullToPointer:
  4160. return IIK_okay;
  4161. default:
  4162. break;
  4163. }
  4164. // If we have a declaration reference, it had better be a local variable.
  4165. } else if (isa<DeclRefExpr>(e)) {
  4166. // set isWeakAccess to true, to mean that there will be an implicit
  4167. // load which requires a cleanup.
  4168. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  4169. isWeakAccess = true;
  4170. if (!isAddressOf) return IIK_nonlocal;
  4171. VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
  4172. if (!var) return IIK_nonlocal;
  4173. return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
  4174. // If we have a conditional operator, check both sides.
  4175. } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
  4176. if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
  4177. isWeakAccess))
  4178. return iik;
  4179. return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
  4180. // These are never scalar.
  4181. } else if (isa<ArraySubscriptExpr>(e)) {
  4182. return IIK_nonscalar;
  4183. // Otherwise, it needs to be a null pointer constant.
  4184. } else {
  4185. return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
  4186. ? IIK_okay : IIK_nonlocal);
  4187. }
  4188. return IIK_nonlocal;
  4189. }
  4190. /// Check whether the given expression is a valid operand for an
  4191. /// indirect copy/restore.
  4192. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
  4193. assert(src->isRValue());
  4194. bool isWeakAccess = false;
  4195. InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
  4196. // If isWeakAccess to true, there will be an implicit
  4197. // load which requires a cleanup.
  4198. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
  4199. S.ExprNeedsCleanups = true;
  4200. if (iik == IIK_okay) return;
  4201. S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
  4202. << ((unsigned) iik - 1) // shift index into diagnostic explanations
  4203. << src->getSourceRange();
  4204. }
  4205. /// \brief Determine whether we have compatible array types for the
  4206. /// purposes of GNU by-copy array initialization.
  4207. static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
  4208. const ArrayType *Source) {
  4209. // If the source and destination array types are equivalent, we're
  4210. // done.
  4211. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
  4212. return true;
  4213. // Make sure that the element types are the same.
  4214. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
  4215. return false;
  4216. // The only mismatch we allow is when the destination is an
  4217. // incomplete array type and the source is a constant array type.
  4218. return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
  4219. }
  4220. static bool tryObjCWritebackConversion(Sema &S,
  4221. InitializationSequence &Sequence,
  4222. const InitializedEntity &Entity,
  4223. Expr *Initializer) {
  4224. bool ArrayDecay = false;
  4225. QualType ArgType = Initializer->getType();
  4226. QualType ArgPointee;
  4227. if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
  4228. ArrayDecay = true;
  4229. ArgPointee = ArgArrayType->getElementType();
  4230. ArgType = S.Context.getPointerType(ArgPointee);
  4231. }
  4232. // Handle write-back conversion.
  4233. QualType ConvertedArgType;
  4234. if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
  4235. ConvertedArgType))
  4236. return false;
  4237. // We should copy unless we're passing to an argument explicitly
  4238. // marked 'out'.
  4239. bool ShouldCopy = true;
  4240. if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  4241. ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  4242. // Do we need an lvalue conversion?
  4243. if (ArrayDecay || Initializer->isGLValue()) {
  4244. ImplicitConversionSequence ICS;
  4245. ICS.setStandard();
  4246. ICS.Standard.setAsIdentityConversion();
  4247. QualType ResultType;
  4248. if (ArrayDecay) {
  4249. ICS.Standard.First = ICK_Array_To_Pointer;
  4250. ResultType = S.Context.getPointerType(ArgPointee);
  4251. } else {
  4252. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  4253. ResultType = Initializer->getType().getNonLValueExprType(S.Context);
  4254. }
  4255. Sequence.AddConversionSequenceStep(ICS, ResultType);
  4256. }
  4257. Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  4258. return true;
  4259. }
  4260. static bool TryOCLSamplerInitialization(Sema &S,
  4261. InitializationSequence &Sequence,
  4262. QualType DestType,
  4263. Expr *Initializer) {
  4264. if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
  4265. !Initializer->isIntegerConstantExpr(S.getASTContext()))
  4266. return false;
  4267. Sequence.AddOCLSamplerInitStep(DestType);
  4268. return true;
  4269. }
  4270. //
  4271. // OpenCL 1.2 spec, s6.12.10
  4272. //
  4273. // The event argument can also be used to associate the
  4274. // async_work_group_copy with a previous async copy allowing
  4275. // an event to be shared by multiple async copies; otherwise
  4276. // event should be zero.
  4277. //
  4278. static bool TryOCLZeroEventInitialization(Sema &S,
  4279. InitializationSequence &Sequence,
  4280. QualType DestType,
  4281. Expr *Initializer) {
  4282. if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
  4283. !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
  4284. (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
  4285. return false;
  4286. Sequence.AddOCLZeroEventStep(DestType);
  4287. return true;
  4288. }
  4289. InitializationSequence::InitializationSequence(Sema &S,
  4290. const InitializedEntity &Entity,
  4291. const InitializationKind &Kind,
  4292. MultiExprArg Args,
  4293. bool TopLevelOfInitList)
  4294. : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
  4295. InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
  4296. }
  4297. void InitializationSequence::InitializeFrom(Sema &S,
  4298. const InitializedEntity &Entity,
  4299. const InitializationKind &Kind,
  4300. MultiExprArg Args,
  4301. bool TopLevelOfInitList) {
  4302. ASTContext &Context = S.Context;
  4303. // Eliminate non-overload placeholder types in the arguments. We
  4304. // need to do this before checking whether types are dependent
  4305. // because lowering a pseudo-object expression might well give us
  4306. // something of dependent type.
  4307. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  4308. if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
  4309. // FIXME: should we be doing this here?
  4310. ExprResult result = S.CheckPlaceholderExpr(Args[I]);
  4311. if (result.isInvalid()) {
  4312. SetFailed(FK_PlaceholderType);
  4313. return;
  4314. }
  4315. Args[I] = result.get();
  4316. }
  4317. // C++0x [dcl.init]p16:
  4318. // The semantics of initializers are as follows. The destination type is
  4319. // the type of the object or reference being initialized and the source
  4320. // type is the type of the initializer expression. The source type is not
  4321. // defined when the initializer is a braced-init-list or when it is a
  4322. // parenthesized list of expressions.
  4323. QualType DestType = Entity.getType();
  4324. if (DestType->isDependentType() ||
  4325. Expr::hasAnyTypeDependentArguments(Args)) {
  4326. SequenceKind = DependentSequence;
  4327. return;
  4328. }
  4329. // Almost everything is a normal sequence.
  4330. setSequenceKind(NormalSequence);
  4331. QualType SourceType;
  4332. Expr *Initializer = nullptr;
  4333. if (Args.size() == 1) {
  4334. Initializer = Args[0];
  4335. if (S.getLangOpts().ObjC1) {
  4336. if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
  4337. DestType, Initializer->getType(),
  4338. Initializer) ||
  4339. S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
  4340. Args[0] = Initializer;
  4341. }
  4342. if (!isa<InitListExpr>(Initializer))
  4343. SourceType = Initializer->getType();
  4344. }
  4345. // HLSL Change Starts
  4346. if (S.getLangOpts().HLSL) {
  4347. hlsl::InitializeInitSequenceForHLSL(&S, Entity, Kind, Args, TopLevelOfInitList, this);
  4348. return;
  4349. }
  4350. // HLSL Change Ends
  4351. // - If the initializer is a (non-parenthesized) braced-init-list, the
  4352. // object is list-initialized (8.5.4).
  4353. if (Kind.getKind() != InitializationKind::IK_Direct) {
  4354. if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
  4355. TryListInitialization(S, Entity, Kind, InitList, *this);
  4356. return;
  4357. }
  4358. }
  4359. // - If the destination type is a reference type, see 8.5.3.
  4360. if (DestType->isReferenceType()) {
  4361. // C++0x [dcl.init.ref]p1:
  4362. // A variable declared to be a T& or T&&, that is, "reference to type T"
  4363. // (8.3.2), shall be initialized by an object, or function, of type T or
  4364. // by an object that can be converted into a T.
  4365. // (Therefore, multiple arguments are not permitted.)
  4366. if (Args.size() != 1)
  4367. SetFailed(FK_TooManyInitsForReference);
  4368. else
  4369. TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
  4370. return;
  4371. }
  4372. // - If the initializer is (), the object is value-initialized.
  4373. if (Kind.getKind() == InitializationKind::IK_Value ||
  4374. (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
  4375. TryValueInitialization(S, Entity, Kind, *this);
  4376. return;
  4377. }
  4378. // Handle default initialization.
  4379. if (Kind.getKind() == InitializationKind::IK_Default) {
  4380. TryDefaultInitialization(S, Entity, Kind, *this);
  4381. return;
  4382. }
  4383. // - If the destination type is an array of characters, an array of
  4384. // char16_t, an array of char32_t, or an array of wchar_t, and the
  4385. // initializer is a string literal, see 8.5.2.
  4386. // - Otherwise, if the destination type is an array, the program is
  4387. // ill-formed.
  4388. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
  4389. if (Initializer && isa<VariableArrayType>(DestAT)) {
  4390. SetFailed(FK_VariableLengthArrayHasInitializer);
  4391. return;
  4392. }
  4393. if (Initializer) {
  4394. switch (IsStringInit(Initializer, DestAT, Context)) {
  4395. case SIF_None:
  4396. TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
  4397. return;
  4398. case SIF_NarrowStringIntoWideChar:
  4399. SetFailed(FK_NarrowStringIntoWideCharArray);
  4400. return;
  4401. case SIF_WideStringIntoChar:
  4402. SetFailed(FK_WideStringIntoCharArray);
  4403. return;
  4404. case SIF_IncompatWideStringIntoWideChar:
  4405. SetFailed(FK_IncompatWideStringIntoWideChar);
  4406. return;
  4407. case SIF_Other:
  4408. break;
  4409. }
  4410. }
  4411. // Note: as an GNU C extension, we allow initialization of an
  4412. // array from a compound literal that creates an array of the same
  4413. // type, so long as the initializer has no side effects.
  4414. if (!S.getLangOpts().CPlusPlus && Initializer &&
  4415. isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
  4416. Initializer->getType()->isArrayType()) {
  4417. const ArrayType *SourceAT
  4418. = Context.getAsArrayType(Initializer->getType());
  4419. if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
  4420. SetFailed(FK_ArrayTypeMismatch);
  4421. else if (Initializer->HasSideEffects(S.Context))
  4422. SetFailed(FK_NonConstantArrayInit);
  4423. else {
  4424. AddArrayInitStep(DestType);
  4425. }
  4426. }
  4427. // Note: as a GNU C++ extension, we allow list-initialization of a
  4428. // class member of array type from a parenthesized initializer list.
  4429. else if (S.getLangOpts().CPlusPlus &&
  4430. Entity.getKind() == InitializedEntity::EK_Member &&
  4431. Initializer && isa<InitListExpr>(Initializer)) {
  4432. TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
  4433. *this);
  4434. AddParenthesizedArrayInitStep(DestType);
  4435. } else if (DestAT->getElementType()->isCharType())
  4436. SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
  4437. else if (IsWideCharCompatible(DestAT->getElementType(), Context))
  4438. SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
  4439. else
  4440. SetFailed(FK_ArrayNeedsInitList);
  4441. return;
  4442. }
  4443. // Determine whether we should consider writeback conversions for
  4444. // Objective-C ARC.
  4445. bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
  4446. Entity.isParameterKind();
  4447. // We're at the end of the line for C: it's either a write-back conversion
  4448. // or it's a C assignment. There's no need to check anything else.
  4449. if (!S.getLangOpts().CPlusPlus) {
  4450. // If allowed, check whether this is an Objective-C writeback conversion.
  4451. if (allowObjCWritebackConversion &&
  4452. tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
  4453. return;
  4454. }
  4455. if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
  4456. return;
  4457. if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
  4458. return;
  4459. // Handle initialization in C
  4460. AddCAssignmentStep(DestType);
  4461. MaybeProduceObjCObject(S, *this, Entity);
  4462. return;
  4463. }
  4464. assert(S.getLangOpts().CPlusPlus);
  4465. // - If the destination type is a (possibly cv-qualified) class type:
  4466. if (DestType->isRecordType()) {
  4467. // - If the initialization is direct-initialization, or if it is
  4468. // copy-initialization where the cv-unqualified version of the
  4469. // source type is the same class as, or a derived class of, the
  4470. // class of the destination, constructors are considered. [...]
  4471. if (Kind.getKind() == InitializationKind::IK_Direct ||
  4472. (Kind.getKind() == InitializationKind::IK_Copy &&
  4473. (Context.hasSameUnqualifiedType(SourceType, DestType) ||
  4474. S.IsDerivedFrom(SourceType, DestType))))
  4475. TryConstructorInitialization(S, Entity, Kind, Args,
  4476. DestType, *this);
  4477. // - Otherwise (i.e., for the remaining copy-initialization cases),
  4478. // user-defined conversion sequences that can convert from the source
  4479. // type to the destination type or (when a conversion function is
  4480. // used) to a derived class thereof are enumerated as described in
  4481. // 13.3.1.4, and the best one is chosen through overload resolution
  4482. // (13.3).
  4483. else
  4484. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  4485. TopLevelOfInitList);
  4486. return;
  4487. }
  4488. if (Args.size() > 1) {
  4489. SetFailed(FK_TooManyInitsForScalar);
  4490. return;
  4491. }
  4492. assert(Args.size() == 1 && "Zero-argument case handled above");
  4493. // HLSL Change Starts
  4494. assert(Initializer != nullptr && "otherwise prior code changed and Args.size() == 1 no longer reads from first argument");
  4495. _Analysis_assume_(Initializer != nullptr);
  4496. // HLSL Change Ends
  4497. // - Otherwise, if the source type is a (possibly cv-qualified) class
  4498. // type, conversion functions are considered.
  4499. if (!SourceType.isNull() && SourceType->isRecordType()) {
  4500. // For a conversion to _Atomic(T) from either T or a class type derived
  4501. // from T, initialize the T object then convert to _Atomic type.
  4502. bool NeedAtomicConversion = false;
  4503. if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
  4504. if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
  4505. S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
  4506. DestType = Atomic->getValueType();
  4507. NeedAtomicConversion = true;
  4508. }
  4509. }
  4510. TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
  4511. TopLevelOfInitList);
  4512. MaybeProduceObjCObject(S, *this, Entity);
  4513. if (!Failed() && NeedAtomicConversion)
  4514. AddAtomicConversionStep(Entity.getType());
  4515. return;
  4516. }
  4517. // - Otherwise, the initial value of the object being initialized is the
  4518. // (possibly converted) value of the initializer expression. Standard
  4519. // conversions (Clause 4) will be used, if necessary, to convert the
  4520. // initializer expression to the cv-unqualified version of the
  4521. // destination type; no user-defined conversions are considered.
  4522. ImplicitConversionSequence ICS
  4523. = S.TryImplicitConversion(Initializer, DestType,
  4524. /*SuppressUserConversions*/true,
  4525. /*AllowExplicitConversions*/ false,
  4526. /*InOverloadResolution*/ false,
  4527. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  4528. allowObjCWritebackConversion);
  4529. if (ICS.isStandard() &&
  4530. ICS.Standard.Second == ICK_Writeback_Conversion) {
  4531. // Objective-C ARC writeback conversion.
  4532. // We should copy unless we're passing to an argument explicitly
  4533. // marked 'out'.
  4534. bool ShouldCopy = true;
  4535. if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  4536. ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  4537. // If there was an lvalue adjustment, add it as a separate conversion.
  4538. if (ICS.Standard.First == ICK_Array_To_Pointer ||
  4539. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  4540. ImplicitConversionSequence LvalueICS;
  4541. LvalueICS.setStandard();
  4542. LvalueICS.Standard.setAsIdentityConversion();
  4543. LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
  4544. LvalueICS.Standard.First = ICS.Standard.First;
  4545. AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
  4546. }
  4547. AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
  4548. } else if (ICS.isBad()) {
  4549. DeclAccessPair dap;
  4550. if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
  4551. AddZeroInitializationStep(Entity.getType());
  4552. } else if (Initializer->getType() == Context.OverloadTy &&
  4553. !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
  4554. false, dap))
  4555. SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  4556. else
  4557. SetFailed(InitializationSequence::FK_ConversionFailed);
  4558. } else {
  4559. AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
  4560. MaybeProduceObjCObject(S, *this, Entity);
  4561. }
  4562. }
  4563. InitializationSequence::~InitializationSequence() {
  4564. for (auto &S : Steps)
  4565. S.Destroy();
  4566. }
  4567. //===----------------------------------------------------------------------===//
  4568. // Perform initialization
  4569. //===----------------------------------------------------------------------===//
  4570. static Sema::AssignmentAction
  4571. getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
  4572. switch(Entity.getKind()) {
  4573. case InitializedEntity::EK_Variable:
  4574. case InitializedEntity::EK_New:
  4575. case InitializedEntity::EK_Exception:
  4576. case InitializedEntity::EK_Base:
  4577. case InitializedEntity::EK_Delegating:
  4578. return Sema::AA_Initializing;
  4579. case InitializedEntity::EK_Parameter:
  4580. if (Entity.getDecl() &&
  4581. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  4582. return Sema::AA_Sending;
  4583. return Sema::AA_Passing;
  4584. case InitializedEntity::EK_Parameter_CF_Audited:
  4585. if (Entity.getDecl() &&
  4586. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  4587. return Sema::AA_Sending;
  4588. return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
  4589. case InitializedEntity::EK_Result:
  4590. return Sema::AA_Returning;
  4591. case InitializedEntity::EK_Temporary:
  4592. case InitializedEntity::EK_RelatedResult:
  4593. // FIXME: Can we tell apart casting vs. converting?
  4594. return Sema::AA_Casting;
  4595. case InitializedEntity::EK_Member:
  4596. case InitializedEntity::EK_ArrayElement:
  4597. case InitializedEntity::EK_VectorElement:
  4598. case InitializedEntity::EK_ComplexElement:
  4599. case InitializedEntity::EK_BlockElement:
  4600. case InitializedEntity::EK_LambdaCapture:
  4601. case InitializedEntity::EK_CompoundLiteralInit:
  4602. return Sema::AA_Initializing;
  4603. }
  4604. llvm_unreachable("Invalid EntityKind!");
  4605. }
  4606. /// \brief Whether we should bind a created object as a temporary when
  4607. /// initializing the given entity.
  4608. static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
  4609. switch (Entity.getKind()) {
  4610. case InitializedEntity::EK_ArrayElement:
  4611. case InitializedEntity::EK_Member:
  4612. case InitializedEntity::EK_Result:
  4613. case InitializedEntity::EK_New:
  4614. case InitializedEntity::EK_Variable:
  4615. case InitializedEntity::EK_Base:
  4616. case InitializedEntity::EK_Delegating:
  4617. case InitializedEntity::EK_VectorElement:
  4618. case InitializedEntity::EK_ComplexElement:
  4619. case InitializedEntity::EK_Exception:
  4620. case InitializedEntity::EK_BlockElement:
  4621. case InitializedEntity::EK_LambdaCapture:
  4622. case InitializedEntity::EK_CompoundLiteralInit:
  4623. return false;
  4624. case InitializedEntity::EK_Parameter:
  4625. case InitializedEntity::EK_Parameter_CF_Audited:
  4626. case InitializedEntity::EK_Temporary:
  4627. case InitializedEntity::EK_RelatedResult:
  4628. return true;
  4629. }
  4630. llvm_unreachable("missed an InitializedEntity kind?");
  4631. }
  4632. /// \brief Whether the given entity, when initialized with an object
  4633. /// created for that initialization, requires destruction.
  4634. static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
  4635. switch (Entity.getKind()) {
  4636. case InitializedEntity::EK_Result:
  4637. case InitializedEntity::EK_New:
  4638. case InitializedEntity::EK_Base:
  4639. case InitializedEntity::EK_Delegating:
  4640. case InitializedEntity::EK_VectorElement:
  4641. case InitializedEntity::EK_ComplexElement:
  4642. case InitializedEntity::EK_BlockElement:
  4643. case InitializedEntity::EK_LambdaCapture:
  4644. return false;
  4645. case InitializedEntity::EK_Member:
  4646. case InitializedEntity::EK_Variable:
  4647. case InitializedEntity::EK_Parameter:
  4648. case InitializedEntity::EK_Parameter_CF_Audited:
  4649. case InitializedEntity::EK_Temporary:
  4650. case InitializedEntity::EK_ArrayElement:
  4651. case InitializedEntity::EK_Exception:
  4652. case InitializedEntity::EK_CompoundLiteralInit:
  4653. case InitializedEntity::EK_RelatedResult:
  4654. return true;
  4655. }
  4656. llvm_unreachable("missed an InitializedEntity kind?");
  4657. }
  4658. /// \brief Look for copy and move constructors and constructor templates, for
  4659. /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
  4660. static void LookupCopyAndMoveConstructors(Sema &S,
  4661. OverloadCandidateSet &CandidateSet,
  4662. CXXRecordDecl *Class,
  4663. Expr *CurInitExpr) {
  4664. DeclContext::lookup_result R = S.LookupConstructors(Class);
  4665. // The container holding the constructors can under certain conditions
  4666. // be changed while iterating (e.g. because of deserialization).
  4667. // To be safe we copy the lookup results to a new container.
  4668. SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
  4669. for (SmallVectorImpl<NamedDecl *>::iterator
  4670. CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
  4671. NamedDecl *D = *CI;
  4672. CXXConstructorDecl *Constructor = nullptr;
  4673. if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
  4674. // Handle copy/moveconstructors, only.
  4675. if (!Constructor || Constructor->isInvalidDecl() ||
  4676. !Constructor->isCopyOrMoveConstructor() ||
  4677. !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
  4678. continue;
  4679. DeclAccessPair FoundDecl
  4680. = DeclAccessPair::make(Constructor, Constructor->getAccess());
  4681. S.AddOverloadCandidate(Constructor, FoundDecl,
  4682. CurInitExpr, CandidateSet);
  4683. continue;
  4684. }
  4685. // Handle constructor templates.
  4686. FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
  4687. if (ConstructorTmpl->isInvalidDecl())
  4688. continue;
  4689. Constructor = cast<CXXConstructorDecl>(
  4690. ConstructorTmpl->getTemplatedDecl());
  4691. if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
  4692. continue;
  4693. // FIXME: Do we need to limit this to copy-constructor-like
  4694. // candidates?
  4695. DeclAccessPair FoundDecl
  4696. = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
  4697. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
  4698. CurInitExpr, CandidateSet, true);
  4699. }
  4700. }
  4701. /// \brief Get the location at which initialization diagnostics should appear.
  4702. static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
  4703. Expr *Initializer) {
  4704. switch (Entity.getKind()) {
  4705. case InitializedEntity::EK_Result:
  4706. return Entity.getReturnLoc();
  4707. case InitializedEntity::EK_Exception:
  4708. return Entity.getThrowLoc();
  4709. case InitializedEntity::EK_Variable:
  4710. return Entity.getDecl()->getLocation();
  4711. case InitializedEntity::EK_LambdaCapture:
  4712. return Entity.getCaptureLoc();
  4713. case InitializedEntity::EK_ArrayElement:
  4714. case InitializedEntity::EK_Member:
  4715. case InitializedEntity::EK_Parameter:
  4716. case InitializedEntity::EK_Parameter_CF_Audited:
  4717. case InitializedEntity::EK_Temporary:
  4718. case InitializedEntity::EK_New:
  4719. case InitializedEntity::EK_Base:
  4720. case InitializedEntity::EK_Delegating:
  4721. case InitializedEntity::EK_VectorElement:
  4722. case InitializedEntity::EK_ComplexElement:
  4723. case InitializedEntity::EK_BlockElement:
  4724. case InitializedEntity::EK_CompoundLiteralInit:
  4725. case InitializedEntity::EK_RelatedResult:
  4726. return Initializer->getLocStart();
  4727. }
  4728. llvm_unreachable("missed an InitializedEntity kind?");
  4729. }
  4730. /// \brief Make a (potentially elidable) temporary copy of the object
  4731. /// provided by the given initializer by calling the appropriate copy
  4732. /// constructor.
  4733. ///
  4734. /// \param S The Sema object used for type-checking.
  4735. ///
  4736. /// \param T The type of the temporary object, which must either be
  4737. /// the type of the initializer expression or a superclass thereof.
  4738. ///
  4739. /// \param Entity The entity being initialized.
  4740. ///
  4741. /// \param CurInit The initializer expression.
  4742. ///
  4743. /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
  4744. /// is permitted in C++03 (but not C++0x) when binding a reference to
  4745. /// an rvalue.
  4746. ///
  4747. /// \returns An expression that copies the initializer expression into
  4748. /// a temporary object, or an error expression if a copy could not be
  4749. /// created.
  4750. static ExprResult CopyObject(Sema &S,
  4751. QualType T,
  4752. const InitializedEntity &Entity,
  4753. ExprResult CurInit,
  4754. bool IsExtraneousCopy) {
  4755. if (CurInit.isInvalid())
  4756. return CurInit;
  4757. // Determine which class type we're copying to.
  4758. Expr *CurInitExpr = (Expr *)CurInit.get();
  4759. CXXRecordDecl *Class = nullptr;
  4760. if (const RecordType *Record = T->getAs<RecordType>())
  4761. Class = cast<CXXRecordDecl>(Record->getDecl());
  4762. if (!Class)
  4763. return CurInit;
  4764. // C++0x [class.copy]p32:
  4765. // When certain criteria are met, an implementation is allowed to
  4766. // omit the copy/move construction of a class object, even if the
  4767. // copy/move constructor and/or destructor for the object have
  4768. // side effects. [...]
  4769. // - when a temporary class object that has not been bound to a
  4770. // reference (12.2) would be copied/moved to a class object
  4771. // with the same cv-unqualified type, the copy/move operation
  4772. // can be omitted by constructing the temporary object
  4773. // directly into the target of the omitted copy/move
  4774. //
  4775. // Note that the other three bullets are handled elsewhere. Copy
  4776. // elision for return statements and throw expressions are handled as part
  4777. // of constructor initialization, while copy elision for exception handlers
  4778. // is handled by the run-time.
  4779. bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
  4780. SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
  4781. // Make sure that the type we are copying is complete.
  4782. if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
  4783. return CurInit;
  4784. // Perform overload resolution using the class's copy/move constructors.
  4785. // Only consider constructors and constructor templates. Per
  4786. // C++0x [dcl.init]p16, second bullet to class types, this initialization
  4787. // is direct-initialization.
  4788. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  4789. LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
  4790. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  4791. OverloadCandidateSet::iterator Best;
  4792. switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
  4793. case OR_Success:
  4794. break;
  4795. case OR_No_Viable_Function:
  4796. S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
  4797. ? diag::ext_rvalue_to_reference_temp_copy_no_viable
  4798. : diag::err_temp_copy_no_viable)
  4799. << (int)Entity.getKind() << CurInitExpr->getType()
  4800. << CurInitExpr->getSourceRange();
  4801. CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
  4802. if (!IsExtraneousCopy || S.isSFINAEContext())
  4803. return ExprError();
  4804. return CurInit;
  4805. case OR_Ambiguous:
  4806. S.Diag(Loc, diag::err_temp_copy_ambiguous)
  4807. << (int)Entity.getKind() << CurInitExpr->getType()
  4808. << CurInitExpr->getSourceRange();
  4809. CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
  4810. return ExprError();
  4811. case OR_Deleted:
  4812. S.Diag(Loc, diag::err_temp_copy_deleted)
  4813. << (int)Entity.getKind() << CurInitExpr->getType()
  4814. << CurInitExpr->getSourceRange();
  4815. S.NoteDeletedFunction(Best->Function);
  4816. return ExprError();
  4817. }
  4818. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  4819. SmallVector<Expr*, 8> ConstructorArgs;
  4820. CurInit.get(); // Ownership transferred into MultiExprArg, below.
  4821. S.CheckConstructorAccess(Loc, Constructor, Entity,
  4822. Best->FoundDecl.getAccess(), IsExtraneousCopy);
  4823. if (IsExtraneousCopy) {
  4824. // If this is a totally extraneous copy for C++03 reference
  4825. // binding purposes, just return the original initialization
  4826. // expression. We don't generate an (elided) copy operation here
  4827. // because doing so would require us to pass down a flag to avoid
  4828. // infinite recursion, where each step adds another extraneous,
  4829. // elidable copy.
  4830. // Instantiate the default arguments of any extra parameters in
  4831. // the selected copy constructor, as if we were going to create a
  4832. // proper call to the copy constructor.
  4833. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
  4834. ParmVarDecl *Parm = Constructor->getParamDecl(I);
  4835. if (S.RequireCompleteType(Loc, Parm->getType(),
  4836. diag::err_call_incomplete_argument))
  4837. break;
  4838. // Build the default argument expression; we don't actually care
  4839. // if this succeeds or not, because this routine will complain
  4840. // if there was a problem.
  4841. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
  4842. }
  4843. return CurInitExpr;
  4844. }
  4845. // Determine the arguments required to actually perform the
  4846. // constructor call (we might have derived-to-base conversions, or
  4847. // the copy constructor may have default arguments).
  4848. if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
  4849. return ExprError();
  4850. // Actually perform the constructor call.
  4851. CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
  4852. ConstructorArgs,
  4853. HadMultipleCandidates,
  4854. /*ListInit*/ false,
  4855. /*StdInitListInit*/ false,
  4856. /*ZeroInit*/ false,
  4857. CXXConstructExpr::CK_Complete,
  4858. SourceRange());
  4859. // If we're supposed to bind temporaries, do so.
  4860. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
  4861. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  4862. return CurInit;
  4863. }
  4864. /// \brief Check whether elidable copy construction for binding a reference to
  4865. /// a temporary would have succeeded if we were building in C++98 mode, for
  4866. /// -Wc++98-compat.
  4867. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  4868. const InitializedEntity &Entity,
  4869. Expr *CurInitExpr) {
  4870. assert(S.getLangOpts().CPlusPlus11);
  4871. const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
  4872. if (!Record)
  4873. return;
  4874. SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
  4875. if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
  4876. return;
  4877. // Find constructors which would have been considered.
  4878. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  4879. LookupCopyAndMoveConstructors(
  4880. S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
  4881. // Perform overload resolution.
  4882. OverloadCandidateSet::iterator Best;
  4883. OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
  4884. PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
  4885. << OR << (int)Entity.getKind() << CurInitExpr->getType()
  4886. << CurInitExpr->getSourceRange();
  4887. switch (OR) {
  4888. case OR_Success:
  4889. S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
  4890. Entity, Best->FoundDecl.getAccess(), Diag);
  4891. // FIXME: Check default arguments as far as that's possible.
  4892. break;
  4893. case OR_No_Viable_Function:
  4894. S.Diag(Loc, Diag);
  4895. CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
  4896. break;
  4897. case OR_Ambiguous:
  4898. S.Diag(Loc, Diag);
  4899. CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
  4900. break;
  4901. case OR_Deleted:
  4902. S.Diag(Loc, Diag);
  4903. S.NoteDeletedFunction(Best->Function);
  4904. break;
  4905. }
  4906. }
  4907. void InitializationSequence::PrintInitLocationNote(Sema &S,
  4908. const InitializedEntity &Entity) {
  4909. if (Entity.isParameterKind() && Entity.getDecl()) {
  4910. if (Entity.getDecl()->getLocation().isInvalid())
  4911. return;
  4912. if (Entity.getDecl()->getDeclName())
  4913. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
  4914. << Entity.getDecl()->getDeclName();
  4915. else
  4916. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
  4917. }
  4918. else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
  4919. Entity.getMethodDecl())
  4920. S.Diag(Entity.getMethodDecl()->getLocation(),
  4921. diag::note_method_return_type_change)
  4922. << Entity.getMethodDecl()->getDeclName();
  4923. }
  4924. static bool isReferenceBinding(const InitializationSequence::Step &s) {
  4925. return s.Kind == InitializationSequence::SK_BindReference ||
  4926. s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
  4927. }
  4928. /// Returns true if the parameters describe a constructor initialization of
  4929. /// an explicit temporary object, e.g. "Point(x, y)".
  4930. static bool isExplicitTemporary(const InitializedEntity &Entity,
  4931. const InitializationKind &Kind,
  4932. unsigned NumArgs) {
  4933. switch (Entity.getKind()) {
  4934. case InitializedEntity::EK_Temporary:
  4935. case InitializedEntity::EK_CompoundLiteralInit:
  4936. case InitializedEntity::EK_RelatedResult:
  4937. break;
  4938. default:
  4939. return false;
  4940. }
  4941. switch (Kind.getKind()) {
  4942. case InitializationKind::IK_DirectList:
  4943. return true;
  4944. // FIXME: Hack to work around cast weirdness.
  4945. case InitializationKind::IK_Direct:
  4946. case InitializationKind::IK_Value:
  4947. return NumArgs != 1;
  4948. default:
  4949. return false;
  4950. }
  4951. }
  4952. static ExprResult
  4953. PerformConstructorInitialization(Sema &S,
  4954. const InitializedEntity &Entity,
  4955. const InitializationKind &Kind,
  4956. MultiExprArg Args,
  4957. const InitializationSequence::Step& Step,
  4958. bool &ConstructorInitRequiresZeroInit,
  4959. bool IsListInitialization,
  4960. bool IsStdInitListInitialization,
  4961. SourceLocation LBraceLoc,
  4962. SourceLocation RBraceLoc) {
  4963. unsigned NumArgs = Args.size();
  4964. CXXConstructorDecl *Constructor
  4965. = cast<CXXConstructorDecl>(Step.Function.Function);
  4966. bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
  4967. // Build a call to the selected constructor.
  4968. SmallVector<Expr*, 8> ConstructorArgs;
  4969. SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
  4970. ? Kind.getEqualLoc()
  4971. : Kind.getLocation();
  4972. if (Kind.getKind() == InitializationKind::IK_Default) {
  4973. // Force even a trivial, implicit default constructor to be
  4974. // semantically checked. We do this explicitly because we don't build
  4975. // the definition for completely trivial constructors.
  4976. assert(Constructor->getParent() && "No parent class for constructor.");
  4977. if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  4978. Constructor->isTrivial() && !Constructor->isUsed(false))
  4979. S.DefineImplicitDefaultConstructor(Loc, Constructor);
  4980. }
  4981. ExprResult CurInit((Expr *)nullptr);
  4982. // C++ [over.match.copy]p1:
  4983. // - When initializing a temporary to be bound to the first parameter
  4984. // of a constructor that takes a reference to possibly cv-qualified
  4985. // T as its first argument, called with a single argument in the
  4986. // context of direct-initialization, explicit conversion functions
  4987. // are also considered.
  4988. bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
  4989. Args.size() == 1 &&
  4990. Constructor->isCopyOrMoveConstructor();
  4991. // Determine the arguments required to actually perform the constructor
  4992. // call.
  4993. if (S.CompleteConstructorCall(Constructor, Args,
  4994. Loc, ConstructorArgs,
  4995. AllowExplicitConv,
  4996. IsListInitialization))
  4997. return ExprError();
  4998. if (isExplicitTemporary(Entity, Kind, NumArgs)) {
  4999. // An explicitly-constructed temporary, e.g., X(1, 2).
  5000. S.MarkFunctionReferenced(Loc, Constructor);
  5001. if (S.DiagnoseUseOfDecl(Constructor, Loc))
  5002. return ExprError();
  5003. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  5004. if (!TSInfo)
  5005. TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
  5006. SourceRange ParenOrBraceRange =
  5007. (Kind.getKind() == InitializationKind::IK_DirectList)
  5008. ? SourceRange(LBraceLoc, RBraceLoc)
  5009. : Kind.getParenRange();
  5010. CurInit = new (S.Context) CXXTemporaryObjectExpr(
  5011. S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
  5012. HadMultipleCandidates, IsListInitialization,
  5013. IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
  5014. } else {
  5015. CXXConstructExpr::ConstructionKind ConstructKind =
  5016. CXXConstructExpr::CK_Complete;
  5017. if (Entity.getKind() == InitializedEntity::EK_Base) {
  5018. ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
  5019. CXXConstructExpr::CK_VirtualBase :
  5020. CXXConstructExpr::CK_NonVirtualBase;
  5021. } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
  5022. ConstructKind = CXXConstructExpr::CK_Delegating;
  5023. }
  5024. // Only get the parenthesis or brace range if it is a list initialization or
  5025. // direct construction.
  5026. SourceRange ParenOrBraceRange;
  5027. if (IsListInitialization)
  5028. ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
  5029. else if (Kind.getKind() == InitializationKind::IK_Direct)
  5030. ParenOrBraceRange = Kind.getParenRange();
  5031. // If the entity allows NRVO, mark the construction as elidable
  5032. // unconditionally.
  5033. if (Entity.allowsNRVO())
  5034. CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
  5035. Constructor, /*Elidable=*/true,
  5036. ConstructorArgs,
  5037. HadMultipleCandidates,
  5038. IsListInitialization,
  5039. IsStdInitListInitialization,
  5040. ConstructorInitRequiresZeroInit,
  5041. ConstructKind,
  5042. ParenOrBraceRange);
  5043. else
  5044. CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
  5045. Constructor,
  5046. ConstructorArgs,
  5047. HadMultipleCandidates,
  5048. IsListInitialization,
  5049. IsStdInitListInitialization,
  5050. ConstructorInitRequiresZeroInit,
  5051. ConstructKind,
  5052. ParenOrBraceRange);
  5053. }
  5054. if (CurInit.isInvalid())
  5055. return ExprError();
  5056. // Only check access if all of that succeeded.
  5057. S.CheckConstructorAccess(Loc, Constructor, Entity,
  5058. Step.Function.FoundDecl.getAccess());
  5059. if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
  5060. return ExprError();
  5061. if (shouldBindAsTemporary(Entity))
  5062. CurInit = S.MaybeBindToTemporary(CurInit.get());
  5063. return CurInit;
  5064. }
  5065. /// Determine whether the specified InitializedEntity definitely has a lifetime
  5066. /// longer than the current full-expression. Conservatively returns false if
  5067. /// it's unclear.
  5068. static bool
  5069. InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
  5070. const InitializedEntity *Top = &Entity;
  5071. while (Top->getParent())
  5072. Top = Top->getParent();
  5073. switch (Top->getKind()) {
  5074. case InitializedEntity::EK_Variable:
  5075. case InitializedEntity::EK_Result:
  5076. case InitializedEntity::EK_Exception:
  5077. case InitializedEntity::EK_Member:
  5078. case InitializedEntity::EK_New:
  5079. case InitializedEntity::EK_Base:
  5080. case InitializedEntity::EK_Delegating:
  5081. return true;
  5082. case InitializedEntity::EK_ArrayElement:
  5083. case InitializedEntity::EK_VectorElement:
  5084. case InitializedEntity::EK_BlockElement:
  5085. case InitializedEntity::EK_ComplexElement:
  5086. // Could not determine what the full initialization is. Assume it might not
  5087. // outlive the full-expression.
  5088. return false;
  5089. case InitializedEntity::EK_Parameter:
  5090. case InitializedEntity::EK_Parameter_CF_Audited:
  5091. case InitializedEntity::EK_Temporary:
  5092. case InitializedEntity::EK_LambdaCapture:
  5093. case InitializedEntity::EK_CompoundLiteralInit:
  5094. case InitializedEntity::EK_RelatedResult:
  5095. // The entity being initialized might not outlive the full-expression.
  5096. return false;
  5097. }
  5098. llvm_unreachable("unknown entity kind");
  5099. }
  5100. /// Determine the declaration which an initialized entity ultimately refers to,
  5101. /// for the purpose of lifetime-extending a temporary bound to a reference in
  5102. /// the initialization of \p Entity.
  5103. static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
  5104. const InitializedEntity *Entity,
  5105. const InitializedEntity *FallbackDecl = nullptr) {
  5106. // C++11 [class.temporary]p5:
  5107. switch (Entity->getKind()) {
  5108. case InitializedEntity::EK_Variable:
  5109. // The temporary [...] persists for the lifetime of the reference
  5110. return Entity;
  5111. case InitializedEntity::EK_Member:
  5112. // For subobjects, we look at the complete object.
  5113. if (Entity->getParent())
  5114. return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
  5115. Entity);
  5116. // except:
  5117. // -- A temporary bound to a reference member in a constructor's
  5118. // ctor-initializer persists until the constructor exits.
  5119. return Entity;
  5120. case InitializedEntity::EK_Parameter:
  5121. case InitializedEntity::EK_Parameter_CF_Audited:
  5122. // -- A temporary bound to a reference parameter in a function call
  5123. // persists until the completion of the full-expression containing
  5124. // the call.
  5125. case InitializedEntity::EK_Result:
  5126. // -- The lifetime of a temporary bound to the returned value in a
  5127. // function return statement is not extended; the temporary is
  5128. // destroyed at the end of the full-expression in the return statement.
  5129. case InitializedEntity::EK_New:
  5130. // -- A temporary bound to a reference in a new-initializer persists
  5131. // until the completion of the full-expression containing the
  5132. // new-initializer.
  5133. return nullptr;
  5134. case InitializedEntity::EK_Temporary:
  5135. case InitializedEntity::EK_CompoundLiteralInit:
  5136. case InitializedEntity::EK_RelatedResult:
  5137. // We don't yet know the storage duration of the surrounding temporary.
  5138. // Assume it's got full-expression duration for now, it will patch up our
  5139. // storage duration if that's not correct.
  5140. return nullptr;
  5141. case InitializedEntity::EK_ArrayElement:
  5142. // For subobjects, we look at the complete object.
  5143. return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
  5144. FallbackDecl);
  5145. case InitializedEntity::EK_Base:
  5146. case InitializedEntity::EK_Delegating:
  5147. // We can reach this case for aggregate initialization in a constructor:
  5148. // struct A { int &&r; };
  5149. // struct B : A { B() : A{0} {} };
  5150. // In this case, use the innermost field decl as the context.
  5151. return FallbackDecl;
  5152. case InitializedEntity::EK_BlockElement:
  5153. case InitializedEntity::EK_LambdaCapture:
  5154. case InitializedEntity::EK_Exception:
  5155. case InitializedEntity::EK_VectorElement:
  5156. case InitializedEntity::EK_ComplexElement:
  5157. return nullptr;
  5158. }
  5159. llvm_unreachable("unknown entity kind");
  5160. }
  5161. static void performLifetimeExtension(Expr *Init,
  5162. const InitializedEntity *ExtendingEntity);
  5163. /// Update a glvalue expression that is used as the initializer of a reference
  5164. /// to note that its lifetime is extended.
  5165. /// \return \c true if any temporary had its lifetime extended.
  5166. static bool
  5167. performReferenceExtension(Expr *Init,
  5168. const InitializedEntity *ExtendingEntity) {
  5169. // Walk past any constructs which we can lifetime-extend across.
  5170. Expr *Old;
  5171. do {
  5172. Old = Init;
  5173. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  5174. if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
  5175. // This is just redundant braces around an initializer. Step over it.
  5176. Init = ILE->getInit(0);
  5177. }
  5178. }
  5179. // Step over any subobject adjustments; we may have a materialized
  5180. // temporary inside them.
  5181. SmallVector<const Expr *, 2> CommaLHSs;
  5182. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5183. Init = const_cast<Expr *>(
  5184. Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
  5185. // Per current approach for DR1376, look through casts to reference type
  5186. // when performing lifetime extension.
  5187. if (CastExpr *CE = dyn_cast<CastExpr>(Init))
  5188. if (CE->getSubExpr()->isGLValue())
  5189. Init = CE->getSubExpr();
  5190. // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
  5191. // It's unclear if binding a reference to that xvalue extends the array
  5192. // temporary.
  5193. } while (Init != Old);
  5194. if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
  5195. // Update the storage duration of the materialized temporary.
  5196. // FIXME: Rebuild the expression instead of mutating it.
  5197. ME->setExtendingDecl(ExtendingEntity->getDecl(),
  5198. ExtendingEntity->allocateManglingNumber());
  5199. performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
  5200. return true;
  5201. }
  5202. return false;
  5203. }
  5204. /// Update a prvalue expression that is going to be materialized as a
  5205. /// lifetime-extended temporary.
  5206. static void performLifetimeExtension(Expr *Init,
  5207. const InitializedEntity *ExtendingEntity) {
  5208. // Dig out the expression which constructs the extended temporary.
  5209. SmallVector<const Expr *, 2> CommaLHSs;
  5210. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5211. Init = const_cast<Expr *>(
  5212. Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
  5213. if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
  5214. Init = BTE->getSubExpr();
  5215. if (CXXStdInitializerListExpr *ILE =
  5216. dyn_cast<CXXStdInitializerListExpr>(Init)) {
  5217. performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
  5218. return;
  5219. }
  5220. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
  5221. if (ILE->getType()->isArrayType()) {
  5222. for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
  5223. performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
  5224. return;
  5225. }
  5226. if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
  5227. assert(RD->isAggregate() && "aggregate init on non-aggregate");
  5228. // If we lifetime-extend a braced initializer which is initializing an
  5229. // aggregate, and that aggregate contains reference members which are
  5230. // bound to temporaries, those temporaries are also lifetime-extended.
  5231. if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
  5232. ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
  5233. performReferenceExtension(ILE->getInit(0), ExtendingEntity);
  5234. else {
  5235. unsigned Index = 0;
  5236. for (const auto *I : RD->fields()) {
  5237. if (Index >= ILE->getNumInits())
  5238. break;
  5239. if (I->isUnnamedBitfield())
  5240. continue;
  5241. Expr *SubInit = ILE->getInit(Index);
  5242. if (I->getType()->isReferenceType())
  5243. performReferenceExtension(SubInit, ExtendingEntity);
  5244. else if (isa<InitListExpr>(SubInit) ||
  5245. isa<CXXStdInitializerListExpr>(SubInit))
  5246. // This may be either aggregate-initialization of a member or
  5247. // initialization of a std::initializer_list object. Either way,
  5248. // we should recursively lifetime-extend that initializer.
  5249. performLifetimeExtension(SubInit, ExtendingEntity);
  5250. ++Index;
  5251. }
  5252. }
  5253. }
  5254. }
  5255. }
  5256. static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
  5257. const Expr *Init, bool IsInitializerList,
  5258. const ValueDecl *ExtendingDecl) {
  5259. // Warn if a field lifetime-extends a temporary.
  5260. if (isa<FieldDecl>(ExtendingDecl)) {
  5261. if (IsInitializerList) {
  5262. S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
  5263. << /*at end of constructor*/true;
  5264. return;
  5265. }
  5266. bool IsSubobjectMember = false;
  5267. for (const InitializedEntity *Ent = Entity.getParent(); Ent;
  5268. Ent = Ent->getParent()) {
  5269. if (Ent->getKind() != InitializedEntity::EK_Base) {
  5270. IsSubobjectMember = true;
  5271. break;
  5272. }
  5273. }
  5274. S.Diag(Init->getExprLoc(),
  5275. diag::warn_bind_ref_member_to_temporary)
  5276. << ExtendingDecl << Init->getSourceRange()
  5277. << IsSubobjectMember << IsInitializerList;
  5278. if (IsSubobjectMember)
  5279. S.Diag(ExtendingDecl->getLocation(),
  5280. diag::note_ref_subobject_of_member_declared_here);
  5281. else
  5282. S.Diag(ExtendingDecl->getLocation(),
  5283. diag::note_ref_or_ptr_member_declared_here)
  5284. << /*is pointer*/false;
  5285. }
  5286. }
  5287. static void DiagnoseNarrowingInInitList(Sema &S,
  5288. const ImplicitConversionSequence &ICS,
  5289. QualType PreNarrowingType,
  5290. QualType EntityType,
  5291. const Expr *PostInit);
  5292. /// Provide warnings when std::move is used on construction.
  5293. static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
  5294. bool IsReturnStmt) {
  5295. if (!InitExpr)
  5296. return;
  5297. if (!S.ActiveTemplateInstantiations.empty())
  5298. return;
  5299. QualType DestType = InitExpr->getType();
  5300. if (!DestType->isRecordType())
  5301. return;
  5302. unsigned DiagID = 0;
  5303. if (IsReturnStmt) {
  5304. const CXXConstructExpr *CCE =
  5305. dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
  5306. if (!CCE || CCE->getNumArgs() != 1)
  5307. return;
  5308. if (!CCE->getConstructor()->isCopyOrMoveConstructor())
  5309. return;
  5310. InitExpr = CCE->getArg(0)->IgnoreImpCasts();
  5311. }
  5312. // Find the std::move call and get the argument.
  5313. const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
  5314. if (!CE || CE->getNumArgs() != 1)
  5315. return;
  5316. const FunctionDecl *MoveFunction = CE->getDirectCallee();
  5317. if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
  5318. !MoveFunction->getIdentifier() ||
  5319. !MoveFunction->getIdentifier()->isStr("move"))
  5320. return;
  5321. const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
  5322. if (IsReturnStmt) {
  5323. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
  5324. if (!DRE || DRE->refersToEnclosingVariableOrCapture())
  5325. return;
  5326. const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
  5327. if (!VD || !VD->hasLocalStorage())
  5328. return;
  5329. QualType SourceType = VD->getType();
  5330. if (!SourceType->isRecordType())
  5331. return;
  5332. if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
  5333. return;
  5334. }
  5335. // If we're returning a function parameter, copy elision
  5336. // is not possible.
  5337. if (isa<ParmVarDecl>(VD))
  5338. DiagID = diag::warn_redundant_move_on_return;
  5339. else
  5340. DiagID = diag::warn_pessimizing_move_on_return;
  5341. } else {
  5342. DiagID = diag::warn_pessimizing_move_on_initialization;
  5343. const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
  5344. if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
  5345. return;
  5346. }
  5347. S.Diag(CE->getLocStart(), DiagID);
  5348. // Get all the locations for a fix-it. Don't emit the fix-it if any location
  5349. // is within a macro.
  5350. SourceLocation CallBegin = CE->getCallee()->getLocStart();
  5351. if (CallBegin.isMacroID())
  5352. return;
  5353. SourceLocation RParen = CE->getRParenLoc();
  5354. if (RParen.isMacroID())
  5355. return;
  5356. SourceLocation LParen;
  5357. SourceLocation ArgLoc = Arg->getLocStart();
  5358. // Special testing for the argument location. Since the fix-it needs the
  5359. // location right before the argument, the argument location can be in a
  5360. // macro only if it is at the beginning of the macro.
  5361. while (ArgLoc.isMacroID() &&
  5362. S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
  5363. ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
  5364. }
  5365. if (LParen.isMacroID())
  5366. return;
  5367. LParen = ArgLoc.getLocWithOffset(-1);
  5368. S.Diag(CE->getLocStart(), diag::note_remove_move)
  5369. << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
  5370. << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
  5371. }
  5372. ExprResult
  5373. InitializationSequence::Perform(Sema &S,
  5374. const InitializedEntity &Entity,
  5375. const InitializationKind &Kind,
  5376. MultiExprArg Args,
  5377. QualType *ResultType) {
  5378. if (Failed()) {
  5379. Diagnose(S, Entity, Kind, Args);
  5380. return ExprError();
  5381. }
  5382. if (!ZeroInitializationFixit.empty()) {
  5383. unsigned DiagID = diag::err_default_init_const;
  5384. if (Decl *D = Entity.getDecl())
  5385. if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
  5386. DiagID = diag::ext_default_init_const;
  5387. // The initialization would have succeeded with this fixit. Since the fixit
  5388. // is on the error, we need to build a valid AST in this case, so this isn't
  5389. // handled in the Failed() branch above.
  5390. QualType DestType = Entity.getType();
  5391. S.Diag(Kind.getLocation(), DiagID)
  5392. << DestType << (bool)DestType->getAs<RecordType>()
  5393. << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
  5394. ZeroInitializationFixit);
  5395. }
  5396. if (getKind() == DependentSequence) {
  5397. // If the declaration is a non-dependent, incomplete array type
  5398. // that has an initializer, then its type will be completed once
  5399. // the initializer is instantiated.
  5400. if (ResultType && !Entity.getType()->isDependentType() &&
  5401. Args.size() == 1) {
  5402. QualType DeclType = Entity.getType();
  5403. if (const IncompleteArrayType *ArrayT
  5404. = S.Context.getAsIncompleteArrayType(DeclType)) {
  5405. // FIXME: We don't currently have the ability to accurately
  5406. // compute the length of an initializer list without
  5407. // performing full type-checking of the initializer list
  5408. // (since we have to determine where braces are implicitly
  5409. // introduced and such). So, we fall back to making the array
  5410. // type a dependently-sized array type with no specified
  5411. // bound.
  5412. if (isa<InitListExpr>((Expr *)Args[0])) {
  5413. SourceRange Brackets;
  5414. // Scavange the location of the brackets from the entity, if we can.
  5415. if (DeclaratorDecl *DD = Entity.getDecl()) {
  5416. if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
  5417. TypeLoc TL = TInfo->getTypeLoc();
  5418. if (IncompleteArrayTypeLoc ArrayLoc =
  5419. TL.getAs<IncompleteArrayTypeLoc>())
  5420. Brackets = ArrayLoc.getBracketsRange();
  5421. }
  5422. }
  5423. *ResultType
  5424. = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
  5425. /*NumElts=*/nullptr,
  5426. ArrayT->getSizeModifier(),
  5427. ArrayT->getIndexTypeCVRQualifiers(),
  5428. Brackets);
  5429. }
  5430. }
  5431. }
  5432. if (Kind.getKind() == InitializationKind::IK_Direct &&
  5433. !Kind.isExplicitCast()) {
  5434. // Rebuild the ParenListExpr.
  5435. SourceRange ParenRange = Kind.getParenRange();
  5436. return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
  5437. Args);
  5438. }
  5439. assert(Kind.getKind() == InitializationKind::IK_Copy ||
  5440. Kind.isExplicitCast() ||
  5441. Kind.getKind() == InitializationKind::IK_DirectList);
  5442. return ExprResult(Args[0]);
  5443. }
  5444. // No steps means no initialization.
  5445. if (Steps.empty())
  5446. return ExprResult((Expr *)nullptr);
  5447. if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
  5448. Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
  5449. !Entity.isParameterKind()) {
  5450. // Produce a C++98 compatibility warning if we are initializing a reference
  5451. // from an initializer list. For parameters, we produce a better warning
  5452. // elsewhere.
  5453. Expr *Init = Args[0];
  5454. S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
  5455. << Init->getSourceRange();
  5456. }
  5457. // Diagnose cases where we initialize a pointer to an array temporary, and the
  5458. // pointer obviously outlives the temporary.
  5459. if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
  5460. Entity.getType()->isPointerType() &&
  5461. InitializedEntityOutlivesFullExpression(Entity)) {
  5462. Expr *Init = Args[0];
  5463. Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
  5464. if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
  5465. S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
  5466. << Init->getSourceRange();
  5467. }
  5468. QualType DestType = Entity.getType().getNonReferenceType();
  5469. // FIXME: Ugly hack around the fact that Entity.getType() is not
  5470. // the same as Entity.getDecl()->getType() in cases involving type merging,
  5471. // and we want latter when it makes sense.
  5472. if (ResultType)
  5473. *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
  5474. Entity.getType();
  5475. ExprResult CurInit((Expr *)nullptr);
  5476. // For initialization steps that start with a single initializer,
  5477. // grab the only argument out the Args and place it into the "current"
  5478. // initializer.
  5479. switch (Steps.front().Kind) {
  5480. // HLSL Change Starts
  5481. case SK_ListInitialization: {
  5482. // In vector constructor cases, we may synthesize an InitListExpr
  5483. assert(Args.size() == 1 || S.getLangOpts().HLSL);
  5484. CurInit = Args[0];
  5485. Expr* CurInitExpr = CurInit.get();
  5486. if (!CurInitExpr) return ExprError();
  5487. if (CurInitExpr->getStmtClass() != Stmt::StmtClass::InitListExprClass) {
  5488. assert(S.getLangOpts().HLSL);
  5489. for (unsigned i = 0; i < Args.size(); ++i) {
  5490. if (Args[i]->isLValue()) {
  5491. Args[i] = ImplicitCastExpr::Create(S.Context, Args[i]->getType(),
  5492. CK_LValueToRValue, Args[i], /*BasePath=*/0, VK_RValue);
  5493. }
  5494. }
  5495. CurInit = new (S.getASTContext())InitListExpr(S.getASTContext(), SourceLocation(), Args, SourceLocation());
  5496. }
  5497. break;
  5498. }
  5499. // HLSL Change Ends
  5500. case SK_ResolveAddressOfOverloadedFunction:
  5501. case SK_CastDerivedToBaseRValue:
  5502. case SK_CastDerivedToBaseXValue:
  5503. case SK_CastDerivedToBaseLValue:
  5504. case SK_BindReference:
  5505. case SK_BindReferenceToTemporary:
  5506. case SK_ExtraneousCopyToTemporary:
  5507. case SK_UserConversion:
  5508. case SK_QualificationConversionLValue:
  5509. case SK_QualificationConversionXValue:
  5510. case SK_QualificationConversionRValue:
  5511. case SK_AtomicConversion:
  5512. case SK_LValueToRValue:
  5513. case SK_ConversionSequence:
  5514. case SK_ConversionSequenceNoNarrowing:
  5515. case SK_UnwrapInitList:
  5516. case SK_RewrapInitList:
  5517. case SK_CAssignment:
  5518. case SK_StringInit:
  5519. case SK_ObjCObjectConversion:
  5520. case SK_ArrayInit:
  5521. case SK_ParenthesizedArrayInit:
  5522. case SK_PassByIndirectCopyRestore:
  5523. case SK_PassByIndirectRestore:
  5524. case SK_ProduceObjCObject:
  5525. case SK_StdInitializerList:
  5526. case SK_OCLSamplerInit:
  5527. case SK_OCLZeroEvent: {
  5528. assert(Args.size() == 1);
  5529. CurInit = Args[0];
  5530. if (!CurInit.get()) return ExprError();
  5531. break;
  5532. }
  5533. case SK_ConstructorInitialization:
  5534. case SK_ConstructorInitializationFromList:
  5535. case SK_StdInitializerListConstructorCall:
  5536. case SK_ZeroInitialization:
  5537. break;
  5538. }
  5539. // Walk through the computed steps for the initialization sequence,
  5540. // performing the specified conversions along the way.
  5541. bool ConstructorInitRequiresZeroInit = false;
  5542. for (step_iterator Step = step_begin(), StepEnd = step_end();
  5543. Step != StepEnd; ++Step) {
  5544. if (CurInit.isInvalid())
  5545. return ExprError();
  5546. QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
  5547. switch (Step->Kind) {
  5548. case SK_ResolveAddressOfOverloadedFunction:
  5549. // Overload resolution determined which function invoke; update the
  5550. // initializer to reflect that choice.
  5551. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
  5552. if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
  5553. return ExprError();
  5554. CurInit = S.FixOverloadedFunctionReference(CurInit,
  5555. Step->Function.FoundDecl,
  5556. Step->Function.Function);
  5557. break;
  5558. case SK_CastDerivedToBaseRValue:
  5559. case SK_CastDerivedToBaseXValue:
  5560. case SK_CastDerivedToBaseLValue: {
  5561. // We have a derived-to-base cast that produces either an rvalue or an
  5562. // lvalue. Perform that cast.
  5563. CXXCastPath BasePath;
  5564. // Casts to inaccessible base classes are allowed with C-style casts.
  5565. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
  5566. if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
  5567. CurInit.get()->getLocStart(),
  5568. CurInit.get()->getSourceRange(),
  5569. &BasePath, IgnoreBaseAccess))
  5570. return ExprError();
  5571. ExprValueKind VK =
  5572. Step->Kind == SK_CastDerivedToBaseLValue ?
  5573. VK_LValue :
  5574. (Step->Kind == SK_CastDerivedToBaseXValue ?
  5575. VK_XValue :
  5576. VK_RValue);
  5577. CurInit =
  5578. ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
  5579. CurInit.get(), &BasePath, VK);
  5580. break;
  5581. }
  5582. case SK_BindReference:
  5583. // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
  5584. if (CurInit.get()->refersToBitField()) {
  5585. // We don't necessarily have an unambiguous source bit-field.
  5586. FieldDecl *BitField = CurInit.get()->getSourceBitField();
  5587. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
  5588. << Entity.getType().isVolatileQualified()
  5589. << (BitField ? BitField->getDeclName() : DeclarationName())
  5590. << (BitField != nullptr)
  5591. << CurInit.get()->getSourceRange();
  5592. if (BitField)
  5593. S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
  5594. return ExprError();
  5595. }
  5596. if (CurInit.get()->refersToVectorElement()) {
  5597. // References cannot bind to vector elements.
  5598. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
  5599. << Entity.getType().isVolatileQualified()
  5600. << CurInit.get()->getSourceRange();
  5601. PrintInitLocationNote(S, Entity);
  5602. return ExprError();
  5603. }
  5604. // Reference binding does not have any corresponding ASTs.
  5605. // Check exception specifications
  5606. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  5607. return ExprError();
  5608. // Even though we didn't materialize a temporary, the binding may still
  5609. // extend the lifetime of a temporary. This happens if we bind a reference
  5610. // to the result of a cast to reference type.
  5611. if (const InitializedEntity *ExtendingEntity =
  5612. getEntityForTemporaryLifetimeExtension(&Entity))
  5613. if (performReferenceExtension(CurInit.get(), ExtendingEntity))
  5614. warnOnLifetimeExtension(S, Entity, CurInit.get(),
  5615. /*IsInitializerList=*/false,
  5616. ExtendingEntity->getDecl());
  5617. break;
  5618. case SK_BindReferenceToTemporary: {
  5619. // Make sure the "temporary" is actually an rvalue.
  5620. assert(CurInit.get()->isRValue() && "not a temporary");
  5621. // Check exception specifications
  5622. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  5623. return ExprError();
  5624. // Materialize the temporary into memory.
  5625. MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
  5626. Entity.getType().getNonReferenceType(), CurInit.get(),
  5627. Entity.getType()->isLValueReferenceType());
  5628. // Maybe lifetime-extend the temporary's subobjects to match the
  5629. // entity's lifetime.
  5630. if (const InitializedEntity *ExtendingEntity =
  5631. getEntityForTemporaryLifetimeExtension(&Entity))
  5632. if (performReferenceExtension(MTE, ExtendingEntity))
  5633. warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
  5634. ExtendingEntity->getDecl());
  5635. // If we're binding to an Objective-C object that has lifetime, we
  5636. // need cleanups. Likewise if we're extending this temporary to automatic
  5637. // storage duration -- we need to register its cleanup during the
  5638. // full-expression's cleanups.
  5639. if ((S.getLangOpts().ObjCAutoRefCount &&
  5640. MTE->getType()->isObjCLifetimeType()) ||
  5641. (MTE->getStorageDuration() == SD_Automatic &&
  5642. MTE->getType().isDestructedType()))
  5643. S.ExprNeedsCleanups = true;
  5644. CurInit = MTE;
  5645. break;
  5646. }
  5647. case SK_ExtraneousCopyToTemporary:
  5648. CurInit = CopyObject(S, Step->Type, Entity, CurInit,
  5649. /*IsExtraneousCopy=*/true);
  5650. break;
  5651. case SK_UserConversion: {
  5652. // We have a user-defined conversion that invokes either a constructor
  5653. // or a conversion function.
  5654. CastKind CastKind;
  5655. bool IsCopy = false;
  5656. FunctionDecl *Fn = Step->Function.Function;
  5657. DeclAccessPair FoundFn = Step->Function.FoundDecl;
  5658. bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
  5659. bool CreatedObject = false;
  5660. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
  5661. // Build a call to the selected constructor.
  5662. SmallVector<Expr*, 8> ConstructorArgs;
  5663. SourceLocation Loc = CurInit.get()->getLocStart();
  5664. CurInit.get(); // Ownership transferred into MultiExprArg, below.
  5665. // Determine the arguments required to actually perform the constructor
  5666. // call.
  5667. Expr *Arg = CurInit.get();
  5668. if (S.CompleteConstructorCall(Constructor,
  5669. MultiExprArg(&Arg, 1),
  5670. Loc, ConstructorArgs))
  5671. return ExprError();
  5672. // Build an expression that constructs a temporary.
  5673. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
  5674. ConstructorArgs,
  5675. HadMultipleCandidates,
  5676. /*ListInit*/ false,
  5677. /*StdInitListInit*/ false,
  5678. /*ZeroInit*/ false,
  5679. CXXConstructExpr::CK_Complete,
  5680. SourceRange());
  5681. if (CurInit.isInvalid())
  5682. return ExprError();
  5683. S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
  5684. FoundFn.getAccess());
  5685. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  5686. return ExprError();
  5687. CastKind = CK_ConstructorConversion;
  5688. QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
  5689. if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
  5690. S.IsDerivedFrom(SourceType, Class))
  5691. IsCopy = true;
  5692. CreatedObject = true;
  5693. } else {
  5694. // Build a call to the conversion function.
  5695. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
  5696. S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
  5697. FoundFn);
  5698. if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
  5699. return ExprError();
  5700. // FIXME: Should we move this initialization into a separate
  5701. // derived-to-base conversion? I believe the answer is "no", because
  5702. // we don't want to turn off access control here for c-style casts.
  5703. ExprResult CurInitExprRes =
  5704. S.PerformObjectArgumentInitialization(CurInit.get(),
  5705. /*Qualifier=*/nullptr,
  5706. FoundFn, Conversion);
  5707. if(CurInitExprRes.isInvalid())
  5708. return ExprError();
  5709. CurInit = CurInitExprRes;
  5710. // Build the actual call to the conversion function.
  5711. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
  5712. HadMultipleCandidates);
  5713. if (CurInit.isInvalid() || !CurInit.get())
  5714. return ExprError();
  5715. CastKind = CK_UserDefinedConversion;
  5716. CreatedObject = Conversion->getReturnType()->isRecordType();
  5717. }
  5718. bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
  5719. bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
  5720. if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
  5721. QualType T = CurInit.get()->getType();
  5722. if (const RecordType *Record = T->getAs<RecordType>()) {
  5723. CXXDestructorDecl *Destructor
  5724. = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
  5725. S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
  5726. S.PDiag(diag::err_access_dtor_temp) << T);
  5727. S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
  5728. if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
  5729. return ExprError();
  5730. }
  5731. }
  5732. CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
  5733. CastKind, CurInit.get(), nullptr,
  5734. CurInit.get()->getValueKind());
  5735. if (MaybeBindToTemp)
  5736. CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
  5737. if (RequiresCopy)
  5738. CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
  5739. CurInit, /*IsExtraneousCopy=*/false);
  5740. break;
  5741. }
  5742. case SK_QualificationConversionLValue:
  5743. case SK_QualificationConversionXValue:
  5744. case SK_QualificationConversionRValue: {
  5745. // Perform a qualification conversion; these can never go wrong.
  5746. ExprValueKind VK =
  5747. Step->Kind == SK_QualificationConversionLValue ?
  5748. VK_LValue :
  5749. (Step->Kind == SK_QualificationConversionXValue ?
  5750. VK_XValue :
  5751. VK_RValue);
  5752. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
  5753. break;
  5754. }
  5755. case SK_AtomicConversion: {
  5756. assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
  5757. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  5758. CK_NonAtomicToAtomic, VK_RValue);
  5759. break;
  5760. }
  5761. case SK_LValueToRValue: {
  5762. assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
  5763. CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
  5764. CK_LValueToRValue, CurInit.get(),
  5765. /*BasePath=*/nullptr, VK_RValue);
  5766. break;
  5767. }
  5768. case SK_ConversionSequence:
  5769. case SK_ConversionSequenceNoNarrowing: {
  5770. Sema::CheckedConversionKind CCK
  5771. = Kind.isCStyleCast()? Sema::CCK_CStyleCast
  5772. : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
  5773. : Kind.isExplicitCast()? Sema::CCK_OtherCast
  5774. : Sema::CCK_ImplicitConversion;
  5775. ExprResult CurInitExprRes =
  5776. S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
  5777. getAssignmentAction(Entity), CCK);
  5778. if (CurInitExprRes.isInvalid())
  5779. return ExprError();
  5780. CurInit = CurInitExprRes;
  5781. if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
  5782. S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
  5783. DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
  5784. CurInit.get());
  5785. break;
  5786. }
  5787. case SK_ListInitialization: {
  5788. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  5789. // If we're not initializing the top-level entity, we need to create an
  5790. // InitializeTemporary entity for our target type.
  5791. QualType Ty = Step->Type;
  5792. bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
  5793. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
  5794. InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
  5795. // HLSL Change Starts - all analysis done - TODO semantic changes for IR
  5796. if (S.getLangOpts().HLSL) {
  5797. CurInit.get();
  5798. InitList->setType(InitEntity.getType());
  5799. CurInit = shouldBindAsTemporary(InitEntity)
  5800. ? S.MaybeBindToTemporary(InitList)
  5801. : InitList;
  5802. // Hack: We must update *ResultType if available in order to set the
  5803. // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  5804. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  5805. if (ResultType &&
  5806. ResultType->getNonReferenceType()->isIncompleteArrayType()) {
  5807. const IncompleteArrayType *IncompleteAT =
  5808. S.getASTContext().getAsIncompleteArrayType(
  5809. ResultType->getNonReferenceType());
  5810. QualType EltTy = IncompleteAT->getElementType();
  5811. unsigned arraySize = hlsl::CaculateInitListArraySizeForHLSL(&S, InitList, EltTy);
  5812. if (arraySize) {
  5813. llvm::APInt Size(
  5814. /*numBits=*/32, arraySize);
  5815. QualType AT = S.getASTContext().getConstantArrayType(
  5816. EltTy, Size, ArrayType::ArraySizeModifier::Normal,
  5817. /*IndexTypeQuals=*/0);
  5818. *ResultType = AT;
  5819. InitList->setType(AT);
  5820. }
  5821. }
  5822. } else { // HLSL Change Ends code below is conditional
  5823. InitListChecker PerformInitList(S, InitEntity, Kind, // HLSL Change - added Kind
  5824. InitList, Ty, /*VerifyOnly=*/false);
  5825. if (PerformInitList.HadError())
  5826. return ExprError();
  5827. // Hack: We must update *ResultType if available in order to set the
  5828. // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  5829. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  5830. if (ResultType &&
  5831. ResultType->getNonReferenceType()->isIncompleteArrayType()) {
  5832. if ((*ResultType)->isRValueReferenceType())
  5833. Ty = S.Context.getRValueReferenceType(Ty);
  5834. else if ((*ResultType)->isLValueReferenceType())
  5835. Ty = S.Context.getLValueReferenceType(Ty,
  5836. (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
  5837. *ResultType = Ty;
  5838. }
  5839. InitListExpr *StructuredInitList =
  5840. PerformInitList.getFullyStructuredList();
  5841. CurInit.get();
  5842. CurInit = shouldBindAsTemporary(InitEntity)
  5843. ? S.MaybeBindToTemporary(StructuredInitList)
  5844. : StructuredInitList;
  5845. } // HLSL Change - end conditional
  5846. break;
  5847. }
  5848. case SK_ConstructorInitializationFromList: {
  5849. // When an initializer list is passed for a parameter of type "reference
  5850. // to object", we don't get an EK_Temporary entity, but instead an
  5851. // EK_Parameter entity with reference type.
  5852. // FIXME: This is a hack. What we really should do is create a user
  5853. // conversion step for this case, but this makes it considerably more
  5854. // complicated. For now, this will do.
  5855. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  5856. Entity.getType().getNonReferenceType());
  5857. bool UseTemporary = Entity.getType()->isReferenceType();
  5858. assert(Args.size() == 1 && "expected a single argument for list init");
  5859. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  5860. S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
  5861. << InitList->getSourceRange();
  5862. MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
  5863. CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
  5864. Entity,
  5865. Kind, Arg, *Step,
  5866. ConstructorInitRequiresZeroInit,
  5867. /*IsListInitialization*/true,
  5868. /*IsStdInitListInit*/false,
  5869. InitList->getLBraceLoc(),
  5870. InitList->getRBraceLoc());
  5871. break;
  5872. }
  5873. case SK_UnwrapInitList:
  5874. CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
  5875. break;
  5876. case SK_RewrapInitList: {
  5877. Expr *E = CurInit.get();
  5878. InitListExpr *Syntactic = Step->WrappingSyntacticList;
  5879. InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
  5880. Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
  5881. ILE->setSyntacticForm(Syntactic);
  5882. ILE->setType(E->getType());
  5883. ILE->setValueKind(E->getValueKind());
  5884. CurInit = ILE;
  5885. break;
  5886. }
  5887. case SK_ConstructorInitialization:
  5888. case SK_StdInitializerListConstructorCall: {
  5889. // When an initializer list is passed for a parameter of type "reference
  5890. // to object", we don't get an EK_Temporary entity, but instead an
  5891. // EK_Parameter entity with reference type.
  5892. // FIXME: This is a hack. What we really should do is create a user
  5893. // conversion step for this case, but this makes it considerably more
  5894. // complicated. For now, this will do.
  5895. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  5896. Entity.getType().getNonReferenceType());
  5897. bool UseTemporary = Entity.getType()->isReferenceType();
  5898. bool IsStdInitListInit =
  5899. Step->Kind == SK_StdInitializerListConstructorCall;
  5900. CurInit = PerformConstructorInitialization(
  5901. S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
  5902. ConstructorInitRequiresZeroInit,
  5903. /*IsListInitialization*/IsStdInitListInit,
  5904. /*IsStdInitListInitialization*/IsStdInitListInit,
  5905. /*LBraceLoc*/SourceLocation(),
  5906. /*RBraceLoc*/SourceLocation());
  5907. break;
  5908. }
  5909. case SK_ZeroInitialization: {
  5910. step_iterator NextStep = Step;
  5911. ++NextStep;
  5912. if (NextStep != StepEnd &&
  5913. (NextStep->Kind == SK_ConstructorInitialization ||
  5914. NextStep->Kind == SK_ConstructorInitializationFromList)) {
  5915. // The need for zero-initialization is recorded directly into
  5916. // the call to the object's constructor within the next step.
  5917. ConstructorInitRequiresZeroInit = true;
  5918. } else if (Kind.getKind() == InitializationKind::IK_Value &&
  5919. S.getLangOpts().CPlusPlus &&
  5920. !Kind.isImplicitValueInit()) {
  5921. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  5922. if (!TSInfo)
  5923. TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
  5924. Kind.getRange().getBegin());
  5925. CurInit = new (S.Context) CXXScalarValueInitExpr(
  5926. TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
  5927. Kind.getRange().getEnd());
  5928. } else {
  5929. CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
  5930. }
  5931. break;
  5932. }
  5933. case SK_CAssignment: {
  5934. QualType SourceType = CurInit.get()->getType();
  5935. ExprResult Result = CurInit;
  5936. Sema::AssignConvertType ConvTy =
  5937. S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
  5938. Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
  5939. if (Result.isInvalid())
  5940. return ExprError();
  5941. CurInit = Result;
  5942. // If this is a call, allow conversion to a transparent union.
  5943. ExprResult CurInitExprRes = CurInit;
  5944. if (ConvTy != Sema::Compatible &&
  5945. Entity.isParameterKind() &&
  5946. S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
  5947. == Sema::Compatible)
  5948. ConvTy = Sema::Compatible;
  5949. if (CurInitExprRes.isInvalid())
  5950. return ExprError();
  5951. CurInit = CurInitExprRes;
  5952. bool Complained;
  5953. if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
  5954. Step->Type, SourceType,
  5955. CurInit.get(),
  5956. getAssignmentAction(Entity, true),
  5957. &Complained)) {
  5958. PrintInitLocationNote(S, Entity);
  5959. return ExprError();
  5960. } else if (Complained)
  5961. PrintInitLocationNote(S, Entity);
  5962. break;
  5963. }
  5964. case SK_StringInit: {
  5965. QualType Ty = Step->Type;
  5966. CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
  5967. S.Context.getAsArrayType(Ty), S);
  5968. break;
  5969. }
  5970. case SK_ObjCObjectConversion:
  5971. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  5972. CK_ObjCObjectLValueCast,
  5973. CurInit.get()->getValueKind());
  5974. break;
  5975. case SK_ArrayInit:
  5976. // Okay: we checked everything before creating this step. Note that
  5977. // this is a GNU extension.
  5978. S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
  5979. << Step->Type << CurInit.get()->getType()
  5980. << CurInit.get()->getSourceRange();
  5981. // If the destination type is an incomplete array type, update the
  5982. // type accordingly.
  5983. if (ResultType) {
  5984. if (const IncompleteArrayType *IncompleteDest
  5985. = S.Context.getAsIncompleteArrayType(Step->Type)) {
  5986. if (const ConstantArrayType *ConstantSource
  5987. = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
  5988. *ResultType = S.Context.getConstantArrayType(
  5989. IncompleteDest->getElementType(),
  5990. ConstantSource->getSize(),
  5991. ArrayType::Normal, 0);
  5992. }
  5993. }
  5994. }
  5995. break;
  5996. case SK_ParenthesizedArrayInit:
  5997. // Okay: we checked everything before creating this step. Note that
  5998. // this is a GNU extension.
  5999. S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
  6000. << CurInit.get()->getSourceRange();
  6001. break;
  6002. case SK_PassByIndirectCopyRestore:
  6003. case SK_PassByIndirectRestore:
  6004. checkIndirectCopyRestoreSource(S, CurInit.get());
  6005. CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
  6006. CurInit.get(), Step->Type,
  6007. Step->Kind == SK_PassByIndirectCopyRestore);
  6008. break;
  6009. case SK_ProduceObjCObject:
  6010. CurInit =
  6011. ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
  6012. CurInit.get(), nullptr, VK_RValue);
  6013. break;
  6014. case SK_StdInitializerList: {
  6015. S.Diag(CurInit.get()->getExprLoc(),
  6016. diag::warn_cxx98_compat_initializer_list_init)
  6017. << CurInit.get()->getSourceRange();
  6018. // Materialize the temporary into memory.
  6019. MaterializeTemporaryExpr *MTE = new (S.Context)
  6020. MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
  6021. /*BoundToLvalueReference=*/false);
  6022. // Maybe lifetime-extend the array temporary's subobjects to match the
  6023. // entity's lifetime.
  6024. if (const InitializedEntity *ExtendingEntity =
  6025. getEntityForTemporaryLifetimeExtension(&Entity))
  6026. if (performReferenceExtension(MTE, ExtendingEntity))
  6027. warnOnLifetimeExtension(S, Entity, CurInit.get(),
  6028. /*IsInitializerList=*/true,
  6029. ExtendingEntity->getDecl());
  6030. // Wrap it in a construction of a std::initializer_list<T>.
  6031. CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
  6032. // Bind the result, in case the library has given initializer_list a
  6033. // non-trivial destructor.
  6034. if (shouldBindAsTemporary(Entity))
  6035. CurInit = S.MaybeBindToTemporary(CurInit.get());
  6036. break;
  6037. }
  6038. case SK_OCLSamplerInit: {
  6039. assert(Step->Type->isSamplerT() &&
  6040. "Sampler initialization on non-sampler type.");
  6041. QualType SourceType = CurInit.get()->getType();
  6042. if (Entity.isParameterKind()) {
  6043. if (!SourceType->isSamplerT())
  6044. S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
  6045. << SourceType;
  6046. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  6047. llvm_unreachable("Invalid EntityKind!");
  6048. }
  6049. break;
  6050. }
  6051. case SK_OCLZeroEvent: {
  6052. assert(Step->Type->isEventT() &&
  6053. "Event initialization on non-event type.");
  6054. CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
  6055. CK_ZeroToOCLEvent,
  6056. CurInit.get()->getValueKind());
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. // Diagnose non-fatal problems with the completed initialization.
  6062. if (Entity.getKind() == InitializedEntity::EK_Member &&
  6063. cast<FieldDecl>(Entity.getDecl())->isBitField())
  6064. S.CheckBitFieldInitialization(Kind.getLocation(),
  6065. cast<FieldDecl>(Entity.getDecl()),
  6066. CurInit.get());
  6067. // Check for std::move on construction.
  6068. if (const Expr *E = CurInit.get()) {
  6069. CheckMoveOnConstruction(S, E,
  6070. Entity.getKind() == InitializedEntity::EK_Result);
  6071. }
  6072. return CurInit;
  6073. }
  6074. /// Somewhere within T there is an uninitialized reference subobject.
  6075. /// Dig it out and diagnose it.
  6076. static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
  6077. QualType T) {
  6078. if (T->isReferenceType()) {
  6079. S.Diag(Loc, diag::err_reference_without_init)
  6080. << T.getNonReferenceType();
  6081. return true;
  6082. }
  6083. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  6084. if (!RD || !RD->hasUninitializedReferenceMember())
  6085. return false;
  6086. for (const auto *FI : RD->fields()) {
  6087. if (FI->isUnnamedBitfield())
  6088. continue;
  6089. if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
  6090. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  6091. return true;
  6092. }
  6093. }
  6094. for (const auto &BI : RD->bases()) {
  6095. if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
  6096. S.Diag(Loc, diag::note_value_initialization_here) << RD;
  6097. return true;
  6098. }
  6099. }
  6100. return false;
  6101. }
  6102. //===----------------------------------------------------------------------===//
  6103. // Diagnose initialization failures
  6104. //===----------------------------------------------------------------------===//
  6105. /// Emit notes associated with an initialization that failed due to a
  6106. /// "simple" conversion failure.
  6107. static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
  6108. Expr *op) {
  6109. QualType destType = entity.getType();
  6110. if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
  6111. op->getType()->isObjCObjectPointerType()) {
  6112. // Emit a possible note about the conversion failing because the
  6113. // operand is a message send with a related result type.
  6114. S.EmitRelatedResultTypeNote(op);
  6115. // Emit a possible note about a return failing because we're
  6116. // expecting a related result type.
  6117. if (entity.getKind() == InitializedEntity::EK_Result)
  6118. S.EmitRelatedResultTypeNoteForReturn(destType);
  6119. }
  6120. }
  6121. static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
  6122. const InitializationKind &Kind, // HLSL Change - added Kind
  6123. InitListExpr *InitList) {
  6124. QualType DestType = Entity.getType();
  6125. QualType E;
  6126. if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
  6127. QualType ArrayType = S.Context.getConstantArrayType(
  6128. E.withConst(),
  6129. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  6130. InitList->getNumInits()),
  6131. clang::ArrayType::Normal, 0);
  6132. InitializedEntity HiddenArray =
  6133. InitializedEntity::InitializeTemporary(ArrayType);
  6134. return diagnoseListInit(S, HiddenArray, Kind, InitList); // HLSL Change - added Kind
  6135. }
  6136. if (DestType->isReferenceType()) {
  6137. // A list-initialization failure for a reference means that we tried to
  6138. // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
  6139. // inner initialization failed.
  6140. QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
  6141. diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), Kind, InitList);
  6142. SourceLocation Loc = InitList->getLocStart();
  6143. if (auto *D = Entity.getDecl())
  6144. Loc = D->getLocation();
  6145. S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
  6146. return;
  6147. }
  6148. InitListChecker DiagnoseInitList(S, Entity, Kind, InitList, DestType, // HLSL Change - added Kind
  6149. /*VerifyOnly=*/false);
  6150. assert(DiagnoseInitList.HadError() &&
  6151. "Inconsistent init list check result.");
  6152. }
  6153. bool InitializationSequence::Diagnose(Sema &S,
  6154. const InitializedEntity &Entity,
  6155. const InitializationKind &Kind,
  6156. ArrayRef<Expr *> Args) {
  6157. if (!Failed())
  6158. return false;
  6159. QualType DestType = Entity.getType();
  6160. switch (Failure) {
  6161. case FK_TooManyInitsForReference:
  6162. // FIXME: Customize for the initialized entity?
  6163. if (Args.empty()) {
  6164. // Dig out the reference subobject which is uninitialized and diagnose it.
  6165. // If this is value-initialization, this could be nested some way within
  6166. // the target type.
  6167. assert(Kind.getKind() == InitializationKind::IK_Value ||
  6168. DestType->isReferenceType());
  6169. bool Diagnosed =
  6170. DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
  6171. assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
  6172. (void)Diagnosed;
  6173. } else // FIXME: diagnostic below could be better!
  6174. S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
  6175. << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
  6176. break;
  6177. case FK_ArrayNeedsInitList:
  6178. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
  6179. break;
  6180. case FK_ArrayNeedsInitListOrStringLiteral:
  6181. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
  6182. break;
  6183. case FK_ArrayNeedsInitListOrWideStringLiteral:
  6184. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
  6185. break;
  6186. case FK_NarrowStringIntoWideCharArray:
  6187. S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
  6188. break;
  6189. case FK_WideStringIntoCharArray:
  6190. S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
  6191. break;
  6192. case FK_IncompatWideStringIntoWideChar:
  6193. S.Diag(Kind.getLocation(),
  6194. diag::err_array_init_incompat_wide_string_into_wchar);
  6195. break;
  6196. case FK_ArrayTypeMismatch:
  6197. case FK_NonConstantArrayInit:
  6198. S.Diag(Kind.getLocation(),
  6199. (Failure == FK_ArrayTypeMismatch
  6200. ? diag::err_array_init_different_type
  6201. : diag::err_array_init_non_constant_array))
  6202. << DestType.getNonReferenceType()
  6203. << Args[0]->getType()
  6204. << Args[0]->getSourceRange();
  6205. break;
  6206. case FK_VariableLengthArrayHasInitializer:
  6207. S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
  6208. << Args[0]->getSourceRange();
  6209. break;
  6210. case FK_AddressOfOverloadFailed: {
  6211. DeclAccessPair Found;
  6212. S.ResolveAddressOfOverloadedFunction(Args[0],
  6213. DestType.getNonReferenceType(),
  6214. true,
  6215. Found);
  6216. break;
  6217. }
  6218. case FK_ReferenceInitOverloadFailed:
  6219. case FK_UserConversionOverloadFailed:
  6220. switch (FailedOverloadResult) {
  6221. case OR_Ambiguous:
  6222. if (Failure == FK_UserConversionOverloadFailed)
  6223. S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
  6224. << Args[0]->getType() << DestType
  6225. << Args[0]->getSourceRange();
  6226. else
  6227. S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
  6228. << DestType << Args[0]->getType()
  6229. << Args[0]->getSourceRange();
  6230. FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
  6231. break;
  6232. case OR_No_Viable_Function:
  6233. if (!S.RequireCompleteType(Kind.getLocation(),
  6234. DestType.getNonReferenceType(),
  6235. diag::err_typecheck_nonviable_condition_incomplete,
  6236. Args[0]->getType(), Args[0]->getSourceRange()))
  6237. S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
  6238. << Args[0]->getType() << Args[0]->getSourceRange()
  6239. << DestType.getNonReferenceType();
  6240. FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
  6241. break;
  6242. case OR_Deleted: {
  6243. S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
  6244. << Args[0]->getType() << DestType.getNonReferenceType()
  6245. << Args[0]->getSourceRange();
  6246. OverloadCandidateSet::iterator Best;
  6247. OverloadingResult Ovl
  6248. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
  6249. true);
  6250. if (Ovl == OR_Deleted) {
  6251. S.NoteDeletedFunction(Best->Function);
  6252. } else {
  6253. llvm_unreachable("Inconsistent overload resolution?");
  6254. }
  6255. break;
  6256. }
  6257. case OR_Success:
  6258. llvm_unreachable("Conversion did not fail!");
  6259. }
  6260. break;
  6261. case FK_NonConstLValueReferenceBindingToTemporary:
  6262. if (isa<InitListExpr>(Args[0])) {
  6263. S.Diag(Kind.getLocation(),
  6264. diag::err_lvalue_reference_bind_to_initlist)
  6265. << DestType.getNonReferenceType().isVolatileQualified()
  6266. << DestType.getNonReferenceType()
  6267. << Args[0]->getSourceRange();
  6268. break;
  6269. }
  6270. // Intentional fallthrough
  6271. case FK_NonConstLValueReferenceBindingToUnrelated:
  6272. S.Diag(Kind.getLocation(),
  6273. Failure == FK_NonConstLValueReferenceBindingToTemporary
  6274. ? diag::err_lvalue_reference_bind_to_temporary
  6275. : diag::err_lvalue_reference_bind_to_unrelated)
  6276. << DestType.getNonReferenceType().isVolatileQualified()
  6277. << DestType.getNonReferenceType()
  6278. << Args[0]->getType()
  6279. << Args[0]->getSourceRange();
  6280. break;
  6281. case FK_RValueReferenceBindingToLValue:
  6282. S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
  6283. << DestType.getNonReferenceType() << Args[0]->getType()
  6284. << Args[0]->getSourceRange();
  6285. break;
  6286. case FK_ReferenceInitDropsQualifiers: {
  6287. QualType SourceType = Args[0]->getType();
  6288. QualType NonRefType = DestType.getNonReferenceType();
  6289. Qualifiers DroppedQualifiers =
  6290. SourceType.getQualifiers() - NonRefType.getQualifiers();
  6291. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  6292. << SourceType
  6293. << NonRefType
  6294. << DroppedQualifiers.getCVRQualifiers()
  6295. << Args[0]->getSourceRange();
  6296. break;
  6297. }
  6298. case FK_ReferenceInitFailed:
  6299. S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
  6300. << DestType.getNonReferenceType()
  6301. << Args[0]->isLValue()
  6302. << Args[0]->getType()
  6303. << Args[0]->getSourceRange();
  6304. emitBadConversionNotes(S, Entity, Args[0]);
  6305. break;
  6306. case FK_ConversionFailed: {
  6307. QualType FromType = Args[0]->getType();
  6308. PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
  6309. << (int)Entity.getKind()
  6310. << DestType
  6311. << Args[0]->isLValue()
  6312. << FromType
  6313. << Args[0]->getSourceRange();
  6314. S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
  6315. S.Diag(Kind.getLocation(), PDiag);
  6316. emitBadConversionNotes(S, Entity, Args[0]);
  6317. break;
  6318. }
  6319. case FK_ConversionFromPropertyFailed:
  6320. // No-op. This error has already been reported.
  6321. break;
  6322. case FK_TooManyInitsForScalar: {
  6323. SourceRange R;
  6324. auto *InitList = dyn_cast<InitListExpr>(Args[0]);
  6325. if (InitList && InitList->getNumInits() == 1)
  6326. R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
  6327. else
  6328. R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
  6329. R.setBegin(S.getLocForEndOfToken(R.getBegin()));
  6330. if (Kind.isCStyleOrFunctionalCast())
  6331. S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
  6332. << R;
  6333. else
  6334. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  6335. << /*scalar=*/2 << R;
  6336. break;
  6337. }
  6338. case FK_ReferenceBindingToInitList:
  6339. S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
  6340. << DestType.getNonReferenceType() << Args[0]->getSourceRange();
  6341. break;
  6342. case FK_InitListBadDestinationType:
  6343. S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
  6344. << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
  6345. break;
  6346. case FK_ListConstructorOverloadFailed:
  6347. case FK_ConstructorOverloadFailed: {
  6348. SourceRange ArgsRange;
  6349. if (Args.size())
  6350. ArgsRange = SourceRange(Args.front()->getLocStart(),
  6351. Args.back()->getLocEnd());
  6352. if (Failure == FK_ListConstructorOverloadFailed) {
  6353. assert(Args.size() == 1 &&
  6354. "List construction from other than 1 argument.");
  6355. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  6356. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  6357. }
  6358. // FIXME: Using "DestType" for the entity we're printing is probably
  6359. // bad.
  6360. switch (FailedOverloadResult) {
  6361. case OR_Ambiguous:
  6362. S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
  6363. << DestType << ArgsRange;
  6364. FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
  6365. break;
  6366. case OR_No_Viable_Function:
  6367. if (Kind.getKind() == InitializationKind::IK_Default &&
  6368. (Entity.getKind() == InitializedEntity::EK_Base ||
  6369. Entity.getKind() == InitializedEntity::EK_Member) &&
  6370. isa<CXXConstructorDecl>(S.CurContext)) {
  6371. // This is implicit default initialization of a member or
  6372. // base within a constructor. If no viable function was
  6373. // found, notify the user that she needs to explicitly
  6374. // initialize this base/member.
  6375. CXXConstructorDecl *Constructor
  6376. = cast<CXXConstructorDecl>(S.CurContext);
  6377. if (Entity.getKind() == InitializedEntity::EK_Base) {
  6378. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  6379. << (Constructor->getInheritedConstructor() ? 2 :
  6380. Constructor->isImplicit() ? 1 : 0)
  6381. << S.Context.getTypeDeclType(Constructor->getParent())
  6382. << /*base=*/0
  6383. << Entity.getType();
  6384. RecordDecl *BaseDecl
  6385. = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
  6386. ->getDecl();
  6387. S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  6388. << S.Context.getTagDeclType(BaseDecl);
  6389. } else {
  6390. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  6391. << (Constructor->getInheritedConstructor() ? 2 :
  6392. Constructor->isImplicit() ? 1 : 0)
  6393. << S.Context.getTypeDeclType(Constructor->getParent())
  6394. << /*member=*/1
  6395. << Entity.getName();
  6396. S.Diag(Entity.getDecl()->getLocation(),
  6397. diag::note_member_declared_at);
  6398. if (const RecordType *Record
  6399. = Entity.getType()->getAs<RecordType>())
  6400. S.Diag(Record->getDecl()->getLocation(),
  6401. diag::note_previous_decl)
  6402. << S.Context.getTagDeclType(Record->getDecl());
  6403. }
  6404. break;
  6405. }
  6406. S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
  6407. << DestType << ArgsRange;
  6408. FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
  6409. break;
  6410. case OR_Deleted: {
  6411. OverloadCandidateSet::iterator Best;
  6412. OverloadingResult Ovl
  6413. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  6414. if (Ovl != OR_Deleted) {
  6415. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  6416. << true << DestType << ArgsRange;
  6417. llvm_unreachable("Inconsistent overload resolution?");
  6418. break;
  6419. }
  6420. // If this is a defaulted or implicitly-declared function, then
  6421. // it was implicitly deleted. Make it clear that the deletion was
  6422. // implicit.
  6423. if (S.isImplicitlyDeleted(Best->Function))
  6424. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
  6425. << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
  6426. << DestType << ArgsRange;
  6427. else
  6428. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  6429. << true << DestType << ArgsRange;
  6430. S.NoteDeletedFunction(Best->Function);
  6431. break;
  6432. }
  6433. case OR_Success:
  6434. llvm_unreachable("Conversion did not fail!");
  6435. }
  6436. }
  6437. break;
  6438. case FK_DefaultInitOfConst:
  6439. if (Entity.getKind() == InitializedEntity::EK_Member &&
  6440. isa<CXXConstructorDecl>(S.CurContext)) {
  6441. // This is implicit default-initialization of a const member in
  6442. // a constructor. Complain that it needs to be explicitly
  6443. // initialized.
  6444. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
  6445. S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
  6446. << (Constructor->getInheritedConstructor() ? 2 :
  6447. Constructor->isImplicit() ? 1 : 0)
  6448. << S.Context.getTypeDeclType(Constructor->getParent())
  6449. << /*const=*/1
  6450. << Entity.getName();
  6451. S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
  6452. << Entity.getName();
  6453. } else {
  6454. S.Diag(Kind.getLocation(), diag::err_default_init_const)
  6455. << DestType << (bool)DestType->getAs<RecordType>();
  6456. }
  6457. break;
  6458. case FK_Incomplete:
  6459. S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
  6460. diag::err_init_incomplete_type);
  6461. break;
  6462. case FK_ListInitializationFailed: {
  6463. // Run the init list checker again to emit diagnostics.
  6464. // HLSL Change Starts: allow for the possibility of having to construct an InitListExpr.
  6465. if (!S.getLangOpts().HLSL) {
  6466. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  6467. diagnoseListInit(S, Entity, Kind, InitList); // HLSL Change - added Kind
  6468. }
  6469. else {
  6470. // For HLSL, InitializeInitSequenceForHLSL should report error messages.
  6471. }
  6472. // HLSL Change Ends
  6473. break;
  6474. }
  6475. case FK_PlaceholderType: {
  6476. // FIXME: Already diagnosed!
  6477. break;
  6478. }
  6479. case FK_ExplicitConstructor: {
  6480. S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
  6481. << Args[0]->getSourceRange();
  6482. OverloadCandidateSet::iterator Best;
  6483. OverloadingResult Ovl
  6484. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  6485. (void)Ovl;
  6486. assert(Ovl == OR_Success && "Inconsistent overload resolution");
  6487. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  6488. S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
  6489. break;
  6490. }
  6491. }
  6492. PrintInitLocationNote(S, Entity);
  6493. return true;
  6494. }
  6495. void InitializationSequence::dump(raw_ostream &OS) const {
  6496. switch (SequenceKind) {
  6497. case FailedSequence: {
  6498. OS << "Failed sequence: ";
  6499. switch (Failure) {
  6500. case FK_TooManyInitsForReference:
  6501. OS << "too many initializers for reference";
  6502. break;
  6503. case FK_ArrayNeedsInitList:
  6504. OS << "array requires initializer list";
  6505. break;
  6506. case FK_ArrayNeedsInitListOrStringLiteral:
  6507. OS << "array requires initializer list or string literal";
  6508. break;
  6509. case FK_ArrayNeedsInitListOrWideStringLiteral:
  6510. OS << "array requires initializer list or wide string literal";
  6511. break;
  6512. case FK_NarrowStringIntoWideCharArray:
  6513. OS << "narrow string into wide char array";
  6514. break;
  6515. case FK_WideStringIntoCharArray:
  6516. OS << "wide string into char array";
  6517. break;
  6518. case FK_IncompatWideStringIntoWideChar:
  6519. OS << "incompatible wide string into wide char array";
  6520. break;
  6521. case FK_ArrayTypeMismatch:
  6522. OS << "array type mismatch";
  6523. break;
  6524. case FK_NonConstantArrayInit:
  6525. OS << "non-constant array initializer";
  6526. break;
  6527. case FK_AddressOfOverloadFailed:
  6528. OS << "address of overloaded function failed";
  6529. break;
  6530. case FK_ReferenceInitOverloadFailed:
  6531. OS << "overload resolution for reference initialization failed";
  6532. break;
  6533. case FK_NonConstLValueReferenceBindingToTemporary:
  6534. OS << "non-const lvalue reference bound to temporary";
  6535. break;
  6536. case FK_NonConstLValueReferenceBindingToUnrelated:
  6537. OS << "non-const lvalue reference bound to unrelated type";
  6538. break;
  6539. case FK_RValueReferenceBindingToLValue:
  6540. OS << "rvalue reference bound to an lvalue";
  6541. break;
  6542. case FK_ReferenceInitDropsQualifiers:
  6543. OS << "reference initialization drops qualifiers";
  6544. break;
  6545. case FK_ReferenceInitFailed:
  6546. OS << "reference initialization failed";
  6547. break;
  6548. case FK_ConversionFailed:
  6549. OS << "conversion failed";
  6550. break;
  6551. case FK_ConversionFromPropertyFailed:
  6552. OS << "conversion from property failed";
  6553. break;
  6554. case FK_TooManyInitsForScalar:
  6555. OS << "too many initializers for scalar";
  6556. break;
  6557. case FK_ReferenceBindingToInitList:
  6558. OS << "referencing binding to initializer list";
  6559. break;
  6560. case FK_InitListBadDestinationType:
  6561. OS << "initializer list for non-aggregate, non-scalar type";
  6562. break;
  6563. case FK_UserConversionOverloadFailed:
  6564. OS << "overloading failed for user-defined conversion";
  6565. break;
  6566. case FK_ConstructorOverloadFailed:
  6567. OS << "constructor overloading failed";
  6568. break;
  6569. case FK_DefaultInitOfConst:
  6570. OS << "default initialization of a const variable";
  6571. break;
  6572. case FK_Incomplete:
  6573. OS << "initialization of incomplete type";
  6574. break;
  6575. case FK_ListInitializationFailed:
  6576. OS << "list initialization checker failure";
  6577. break;
  6578. case FK_VariableLengthArrayHasInitializer:
  6579. OS << "variable length array has an initializer";
  6580. break;
  6581. case FK_PlaceholderType:
  6582. OS << "initializer expression isn't contextually valid";
  6583. break;
  6584. case FK_ListConstructorOverloadFailed:
  6585. OS << "list constructor overloading failed";
  6586. break;
  6587. case FK_ExplicitConstructor:
  6588. OS << "list copy initialization chose explicit constructor";
  6589. break;
  6590. }
  6591. OS << '\n';
  6592. return;
  6593. }
  6594. case DependentSequence:
  6595. OS << "Dependent sequence\n";
  6596. return;
  6597. case NormalSequence:
  6598. OS << "Normal sequence: ";
  6599. break;
  6600. }
  6601. for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
  6602. if (S != step_begin()) {
  6603. OS << " -> ";
  6604. }
  6605. switch (S->Kind) {
  6606. case SK_ResolveAddressOfOverloadedFunction:
  6607. OS << "resolve address of overloaded function";
  6608. break;
  6609. case SK_CastDerivedToBaseRValue:
  6610. OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
  6611. break;
  6612. case SK_CastDerivedToBaseXValue:
  6613. OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
  6614. break;
  6615. case SK_CastDerivedToBaseLValue:
  6616. OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
  6617. break;
  6618. case SK_BindReference:
  6619. OS << "bind reference to lvalue";
  6620. break;
  6621. case SK_BindReferenceToTemporary:
  6622. OS << "bind reference to a temporary";
  6623. break;
  6624. case SK_ExtraneousCopyToTemporary:
  6625. OS << "extraneous C++03 copy to temporary";
  6626. break;
  6627. case SK_UserConversion:
  6628. OS << "user-defined conversion via " << *S->Function.Function;
  6629. break;
  6630. case SK_QualificationConversionRValue:
  6631. OS << "qualification conversion (rvalue)";
  6632. break;
  6633. case SK_QualificationConversionXValue:
  6634. OS << "qualification conversion (xvalue)";
  6635. break;
  6636. case SK_QualificationConversionLValue:
  6637. OS << "qualification conversion (lvalue)";
  6638. break;
  6639. case SK_AtomicConversion:
  6640. OS << "non-atomic-to-atomic conversion";
  6641. break;
  6642. case SK_LValueToRValue:
  6643. OS << "load (lvalue to rvalue)";
  6644. break;
  6645. case SK_ConversionSequence:
  6646. OS << "implicit conversion sequence (";
  6647. S->ICS->dump(); // FIXME: use OS
  6648. OS << ")";
  6649. break;
  6650. case SK_ConversionSequenceNoNarrowing:
  6651. OS << "implicit conversion sequence with narrowing prohibited (";
  6652. S->ICS->dump(); // FIXME: use OS
  6653. OS << ")";
  6654. break;
  6655. case SK_ListInitialization:
  6656. OS << "list aggregate initialization";
  6657. break;
  6658. case SK_UnwrapInitList:
  6659. OS << "unwrap reference initializer list";
  6660. break;
  6661. case SK_RewrapInitList:
  6662. OS << "rewrap reference initializer list";
  6663. break;
  6664. case SK_ConstructorInitialization:
  6665. OS << "constructor initialization";
  6666. break;
  6667. case SK_ConstructorInitializationFromList:
  6668. OS << "list initialization via constructor";
  6669. break;
  6670. case SK_ZeroInitialization:
  6671. OS << "zero initialization";
  6672. break;
  6673. case SK_CAssignment:
  6674. OS << "C assignment";
  6675. break;
  6676. case SK_StringInit:
  6677. OS << "string initialization";
  6678. break;
  6679. case SK_ObjCObjectConversion:
  6680. OS << "Objective-C object conversion";
  6681. break;
  6682. case SK_ArrayInit:
  6683. OS << "array initialization";
  6684. break;
  6685. case SK_ParenthesizedArrayInit:
  6686. OS << "parenthesized array initialization";
  6687. break;
  6688. case SK_PassByIndirectCopyRestore:
  6689. OS << "pass by indirect copy and restore";
  6690. break;
  6691. case SK_PassByIndirectRestore:
  6692. OS << "pass by indirect restore";
  6693. break;
  6694. case SK_ProduceObjCObject:
  6695. OS << "Objective-C object retension";
  6696. break;
  6697. case SK_StdInitializerList:
  6698. OS << "std::initializer_list from initializer list";
  6699. break;
  6700. case SK_StdInitializerListConstructorCall:
  6701. OS << "list initialization from std::initializer_list";
  6702. break;
  6703. case SK_OCLSamplerInit:
  6704. OS << "OpenCL sampler_t from integer constant";
  6705. break;
  6706. case SK_OCLZeroEvent:
  6707. OS << "OpenCL event_t from zero";
  6708. break;
  6709. }
  6710. OS << " [" << S->Type.getAsString() << ']';
  6711. }
  6712. OS << '\n';
  6713. }
  6714. void InitializationSequence::dump() const {
  6715. dump(llvm::errs());
  6716. }
  6717. static void DiagnoseNarrowingInInitList(Sema &S,
  6718. const ImplicitConversionSequence &ICS,
  6719. QualType PreNarrowingType,
  6720. QualType EntityType,
  6721. const Expr *PostInit) {
  6722. const StandardConversionSequence *SCS = nullptr;
  6723. switch (ICS.getKind()) {
  6724. case ImplicitConversionSequence::StandardConversion:
  6725. SCS = &ICS.Standard;
  6726. break;
  6727. case ImplicitConversionSequence::UserDefinedConversion:
  6728. SCS = &ICS.UserDefined.After;
  6729. break;
  6730. case ImplicitConversionSequence::AmbiguousConversion:
  6731. case ImplicitConversionSequence::EllipsisConversion:
  6732. case ImplicitConversionSequence::BadConversion:
  6733. return;
  6734. }
  6735. // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
  6736. APValue ConstantValue;
  6737. QualType ConstantType;
  6738. switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
  6739. ConstantType)) {
  6740. case NK_Not_Narrowing:
  6741. // No narrowing occurred.
  6742. return;
  6743. case NK_Type_Narrowing:
  6744. // This was a floating-to-integer conversion, which is always considered a
  6745. // narrowing conversion even if the value is a constant and can be
  6746. // represented exactly as an integer.
  6747. S.Diag(PostInit->getLocStart(),
  6748. (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
  6749. ? diag::warn_init_list_type_narrowing
  6750. : diag::ext_init_list_type_narrowing)
  6751. << PostInit->getSourceRange()
  6752. << PreNarrowingType.getLocalUnqualifiedType()
  6753. << EntityType.getLocalUnqualifiedType();
  6754. break;
  6755. case NK_Constant_Narrowing:
  6756. // A constant value was narrowed.
  6757. S.Diag(PostInit->getLocStart(),
  6758. (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
  6759. ? diag::warn_init_list_constant_narrowing
  6760. : diag::ext_init_list_constant_narrowing)
  6761. << PostInit->getSourceRange()
  6762. << ConstantValue.getAsString(S.getASTContext(), ConstantType)
  6763. << EntityType.getLocalUnqualifiedType();
  6764. break;
  6765. case NK_Variable_Narrowing:
  6766. // A variable's value may have been narrowed.
  6767. S.Diag(PostInit->getLocStart(),
  6768. (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
  6769. ? diag::warn_init_list_variable_narrowing
  6770. : diag::ext_init_list_variable_narrowing)
  6771. << PostInit->getSourceRange()
  6772. << PreNarrowingType.getLocalUnqualifiedType()
  6773. << EntityType.getLocalUnqualifiedType();
  6774. break;
  6775. }
  6776. SmallString<128> StaticCast;
  6777. llvm::raw_svector_ostream OS(StaticCast);
  6778. OS << "static_cast<";
  6779. if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
  6780. // It's important to use the typedef's name if there is one so that the
  6781. // fixit doesn't break code using types like int64_t.
  6782. //
  6783. // FIXME: This will break if the typedef requires qualification. But
  6784. // getQualifiedNameAsString() includes non-machine-parsable components.
  6785. OS << *TT->getDecl();
  6786. } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
  6787. OS << BT->getName(S.getLangOpts());
  6788. else {
  6789. // Oops, we didn't find the actual type of the variable. Don't emit a fixit
  6790. // with a broken cast.
  6791. return;
  6792. }
  6793. OS << ">(";
  6794. S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
  6795. << PostInit->getSourceRange()
  6796. << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
  6797. << FixItHint::CreateInsertion(
  6798. S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
  6799. }
  6800. //===----------------------------------------------------------------------===//
  6801. // Initialization helper functions
  6802. //===----------------------------------------------------------------------===//
  6803. bool
  6804. Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
  6805. ExprResult Init) {
  6806. if (Init.isInvalid())
  6807. return false;
  6808. Expr *InitE = Init.get();
  6809. assert(InitE && "No initialization expression");
  6810. InitializationKind Kind
  6811. = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
  6812. InitializationSequence Seq(*this, Entity, Kind, InitE);
  6813. return !Seq.Failed();
  6814. }
  6815. ExprResult
  6816. Sema::PerformCopyInitialization(const InitializedEntity &Entity,
  6817. SourceLocation EqualLoc,
  6818. ExprResult Init,
  6819. bool TopLevelOfInitList,
  6820. bool AllowExplicit) {
  6821. if (Init.isInvalid())
  6822. return ExprError();
  6823. Expr *InitE = Init.get();
  6824. assert(InitE && "No initialization expression?");
  6825. if (EqualLoc.isInvalid())
  6826. EqualLoc = InitE->getLocStart();
  6827. InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
  6828. EqualLoc,
  6829. AllowExplicit);
  6830. InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
  6831. ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
  6832. return Result;
  6833. }