SemaInit.cpp 364 KB

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