SemaInit.cpp 341 KB

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