SemaInit.cpp 235 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068
  1. //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for initializers.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Designator.h"
  14. #include "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "llvm/ADT/APInt.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <map>
  28. using namespace clang;
  29. //===----------------------------------------------------------------------===//
  30. // Sema Initialization Checking
  31. //===----------------------------------------------------------------------===//
  32. static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
  33. ASTContext &Context) {
  34. if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
  35. return 0;
  36. // See if this is a string literal or @encode.
  37. Init = Init->IgnoreParens();
  38. // Handle @encode, which is a narrow string.
  39. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
  40. return Init;
  41. // Otherwise we can only handle string literals.
  42. StringLiteral *SL = dyn_cast<StringLiteral>(Init);
  43. if (SL == 0) return 0;
  44. QualType ElemTy = Context.getCanonicalType(AT->getElementType());
  45. switch (SL->getKind()) {
  46. case StringLiteral::Ascii:
  47. case StringLiteral::UTF8:
  48. // char array can be initialized with a narrow string.
  49. // Only allow char x[] = "foo"; not char x[] = L"foo";
  50. return ElemTy->isCharType() ? Init : 0;
  51. case StringLiteral::UTF16:
  52. return ElemTy->isChar16Type() ? Init : 0;
  53. case StringLiteral::UTF32:
  54. return ElemTy->isChar32Type() ? Init : 0;
  55. case StringLiteral::Wide:
  56. // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
  57. // correction from DR343): "An array with element type compatible with a
  58. // qualified or unqualified version of wchar_t may be initialized by a wide
  59. // string literal, optionally enclosed in braces."
  60. if (Context.typesAreCompatible(Context.getWCharType(),
  61. ElemTy.getUnqualifiedType()))
  62. return Init;
  63. return 0;
  64. }
  65. llvm_unreachable("missed a StringLiteral kind?");
  66. }
  67. static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
  68. const ArrayType *arrayType = Context.getAsArrayType(declType);
  69. if (!arrayType) return 0;
  70. return IsStringInit(init, arrayType, Context);
  71. }
  72. static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
  73. Sema &S) {
  74. // Get the length of the string as parsed.
  75. uint64_t StrLength =
  76. cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
  77. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  78. // C99 6.7.8p14. We have an array of character type with unknown size
  79. // being initialized to a string literal.
  80. llvm::APSInt ConstVal(32);
  81. ConstVal = StrLength;
  82. // Return a new array type (C99 6.7.8p22).
  83. DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
  84. ConstVal,
  85. ArrayType::Normal, 0);
  86. return;
  87. }
  88. const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
  89. // We have an array of character type with known size. However,
  90. // the size may be smaller or larger than the string we are initializing.
  91. // FIXME: Avoid truncation for 64-bit length strings.
  92. if (S.getLangOptions().CPlusPlus) {
  93. if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
  94. // For Pascal strings it's OK to strip off the terminating null character,
  95. // so the example below is valid:
  96. //
  97. // unsigned char a[2] = "\pa";
  98. if (SL->isPascal())
  99. StrLength--;
  100. }
  101. // [dcl.init.string]p2
  102. if (StrLength > CAT->getSize().getZExtValue())
  103. S.Diag(Str->getSourceRange().getBegin(),
  104. diag::err_initializer_string_for_char_array_too_long)
  105. << Str->getSourceRange();
  106. } else {
  107. // C99 6.7.8p14.
  108. if (StrLength-1 > CAT->getSize().getZExtValue())
  109. S.Diag(Str->getSourceRange().getBegin(),
  110. diag::warn_initializer_string_for_char_array_too_long)
  111. << Str->getSourceRange();
  112. }
  113. // Set the type to the actual size that we are initializing. If we have
  114. // something like:
  115. // char x[1] = "foo";
  116. // then this will set the string literal's type to char[1].
  117. Str->setType(DeclT);
  118. }
  119. //===----------------------------------------------------------------------===//
  120. // Semantic checking for initializer lists.
  121. //===----------------------------------------------------------------------===//
  122. /// @brief Semantic checking for initializer lists.
  123. ///
  124. /// The InitListChecker class contains a set of routines that each
  125. /// handle the initialization of a certain kind of entity, e.g.,
  126. /// arrays, vectors, struct/union types, scalars, etc. The
  127. /// InitListChecker itself performs a recursive walk of the subobject
  128. /// structure of the type to be initialized, while stepping through
  129. /// the initializer list one element at a time. The IList and Index
  130. /// parameters to each of the Check* routines contain the active
  131. /// (syntactic) initializer list and the index into that initializer
  132. /// list that represents the current initializer. Each routine is
  133. /// responsible for moving that Index forward as it consumes elements.
  134. ///
  135. /// Each Check* routine also has a StructuredList/StructuredIndex
  136. /// arguments, which contains the current "structured" (semantic)
  137. /// initializer list and the index into that initializer list where we
  138. /// are copying initializers as we map them over to the semantic
  139. /// list. Once we have completed our recursive walk of the subobject
  140. /// structure, we will have constructed a full semantic initializer
  141. /// list.
  142. ///
  143. /// C99 designators cause changes in the initializer list traversal,
  144. /// because they make the initialization "jump" into a specific
  145. /// subobject and then continue the initialization from that
  146. /// point. CheckDesignatedInitializer() recursively steps into the
  147. /// designated subobject and manages backing out the recursion to
  148. /// initialize the subobjects after the one designated.
  149. namespace {
  150. class InitListChecker {
  151. Sema &SemaRef;
  152. bool hadError;
  153. bool VerifyOnly; // no diagnostics, no structure building
  154. bool AllowBraceElision;
  155. std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
  156. InitListExpr *FullyStructuredList;
  157. void CheckImplicitInitList(const InitializedEntity &Entity,
  158. InitListExpr *ParentIList, QualType T,
  159. unsigned &Index, InitListExpr *StructuredList,
  160. unsigned &StructuredIndex);
  161. void CheckExplicitInitList(const InitializedEntity &Entity,
  162. InitListExpr *IList, QualType &T,
  163. unsigned &Index, InitListExpr *StructuredList,
  164. unsigned &StructuredIndex,
  165. bool TopLevelObject = false);
  166. void CheckListElementTypes(const InitializedEntity &Entity,
  167. InitListExpr *IList, QualType &DeclType,
  168. bool SubobjectIsDesignatorContext,
  169. unsigned &Index,
  170. InitListExpr *StructuredList,
  171. unsigned &StructuredIndex,
  172. bool TopLevelObject = false);
  173. void CheckSubElementType(const InitializedEntity &Entity,
  174. InitListExpr *IList, QualType ElemType,
  175. unsigned &Index,
  176. InitListExpr *StructuredList,
  177. unsigned &StructuredIndex);
  178. void CheckComplexType(const InitializedEntity &Entity,
  179. InitListExpr *IList, QualType DeclType,
  180. unsigned &Index,
  181. InitListExpr *StructuredList,
  182. unsigned &StructuredIndex);
  183. void CheckScalarType(const InitializedEntity &Entity,
  184. InitListExpr *IList, QualType DeclType,
  185. unsigned &Index,
  186. InitListExpr *StructuredList,
  187. unsigned &StructuredIndex);
  188. void CheckReferenceType(const InitializedEntity &Entity,
  189. InitListExpr *IList, QualType DeclType,
  190. unsigned &Index,
  191. InitListExpr *StructuredList,
  192. unsigned &StructuredIndex);
  193. void CheckVectorType(const InitializedEntity &Entity,
  194. InitListExpr *IList, QualType DeclType, unsigned &Index,
  195. InitListExpr *StructuredList,
  196. unsigned &StructuredIndex);
  197. void CheckStructUnionTypes(const InitializedEntity &Entity,
  198. InitListExpr *IList, QualType DeclType,
  199. RecordDecl::field_iterator Field,
  200. bool SubobjectIsDesignatorContext, unsigned &Index,
  201. InitListExpr *StructuredList,
  202. unsigned &StructuredIndex,
  203. bool TopLevelObject = false);
  204. void CheckArrayType(const InitializedEntity &Entity,
  205. InitListExpr *IList, QualType &DeclType,
  206. llvm::APSInt elementIndex,
  207. bool SubobjectIsDesignatorContext, unsigned &Index,
  208. InitListExpr *StructuredList,
  209. unsigned &StructuredIndex);
  210. bool CheckDesignatedInitializer(const InitializedEntity &Entity,
  211. InitListExpr *IList, DesignatedInitExpr *DIE,
  212. unsigned DesigIdx,
  213. QualType &CurrentObjectType,
  214. RecordDecl::field_iterator *NextField,
  215. llvm::APSInt *NextElementIndex,
  216. unsigned &Index,
  217. InitListExpr *StructuredList,
  218. unsigned &StructuredIndex,
  219. bool FinishSubobjectInit,
  220. bool TopLevelObject);
  221. InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  222. QualType CurrentObjectType,
  223. InitListExpr *StructuredList,
  224. unsigned StructuredIndex,
  225. SourceRange InitRange);
  226. void UpdateStructuredListElement(InitListExpr *StructuredList,
  227. unsigned &StructuredIndex,
  228. Expr *expr);
  229. int numArrayElements(QualType DeclType);
  230. int numStructUnionElements(QualType DeclType);
  231. void FillInValueInitForField(unsigned Init, FieldDecl *Field,
  232. const InitializedEntity &ParentEntity,
  233. InitListExpr *ILE, bool &RequiresSecondPass);
  234. void FillInValueInitializations(const InitializedEntity &Entity,
  235. InitListExpr *ILE, bool &RequiresSecondPass);
  236. bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
  237. Expr *InitExpr, FieldDecl *Field,
  238. bool TopLevelObject);
  239. void CheckValueInitializable(const InitializedEntity &Entity);
  240. public:
  241. InitListChecker(Sema &S, const InitializedEntity &Entity,
  242. InitListExpr *IL, QualType &T, bool VerifyOnly,
  243. bool AllowBraceElision);
  244. bool HadError() { return hadError; }
  245. // @brief Retrieves the fully-structured initializer list used for
  246. // semantic analysis and code generation.
  247. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
  248. };
  249. } // end anonymous namespace
  250. void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
  251. assert(VerifyOnly &&
  252. "CheckValueInitializable is only inteded for verification mode.");
  253. SourceLocation Loc;
  254. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  255. true);
  256. InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
  257. if (InitSeq.Failed())
  258. hadError = true;
  259. }
  260. void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
  261. const InitializedEntity &ParentEntity,
  262. InitListExpr *ILE,
  263. bool &RequiresSecondPass) {
  264. SourceLocation Loc = ILE->getSourceRange().getBegin();
  265. unsigned NumInits = ILE->getNumInits();
  266. InitializedEntity MemberEntity
  267. = InitializedEntity::InitializeMember(Field, &ParentEntity);
  268. if (Init >= NumInits || !ILE->getInit(Init)) {
  269. // FIXME: We probably don't need to handle references
  270. // specially here, since value-initialization of references is
  271. // handled in InitializationSequence.
  272. if (Field->getType()->isReferenceType()) {
  273. // C++ [dcl.init.aggr]p9:
  274. // If an incomplete or empty initializer-list leaves a
  275. // member of reference type uninitialized, the program is
  276. // ill-formed.
  277. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
  278. << Field->getType()
  279. << ILE->getSyntacticForm()->getSourceRange();
  280. SemaRef.Diag(Field->getLocation(),
  281. diag::note_uninit_reference_member);
  282. hadError = true;
  283. return;
  284. }
  285. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  286. true);
  287. InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
  288. if (!InitSeq) {
  289. InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
  290. hadError = true;
  291. return;
  292. }
  293. ExprResult MemberInit
  294. = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
  295. if (MemberInit.isInvalid()) {
  296. hadError = true;
  297. return;
  298. }
  299. if (hadError) {
  300. // Do nothing
  301. } else if (Init < NumInits) {
  302. ILE->setInit(Init, MemberInit.takeAs<Expr>());
  303. } else if (InitSeq.isConstructorInitialization()) {
  304. // Value-initialization requires a constructor call, so
  305. // extend the initializer list to include the constructor
  306. // call and make a note that we'll need to take another pass
  307. // through the initializer list.
  308. ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
  309. RequiresSecondPass = true;
  310. }
  311. } else if (InitListExpr *InnerILE
  312. = dyn_cast<InitListExpr>(ILE->getInit(Init)))
  313. FillInValueInitializations(MemberEntity, InnerILE,
  314. RequiresSecondPass);
  315. }
  316. /// Recursively replaces NULL values within the given initializer list
  317. /// with expressions that perform value-initialization of the
  318. /// appropriate type.
  319. void
  320. InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
  321. InitListExpr *ILE,
  322. bool &RequiresSecondPass) {
  323. assert((ILE->getType() != SemaRef.Context.VoidTy) &&
  324. "Should not have void type");
  325. SourceLocation Loc = ILE->getSourceRange().getBegin();
  326. if (ILE->getSyntacticForm())
  327. Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
  328. if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
  329. if (RType->getDecl()->isUnion() &&
  330. ILE->getInitializedFieldInUnion())
  331. FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
  332. Entity, ILE, RequiresSecondPass);
  333. else {
  334. unsigned Init = 0;
  335. for (RecordDecl::field_iterator
  336. Field = RType->getDecl()->field_begin(),
  337. FieldEnd = RType->getDecl()->field_end();
  338. Field != FieldEnd; ++Field) {
  339. if (Field->isUnnamedBitfield())
  340. continue;
  341. if (hadError)
  342. return;
  343. FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
  344. if (hadError)
  345. return;
  346. ++Init;
  347. // Only look at the first initialization of a union.
  348. if (RType->getDecl()->isUnion())
  349. break;
  350. }
  351. }
  352. return;
  353. }
  354. QualType ElementType;
  355. InitializedEntity ElementEntity = Entity;
  356. unsigned NumInits = ILE->getNumInits();
  357. unsigned NumElements = NumInits;
  358. if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
  359. ElementType = AType->getElementType();
  360. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
  361. NumElements = CAType->getSize().getZExtValue();
  362. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  363. 0, Entity);
  364. } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
  365. ElementType = VType->getElementType();
  366. NumElements = VType->getNumElements();
  367. ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
  368. 0, Entity);
  369. } else
  370. ElementType = ILE->getType();
  371. for (unsigned Init = 0; Init != NumElements; ++Init) {
  372. if (hadError)
  373. return;
  374. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
  375. ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
  376. ElementEntity.setElementIndex(Init);
  377. Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
  378. if (!InitExpr && !ILE->hasArrayFiller()) {
  379. InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
  380. true);
  381. InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
  382. if (!InitSeq) {
  383. InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
  384. hadError = true;
  385. return;
  386. }
  387. ExprResult ElementInit
  388. = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
  389. if (ElementInit.isInvalid()) {
  390. hadError = true;
  391. return;
  392. }
  393. if (hadError) {
  394. // Do nothing
  395. } else if (Init < NumInits) {
  396. // For arrays, just set the expression used for value-initialization
  397. // of the "holes" in the array.
  398. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
  399. ILE->setArrayFiller(ElementInit.takeAs<Expr>());
  400. else
  401. ILE->setInit(Init, ElementInit.takeAs<Expr>());
  402. } else {
  403. // For arrays, just set the expression used for value-initialization
  404. // of the rest of elements and exit.
  405. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
  406. ILE->setArrayFiller(ElementInit.takeAs<Expr>());
  407. return;
  408. }
  409. if (InitSeq.isConstructorInitialization()) {
  410. // Value-initialization requires a constructor call, so
  411. // extend the initializer list to include the constructor
  412. // call and make a note that we'll need to take another pass
  413. // through the initializer list.
  414. ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
  415. RequiresSecondPass = true;
  416. }
  417. }
  418. } else if (InitListExpr *InnerILE
  419. = dyn_cast_or_null<InitListExpr>(InitExpr))
  420. FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
  421. }
  422. }
  423. InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
  424. InitListExpr *IL, QualType &T,
  425. bool VerifyOnly, bool AllowBraceElision)
  426. : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
  427. hadError = false;
  428. unsigned newIndex = 0;
  429. unsigned newStructuredIndex = 0;
  430. FullyStructuredList
  431. = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
  432. CheckExplicitInitList(Entity, IL, T, newIndex,
  433. FullyStructuredList, newStructuredIndex,
  434. /*TopLevelObject=*/true);
  435. if (!hadError && !VerifyOnly) {
  436. bool RequiresSecondPass = false;
  437. FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
  438. if (RequiresSecondPass && !hadError)
  439. FillInValueInitializations(Entity, FullyStructuredList,
  440. RequiresSecondPass);
  441. }
  442. }
  443. int InitListChecker::numArrayElements(QualType DeclType) {
  444. // FIXME: use a proper constant
  445. int maxElements = 0x7FFFFFFF;
  446. if (const ConstantArrayType *CAT =
  447. SemaRef.Context.getAsConstantArrayType(DeclType)) {
  448. maxElements = static_cast<int>(CAT->getSize().getZExtValue());
  449. }
  450. return maxElements;
  451. }
  452. int InitListChecker::numStructUnionElements(QualType DeclType) {
  453. RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
  454. int InitializableMembers = 0;
  455. for (RecordDecl::field_iterator
  456. Field = structDecl->field_begin(),
  457. FieldEnd = structDecl->field_end();
  458. Field != FieldEnd; ++Field) {
  459. if (!Field->isUnnamedBitfield())
  460. ++InitializableMembers;
  461. }
  462. if (structDecl->isUnion())
  463. return std::min(InitializableMembers, 1);
  464. return InitializableMembers - structDecl->hasFlexibleArrayMember();
  465. }
  466. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
  467. InitListExpr *ParentIList,
  468. QualType T, unsigned &Index,
  469. InitListExpr *StructuredList,
  470. unsigned &StructuredIndex) {
  471. int maxElements = 0;
  472. if (T->isArrayType())
  473. maxElements = numArrayElements(T);
  474. else if (T->isRecordType())
  475. maxElements = numStructUnionElements(T);
  476. else if (T->isVectorType())
  477. maxElements = T->getAs<VectorType>()->getNumElements();
  478. else
  479. llvm_unreachable("CheckImplicitInitList(): Illegal type");
  480. if (maxElements == 0) {
  481. if (!VerifyOnly)
  482. SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
  483. diag::err_implicit_empty_initializer);
  484. ++Index;
  485. hadError = true;
  486. return;
  487. }
  488. // Build a structured initializer list corresponding to this subobject.
  489. InitListExpr *StructuredSubobjectInitList
  490. = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
  491. StructuredIndex,
  492. SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
  493. ParentIList->getSourceRange().getEnd()));
  494. unsigned StructuredSubobjectInitIndex = 0;
  495. // Check the element types and build the structural subobject.
  496. unsigned StartIndex = Index;
  497. CheckListElementTypes(Entity, ParentIList, T,
  498. /*SubobjectIsDesignatorContext=*/false, Index,
  499. StructuredSubobjectInitList,
  500. StructuredSubobjectInitIndex);
  501. if (VerifyOnly) {
  502. if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
  503. hadError = true;
  504. } else {
  505. StructuredSubobjectInitList->setType(T);
  506. unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
  507. // Update the structured sub-object initializer so that it's ending
  508. // range corresponds with the end of the last initializer it used.
  509. if (EndIndex < ParentIList->getNumInits()) {
  510. SourceLocation EndLoc
  511. = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
  512. StructuredSubobjectInitList->setRBraceLoc(EndLoc);
  513. }
  514. // Complain about missing braces.
  515. if (T->isArrayType() || T->isRecordType()) {
  516. SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
  517. AllowBraceElision ? diag::warn_missing_braces :
  518. diag::err_missing_braces)
  519. << StructuredSubobjectInitList->getSourceRange()
  520. << FixItHint::CreateInsertion(
  521. StructuredSubobjectInitList->getLocStart(), "{")
  522. << FixItHint::CreateInsertion(
  523. SemaRef.PP.getLocForEndOfToken(
  524. StructuredSubobjectInitList->getLocEnd()),
  525. "}");
  526. if (!AllowBraceElision)
  527. hadError = true;
  528. }
  529. }
  530. }
  531. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
  532. InitListExpr *IList, QualType &T,
  533. unsigned &Index,
  534. InitListExpr *StructuredList,
  535. unsigned &StructuredIndex,
  536. bool TopLevelObject) {
  537. assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
  538. if (!VerifyOnly) {
  539. SyntacticToSemantic[IList] = StructuredList;
  540. StructuredList->setSyntacticForm(IList);
  541. }
  542. CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
  543. Index, StructuredList, StructuredIndex, TopLevelObject);
  544. if (!VerifyOnly) {
  545. QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
  546. IList->setType(ExprTy);
  547. StructuredList->setType(ExprTy);
  548. }
  549. if (hadError)
  550. return;
  551. if (Index < IList->getNumInits()) {
  552. // We have leftover initializers
  553. if (VerifyOnly) {
  554. if (SemaRef.getLangOptions().CPlusPlus ||
  555. (SemaRef.getLangOptions().OpenCL &&
  556. IList->getType()->isVectorType())) {
  557. hadError = true;
  558. }
  559. return;
  560. }
  561. if (StructuredIndex == 1 &&
  562. IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
  563. unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
  564. if (SemaRef.getLangOptions().CPlusPlus) {
  565. DK = diag::err_excess_initializers_in_char_array_initializer;
  566. hadError = true;
  567. }
  568. // Special-case
  569. SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
  570. << IList->getInit(Index)->getSourceRange();
  571. } else if (!T->isIncompleteType()) {
  572. // Don't complain for incomplete types, since we'll get an error
  573. // elsewhere
  574. QualType CurrentObjectType = StructuredList->getType();
  575. int initKind =
  576. CurrentObjectType->isArrayType()? 0 :
  577. CurrentObjectType->isVectorType()? 1 :
  578. CurrentObjectType->isScalarType()? 2 :
  579. CurrentObjectType->isUnionType()? 3 :
  580. 4;
  581. unsigned DK = diag::warn_excess_initializers;
  582. if (SemaRef.getLangOptions().CPlusPlus) {
  583. DK = diag::err_excess_initializers;
  584. hadError = true;
  585. }
  586. if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
  587. DK = diag::err_excess_initializers;
  588. hadError = true;
  589. }
  590. SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
  591. << initKind << IList->getInit(Index)->getSourceRange();
  592. }
  593. }
  594. if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
  595. !TopLevelObject)
  596. SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
  597. << IList->getSourceRange()
  598. << FixItHint::CreateRemoval(IList->getLocStart())
  599. << FixItHint::CreateRemoval(IList->getLocEnd());
  600. }
  601. void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
  602. InitListExpr *IList,
  603. QualType &DeclType,
  604. bool SubobjectIsDesignatorContext,
  605. unsigned &Index,
  606. InitListExpr *StructuredList,
  607. unsigned &StructuredIndex,
  608. bool TopLevelObject) {
  609. if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
  610. // Explicitly braced initializer for complex type can be real+imaginary
  611. // parts.
  612. CheckComplexType(Entity, IList, DeclType, Index,
  613. StructuredList, StructuredIndex);
  614. } else if (DeclType->isScalarType()) {
  615. CheckScalarType(Entity, IList, DeclType, Index,
  616. StructuredList, StructuredIndex);
  617. } else if (DeclType->isVectorType()) {
  618. CheckVectorType(Entity, IList, DeclType, Index,
  619. StructuredList, StructuredIndex);
  620. } else if (DeclType->isAggregateType()) {
  621. if (DeclType->isRecordType()) {
  622. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  623. CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
  624. SubobjectIsDesignatorContext, Index,
  625. StructuredList, StructuredIndex,
  626. TopLevelObject);
  627. } else if (DeclType->isArrayType()) {
  628. llvm::APSInt Zero(
  629. SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
  630. false);
  631. CheckArrayType(Entity, IList, DeclType, Zero,
  632. SubobjectIsDesignatorContext, Index,
  633. StructuredList, StructuredIndex);
  634. } else
  635. llvm_unreachable("Aggregate that isn't a structure or array?!");
  636. } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
  637. // This type is invalid, issue a diagnostic.
  638. ++Index;
  639. if (!VerifyOnly)
  640. SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
  641. << DeclType;
  642. hadError = true;
  643. } else if (DeclType->isRecordType()) {
  644. // C++ [dcl.init]p14:
  645. // [...] If the class is an aggregate (8.5.1), and the initializer
  646. // is a brace-enclosed list, see 8.5.1.
  647. //
  648. // Note: 8.5.1 is handled below; here, we diagnose the case where
  649. // we have an initializer list and a destination type that is not
  650. // an aggregate.
  651. // FIXME: In C++0x, this is yet another form of initialization.
  652. if (!VerifyOnly)
  653. SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
  654. << DeclType << IList->getSourceRange();
  655. hadError = true;
  656. } else if (DeclType->isReferenceType()) {
  657. CheckReferenceType(Entity, IList, DeclType, Index,
  658. StructuredList, StructuredIndex);
  659. } else if (DeclType->isObjCObjectType()) {
  660. if (!VerifyOnly)
  661. SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
  662. << DeclType;
  663. hadError = true;
  664. } else {
  665. if (!VerifyOnly)
  666. SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
  667. << DeclType;
  668. hadError = true;
  669. }
  670. }
  671. void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
  672. InitListExpr *IList,
  673. QualType ElemType,
  674. unsigned &Index,
  675. InitListExpr *StructuredList,
  676. unsigned &StructuredIndex) {
  677. Expr *expr = IList->getInit(Index);
  678. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
  679. unsigned newIndex = 0;
  680. unsigned newStructuredIndex = 0;
  681. InitListExpr *newStructuredList
  682. = getStructuredSubobjectInit(IList, Index, ElemType,
  683. StructuredList, StructuredIndex,
  684. SubInitList->getSourceRange());
  685. CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
  686. newStructuredList, newStructuredIndex);
  687. ++StructuredIndex;
  688. ++Index;
  689. return;
  690. } else if (ElemType->isScalarType()) {
  691. return CheckScalarType(Entity, IList, ElemType, Index,
  692. StructuredList, StructuredIndex);
  693. } else if (ElemType->isReferenceType()) {
  694. return CheckReferenceType(Entity, IList, ElemType, Index,
  695. StructuredList, StructuredIndex);
  696. }
  697. if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
  698. // arrayType can be incomplete if we're initializing a flexible
  699. // array member. There's nothing we can do with the completed
  700. // type here, though.
  701. if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
  702. if (!VerifyOnly) {
  703. CheckStringInit(Str, ElemType, arrayType, SemaRef);
  704. UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
  705. }
  706. ++Index;
  707. return;
  708. }
  709. // Fall through for subaggregate initialization.
  710. } else if (SemaRef.getLangOptions().CPlusPlus) {
  711. // C++ [dcl.init.aggr]p12:
  712. // All implicit type conversions (clause 4) are considered when
  713. // initializing the aggregate member with an initializer from
  714. // an initializer-list. If the initializer can initialize a
  715. // member, the member is initialized. [...]
  716. // FIXME: Better EqualLoc?
  717. InitializationKind Kind =
  718. InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
  719. InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
  720. if (Seq) {
  721. if (!VerifyOnly) {
  722. ExprResult Result =
  723. Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
  724. if (Result.isInvalid())
  725. hadError = true;
  726. UpdateStructuredListElement(StructuredList, StructuredIndex,
  727. Result.takeAs<Expr>());
  728. }
  729. ++Index;
  730. return;
  731. }
  732. // Fall through for subaggregate initialization
  733. } else {
  734. // C99 6.7.8p13:
  735. //
  736. // The initializer for a structure or union object that has
  737. // automatic storage duration shall be either an initializer
  738. // list as described below, or a single expression that has
  739. // compatible structure or union type. In the latter case, the
  740. // initial value of the object, including unnamed members, is
  741. // that of the expression.
  742. ExprResult ExprRes = SemaRef.Owned(expr);
  743. if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
  744. SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
  745. !VerifyOnly)
  746. == Sema::Compatible) {
  747. if (ExprRes.isInvalid())
  748. hadError = true;
  749. else {
  750. ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
  751. if (ExprRes.isInvalid())
  752. hadError = true;
  753. }
  754. UpdateStructuredListElement(StructuredList, StructuredIndex,
  755. ExprRes.takeAs<Expr>());
  756. ++Index;
  757. return;
  758. }
  759. ExprRes.release();
  760. // Fall through for subaggregate initialization
  761. }
  762. // C++ [dcl.init.aggr]p12:
  763. //
  764. // [...] Otherwise, if the member is itself a non-empty
  765. // subaggregate, brace elision is assumed and the initializer is
  766. // considered for the initialization of the first member of
  767. // the subaggregate.
  768. if (!SemaRef.getLangOptions().OpenCL &&
  769. (ElemType->isAggregateType() || ElemType->isVectorType())) {
  770. CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
  771. StructuredIndex);
  772. ++StructuredIndex;
  773. } else {
  774. if (!VerifyOnly) {
  775. // We cannot initialize this element, so let
  776. // PerformCopyInitialization produce the appropriate diagnostic.
  777. SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
  778. SemaRef.Owned(expr),
  779. /*TopLevelOfInitList=*/true);
  780. }
  781. hadError = true;
  782. ++Index;
  783. ++StructuredIndex;
  784. }
  785. }
  786. void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
  787. InitListExpr *IList, QualType DeclType,
  788. unsigned &Index,
  789. InitListExpr *StructuredList,
  790. unsigned &StructuredIndex) {
  791. assert(Index == 0 && "Index in explicit init list must be zero");
  792. // As an extension, clang supports complex initializers, which initialize
  793. // a complex number component-wise. When an explicit initializer list for
  794. // a complex number contains two two initializers, this extension kicks in:
  795. // it exepcts the initializer list to contain two elements convertible to
  796. // the element type of the complex type. The first element initializes
  797. // the real part, and the second element intitializes the imaginary part.
  798. if (IList->getNumInits() != 2)
  799. return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
  800. StructuredIndex);
  801. // This is an extension in C. (The builtin _Complex type does not exist
  802. // in the C++ standard.)
  803. if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
  804. SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
  805. << IList->getSourceRange();
  806. // Initialize the complex number.
  807. QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
  808. InitializedEntity ElementEntity =
  809. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  810. for (unsigned i = 0; i < 2; ++i) {
  811. ElementEntity.setElementIndex(Index);
  812. CheckSubElementType(ElementEntity, IList, elementType, Index,
  813. StructuredList, StructuredIndex);
  814. }
  815. }
  816. void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
  817. InitListExpr *IList, QualType DeclType,
  818. unsigned &Index,
  819. InitListExpr *StructuredList,
  820. unsigned &StructuredIndex) {
  821. if (Index >= IList->getNumInits()) {
  822. if (!VerifyOnly)
  823. SemaRef.Diag(IList->getLocStart(),
  824. SemaRef.getLangOptions().CPlusPlus0x ?
  825. diag::warn_cxx98_compat_empty_scalar_initializer :
  826. diag::err_empty_scalar_initializer)
  827. << IList->getSourceRange();
  828. hadError = !SemaRef.getLangOptions().CPlusPlus0x;
  829. ++Index;
  830. ++StructuredIndex;
  831. return;
  832. }
  833. Expr *expr = IList->getInit(Index);
  834. if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
  835. if (!VerifyOnly)
  836. SemaRef.Diag(SubIList->getLocStart(),
  837. diag::warn_many_braces_around_scalar_init)
  838. << SubIList->getSourceRange();
  839. CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
  840. StructuredIndex);
  841. return;
  842. } else if (isa<DesignatedInitExpr>(expr)) {
  843. if (!VerifyOnly)
  844. SemaRef.Diag(expr->getSourceRange().getBegin(),
  845. diag::err_designator_for_scalar_init)
  846. << DeclType << expr->getSourceRange();
  847. hadError = true;
  848. ++Index;
  849. ++StructuredIndex;
  850. return;
  851. }
  852. if (VerifyOnly) {
  853. if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
  854. hadError = true;
  855. ++Index;
  856. return;
  857. }
  858. ExprResult Result =
  859. SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
  860. SemaRef.Owned(expr),
  861. /*TopLevelOfInitList=*/true);
  862. Expr *ResultExpr = 0;
  863. if (Result.isInvalid())
  864. hadError = true; // types weren't compatible.
  865. else {
  866. ResultExpr = Result.takeAs<Expr>();
  867. if (ResultExpr != expr) {
  868. // The type was promoted, update initializer list.
  869. IList->setInit(Index, ResultExpr);
  870. }
  871. }
  872. if (hadError)
  873. ++StructuredIndex;
  874. else
  875. UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
  876. ++Index;
  877. }
  878. void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
  879. InitListExpr *IList, QualType DeclType,
  880. unsigned &Index,
  881. InitListExpr *StructuredList,
  882. unsigned &StructuredIndex) {
  883. if (Index >= IList->getNumInits()) {
  884. // FIXME: It would be wonderful if we could point at the actual member. In
  885. // general, it would be useful to pass location information down the stack,
  886. // so that we know the location (or decl) of the "current object" being
  887. // initialized.
  888. if (!VerifyOnly)
  889. SemaRef.Diag(IList->getLocStart(),
  890. diag::err_init_reference_member_uninitialized)
  891. << DeclType
  892. << IList->getSourceRange();
  893. hadError = true;
  894. ++Index;
  895. ++StructuredIndex;
  896. return;
  897. }
  898. Expr *expr = IList->getInit(Index);
  899. if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
  900. if (!VerifyOnly)
  901. SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
  902. << DeclType << IList->getSourceRange();
  903. hadError = true;
  904. ++Index;
  905. ++StructuredIndex;
  906. return;
  907. }
  908. if (VerifyOnly) {
  909. if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
  910. hadError = true;
  911. ++Index;
  912. return;
  913. }
  914. ExprResult Result =
  915. SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
  916. SemaRef.Owned(expr),
  917. /*TopLevelOfInitList=*/true);
  918. if (Result.isInvalid())
  919. hadError = true;
  920. expr = Result.takeAs<Expr>();
  921. IList->setInit(Index, expr);
  922. if (hadError)
  923. ++StructuredIndex;
  924. else
  925. UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
  926. ++Index;
  927. }
  928. void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
  929. InitListExpr *IList, QualType DeclType,
  930. unsigned &Index,
  931. InitListExpr *StructuredList,
  932. unsigned &StructuredIndex) {
  933. const VectorType *VT = DeclType->getAs<VectorType>();
  934. unsigned maxElements = VT->getNumElements();
  935. unsigned numEltsInit = 0;
  936. QualType elementType = VT->getElementType();
  937. if (Index >= IList->getNumInits()) {
  938. // Make sure the element type can be value-initialized.
  939. if (VerifyOnly)
  940. CheckValueInitializable(
  941. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
  942. return;
  943. }
  944. if (!SemaRef.getLangOptions().OpenCL) {
  945. // If the initializing element is a vector, try to copy-initialize
  946. // instead of breaking it apart (which is doomed to failure anyway).
  947. Expr *Init = IList->getInit(Index);
  948. if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
  949. if (VerifyOnly) {
  950. if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
  951. hadError = true;
  952. ++Index;
  953. return;
  954. }
  955. ExprResult Result =
  956. SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
  957. SemaRef.Owned(Init),
  958. /*TopLevelOfInitList=*/true);
  959. Expr *ResultExpr = 0;
  960. if (Result.isInvalid())
  961. hadError = true; // types weren't compatible.
  962. else {
  963. ResultExpr = Result.takeAs<Expr>();
  964. if (ResultExpr != Init) {
  965. // The type was promoted, update initializer list.
  966. IList->setInit(Index, ResultExpr);
  967. }
  968. }
  969. if (hadError)
  970. ++StructuredIndex;
  971. else
  972. UpdateStructuredListElement(StructuredList, StructuredIndex,
  973. ResultExpr);
  974. ++Index;
  975. return;
  976. }
  977. InitializedEntity ElementEntity =
  978. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  979. for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
  980. // Don't attempt to go past the end of the init list
  981. if (Index >= IList->getNumInits()) {
  982. if (VerifyOnly)
  983. CheckValueInitializable(ElementEntity);
  984. break;
  985. }
  986. ElementEntity.setElementIndex(Index);
  987. CheckSubElementType(ElementEntity, IList, elementType, Index,
  988. StructuredList, StructuredIndex);
  989. }
  990. return;
  991. }
  992. InitializedEntity ElementEntity =
  993. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  994. // OpenCL initializers allows vectors to be constructed from vectors.
  995. for (unsigned i = 0; i < maxElements; ++i) {
  996. // Don't attempt to go past the end of the init list
  997. if (Index >= IList->getNumInits())
  998. break;
  999. ElementEntity.setElementIndex(Index);
  1000. QualType IType = IList->getInit(Index)->getType();
  1001. if (!IType->isVectorType()) {
  1002. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1003. StructuredList, StructuredIndex);
  1004. ++numEltsInit;
  1005. } else {
  1006. QualType VecType;
  1007. const VectorType *IVT = IType->getAs<VectorType>();
  1008. unsigned numIElts = IVT->getNumElements();
  1009. if (IType->isExtVectorType())
  1010. VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
  1011. else
  1012. VecType = SemaRef.Context.getVectorType(elementType, numIElts,
  1013. IVT->getVectorKind());
  1014. CheckSubElementType(ElementEntity, IList, VecType, Index,
  1015. StructuredList, StructuredIndex);
  1016. numEltsInit += numIElts;
  1017. }
  1018. }
  1019. // OpenCL requires all elements to be initialized.
  1020. if (numEltsInit != maxElements) {
  1021. if (!VerifyOnly)
  1022. SemaRef.Diag(IList->getSourceRange().getBegin(),
  1023. diag::err_vector_incorrect_num_initializers)
  1024. << (numEltsInit < maxElements) << maxElements << numEltsInit;
  1025. hadError = true;
  1026. }
  1027. }
  1028. void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
  1029. InitListExpr *IList, QualType &DeclType,
  1030. llvm::APSInt elementIndex,
  1031. bool SubobjectIsDesignatorContext,
  1032. unsigned &Index,
  1033. InitListExpr *StructuredList,
  1034. unsigned &StructuredIndex) {
  1035. const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
  1036. // Check for the special-case of initializing an array with a string.
  1037. if (Index < IList->getNumInits()) {
  1038. if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
  1039. SemaRef.Context)) {
  1040. // We place the string literal directly into the resulting
  1041. // initializer list. This is the only place where the structure
  1042. // of the structured initializer list doesn't match exactly,
  1043. // because doing so would involve allocating one character
  1044. // constant for each string.
  1045. if (!VerifyOnly) {
  1046. CheckStringInit(Str, DeclType, arrayType, SemaRef);
  1047. UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
  1048. StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
  1049. }
  1050. ++Index;
  1051. return;
  1052. }
  1053. }
  1054. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
  1055. // Check for VLAs; in standard C it would be possible to check this
  1056. // earlier, but I don't know where clang accepts VLAs (gcc accepts
  1057. // them in all sorts of strange places).
  1058. if (!VerifyOnly)
  1059. SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
  1060. diag::err_variable_object_no_init)
  1061. << VAT->getSizeExpr()->getSourceRange();
  1062. hadError = true;
  1063. ++Index;
  1064. ++StructuredIndex;
  1065. return;
  1066. }
  1067. // We might know the maximum number of elements in advance.
  1068. llvm::APSInt maxElements(elementIndex.getBitWidth(),
  1069. elementIndex.isUnsigned());
  1070. bool maxElementsKnown = false;
  1071. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
  1072. maxElements = CAT->getSize();
  1073. elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
  1074. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1075. maxElementsKnown = true;
  1076. }
  1077. QualType elementType = arrayType->getElementType();
  1078. while (Index < IList->getNumInits()) {
  1079. Expr *Init = IList->getInit(Index);
  1080. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1081. // If we're not the subobject that matches up with the '{' for
  1082. // the designator, we shouldn't be handling the
  1083. // designator. Return immediately.
  1084. if (!SubobjectIsDesignatorContext)
  1085. return;
  1086. // Handle this designated initializer. elementIndex will be
  1087. // updated to be the next array element we'll initialize.
  1088. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1089. DeclType, 0, &elementIndex, Index,
  1090. StructuredList, StructuredIndex, true,
  1091. false)) {
  1092. hadError = true;
  1093. continue;
  1094. }
  1095. if (elementIndex.getBitWidth() > maxElements.getBitWidth())
  1096. maxElements = maxElements.extend(elementIndex.getBitWidth());
  1097. else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
  1098. elementIndex = elementIndex.extend(maxElements.getBitWidth());
  1099. elementIndex.setIsUnsigned(maxElements.isUnsigned());
  1100. // If the array is of incomplete type, keep track of the number of
  1101. // elements in the initializer.
  1102. if (!maxElementsKnown && elementIndex > maxElements)
  1103. maxElements = elementIndex;
  1104. continue;
  1105. }
  1106. // If we know the maximum number of elements, and we've already
  1107. // hit it, stop consuming elements in the initializer list.
  1108. if (maxElementsKnown && elementIndex == maxElements)
  1109. break;
  1110. InitializedEntity ElementEntity =
  1111. InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
  1112. Entity);
  1113. // Check this element.
  1114. CheckSubElementType(ElementEntity, IList, elementType, Index,
  1115. StructuredList, StructuredIndex);
  1116. ++elementIndex;
  1117. // If the array is of incomplete type, keep track of the number of
  1118. // elements in the initializer.
  1119. if (!maxElementsKnown && elementIndex > maxElements)
  1120. maxElements = elementIndex;
  1121. }
  1122. if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
  1123. // If this is an incomplete array type, the actual type needs to
  1124. // be calculated here.
  1125. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
  1126. if (maxElements == Zero) {
  1127. // Sizing an array implicitly to zero is not allowed by ISO C,
  1128. // but is supported by GNU.
  1129. SemaRef.Diag(IList->getLocStart(),
  1130. diag::ext_typecheck_zero_array_size);
  1131. }
  1132. DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
  1133. ArrayType::Normal, 0);
  1134. }
  1135. if (!hadError && VerifyOnly) {
  1136. // Check if there are any members of the array that get value-initialized.
  1137. // If so, check if doing that is possible.
  1138. // FIXME: This needs to detect holes left by designated initializers too.
  1139. if (maxElementsKnown && elementIndex < maxElements)
  1140. CheckValueInitializable(InitializedEntity::InitializeElement(
  1141. SemaRef.Context, 0, Entity));
  1142. }
  1143. }
  1144. bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
  1145. Expr *InitExpr,
  1146. FieldDecl *Field,
  1147. bool TopLevelObject) {
  1148. // Handle GNU flexible array initializers.
  1149. unsigned FlexArrayDiag;
  1150. if (isa<InitListExpr>(InitExpr) &&
  1151. cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
  1152. // Empty flexible array init always allowed as an extension
  1153. FlexArrayDiag = diag::ext_flexible_array_init;
  1154. } else if (SemaRef.getLangOptions().CPlusPlus) {
  1155. // Disallow flexible array init in C++; it is not required for gcc
  1156. // compatibility, and it needs work to IRGen correctly in general.
  1157. FlexArrayDiag = diag::err_flexible_array_init;
  1158. } else if (!TopLevelObject) {
  1159. // Disallow flexible array init on non-top-level object
  1160. FlexArrayDiag = diag::err_flexible_array_init;
  1161. } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
  1162. // Disallow flexible array init on anything which is not a variable.
  1163. FlexArrayDiag = diag::err_flexible_array_init;
  1164. } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
  1165. // Disallow flexible array init on local variables.
  1166. FlexArrayDiag = diag::err_flexible_array_init;
  1167. } else {
  1168. // Allow other cases.
  1169. FlexArrayDiag = diag::ext_flexible_array_init;
  1170. }
  1171. if (!VerifyOnly) {
  1172. SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
  1173. FlexArrayDiag)
  1174. << InitExpr->getSourceRange().getBegin();
  1175. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1176. << Field;
  1177. }
  1178. return FlexArrayDiag != diag::ext_flexible_array_init;
  1179. }
  1180. void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
  1181. InitListExpr *IList,
  1182. QualType DeclType,
  1183. RecordDecl::field_iterator Field,
  1184. bool SubobjectIsDesignatorContext,
  1185. unsigned &Index,
  1186. InitListExpr *StructuredList,
  1187. unsigned &StructuredIndex,
  1188. bool TopLevelObject) {
  1189. RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
  1190. // If the record is invalid, some of it's members are invalid. To avoid
  1191. // confusion, we forgo checking the intializer for the entire record.
  1192. if (structDecl->isInvalidDecl()) {
  1193. hadError = true;
  1194. return;
  1195. }
  1196. if (DeclType->isUnionType() && IList->getNumInits() == 0) {
  1197. // Value-initialize the first named member of the union.
  1198. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1199. for (RecordDecl::field_iterator FieldEnd = RD->field_end();
  1200. Field != FieldEnd; ++Field) {
  1201. if (Field->getDeclName()) {
  1202. if (VerifyOnly)
  1203. CheckValueInitializable(
  1204. InitializedEntity::InitializeMember(*Field, &Entity));
  1205. else
  1206. StructuredList->setInitializedFieldInUnion(*Field);
  1207. break;
  1208. }
  1209. }
  1210. return;
  1211. }
  1212. // If structDecl is a forward declaration, this loop won't do
  1213. // anything except look at designated initializers; That's okay,
  1214. // because an error should get printed out elsewhere. It might be
  1215. // worthwhile to skip over the rest of the initializer, though.
  1216. RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
  1217. RecordDecl::field_iterator FieldEnd = RD->field_end();
  1218. bool InitializedSomething = false;
  1219. bool CheckForMissingFields = true;
  1220. while (Index < IList->getNumInits()) {
  1221. Expr *Init = IList->getInit(Index);
  1222. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
  1223. // If we're not the subobject that matches up with the '{' for
  1224. // the designator, we shouldn't be handling the
  1225. // designator. Return immediately.
  1226. if (!SubobjectIsDesignatorContext)
  1227. return;
  1228. // Handle this designated initializer. Field will be updated to
  1229. // the next field that we'll be initializing.
  1230. if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
  1231. DeclType, &Field, 0, Index,
  1232. StructuredList, StructuredIndex,
  1233. true, TopLevelObject))
  1234. hadError = true;
  1235. InitializedSomething = true;
  1236. // Disable check for missing fields when designators are used.
  1237. // This matches gcc behaviour.
  1238. CheckForMissingFields = false;
  1239. continue;
  1240. }
  1241. if (Field == FieldEnd) {
  1242. // We've run out of fields. We're done.
  1243. break;
  1244. }
  1245. // We've already initialized a member of a union. We're done.
  1246. if (InitializedSomething && DeclType->isUnionType())
  1247. break;
  1248. // If we've hit the flexible array member at the end, we're done.
  1249. if (Field->getType()->isIncompleteArrayType())
  1250. break;
  1251. if (Field->isUnnamedBitfield()) {
  1252. // Don't initialize unnamed bitfields, e.g. "int : 20;"
  1253. ++Field;
  1254. continue;
  1255. }
  1256. // Make sure we can use this declaration.
  1257. bool InvalidUse;
  1258. if (VerifyOnly)
  1259. InvalidUse = !SemaRef.CanUseDecl(*Field);
  1260. else
  1261. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
  1262. IList->getInit(Index)->getLocStart());
  1263. if (InvalidUse) {
  1264. ++Index;
  1265. ++Field;
  1266. hadError = true;
  1267. continue;
  1268. }
  1269. InitializedEntity MemberEntity =
  1270. InitializedEntity::InitializeMember(*Field, &Entity);
  1271. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1272. StructuredList, StructuredIndex);
  1273. InitializedSomething = true;
  1274. if (DeclType->isUnionType() && !VerifyOnly) {
  1275. // Initialize the first field within the union.
  1276. StructuredList->setInitializedFieldInUnion(*Field);
  1277. }
  1278. ++Field;
  1279. }
  1280. // Emit warnings for missing struct field initializers.
  1281. if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
  1282. Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
  1283. !DeclType->isUnionType()) {
  1284. // It is possible we have one or more unnamed bitfields remaining.
  1285. // Find first (if any) named field and emit warning.
  1286. for (RecordDecl::field_iterator it = Field, end = RD->field_end();
  1287. it != end; ++it) {
  1288. if (!it->isUnnamedBitfield()) {
  1289. SemaRef.Diag(IList->getSourceRange().getEnd(),
  1290. diag::warn_missing_field_initializers) << it->getName();
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. // Check that any remaining fields can be value-initialized.
  1296. if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
  1297. !Field->getType()->isIncompleteArrayType()) {
  1298. // FIXME: Should check for holes left by designated initializers too.
  1299. for (; Field != FieldEnd && !hadError; ++Field) {
  1300. if (!Field->isUnnamedBitfield())
  1301. CheckValueInitializable(
  1302. InitializedEntity::InitializeMember(*Field, &Entity));
  1303. }
  1304. }
  1305. if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
  1306. Index >= IList->getNumInits())
  1307. return;
  1308. if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
  1309. TopLevelObject)) {
  1310. hadError = true;
  1311. ++Index;
  1312. return;
  1313. }
  1314. InitializedEntity MemberEntity =
  1315. InitializedEntity::InitializeMember(*Field, &Entity);
  1316. if (isa<InitListExpr>(IList->getInit(Index)))
  1317. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1318. StructuredList, StructuredIndex);
  1319. else
  1320. CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
  1321. StructuredList, StructuredIndex);
  1322. }
  1323. /// \brief Expand a field designator that refers to a member of an
  1324. /// anonymous struct or union into a series of field designators that
  1325. /// refers to the field within the appropriate subobject.
  1326. ///
  1327. static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
  1328. DesignatedInitExpr *DIE,
  1329. unsigned DesigIdx,
  1330. IndirectFieldDecl *IndirectField) {
  1331. typedef DesignatedInitExpr::Designator Designator;
  1332. // Build the replacement designators.
  1333. SmallVector<Designator, 4> Replacements;
  1334. for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
  1335. PE = IndirectField->chain_end(); PI != PE; ++PI) {
  1336. if (PI + 1 == PE)
  1337. Replacements.push_back(Designator((IdentifierInfo *)0,
  1338. DIE->getDesignator(DesigIdx)->getDotLoc(),
  1339. DIE->getDesignator(DesigIdx)->getFieldLoc()));
  1340. else
  1341. Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
  1342. SourceLocation()));
  1343. assert(isa<FieldDecl>(*PI));
  1344. Replacements.back().setField(cast<FieldDecl>(*PI));
  1345. }
  1346. // Expand the current designator into the set of replacement
  1347. // designators, so we have a full subobject path down to where the
  1348. // member of the anonymous struct/union is actually stored.
  1349. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
  1350. &Replacements[0] + Replacements.size());
  1351. }
  1352. /// \brief Given an implicit anonymous field, search the IndirectField that
  1353. /// corresponds to FieldName.
  1354. static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
  1355. IdentifierInfo *FieldName) {
  1356. assert(AnonField->isAnonymousStructOrUnion());
  1357. Decl *NextDecl = AnonField->getNextDeclInContext();
  1358. while (IndirectFieldDecl *IF =
  1359. dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
  1360. if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
  1361. return IF;
  1362. NextDecl = NextDecl->getNextDeclInContext();
  1363. }
  1364. return 0;
  1365. }
  1366. static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
  1367. DesignatedInitExpr *DIE) {
  1368. unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
  1369. SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
  1370. for (unsigned I = 0; I < NumIndexExprs; ++I)
  1371. IndexExprs[I] = DIE->getSubExpr(I + 1);
  1372. return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
  1373. DIE->size(), IndexExprs.data(),
  1374. NumIndexExprs, DIE->getEqualOrColonLoc(),
  1375. DIE->usesGNUSyntax(), DIE->getInit());
  1376. }
  1377. namespace {
  1378. // Callback to only accept typo corrections that are for field members of
  1379. // the given struct or union.
  1380. class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
  1381. public:
  1382. explicit FieldInitializerValidatorCCC(RecordDecl *RD)
  1383. : Record(RD) {}
  1384. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  1385. FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
  1386. return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
  1387. }
  1388. private:
  1389. RecordDecl *Record;
  1390. };
  1391. }
  1392. /// @brief Check the well-formedness of a C99 designated initializer.
  1393. ///
  1394. /// Determines whether the designated initializer @p DIE, which
  1395. /// resides at the given @p Index within the initializer list @p
  1396. /// IList, is well-formed for a current object of type @p DeclType
  1397. /// (C99 6.7.8). The actual subobject that this designator refers to
  1398. /// within the current subobject is returned in either
  1399. /// @p NextField or @p NextElementIndex (whichever is appropriate).
  1400. ///
  1401. /// @param IList The initializer list in which this designated
  1402. /// initializer occurs.
  1403. ///
  1404. /// @param DIE The designated initializer expression.
  1405. ///
  1406. /// @param DesigIdx The index of the current designator.
  1407. ///
  1408. /// @param DeclType The type of the "current object" (C99 6.7.8p17),
  1409. /// into which the designation in @p DIE should refer.
  1410. ///
  1411. /// @param NextField If non-NULL and the first designator in @p DIE is
  1412. /// a field, this will be set to the field declaration corresponding
  1413. /// to the field named by the designator.
  1414. ///
  1415. /// @param NextElementIndex If non-NULL and the first designator in @p
  1416. /// DIE is an array designator or GNU array-range designator, this
  1417. /// will be set to the last index initialized by this designator.
  1418. ///
  1419. /// @param Index Index into @p IList where the designated initializer
  1420. /// @p DIE occurs.
  1421. ///
  1422. /// @param StructuredList The initializer list expression that
  1423. /// describes all of the subobject initializers in the order they'll
  1424. /// actually be initialized.
  1425. ///
  1426. /// @returns true if there was an error, false otherwise.
  1427. bool
  1428. InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
  1429. InitListExpr *IList,
  1430. DesignatedInitExpr *DIE,
  1431. unsigned DesigIdx,
  1432. QualType &CurrentObjectType,
  1433. RecordDecl::field_iterator *NextField,
  1434. llvm::APSInt *NextElementIndex,
  1435. unsigned &Index,
  1436. InitListExpr *StructuredList,
  1437. unsigned &StructuredIndex,
  1438. bool FinishSubobjectInit,
  1439. bool TopLevelObject) {
  1440. if (DesigIdx == DIE->size()) {
  1441. // Check the actual initialization for the designated object type.
  1442. bool prevHadError = hadError;
  1443. // Temporarily remove the designator expression from the
  1444. // initializer list that the child calls see, so that we don't try
  1445. // to re-process the designator.
  1446. unsigned OldIndex = Index;
  1447. IList->setInit(OldIndex, DIE->getInit());
  1448. CheckSubElementType(Entity, IList, CurrentObjectType, Index,
  1449. StructuredList, StructuredIndex);
  1450. // Restore the designated initializer expression in the syntactic
  1451. // form of the initializer list.
  1452. if (IList->getInit(OldIndex) != DIE->getInit())
  1453. DIE->setInit(IList->getInit(OldIndex));
  1454. IList->setInit(OldIndex, DIE);
  1455. return hadError && !prevHadError;
  1456. }
  1457. DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
  1458. bool IsFirstDesignator = (DesigIdx == 0);
  1459. if (!VerifyOnly) {
  1460. assert((IsFirstDesignator || StructuredList) &&
  1461. "Need a non-designated initializer list to start from");
  1462. // Determine the structural initializer list that corresponds to the
  1463. // current subobject.
  1464. StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
  1465. : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
  1466. StructuredList, StructuredIndex,
  1467. SourceRange(D->getStartLocation(),
  1468. DIE->getSourceRange().getEnd()));
  1469. assert(StructuredList && "Expected a structured initializer list");
  1470. }
  1471. if (D->isFieldDesignator()) {
  1472. // C99 6.7.8p7:
  1473. //
  1474. // If a designator has the form
  1475. //
  1476. // . identifier
  1477. //
  1478. // then the current object (defined below) shall have
  1479. // structure or union type and the identifier shall be the
  1480. // name of a member of that type.
  1481. const RecordType *RT = CurrentObjectType->getAs<RecordType>();
  1482. if (!RT) {
  1483. SourceLocation Loc = D->getDotLoc();
  1484. if (Loc.isInvalid())
  1485. Loc = D->getFieldLoc();
  1486. if (!VerifyOnly)
  1487. SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
  1488. << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
  1489. ++Index;
  1490. return true;
  1491. }
  1492. // Note: we perform a linear search of the fields here, despite
  1493. // the fact that we have a faster lookup method, because we always
  1494. // need to compute the field's index.
  1495. FieldDecl *KnownField = D->getField();
  1496. IdentifierInfo *FieldName = D->getFieldName();
  1497. unsigned FieldIndex = 0;
  1498. RecordDecl::field_iterator
  1499. Field = RT->getDecl()->field_begin(),
  1500. FieldEnd = RT->getDecl()->field_end();
  1501. for (; Field != FieldEnd; ++Field) {
  1502. if (Field->isUnnamedBitfield())
  1503. continue;
  1504. // If we find a field representing an anonymous field, look in the
  1505. // IndirectFieldDecl that follow for the designated initializer.
  1506. if (!KnownField && Field->isAnonymousStructOrUnion()) {
  1507. if (IndirectFieldDecl *IF =
  1508. FindIndirectFieldDesignator(*Field, FieldName)) {
  1509. // In verify mode, don't modify the original.
  1510. if (VerifyOnly)
  1511. DIE = CloneDesignatedInitExpr(SemaRef, DIE);
  1512. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
  1513. D = DIE->getDesignator(DesigIdx);
  1514. break;
  1515. }
  1516. }
  1517. if (KnownField && KnownField == *Field)
  1518. break;
  1519. if (FieldName && FieldName == Field->getIdentifier())
  1520. break;
  1521. ++FieldIndex;
  1522. }
  1523. if (Field == FieldEnd) {
  1524. if (VerifyOnly) {
  1525. ++Index;
  1526. return true; // No typo correction when just trying this out.
  1527. }
  1528. // There was no normal field in the struct with the designated
  1529. // name. Perform another lookup for this name, which may find
  1530. // something that we can't designate (e.g., a member function),
  1531. // may find nothing, or may find a member of an anonymous
  1532. // struct/union.
  1533. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
  1534. FieldDecl *ReplacementField = 0;
  1535. if (Lookup.first == Lookup.second) {
  1536. // Name lookup didn't find anything. Determine whether this
  1537. // was a typo for another field name.
  1538. FieldInitializerValidatorCCC Validator(RT->getDecl());
  1539. TypoCorrection Corrected = SemaRef.CorrectTypo(
  1540. DeclarationNameInfo(FieldName, D->getFieldLoc()),
  1541. Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
  1542. RT->getDecl());
  1543. if (Corrected) {
  1544. std::string CorrectedStr(
  1545. Corrected.getAsString(SemaRef.getLangOptions()));
  1546. std::string CorrectedQuotedStr(
  1547. Corrected.getQuoted(SemaRef.getLangOptions()));
  1548. ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
  1549. SemaRef.Diag(D->getFieldLoc(),
  1550. diag::err_field_designator_unknown_suggest)
  1551. << FieldName << CurrentObjectType << CorrectedQuotedStr
  1552. << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
  1553. SemaRef.Diag(ReplacementField->getLocation(),
  1554. diag::note_previous_decl) << CorrectedQuotedStr;
  1555. hadError = true;
  1556. } else {
  1557. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
  1558. << FieldName << CurrentObjectType;
  1559. ++Index;
  1560. return true;
  1561. }
  1562. }
  1563. if (!ReplacementField) {
  1564. // Name lookup found something, but it wasn't a field.
  1565. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
  1566. << FieldName;
  1567. SemaRef.Diag((*Lookup.first)->getLocation(),
  1568. diag::note_field_designator_found);
  1569. ++Index;
  1570. return true;
  1571. }
  1572. if (!KnownField) {
  1573. // The replacement field comes from typo correction; find it
  1574. // in the list of fields.
  1575. FieldIndex = 0;
  1576. Field = RT->getDecl()->field_begin();
  1577. for (; Field != FieldEnd; ++Field) {
  1578. if (Field->isUnnamedBitfield())
  1579. continue;
  1580. if (ReplacementField == *Field ||
  1581. Field->getIdentifier() == ReplacementField->getIdentifier())
  1582. break;
  1583. ++FieldIndex;
  1584. }
  1585. }
  1586. }
  1587. // All of the fields of a union are located at the same place in
  1588. // the initializer list.
  1589. if (RT->getDecl()->isUnion()) {
  1590. FieldIndex = 0;
  1591. if (!VerifyOnly)
  1592. StructuredList->setInitializedFieldInUnion(*Field);
  1593. }
  1594. // Make sure we can use this declaration.
  1595. bool InvalidUse;
  1596. if (VerifyOnly)
  1597. InvalidUse = !SemaRef.CanUseDecl(*Field);
  1598. else
  1599. InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
  1600. if (InvalidUse) {
  1601. ++Index;
  1602. return true;
  1603. }
  1604. if (!VerifyOnly) {
  1605. // Update the designator with the field declaration.
  1606. D->setField(*Field);
  1607. // Make sure that our non-designated initializer list has space
  1608. // for a subobject corresponding to this field.
  1609. if (FieldIndex >= StructuredList->getNumInits())
  1610. StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
  1611. }
  1612. // This designator names a flexible array member.
  1613. if (Field->getType()->isIncompleteArrayType()) {
  1614. bool Invalid = false;
  1615. if ((DesigIdx + 1) != DIE->size()) {
  1616. // We can't designate an object within the flexible array
  1617. // member (because GCC doesn't allow it).
  1618. if (!VerifyOnly) {
  1619. DesignatedInitExpr::Designator *NextD
  1620. = DIE->getDesignator(DesigIdx + 1);
  1621. SemaRef.Diag(NextD->getStartLocation(),
  1622. diag::err_designator_into_flexible_array_member)
  1623. << SourceRange(NextD->getStartLocation(),
  1624. DIE->getSourceRange().getEnd());
  1625. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1626. << *Field;
  1627. }
  1628. Invalid = true;
  1629. }
  1630. if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
  1631. !isa<StringLiteral>(DIE->getInit())) {
  1632. // The initializer is not an initializer list.
  1633. if (!VerifyOnly) {
  1634. SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
  1635. diag::err_flexible_array_init_needs_braces)
  1636. << DIE->getInit()->getSourceRange();
  1637. SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
  1638. << *Field;
  1639. }
  1640. Invalid = true;
  1641. }
  1642. // Check GNU flexible array initializer.
  1643. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
  1644. TopLevelObject))
  1645. Invalid = true;
  1646. if (Invalid) {
  1647. ++Index;
  1648. return true;
  1649. }
  1650. // Initialize the array.
  1651. bool prevHadError = hadError;
  1652. unsigned newStructuredIndex = FieldIndex;
  1653. unsigned OldIndex = Index;
  1654. IList->setInit(Index, DIE->getInit());
  1655. InitializedEntity MemberEntity =
  1656. InitializedEntity::InitializeMember(*Field, &Entity);
  1657. CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
  1658. StructuredList, newStructuredIndex);
  1659. IList->setInit(OldIndex, DIE);
  1660. if (hadError && !prevHadError) {
  1661. ++Field;
  1662. ++FieldIndex;
  1663. if (NextField)
  1664. *NextField = Field;
  1665. StructuredIndex = FieldIndex;
  1666. return true;
  1667. }
  1668. } else {
  1669. // Recurse to check later designated subobjects.
  1670. QualType FieldType = (*Field)->getType();
  1671. unsigned newStructuredIndex = FieldIndex;
  1672. InitializedEntity MemberEntity =
  1673. InitializedEntity::InitializeMember(*Field, &Entity);
  1674. if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
  1675. FieldType, 0, 0, Index,
  1676. StructuredList, newStructuredIndex,
  1677. true, false))
  1678. return true;
  1679. }
  1680. // Find the position of the next field to be initialized in this
  1681. // subobject.
  1682. ++Field;
  1683. ++FieldIndex;
  1684. // If this the first designator, our caller will continue checking
  1685. // the rest of this struct/class/union subobject.
  1686. if (IsFirstDesignator) {
  1687. if (NextField)
  1688. *NextField = Field;
  1689. StructuredIndex = FieldIndex;
  1690. return false;
  1691. }
  1692. if (!FinishSubobjectInit)
  1693. return false;
  1694. // We've already initialized something in the union; we're done.
  1695. if (RT->getDecl()->isUnion())
  1696. return hadError;
  1697. // Check the remaining fields within this class/struct/union subobject.
  1698. bool prevHadError = hadError;
  1699. CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
  1700. StructuredList, FieldIndex);
  1701. return hadError && !prevHadError;
  1702. }
  1703. // C99 6.7.8p6:
  1704. //
  1705. // If a designator has the form
  1706. //
  1707. // [ constant-expression ]
  1708. //
  1709. // then the current object (defined below) shall have array
  1710. // type and the expression shall be an integer constant
  1711. // expression. If the array is of unknown size, any
  1712. // nonnegative value is valid.
  1713. //
  1714. // Additionally, cope with the GNU extension that permits
  1715. // designators of the form
  1716. //
  1717. // [ constant-expression ... constant-expression ]
  1718. const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
  1719. if (!AT) {
  1720. if (!VerifyOnly)
  1721. SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
  1722. << CurrentObjectType;
  1723. ++Index;
  1724. return true;
  1725. }
  1726. Expr *IndexExpr = 0;
  1727. llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
  1728. if (D->isArrayDesignator()) {
  1729. IndexExpr = DIE->getArrayIndex(*D);
  1730. DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
  1731. DesignatedEndIndex = DesignatedStartIndex;
  1732. } else {
  1733. assert(D->isArrayRangeDesignator() && "Need array-range designator");
  1734. DesignatedStartIndex =
  1735. DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
  1736. DesignatedEndIndex =
  1737. DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
  1738. IndexExpr = DIE->getArrayRangeEnd(*D);
  1739. // Codegen can't handle evaluating array range designators that have side
  1740. // effects, because we replicate the AST value for each initialized element.
  1741. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
  1742. // elements with something that has a side effect, so codegen can emit an
  1743. // "error unsupported" error instead of miscompiling the app.
  1744. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
  1745. DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
  1746. FullyStructuredList->sawArrayRangeDesignator();
  1747. }
  1748. if (isa<ConstantArrayType>(AT)) {
  1749. llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
  1750. DesignatedStartIndex
  1751. = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
  1752. DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
  1753. DesignatedEndIndex
  1754. = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
  1755. DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
  1756. if (DesignatedEndIndex >= MaxElements) {
  1757. if (!VerifyOnly)
  1758. SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
  1759. diag::err_array_designator_too_large)
  1760. << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
  1761. << IndexExpr->getSourceRange();
  1762. ++Index;
  1763. return true;
  1764. }
  1765. } else {
  1766. // Make sure the bit-widths and signedness match.
  1767. if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
  1768. DesignatedEndIndex
  1769. = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
  1770. else if (DesignatedStartIndex.getBitWidth() <
  1771. DesignatedEndIndex.getBitWidth())
  1772. DesignatedStartIndex
  1773. = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
  1774. DesignatedStartIndex.setIsUnsigned(true);
  1775. DesignatedEndIndex.setIsUnsigned(true);
  1776. }
  1777. // Make sure that our non-designated initializer list has space
  1778. // for a subobject corresponding to this array element.
  1779. if (!VerifyOnly &&
  1780. DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
  1781. StructuredList->resizeInits(SemaRef.Context,
  1782. DesignatedEndIndex.getZExtValue() + 1);
  1783. // Repeatedly perform subobject initializations in the range
  1784. // [DesignatedStartIndex, DesignatedEndIndex].
  1785. // Move to the next designator
  1786. unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
  1787. unsigned OldIndex = Index;
  1788. InitializedEntity ElementEntity =
  1789. InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
  1790. while (DesignatedStartIndex <= DesignatedEndIndex) {
  1791. // Recurse to check later designated subobjects.
  1792. QualType ElementType = AT->getElementType();
  1793. Index = OldIndex;
  1794. ElementEntity.setElementIndex(ElementIndex);
  1795. if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
  1796. ElementType, 0, 0, Index,
  1797. StructuredList, ElementIndex,
  1798. (DesignatedStartIndex == DesignatedEndIndex),
  1799. false))
  1800. return true;
  1801. // Move to the next index in the array that we'll be initializing.
  1802. ++DesignatedStartIndex;
  1803. ElementIndex = DesignatedStartIndex.getZExtValue();
  1804. }
  1805. // If this the first designator, our caller will continue checking
  1806. // the rest of this array subobject.
  1807. if (IsFirstDesignator) {
  1808. if (NextElementIndex)
  1809. *NextElementIndex = DesignatedStartIndex;
  1810. StructuredIndex = ElementIndex;
  1811. return false;
  1812. }
  1813. if (!FinishSubobjectInit)
  1814. return false;
  1815. // Check the remaining elements within this array subobject.
  1816. bool prevHadError = hadError;
  1817. CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
  1818. /*SubobjectIsDesignatorContext=*/false, Index,
  1819. StructuredList, ElementIndex);
  1820. return hadError && !prevHadError;
  1821. }
  1822. // Get the structured initializer list for a subobject of type
  1823. // @p CurrentObjectType.
  1824. InitListExpr *
  1825. InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
  1826. QualType CurrentObjectType,
  1827. InitListExpr *StructuredList,
  1828. unsigned StructuredIndex,
  1829. SourceRange InitRange) {
  1830. if (VerifyOnly)
  1831. return 0; // No structured list in verification-only mode.
  1832. Expr *ExistingInit = 0;
  1833. if (!StructuredList)
  1834. ExistingInit = SyntacticToSemantic[IList];
  1835. else if (StructuredIndex < StructuredList->getNumInits())
  1836. ExistingInit = StructuredList->getInit(StructuredIndex);
  1837. if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
  1838. return Result;
  1839. if (ExistingInit) {
  1840. // We are creating an initializer list that initializes the
  1841. // subobjects of the current object, but there was already an
  1842. // initialization that completely initialized the current
  1843. // subobject, e.g., by a compound literal:
  1844. //
  1845. // struct X { int a, b; };
  1846. // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
  1847. //
  1848. // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
  1849. // designated initializer re-initializes the whole
  1850. // subobject [0], overwriting previous initializers.
  1851. SemaRef.Diag(InitRange.getBegin(),
  1852. diag::warn_subobject_initializer_overrides)
  1853. << InitRange;
  1854. SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
  1855. diag::note_previous_initializer)
  1856. << /*FIXME:has side effects=*/0
  1857. << ExistingInit->getSourceRange();
  1858. }
  1859. InitListExpr *Result
  1860. = new (SemaRef.Context) InitListExpr(SemaRef.Context,
  1861. InitRange.getBegin(), 0, 0,
  1862. InitRange.getEnd());
  1863. Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
  1864. // Pre-allocate storage for the structured initializer list.
  1865. unsigned NumElements = 0;
  1866. unsigned NumInits = 0;
  1867. bool GotNumInits = false;
  1868. if (!StructuredList) {
  1869. NumInits = IList->getNumInits();
  1870. GotNumInits = true;
  1871. } else if (Index < IList->getNumInits()) {
  1872. if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
  1873. NumInits = SubList->getNumInits();
  1874. GotNumInits = true;
  1875. }
  1876. }
  1877. if (const ArrayType *AType
  1878. = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
  1879. if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
  1880. NumElements = CAType->getSize().getZExtValue();
  1881. // Simple heuristic so that we don't allocate a very large
  1882. // initializer with many empty entries at the end.
  1883. if (GotNumInits && NumElements > NumInits)
  1884. NumElements = 0;
  1885. }
  1886. } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
  1887. NumElements = VType->getNumElements();
  1888. else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
  1889. RecordDecl *RDecl = RType->getDecl();
  1890. if (RDecl->isUnion())
  1891. NumElements = 1;
  1892. else
  1893. NumElements = std::distance(RDecl->field_begin(),
  1894. RDecl->field_end());
  1895. }
  1896. Result->reserveInits(SemaRef.Context, NumElements);
  1897. // Link this new initializer list into the structured initializer
  1898. // lists.
  1899. if (StructuredList)
  1900. StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
  1901. else {
  1902. Result->setSyntacticForm(IList);
  1903. SyntacticToSemantic[IList] = Result;
  1904. }
  1905. return Result;
  1906. }
  1907. /// Update the initializer at index @p StructuredIndex within the
  1908. /// structured initializer list to the value @p expr.
  1909. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
  1910. unsigned &StructuredIndex,
  1911. Expr *expr) {
  1912. // No structured initializer list to update
  1913. if (!StructuredList)
  1914. return;
  1915. if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
  1916. StructuredIndex, expr)) {
  1917. // This initializer overwrites a previous initializer. Warn.
  1918. SemaRef.Diag(expr->getSourceRange().getBegin(),
  1919. diag::warn_initializer_overrides)
  1920. << expr->getSourceRange();
  1921. SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
  1922. diag::note_previous_initializer)
  1923. << /*FIXME:has side effects=*/0
  1924. << PrevInit->getSourceRange();
  1925. }
  1926. ++StructuredIndex;
  1927. }
  1928. /// Check that the given Index expression is a valid array designator
  1929. /// value. This is essentially just a wrapper around
  1930. /// VerifyIntegerConstantExpression that also checks for negative values
  1931. /// and produces a reasonable diagnostic if there is a
  1932. /// failure. Returns the index expression, possibly with an implicit cast
  1933. /// added, on success. If everything went okay, Value will receive the
  1934. /// value of the constant expression.
  1935. static ExprResult
  1936. CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
  1937. SourceLocation Loc = Index->getSourceRange().getBegin();
  1938. // Make sure this is an integer constant expression.
  1939. ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
  1940. if (Result.isInvalid())
  1941. return Result;
  1942. if (Value.isSigned() && Value.isNegative())
  1943. return S.Diag(Loc, diag::err_array_designator_negative)
  1944. << Value.toString(10) << Index->getSourceRange();
  1945. Value.setIsUnsigned(true);
  1946. return Result;
  1947. }
  1948. ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
  1949. SourceLocation Loc,
  1950. bool GNUSyntax,
  1951. ExprResult Init) {
  1952. typedef DesignatedInitExpr::Designator ASTDesignator;
  1953. bool Invalid = false;
  1954. SmallVector<ASTDesignator, 32> Designators;
  1955. SmallVector<Expr *, 32> InitExpressions;
  1956. // Build designators and check array designator expressions.
  1957. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
  1958. const Designator &D = Desig.getDesignator(Idx);
  1959. switch (D.getKind()) {
  1960. case Designator::FieldDesignator:
  1961. Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
  1962. D.getFieldLoc()));
  1963. break;
  1964. case Designator::ArrayDesignator: {
  1965. Expr *Index = static_cast<Expr *>(D.getArrayIndex());
  1966. llvm::APSInt IndexValue;
  1967. if (!Index->isTypeDependent() && !Index->isValueDependent())
  1968. Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
  1969. if (!Index)
  1970. Invalid = true;
  1971. else {
  1972. Designators.push_back(ASTDesignator(InitExpressions.size(),
  1973. D.getLBracketLoc(),
  1974. D.getRBracketLoc()));
  1975. InitExpressions.push_back(Index);
  1976. }
  1977. break;
  1978. }
  1979. case Designator::ArrayRangeDesignator: {
  1980. Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
  1981. Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
  1982. llvm::APSInt StartValue;
  1983. llvm::APSInt EndValue;
  1984. bool StartDependent = StartIndex->isTypeDependent() ||
  1985. StartIndex->isValueDependent();
  1986. bool EndDependent = EndIndex->isTypeDependent() ||
  1987. EndIndex->isValueDependent();
  1988. if (!StartDependent)
  1989. StartIndex =
  1990. CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
  1991. if (!EndDependent)
  1992. EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
  1993. if (!StartIndex || !EndIndex)
  1994. Invalid = true;
  1995. else {
  1996. // Make sure we're comparing values with the same bit width.
  1997. if (StartDependent || EndDependent) {
  1998. // Nothing to compute.
  1999. } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
  2000. EndValue = EndValue.extend(StartValue.getBitWidth());
  2001. else if (StartValue.getBitWidth() < EndValue.getBitWidth())
  2002. StartValue = StartValue.extend(EndValue.getBitWidth());
  2003. if (!StartDependent && !EndDependent && EndValue < StartValue) {
  2004. Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
  2005. << StartValue.toString(10) << EndValue.toString(10)
  2006. << StartIndex->getSourceRange() << EndIndex->getSourceRange();
  2007. Invalid = true;
  2008. } else {
  2009. Designators.push_back(ASTDesignator(InitExpressions.size(),
  2010. D.getLBracketLoc(),
  2011. D.getEllipsisLoc(),
  2012. D.getRBracketLoc()));
  2013. InitExpressions.push_back(StartIndex);
  2014. InitExpressions.push_back(EndIndex);
  2015. }
  2016. }
  2017. break;
  2018. }
  2019. }
  2020. }
  2021. if (Invalid || Init.isInvalid())
  2022. return ExprError();
  2023. // Clear out the expressions within the designation.
  2024. Desig.ClearExprs(*this);
  2025. DesignatedInitExpr *DIE
  2026. = DesignatedInitExpr::Create(Context,
  2027. Designators.data(), Designators.size(),
  2028. InitExpressions.data(), InitExpressions.size(),
  2029. Loc, GNUSyntax, Init.takeAs<Expr>());
  2030. if (!getLangOptions().C99)
  2031. Diag(DIE->getLocStart(), diag::ext_designated_init)
  2032. << DIE->getSourceRange();
  2033. return Owned(DIE);
  2034. }
  2035. //===----------------------------------------------------------------------===//
  2036. // Initialization entity
  2037. //===----------------------------------------------------------------------===//
  2038. InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
  2039. const InitializedEntity &Parent)
  2040. : Parent(&Parent), Index(Index)
  2041. {
  2042. if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
  2043. Kind = EK_ArrayElement;
  2044. Type = AT->getElementType();
  2045. } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
  2046. Kind = EK_VectorElement;
  2047. Type = VT->getElementType();
  2048. } else {
  2049. const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
  2050. assert(CT && "Unexpected type");
  2051. Kind = EK_ComplexElement;
  2052. Type = CT->getElementType();
  2053. }
  2054. }
  2055. InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
  2056. CXXBaseSpecifier *Base,
  2057. bool IsInheritedVirtualBase)
  2058. {
  2059. InitializedEntity Result;
  2060. Result.Kind = EK_Base;
  2061. Result.Base = reinterpret_cast<uintptr_t>(Base);
  2062. if (IsInheritedVirtualBase)
  2063. Result.Base |= 0x01;
  2064. Result.Type = Base->getType();
  2065. return Result;
  2066. }
  2067. DeclarationName InitializedEntity::getName() const {
  2068. switch (getKind()) {
  2069. case EK_Parameter: {
  2070. ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2071. return (D ? D->getDeclName() : DeclarationName());
  2072. }
  2073. case EK_Variable:
  2074. case EK_Member:
  2075. return VariableOrMember->getDeclName();
  2076. case EK_LambdaCapture:
  2077. return Capture.Var->getDeclName();
  2078. case EK_Result:
  2079. case EK_Exception:
  2080. case EK_New:
  2081. case EK_Temporary:
  2082. case EK_Base:
  2083. case EK_Delegating:
  2084. case EK_ArrayElement:
  2085. case EK_VectorElement:
  2086. case EK_ComplexElement:
  2087. case EK_BlockElement:
  2088. return DeclarationName();
  2089. }
  2090. llvm_unreachable("Invalid EntityKind!");
  2091. }
  2092. DeclaratorDecl *InitializedEntity::getDecl() const {
  2093. switch (getKind()) {
  2094. case EK_Variable:
  2095. case EK_Member:
  2096. return VariableOrMember;
  2097. case EK_Parameter:
  2098. return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
  2099. case EK_Result:
  2100. case EK_Exception:
  2101. case EK_New:
  2102. case EK_Temporary:
  2103. case EK_Base:
  2104. case EK_Delegating:
  2105. case EK_ArrayElement:
  2106. case EK_VectorElement:
  2107. case EK_ComplexElement:
  2108. case EK_BlockElement:
  2109. case EK_LambdaCapture:
  2110. return 0;
  2111. }
  2112. llvm_unreachable("Invalid EntityKind!");
  2113. }
  2114. bool InitializedEntity::allowsNRVO() const {
  2115. switch (getKind()) {
  2116. case EK_Result:
  2117. case EK_Exception:
  2118. return LocAndNRVO.NRVO;
  2119. case EK_Variable:
  2120. case EK_Parameter:
  2121. case EK_Member:
  2122. case EK_New:
  2123. case EK_Temporary:
  2124. case EK_Base:
  2125. case EK_Delegating:
  2126. case EK_ArrayElement:
  2127. case EK_VectorElement:
  2128. case EK_ComplexElement:
  2129. case EK_BlockElement:
  2130. case EK_LambdaCapture:
  2131. break;
  2132. }
  2133. return false;
  2134. }
  2135. //===----------------------------------------------------------------------===//
  2136. // Initialization sequence
  2137. //===----------------------------------------------------------------------===//
  2138. void InitializationSequence::Step::Destroy() {
  2139. switch (Kind) {
  2140. case SK_ResolveAddressOfOverloadedFunction:
  2141. case SK_CastDerivedToBaseRValue:
  2142. case SK_CastDerivedToBaseXValue:
  2143. case SK_CastDerivedToBaseLValue:
  2144. case SK_BindReference:
  2145. case SK_BindReferenceToTemporary:
  2146. case SK_ExtraneousCopyToTemporary:
  2147. case SK_UserConversion:
  2148. case SK_QualificationConversionRValue:
  2149. case SK_QualificationConversionXValue:
  2150. case SK_QualificationConversionLValue:
  2151. case SK_ListInitialization:
  2152. case SK_ListConstructorCall:
  2153. case SK_UnwrapInitList:
  2154. case SK_RewrapInitList:
  2155. case SK_ConstructorInitialization:
  2156. case SK_ZeroInitialization:
  2157. case SK_CAssignment:
  2158. case SK_StringInit:
  2159. case SK_ObjCObjectConversion:
  2160. case SK_ArrayInit:
  2161. case SK_PassByIndirectCopyRestore:
  2162. case SK_PassByIndirectRestore:
  2163. case SK_ProduceObjCObject:
  2164. case SK_StdInitializerList:
  2165. break;
  2166. case SK_ConversionSequence:
  2167. delete ICS;
  2168. }
  2169. }
  2170. bool InitializationSequence::isDirectReferenceBinding() const {
  2171. return !Steps.empty() && Steps.back().Kind == SK_BindReference;
  2172. }
  2173. bool InitializationSequence::isAmbiguous() const {
  2174. if (!Failed())
  2175. return false;
  2176. switch (getFailureKind()) {
  2177. case FK_TooManyInitsForReference:
  2178. case FK_ArrayNeedsInitList:
  2179. case FK_ArrayNeedsInitListOrStringLiteral:
  2180. case FK_AddressOfOverloadFailed: // FIXME: Could do better
  2181. case FK_NonConstLValueReferenceBindingToTemporary:
  2182. case FK_NonConstLValueReferenceBindingToUnrelated:
  2183. case FK_RValueReferenceBindingToLValue:
  2184. case FK_ReferenceInitDropsQualifiers:
  2185. case FK_ReferenceInitFailed:
  2186. case FK_ConversionFailed:
  2187. case FK_ConversionFromPropertyFailed:
  2188. case FK_TooManyInitsForScalar:
  2189. case FK_ReferenceBindingToInitList:
  2190. case FK_InitListBadDestinationType:
  2191. case FK_DefaultInitOfConst:
  2192. case FK_Incomplete:
  2193. case FK_ArrayTypeMismatch:
  2194. case FK_NonConstantArrayInit:
  2195. case FK_ListInitializationFailed:
  2196. case FK_VariableLengthArrayHasInitializer:
  2197. case FK_PlaceholderType:
  2198. case FK_InitListElementCopyFailure:
  2199. return false;
  2200. case FK_ReferenceInitOverloadFailed:
  2201. case FK_UserConversionOverloadFailed:
  2202. case FK_ConstructorOverloadFailed:
  2203. case FK_ListConstructorOverloadFailed:
  2204. return FailedOverloadResult == OR_Ambiguous;
  2205. }
  2206. llvm_unreachable("Invalid EntityKind!");
  2207. }
  2208. bool InitializationSequence::isConstructorInitialization() const {
  2209. return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
  2210. }
  2211. void
  2212. InitializationSequence
  2213. ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
  2214. DeclAccessPair Found,
  2215. bool HadMultipleCandidates) {
  2216. Step S;
  2217. S.Kind = SK_ResolveAddressOfOverloadedFunction;
  2218. S.Type = Function->getType();
  2219. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2220. S.Function.Function = Function;
  2221. S.Function.FoundDecl = Found;
  2222. Steps.push_back(S);
  2223. }
  2224. void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
  2225. ExprValueKind VK) {
  2226. Step S;
  2227. switch (VK) {
  2228. case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
  2229. case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
  2230. case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
  2231. }
  2232. S.Type = BaseType;
  2233. Steps.push_back(S);
  2234. }
  2235. void InitializationSequence::AddReferenceBindingStep(QualType T,
  2236. bool BindingTemporary) {
  2237. Step S;
  2238. S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
  2239. S.Type = T;
  2240. Steps.push_back(S);
  2241. }
  2242. void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
  2243. Step S;
  2244. S.Kind = SK_ExtraneousCopyToTemporary;
  2245. S.Type = T;
  2246. Steps.push_back(S);
  2247. }
  2248. void
  2249. InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
  2250. DeclAccessPair FoundDecl,
  2251. QualType T,
  2252. bool HadMultipleCandidates) {
  2253. Step S;
  2254. S.Kind = SK_UserConversion;
  2255. S.Type = T;
  2256. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2257. S.Function.Function = Function;
  2258. S.Function.FoundDecl = FoundDecl;
  2259. Steps.push_back(S);
  2260. }
  2261. void InitializationSequence::AddQualificationConversionStep(QualType Ty,
  2262. ExprValueKind VK) {
  2263. Step S;
  2264. S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
  2265. switch (VK) {
  2266. case VK_RValue:
  2267. S.Kind = SK_QualificationConversionRValue;
  2268. break;
  2269. case VK_XValue:
  2270. S.Kind = SK_QualificationConversionXValue;
  2271. break;
  2272. case VK_LValue:
  2273. S.Kind = SK_QualificationConversionLValue;
  2274. break;
  2275. }
  2276. S.Type = Ty;
  2277. Steps.push_back(S);
  2278. }
  2279. void InitializationSequence::AddConversionSequenceStep(
  2280. const ImplicitConversionSequence &ICS,
  2281. QualType T) {
  2282. Step S;
  2283. S.Kind = SK_ConversionSequence;
  2284. S.Type = T;
  2285. S.ICS = new ImplicitConversionSequence(ICS);
  2286. Steps.push_back(S);
  2287. }
  2288. void InitializationSequence::AddListInitializationStep(QualType T) {
  2289. Step S;
  2290. S.Kind = SK_ListInitialization;
  2291. S.Type = T;
  2292. Steps.push_back(S);
  2293. }
  2294. void
  2295. InitializationSequence
  2296. ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
  2297. AccessSpecifier Access,
  2298. QualType T,
  2299. bool HadMultipleCandidates,
  2300. bool FromInitList, bool AsInitList) {
  2301. Step S;
  2302. S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
  2303. : SK_ConstructorInitialization;
  2304. S.Type = T;
  2305. S.Function.HadMultipleCandidates = HadMultipleCandidates;
  2306. S.Function.Function = Constructor;
  2307. S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
  2308. Steps.push_back(S);
  2309. }
  2310. void InitializationSequence::AddZeroInitializationStep(QualType T) {
  2311. Step S;
  2312. S.Kind = SK_ZeroInitialization;
  2313. S.Type = T;
  2314. Steps.push_back(S);
  2315. }
  2316. void InitializationSequence::AddCAssignmentStep(QualType T) {
  2317. Step S;
  2318. S.Kind = SK_CAssignment;
  2319. S.Type = T;
  2320. Steps.push_back(S);
  2321. }
  2322. void InitializationSequence::AddStringInitStep(QualType T) {
  2323. Step S;
  2324. S.Kind = SK_StringInit;
  2325. S.Type = T;
  2326. Steps.push_back(S);
  2327. }
  2328. void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
  2329. Step S;
  2330. S.Kind = SK_ObjCObjectConversion;
  2331. S.Type = T;
  2332. Steps.push_back(S);
  2333. }
  2334. void InitializationSequence::AddArrayInitStep(QualType T) {
  2335. Step S;
  2336. S.Kind = SK_ArrayInit;
  2337. S.Type = T;
  2338. Steps.push_back(S);
  2339. }
  2340. void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
  2341. bool shouldCopy) {
  2342. Step s;
  2343. s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
  2344. : SK_PassByIndirectRestore);
  2345. s.Type = type;
  2346. Steps.push_back(s);
  2347. }
  2348. void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
  2349. Step S;
  2350. S.Kind = SK_ProduceObjCObject;
  2351. S.Type = T;
  2352. Steps.push_back(S);
  2353. }
  2354. void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
  2355. Step S;
  2356. S.Kind = SK_StdInitializerList;
  2357. S.Type = T;
  2358. Steps.push_back(S);
  2359. }
  2360. void InitializationSequence::RewrapReferenceInitList(QualType T,
  2361. InitListExpr *Syntactic) {
  2362. assert(Syntactic->getNumInits() == 1 &&
  2363. "Can only rewrap trivial init lists.");
  2364. Step S;
  2365. S.Kind = SK_UnwrapInitList;
  2366. S.Type = Syntactic->getInit(0)->getType();
  2367. Steps.insert(Steps.begin(), S);
  2368. S.Kind = SK_RewrapInitList;
  2369. S.Type = T;
  2370. S.WrappingSyntacticList = Syntactic;
  2371. Steps.push_back(S);
  2372. }
  2373. void InitializationSequence::SetOverloadFailure(FailureKind Failure,
  2374. OverloadingResult Result) {
  2375. setSequenceKind(FailedSequence);
  2376. this->Failure = Failure;
  2377. this->FailedOverloadResult = Result;
  2378. }
  2379. //===----------------------------------------------------------------------===//
  2380. // Attempt initialization
  2381. //===----------------------------------------------------------------------===//
  2382. static void MaybeProduceObjCObject(Sema &S,
  2383. InitializationSequence &Sequence,
  2384. const InitializedEntity &Entity) {
  2385. if (!S.getLangOptions().ObjCAutoRefCount) return;
  2386. /// When initializing a parameter, produce the value if it's marked
  2387. /// __attribute__((ns_consumed)).
  2388. if (Entity.getKind() == InitializedEntity::EK_Parameter) {
  2389. if (!Entity.isParameterConsumed())
  2390. return;
  2391. assert(Entity.getType()->isObjCRetainableType() &&
  2392. "consuming an object of unretainable type?");
  2393. Sequence.AddProduceObjCObjectStep(Entity.getType());
  2394. /// When initializing a return value, if the return type is a
  2395. /// retainable type, then returns need to immediately retain the
  2396. /// object. If an autorelease is required, it will be done at the
  2397. /// last instant.
  2398. } else if (Entity.getKind() == InitializedEntity::EK_Result) {
  2399. if (!Entity.getType()->isObjCRetainableType())
  2400. return;
  2401. Sequence.AddProduceObjCObjectStep(Entity.getType());
  2402. }
  2403. }
  2404. /// \brief When initializing from init list via constructor, deal with the
  2405. /// empty init list and std::initializer_list special cases.
  2406. ///
  2407. /// \return True if this was a special case, false otherwise.
  2408. static bool TryListConstructionSpecialCases(Sema &S,
  2409. InitListExpr *List,
  2410. CXXRecordDecl *DestRecordDecl,
  2411. QualType DestType,
  2412. InitializationSequence &Sequence) {
  2413. // C++11 [dcl.init.list]p3:
  2414. // List-initialization of an object or reference of type T is defined as
  2415. // follows:
  2416. // - If T is an aggregate, aggregate initialization is performed.
  2417. if (DestType->isAggregateType())
  2418. return false;
  2419. // - Otherwise, if the initializer list has no elements and T is a class
  2420. // type with a default constructor, the object is value-initialized.
  2421. if (List->getNumInits() == 0) {
  2422. if (CXXConstructorDecl *DefaultConstructor =
  2423. S.LookupDefaultConstructor(DestRecordDecl)) {
  2424. if (DefaultConstructor->isDeleted() ||
  2425. S.isFunctionConsideredUnavailable(DefaultConstructor)) {
  2426. // Fake an overload resolution failure.
  2427. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  2428. DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
  2429. DefaultConstructor->getAccess());
  2430. if (FunctionTemplateDecl *ConstructorTmpl =
  2431. dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
  2432. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2433. /*ExplicitArgs*/ 0,
  2434. 0, 0, CandidateSet,
  2435. /*SuppressUserConversions*/ false);
  2436. else
  2437. S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
  2438. 0, 0, CandidateSet,
  2439. /*SuppressUserConversions*/ false);
  2440. Sequence.SetOverloadFailure(
  2441. InitializationSequence::FK_ListConstructorOverloadFailed,
  2442. OR_Deleted);
  2443. } else
  2444. Sequence.AddConstructorInitializationStep(DefaultConstructor,
  2445. DefaultConstructor->getAccess(),
  2446. DestType,
  2447. /*MultipleCandidates=*/false,
  2448. /*FromInitList=*/true,
  2449. /*AsInitList=*/false);
  2450. return true;
  2451. }
  2452. }
  2453. // - Otherwise, if T is a specialization of std::initializer_list, [...]
  2454. QualType E;
  2455. if (S.isStdInitializerList(DestType, &E)) {
  2456. // Check that each individual element can be copy-constructed. But since we
  2457. // have no place to store further information, we'll recalculate everything
  2458. // later.
  2459. InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
  2460. S.Context.getConstantArrayType(E,
  2461. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  2462. List->getNumInits()),
  2463. ArrayType::Normal, 0));
  2464. InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
  2465. 0, HiddenArray);
  2466. for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
  2467. Element.setElementIndex(i);
  2468. if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
  2469. Sequence.SetFailed(
  2470. InitializationSequence::FK_InitListElementCopyFailure);
  2471. return true;
  2472. }
  2473. }
  2474. Sequence.AddStdInitializerListConstructionStep(DestType);
  2475. return true;
  2476. }
  2477. // Not a special case.
  2478. return false;
  2479. }
  2480. static OverloadingResult
  2481. ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
  2482. Expr **Args, unsigned NumArgs,
  2483. OverloadCandidateSet &CandidateSet,
  2484. DeclContext::lookup_iterator Con,
  2485. DeclContext::lookup_iterator ConEnd,
  2486. OverloadCandidateSet::iterator &Best,
  2487. bool CopyInitializing, bool AllowExplicit,
  2488. bool OnlyListConstructors) {
  2489. CandidateSet.clear();
  2490. for (; Con != ConEnd; ++Con) {
  2491. NamedDecl *D = *Con;
  2492. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2493. bool SuppressUserConversions = false;
  2494. // Find the constructor (which may be a template).
  2495. CXXConstructorDecl *Constructor = 0;
  2496. FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
  2497. if (ConstructorTmpl)
  2498. Constructor = cast<CXXConstructorDecl>(
  2499. ConstructorTmpl->getTemplatedDecl());
  2500. else {
  2501. Constructor = cast<CXXConstructorDecl>(D);
  2502. // If we're performing copy initialization using a copy constructor, we
  2503. // suppress user-defined conversions on the arguments.
  2504. // FIXME: Move constructors?
  2505. if (CopyInitializing && Constructor->isCopyConstructor())
  2506. SuppressUserConversions = true;
  2507. }
  2508. if (!Constructor->isInvalidDecl() &&
  2509. (AllowExplicit || !Constructor->isExplicit()) &&
  2510. (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
  2511. if (ConstructorTmpl)
  2512. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2513. /*ExplicitArgs*/ 0,
  2514. Args, NumArgs, CandidateSet,
  2515. SuppressUserConversions);
  2516. else
  2517. S.AddOverloadCandidate(Constructor, FoundDecl,
  2518. Args, NumArgs, CandidateSet,
  2519. SuppressUserConversions);
  2520. }
  2521. }
  2522. // Perform overload resolution and return the result.
  2523. return CandidateSet.BestViableFunction(S, DeclLoc, Best);
  2524. }
  2525. /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
  2526. /// enumerates the constructors of the initialized entity and performs overload
  2527. /// resolution to select the best.
  2528. /// If InitListSyntax is true, this is list-initialization of a non-aggregate
  2529. /// class type.
  2530. static void TryConstructorInitialization(Sema &S,
  2531. const InitializedEntity &Entity,
  2532. const InitializationKind &Kind,
  2533. Expr **Args, unsigned NumArgs,
  2534. QualType DestType,
  2535. InitializationSequence &Sequence,
  2536. bool InitListSyntax = false) {
  2537. assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
  2538. "InitListSyntax must come with a single initializer list argument.");
  2539. // Check constructor arguments for self reference.
  2540. if (DeclaratorDecl *DD = Entity.getDecl())
  2541. // Parameters arguments are occassionially constructed with itself,
  2542. // for instance, in recursive functions. Skip them.
  2543. if (!isa<ParmVarDecl>(DD))
  2544. for (unsigned i = 0; i < NumArgs; ++i)
  2545. S.CheckSelfReference(DD, Args[i]);
  2546. // The type we're constructing needs to be complete.
  2547. if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
  2548. Sequence.SetFailed(InitializationSequence::FK_Incomplete);
  2549. return;
  2550. }
  2551. const RecordType *DestRecordType = DestType->getAs<RecordType>();
  2552. assert(DestRecordType && "Constructor initialization requires record type");
  2553. CXXRecordDecl *DestRecordDecl
  2554. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  2555. if (InitListSyntax &&
  2556. TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
  2557. DestRecordDecl, DestType, Sequence))
  2558. return;
  2559. // Build the candidate set directly in the initialization sequence
  2560. // structure, so that it will persist if we fail.
  2561. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  2562. // Determine whether we are allowed to call explicit constructors or
  2563. // explicit conversion operators.
  2564. bool AllowExplicit = Kind.AllowExplicit();
  2565. bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
  2566. // - Otherwise, if T is a class type, constructors are considered. The
  2567. // applicable constructors are enumerated, and the best one is chosen
  2568. // through overload resolution.
  2569. DeclContext::lookup_iterator ConStart, ConEnd;
  2570. llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
  2571. OverloadingResult Result = OR_No_Viable_Function;
  2572. OverloadCandidateSet::iterator Best;
  2573. bool AsInitializerList = false;
  2574. // C++11 [over.match.list]p1:
  2575. // When objects of non-aggregate type T are list-initialized, overload
  2576. // resolution selects the constructor in two phases:
  2577. // - Initially, the candidate functions are the initializer-list
  2578. // constructors of the class T and the argument list consists of the
  2579. // initializer list as a single argument.
  2580. if (InitListSyntax) {
  2581. AsInitializerList = true;
  2582. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
  2583. CandidateSet, ConStart, ConEnd, Best,
  2584. CopyInitialization, AllowExplicit,
  2585. /*OnlyListConstructor=*/true);
  2586. // Time to unwrap the init list.
  2587. InitListExpr *ILE = cast<InitListExpr>(Args[0]);
  2588. Args = ILE->getInits();
  2589. NumArgs = ILE->getNumInits();
  2590. }
  2591. // C++11 [over.match.list]p1:
  2592. // - If no viable initializer-list constructor is found, overload resolution
  2593. // is performed again, where the candidate functions are all the
  2594. // constructors of the class T nad the argument list consists of the
  2595. // elements of the initializer list.
  2596. if (Result == OR_No_Viable_Function) {
  2597. AsInitializerList = false;
  2598. Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
  2599. CandidateSet, ConStart, ConEnd, Best,
  2600. CopyInitialization, AllowExplicit,
  2601. /*OnlyListConstructors=*/false);
  2602. }
  2603. if (Result) {
  2604. Sequence.SetOverloadFailure(InitListSyntax ?
  2605. InitializationSequence::FK_ListConstructorOverloadFailed :
  2606. InitializationSequence::FK_ConstructorOverloadFailed,
  2607. Result);
  2608. return;
  2609. }
  2610. // C++0x [dcl.init]p6:
  2611. // If a program calls for the default initialization of an object
  2612. // of a const-qualified type T, T shall be a class type with a
  2613. // user-provided default constructor.
  2614. if (Kind.getKind() == InitializationKind::IK_Default &&
  2615. Entity.getType().isConstQualified() &&
  2616. cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
  2617. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  2618. return;
  2619. }
  2620. // Add the constructor initialization step. Any cv-qualification conversion is
  2621. // subsumed by the initialization.
  2622. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2623. CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
  2624. Sequence.AddConstructorInitializationStep(CtorDecl,
  2625. Best->FoundDecl.getAccess(),
  2626. DestType, HadMultipleCandidates,
  2627. InitListSyntax, AsInitializerList);
  2628. }
  2629. static bool
  2630. ResolveOverloadedFunctionForReferenceBinding(Sema &S,
  2631. Expr *Initializer,
  2632. QualType &SourceType,
  2633. QualType &UnqualifiedSourceType,
  2634. QualType UnqualifiedTargetType,
  2635. InitializationSequence &Sequence) {
  2636. if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
  2637. S.Context.OverloadTy) {
  2638. DeclAccessPair Found;
  2639. bool HadMultipleCandidates = false;
  2640. if (FunctionDecl *Fn
  2641. = S.ResolveAddressOfOverloadedFunction(Initializer,
  2642. UnqualifiedTargetType,
  2643. false, Found,
  2644. &HadMultipleCandidates)) {
  2645. Sequence.AddAddressOverloadResolutionStep(Fn, Found,
  2646. HadMultipleCandidates);
  2647. SourceType = Fn->getType();
  2648. UnqualifiedSourceType = SourceType.getUnqualifiedType();
  2649. } else if (!UnqualifiedTargetType->isRecordType()) {
  2650. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  2651. return true;
  2652. }
  2653. }
  2654. return false;
  2655. }
  2656. static void TryReferenceInitializationCore(Sema &S,
  2657. const InitializedEntity &Entity,
  2658. const InitializationKind &Kind,
  2659. Expr *Initializer,
  2660. QualType cv1T1, QualType T1,
  2661. Qualifiers T1Quals,
  2662. QualType cv2T2, QualType T2,
  2663. Qualifiers T2Quals,
  2664. InitializationSequence &Sequence);
  2665. static void TryListInitialization(Sema &S,
  2666. const InitializedEntity &Entity,
  2667. const InitializationKind &Kind,
  2668. InitListExpr *InitList,
  2669. InitializationSequence &Sequence);
  2670. /// \brief Attempt list initialization of a reference.
  2671. static void TryReferenceListInitialization(Sema &S,
  2672. const InitializedEntity &Entity,
  2673. const InitializationKind &Kind,
  2674. InitListExpr *InitList,
  2675. InitializationSequence &Sequence)
  2676. {
  2677. // First, catch C++03 where this isn't possible.
  2678. if (!S.getLangOptions().CPlusPlus0x) {
  2679. Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
  2680. return;
  2681. }
  2682. QualType DestType = Entity.getType();
  2683. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  2684. Qualifiers T1Quals;
  2685. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  2686. // Reference initialization via an initializer list works thus:
  2687. // If the initializer list consists of a single element that is
  2688. // reference-related to the referenced type, bind directly to that element
  2689. // (possibly creating temporaries).
  2690. // Otherwise, initialize a temporary with the initializer list and
  2691. // bind to that.
  2692. if (InitList->getNumInits() == 1) {
  2693. Expr *Initializer = InitList->getInit(0);
  2694. QualType cv2T2 = Initializer->getType();
  2695. Qualifiers T2Quals;
  2696. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  2697. // If this fails, creating a temporary wouldn't work either.
  2698. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  2699. T1, Sequence))
  2700. return;
  2701. SourceLocation DeclLoc = Initializer->getLocStart();
  2702. bool dummy1, dummy2, dummy3;
  2703. Sema::ReferenceCompareResult RefRelationship
  2704. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
  2705. dummy2, dummy3);
  2706. if (RefRelationship >= Sema::Ref_Related) {
  2707. // Try to bind the reference here.
  2708. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  2709. T1Quals, cv2T2, T2, T2Quals, Sequence);
  2710. if (Sequence)
  2711. Sequence.RewrapReferenceInitList(cv1T1, InitList);
  2712. return;
  2713. }
  2714. }
  2715. // Not reference-related. Create a temporary and bind to that.
  2716. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  2717. TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
  2718. if (Sequence) {
  2719. if (DestType->isRValueReferenceType() ||
  2720. (T1Quals.hasConst() && !T1Quals.hasVolatile()))
  2721. Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
  2722. else
  2723. Sequence.SetFailed(
  2724. InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  2725. }
  2726. }
  2727. /// \brief Attempt list initialization (C++0x [dcl.init.list])
  2728. static void TryListInitialization(Sema &S,
  2729. const InitializedEntity &Entity,
  2730. const InitializationKind &Kind,
  2731. InitListExpr *InitList,
  2732. InitializationSequence &Sequence) {
  2733. QualType DestType = Entity.getType();
  2734. // C++ doesn't allow scalar initialization with more than one argument.
  2735. // But C99 complex numbers are scalars and it makes sense there.
  2736. if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
  2737. !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
  2738. Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
  2739. return;
  2740. }
  2741. if (DestType->isReferenceType()) {
  2742. TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
  2743. return;
  2744. }
  2745. if (DestType->isRecordType() && !DestType->isAggregateType()) {
  2746. if (S.getLangOptions().CPlusPlus0x) {
  2747. Expr *Arg = InitList;
  2748. // A direct-initializer is not list-syntax, i.e. there's no special
  2749. // treatment of "A a({1, 2});".
  2750. TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
  2751. Sequence, Kind.getKind() != InitializationKind::IK_Direct);
  2752. } else
  2753. Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
  2754. return;
  2755. }
  2756. InitListChecker CheckInitList(S, Entity, InitList,
  2757. DestType, /*VerifyOnly=*/true,
  2758. Kind.getKind() != InitializationKind::IK_DirectList ||
  2759. !S.getLangOptions().CPlusPlus0x);
  2760. if (CheckInitList.HadError()) {
  2761. Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
  2762. return;
  2763. }
  2764. // Add the list initialization step with the built init list.
  2765. Sequence.AddListInitializationStep(DestType);
  2766. }
  2767. /// \brief Try a reference initialization that involves calling a conversion
  2768. /// function.
  2769. static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
  2770. const InitializedEntity &Entity,
  2771. const InitializationKind &Kind,
  2772. Expr *Initializer,
  2773. bool AllowRValues,
  2774. InitializationSequence &Sequence) {
  2775. QualType DestType = Entity.getType();
  2776. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  2777. QualType T1 = cv1T1.getUnqualifiedType();
  2778. QualType cv2T2 = Initializer->getType();
  2779. QualType T2 = cv2T2.getUnqualifiedType();
  2780. bool DerivedToBase;
  2781. bool ObjCConversion;
  2782. bool ObjCLifetimeConversion;
  2783. assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
  2784. T1, T2, DerivedToBase,
  2785. ObjCConversion,
  2786. ObjCLifetimeConversion) &&
  2787. "Must have incompatible references when binding via conversion");
  2788. (void)DerivedToBase;
  2789. (void)ObjCConversion;
  2790. (void)ObjCLifetimeConversion;
  2791. // Build the candidate set directly in the initialization sequence
  2792. // structure, so that it will persist if we fail.
  2793. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  2794. CandidateSet.clear();
  2795. // Determine whether we are allowed to call explicit constructors or
  2796. // explicit conversion operators.
  2797. bool AllowExplicit = Kind.AllowExplicit();
  2798. const RecordType *T1RecordType = 0;
  2799. if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
  2800. !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
  2801. // The type we're converting to is a class type. Enumerate its constructors
  2802. // to see if there is a suitable conversion.
  2803. CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
  2804. DeclContext::lookup_iterator Con, ConEnd;
  2805. for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
  2806. Con != ConEnd; ++Con) {
  2807. NamedDecl *D = *Con;
  2808. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2809. // Find the constructor (which may be a template).
  2810. CXXConstructorDecl *Constructor = 0;
  2811. FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
  2812. if (ConstructorTmpl)
  2813. Constructor = cast<CXXConstructorDecl>(
  2814. ConstructorTmpl->getTemplatedDecl());
  2815. else
  2816. Constructor = cast<CXXConstructorDecl>(D);
  2817. if (!Constructor->isInvalidDecl() &&
  2818. Constructor->isConvertingConstructor(AllowExplicit)) {
  2819. if (ConstructorTmpl)
  2820. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2821. /*ExplicitArgs*/ 0,
  2822. &Initializer, 1, CandidateSet,
  2823. /*SuppressUserConversions=*/true);
  2824. else
  2825. S.AddOverloadCandidate(Constructor, FoundDecl,
  2826. &Initializer, 1, CandidateSet,
  2827. /*SuppressUserConversions=*/true);
  2828. }
  2829. }
  2830. }
  2831. if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
  2832. return OR_No_Viable_Function;
  2833. const RecordType *T2RecordType = 0;
  2834. if ((T2RecordType = T2->getAs<RecordType>()) &&
  2835. !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
  2836. // The type we're converting from is a class type, enumerate its conversion
  2837. // functions.
  2838. CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
  2839. const UnresolvedSetImpl *Conversions
  2840. = T2RecordDecl->getVisibleConversionFunctions();
  2841. for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
  2842. E = Conversions->end(); I != E; ++I) {
  2843. NamedDecl *D = *I;
  2844. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  2845. if (isa<UsingShadowDecl>(D))
  2846. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2847. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  2848. CXXConversionDecl *Conv;
  2849. if (ConvTemplate)
  2850. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2851. else
  2852. Conv = cast<CXXConversionDecl>(D);
  2853. // If the conversion function doesn't return a reference type,
  2854. // it can't be considered for this conversion unless we're allowed to
  2855. // consider rvalues.
  2856. // FIXME: Do we need to make sure that we only consider conversion
  2857. // candidates with reference-compatible results? That might be needed to
  2858. // break recursion.
  2859. if ((AllowExplicit || !Conv->isExplicit()) &&
  2860. (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
  2861. if (ConvTemplate)
  2862. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
  2863. ActingDC, Initializer,
  2864. DestType, CandidateSet);
  2865. else
  2866. S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
  2867. Initializer, DestType, CandidateSet);
  2868. }
  2869. }
  2870. }
  2871. if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
  2872. return OR_No_Viable_Function;
  2873. SourceLocation DeclLoc = Initializer->getLocStart();
  2874. // Perform overload resolution. If it fails, return the failed result.
  2875. OverloadCandidateSet::iterator Best;
  2876. if (OverloadingResult Result
  2877. = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
  2878. return Result;
  2879. FunctionDecl *Function = Best->Function;
  2880. // This is the overload that will actually be used for the initialization, so
  2881. // mark it as used.
  2882. S.MarkFunctionReferenced(DeclLoc, Function);
  2883. // Compute the returned type of the conversion.
  2884. if (isa<CXXConversionDecl>(Function))
  2885. T2 = Function->getResultType();
  2886. else
  2887. T2 = cv1T1;
  2888. // Add the user-defined conversion step.
  2889. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2890. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  2891. T2.getNonLValueExprType(S.Context),
  2892. HadMultipleCandidates);
  2893. // Determine whether we need to perform derived-to-base or
  2894. // cv-qualification adjustments.
  2895. ExprValueKind VK = VK_RValue;
  2896. if (T2->isLValueReferenceType())
  2897. VK = VK_LValue;
  2898. else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
  2899. VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
  2900. bool NewDerivedToBase = false;
  2901. bool NewObjCConversion = false;
  2902. bool NewObjCLifetimeConversion = false;
  2903. Sema::ReferenceCompareResult NewRefRelationship
  2904. = S.CompareReferenceRelationship(DeclLoc, T1,
  2905. T2.getNonLValueExprType(S.Context),
  2906. NewDerivedToBase, NewObjCConversion,
  2907. NewObjCLifetimeConversion);
  2908. if (NewRefRelationship == Sema::Ref_Incompatible) {
  2909. // If the type we've converted to is not reference-related to the
  2910. // type we're looking for, then there is another conversion step
  2911. // we need to perform to produce a temporary of the right type
  2912. // that we'll be binding to.
  2913. ImplicitConversionSequence ICS;
  2914. ICS.setStandard();
  2915. ICS.Standard = Best->FinalConversion;
  2916. T2 = ICS.Standard.getToType(2);
  2917. Sequence.AddConversionSequenceStep(ICS, T2);
  2918. } else if (NewDerivedToBase)
  2919. Sequence.AddDerivedToBaseCastStep(
  2920. S.Context.getQualifiedType(T1,
  2921. T2.getNonReferenceType().getQualifiers()),
  2922. VK);
  2923. else if (NewObjCConversion)
  2924. Sequence.AddObjCObjectConversionStep(
  2925. S.Context.getQualifiedType(T1,
  2926. T2.getNonReferenceType().getQualifiers()));
  2927. if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
  2928. Sequence.AddQualificationConversionStep(cv1T1, VK);
  2929. Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
  2930. return OR_Success;
  2931. }
  2932. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  2933. const InitializedEntity &Entity,
  2934. Expr *CurInitExpr);
  2935. /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
  2936. static void TryReferenceInitialization(Sema &S,
  2937. const InitializedEntity &Entity,
  2938. const InitializationKind &Kind,
  2939. Expr *Initializer,
  2940. InitializationSequence &Sequence) {
  2941. QualType DestType = Entity.getType();
  2942. QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
  2943. Qualifiers T1Quals;
  2944. QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
  2945. QualType cv2T2 = Initializer->getType();
  2946. Qualifiers T2Quals;
  2947. QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
  2948. // If the initializer is the address of an overloaded function, try
  2949. // to resolve the overloaded function. If all goes well, T2 is the
  2950. // type of the resulting function.
  2951. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
  2952. T1, Sequence))
  2953. return;
  2954. // Delegate everything else to a subfunction.
  2955. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
  2956. T1Quals, cv2T2, T2, T2Quals, Sequence);
  2957. }
  2958. /// \brief Reference initialization without resolving overloaded functions.
  2959. static void TryReferenceInitializationCore(Sema &S,
  2960. const InitializedEntity &Entity,
  2961. const InitializationKind &Kind,
  2962. Expr *Initializer,
  2963. QualType cv1T1, QualType T1,
  2964. Qualifiers T1Quals,
  2965. QualType cv2T2, QualType T2,
  2966. Qualifiers T2Quals,
  2967. InitializationSequence &Sequence) {
  2968. QualType DestType = Entity.getType();
  2969. SourceLocation DeclLoc = Initializer->getLocStart();
  2970. // Compute some basic properties of the types and the initializer.
  2971. bool isLValueRef = DestType->isLValueReferenceType();
  2972. bool isRValueRef = !isLValueRef;
  2973. bool DerivedToBase = false;
  2974. bool ObjCConversion = false;
  2975. bool ObjCLifetimeConversion = false;
  2976. Expr::Classification InitCategory = Initializer->Classify(S.Context);
  2977. Sema::ReferenceCompareResult RefRelationship
  2978. = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
  2979. ObjCConversion, ObjCLifetimeConversion);
  2980. // C++0x [dcl.init.ref]p5:
  2981. // A reference to type "cv1 T1" is initialized by an expression of type
  2982. // "cv2 T2" as follows:
  2983. //
  2984. // - If the reference is an lvalue reference and the initializer
  2985. // expression
  2986. // Note the analogous bullet points for rvlaue refs to functions. Because
  2987. // there are no function rvalues in C++, rvalue refs to functions are treated
  2988. // like lvalue refs.
  2989. OverloadingResult ConvOvlResult = OR_Success;
  2990. bool T1Function = T1->isFunctionType();
  2991. if (isLValueRef || T1Function) {
  2992. if (InitCategory.isLValue() &&
  2993. (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
  2994. (Kind.isCStyleOrFunctionalCast() &&
  2995. RefRelationship == Sema::Ref_Related))) {
  2996. // - is an lvalue (but is not a bit-field), and "cv1 T1" is
  2997. // reference-compatible with "cv2 T2," or
  2998. //
  2999. // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
  3000. // bit-field when we're determining whether the reference initialization
  3001. // can occur. However, we do pay attention to whether it is a bit-field
  3002. // to decide whether we're actually binding to a temporary created from
  3003. // the bit-field.
  3004. if (DerivedToBase)
  3005. Sequence.AddDerivedToBaseCastStep(
  3006. S.Context.getQualifiedType(T1, T2Quals),
  3007. VK_LValue);
  3008. else if (ObjCConversion)
  3009. Sequence.AddObjCObjectConversionStep(
  3010. S.Context.getQualifiedType(T1, T2Quals));
  3011. if (T1Quals != T2Quals)
  3012. Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
  3013. bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
  3014. (Initializer->getBitField() || Initializer->refersToVectorElement());
  3015. Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
  3016. return;
  3017. }
  3018. // - has a class type (i.e., T2 is a class type), where T1 is not
  3019. // reference-related to T2, and can be implicitly converted to an
  3020. // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
  3021. // with "cv3 T3" (this conversion is selected by enumerating the
  3022. // applicable conversion functions (13.3.1.6) and choosing the best
  3023. // one through overload resolution (13.3)),
  3024. // If we have an rvalue ref to function type here, the rhs must be
  3025. // an rvalue.
  3026. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
  3027. (isLValueRef || InitCategory.isRValue())) {
  3028. ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
  3029. Initializer,
  3030. /*AllowRValues=*/isRValueRef,
  3031. Sequence);
  3032. if (ConvOvlResult == OR_Success)
  3033. return;
  3034. if (ConvOvlResult != OR_No_Viable_Function) {
  3035. Sequence.SetOverloadFailure(
  3036. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3037. ConvOvlResult);
  3038. }
  3039. }
  3040. }
  3041. // - Otherwise, the reference shall be an lvalue reference to a
  3042. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3043. // shall be an rvalue reference.
  3044. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
  3045. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  3046. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3047. else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  3048. Sequence.SetOverloadFailure(
  3049. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3050. ConvOvlResult);
  3051. else
  3052. Sequence.SetFailed(InitCategory.isLValue()
  3053. ? (RefRelationship == Sema::Ref_Related
  3054. ? InitializationSequence::FK_ReferenceInitDropsQualifiers
  3055. : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
  3056. : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
  3057. return;
  3058. }
  3059. // - If the initializer expression
  3060. // - is an xvalue, class prvalue, array prvalue, or function lvalue and
  3061. // "cv1 T1" is reference-compatible with "cv2 T2"
  3062. // Note: functions are handled below.
  3063. if (!T1Function &&
  3064. (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
  3065. (Kind.isCStyleOrFunctionalCast() &&
  3066. RefRelationship == Sema::Ref_Related)) &&
  3067. (InitCategory.isXValue() ||
  3068. (InitCategory.isPRValue() && T2->isRecordType()) ||
  3069. (InitCategory.isPRValue() && T2->isArrayType()))) {
  3070. ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
  3071. if (InitCategory.isPRValue() && T2->isRecordType()) {
  3072. // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
  3073. // compiler the freedom to perform a copy here or bind to the
  3074. // object, while C++0x requires that we bind directly to the
  3075. // object. Hence, we always bind to the object without making an
  3076. // extra copy. However, in C++03 requires that we check for the
  3077. // presence of a suitable copy constructor:
  3078. //
  3079. // The constructor that would be used to make the copy shall
  3080. // be callable whether or not the copy is actually done.
  3081. if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
  3082. Sequence.AddExtraneousCopyToTemporary(cv2T2);
  3083. else if (S.getLangOptions().CPlusPlus0x)
  3084. CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
  3085. }
  3086. if (DerivedToBase)
  3087. Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
  3088. ValueKind);
  3089. else if (ObjCConversion)
  3090. Sequence.AddObjCObjectConversionStep(
  3091. S.Context.getQualifiedType(T1, T2Quals));
  3092. if (T1Quals != T2Quals)
  3093. Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
  3094. Sequence.AddReferenceBindingStep(cv1T1,
  3095. /*bindingTemporary=*/InitCategory.isPRValue());
  3096. return;
  3097. }
  3098. // - has a class type (i.e., T2 is a class type), where T1 is not
  3099. // reference-related to T2, and can be implicitly converted to an
  3100. // xvalue, class prvalue, or function lvalue of type "cv3 T3",
  3101. // where "cv1 T1" is reference-compatible with "cv3 T3",
  3102. if (T2->isRecordType()) {
  3103. if (RefRelationship == Sema::Ref_Incompatible) {
  3104. ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
  3105. Kind, Initializer,
  3106. /*AllowRValues=*/true,
  3107. Sequence);
  3108. if (ConvOvlResult)
  3109. Sequence.SetOverloadFailure(
  3110. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3111. ConvOvlResult);
  3112. return;
  3113. }
  3114. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  3115. return;
  3116. }
  3117. // - Otherwise, a temporary of type "cv1 T1" is created and initialized
  3118. // from the initializer expression using the rules for a non-reference
  3119. // copy initialization (8.5). The reference is then bound to the
  3120. // temporary. [...]
  3121. // Determine whether we are allowed to call explicit constructors or
  3122. // explicit conversion operators.
  3123. bool AllowExplicit = Kind.AllowExplicit();
  3124. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
  3125. ImplicitConversionSequence ICS
  3126. = S.TryImplicitConversion(Initializer, TempEntity.getType(),
  3127. /*SuppressUserConversions*/ false,
  3128. AllowExplicit,
  3129. /*FIXME:InOverloadResolution=*/false,
  3130. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  3131. /*AllowObjCWritebackConversion=*/false);
  3132. if (ICS.isBad()) {
  3133. // FIXME: Use the conversion function set stored in ICS to turn
  3134. // this into an overloading ambiguity diagnostic. However, we need
  3135. // to keep that set as an OverloadCandidateSet rather than as some
  3136. // other kind of set.
  3137. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
  3138. Sequence.SetOverloadFailure(
  3139. InitializationSequence::FK_ReferenceInitOverloadFailed,
  3140. ConvOvlResult);
  3141. else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
  3142. Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3143. else
  3144. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
  3145. return;
  3146. } else {
  3147. Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
  3148. }
  3149. // [...] If T1 is reference-related to T2, cv1 must be the
  3150. // same cv-qualification as, or greater cv-qualification
  3151. // than, cv2; otherwise, the program is ill-formed.
  3152. unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
  3153. unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
  3154. if (RefRelationship == Sema::Ref_Related &&
  3155. (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
  3156. Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
  3157. return;
  3158. }
  3159. // [...] If T1 is reference-related to T2 and the reference is an rvalue
  3160. // reference, the initializer expression shall not be an lvalue.
  3161. if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
  3162. InitCategory.isLValue()) {
  3163. Sequence.SetFailed(
  3164. InitializationSequence::FK_RValueReferenceBindingToLValue);
  3165. return;
  3166. }
  3167. Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
  3168. return;
  3169. }
  3170. /// \brief Attempt character array initialization from a string literal
  3171. /// (C++ [dcl.init.string], C99 6.7.8).
  3172. static void TryStringLiteralInitialization(Sema &S,
  3173. const InitializedEntity &Entity,
  3174. const InitializationKind &Kind,
  3175. Expr *Initializer,
  3176. InitializationSequence &Sequence) {
  3177. Sequence.AddStringInitStep(Entity.getType());
  3178. }
  3179. /// \brief Attempt value initialization (C++ [dcl.init]p7).
  3180. static void TryValueInitialization(Sema &S,
  3181. const InitializedEntity &Entity,
  3182. const InitializationKind &Kind,
  3183. InitializationSequence &Sequence) {
  3184. // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
  3185. //
  3186. // To value-initialize an object of type T means:
  3187. QualType T = Entity.getType();
  3188. // -- if T is an array type, then each element is value-initialized;
  3189. T = S.Context.getBaseElementType(T);
  3190. if (const RecordType *RT = T->getAs<RecordType>()) {
  3191. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  3192. // C++98:
  3193. // -- if T is a class type (clause 9) with a user-declared
  3194. // constructor (12.1), then the default constructor for T is
  3195. // called (and the initialization is ill-formed if T has no
  3196. // accessible default constructor);
  3197. if (!S.getLangOptions().CPlusPlus0x) {
  3198. if (ClassDecl->hasUserDeclaredConstructor())
  3199. // FIXME: we really want to refer to a single subobject of the array,
  3200. // but Entity doesn't have a way to capture that (yet).
  3201. return TryConstructorInitialization(S, Entity, Kind, 0, 0,
  3202. T, Sequence);
  3203. } else {
  3204. // C++11:
  3205. // -- if T is a class type (clause 9) with either no default constructor
  3206. // (12.1 [class.ctor]) or a default constructor that is user-provided
  3207. // or deleted, then the object is default-initialized;
  3208. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
  3209. if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
  3210. return TryConstructorInitialization(S, Entity, Kind, 0, 0,
  3211. T, Sequence);
  3212. }
  3213. // -- if T is a (possibly cv-qualified) non-union class type without a
  3214. // user-provided or deleted default constructor, then the object is
  3215. // zero-initialized and, if T has a non-trivial default constructor,
  3216. // default-initialized;
  3217. if ((ClassDecl->getTagKind() == TTK_Class ||
  3218. ClassDecl->getTagKind() == TTK_Struct)) {
  3219. Sequence.AddZeroInitializationStep(Entity.getType());
  3220. return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
  3221. }
  3222. }
  3223. }
  3224. Sequence.AddZeroInitializationStep(Entity.getType());
  3225. }
  3226. /// \brief Attempt default initialization (C++ [dcl.init]p6).
  3227. static void TryDefaultInitialization(Sema &S,
  3228. const InitializedEntity &Entity,
  3229. const InitializationKind &Kind,
  3230. InitializationSequence &Sequence) {
  3231. assert(Kind.getKind() == InitializationKind::IK_Default);
  3232. // C++ [dcl.init]p6:
  3233. // To default-initialize an object of type T means:
  3234. // - if T is an array type, each element is default-initialized;
  3235. QualType DestType = S.Context.getBaseElementType(Entity.getType());
  3236. // - if T is a (possibly cv-qualified) class type (Clause 9), the default
  3237. // constructor for T is called (and the initialization is ill-formed if
  3238. // T has no accessible default constructor);
  3239. if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
  3240. TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
  3241. return;
  3242. }
  3243. // - otherwise, no initialization is performed.
  3244. // If a program calls for the default initialization of an object of
  3245. // a const-qualified type T, T shall be a class type with a user-provided
  3246. // default constructor.
  3247. if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
  3248. Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
  3249. return;
  3250. }
  3251. // If the destination type has a lifetime property, zero-initialize it.
  3252. if (DestType.getQualifiers().hasObjCLifetime()) {
  3253. Sequence.AddZeroInitializationStep(Entity.getType());
  3254. return;
  3255. }
  3256. }
  3257. /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
  3258. /// which enumerates all conversion functions and performs overload resolution
  3259. /// to select the best.
  3260. static void TryUserDefinedConversion(Sema &S,
  3261. const InitializedEntity &Entity,
  3262. const InitializationKind &Kind,
  3263. Expr *Initializer,
  3264. InitializationSequence &Sequence) {
  3265. QualType DestType = Entity.getType();
  3266. assert(!DestType->isReferenceType() && "References are handled elsewhere");
  3267. QualType SourceType = Initializer->getType();
  3268. assert((DestType->isRecordType() || SourceType->isRecordType()) &&
  3269. "Must have a class type to perform a user-defined conversion");
  3270. // Build the candidate set directly in the initialization sequence
  3271. // structure, so that it will persist if we fail.
  3272. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
  3273. CandidateSet.clear();
  3274. // Determine whether we are allowed to call explicit constructors or
  3275. // explicit conversion operators.
  3276. bool AllowExplicit = Kind.AllowExplicit();
  3277. if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
  3278. // The type we're converting to is a class type. Enumerate its constructors
  3279. // to see if there is a suitable conversion.
  3280. CXXRecordDecl *DestRecordDecl
  3281. = cast<CXXRecordDecl>(DestRecordType->getDecl());
  3282. // Try to complete the type we're converting to.
  3283. if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
  3284. DeclContext::lookup_iterator Con, ConEnd;
  3285. for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
  3286. Con != ConEnd; ++Con) {
  3287. NamedDecl *D = *Con;
  3288. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  3289. // Find the constructor (which may be a template).
  3290. CXXConstructorDecl *Constructor = 0;
  3291. FunctionTemplateDecl *ConstructorTmpl
  3292. = dyn_cast<FunctionTemplateDecl>(D);
  3293. if (ConstructorTmpl)
  3294. Constructor = cast<CXXConstructorDecl>(
  3295. ConstructorTmpl->getTemplatedDecl());
  3296. else
  3297. Constructor = cast<CXXConstructorDecl>(D);
  3298. if (!Constructor->isInvalidDecl() &&
  3299. Constructor->isConvertingConstructor(AllowExplicit)) {
  3300. if (ConstructorTmpl)
  3301. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  3302. /*ExplicitArgs*/ 0,
  3303. &Initializer, 1, CandidateSet,
  3304. /*SuppressUserConversions=*/true);
  3305. else
  3306. S.AddOverloadCandidate(Constructor, FoundDecl,
  3307. &Initializer, 1, CandidateSet,
  3308. /*SuppressUserConversions=*/true);
  3309. }
  3310. }
  3311. }
  3312. }
  3313. SourceLocation DeclLoc = Initializer->getLocStart();
  3314. if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
  3315. // The type we're converting from is a class type, enumerate its conversion
  3316. // functions.
  3317. // We can only enumerate the conversion functions for a complete type; if
  3318. // the type isn't complete, simply skip this step.
  3319. if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
  3320. CXXRecordDecl *SourceRecordDecl
  3321. = cast<CXXRecordDecl>(SourceRecordType->getDecl());
  3322. const UnresolvedSetImpl *Conversions
  3323. = SourceRecordDecl->getVisibleConversionFunctions();
  3324. for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
  3325. E = Conversions->end();
  3326. I != E; ++I) {
  3327. NamedDecl *D = *I;
  3328. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3329. if (isa<UsingShadowDecl>(D))
  3330. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3331. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
  3332. CXXConversionDecl *Conv;
  3333. if (ConvTemplate)
  3334. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3335. else
  3336. Conv = cast<CXXConversionDecl>(D);
  3337. if (AllowExplicit || !Conv->isExplicit()) {
  3338. if (ConvTemplate)
  3339. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
  3340. ActingDC, Initializer, DestType,
  3341. CandidateSet);
  3342. else
  3343. S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
  3344. Initializer, DestType, CandidateSet);
  3345. }
  3346. }
  3347. }
  3348. }
  3349. // Perform overload resolution. If it fails, return the failed result.
  3350. OverloadCandidateSet::iterator Best;
  3351. if (OverloadingResult Result
  3352. = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3353. Sequence.SetOverloadFailure(
  3354. InitializationSequence::FK_UserConversionOverloadFailed,
  3355. Result);
  3356. return;
  3357. }
  3358. FunctionDecl *Function = Best->Function;
  3359. S.MarkFunctionReferenced(DeclLoc, Function);
  3360. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3361. if (isa<CXXConstructorDecl>(Function)) {
  3362. // Add the user-defined conversion step. Any cv-qualification conversion is
  3363. // subsumed by the initialization. Per DR5, the created temporary is of the
  3364. // cv-unqualified type of the destination.
  3365. Sequence.AddUserConversionStep(Function, Best->FoundDecl,
  3366. DestType.getUnqualifiedType(),
  3367. HadMultipleCandidates);
  3368. return;
  3369. }
  3370. // Add the user-defined conversion step that calls the conversion function.
  3371. QualType ConvType = Function->getCallResultType();
  3372. if (ConvType->getAs<RecordType>()) {
  3373. // If we're converting to a class type, there may be an copy of
  3374. // the resulting temporary object (possible to create an object of
  3375. // a base class type). That copy is not a separate conversion, so
  3376. // we just make a note of the actual destination type (possibly a
  3377. // base class of the type returned by the conversion function) and
  3378. // let the user-defined conversion step handle the conversion.
  3379. Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
  3380. HadMultipleCandidates);
  3381. return;
  3382. }
  3383. Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
  3384. HadMultipleCandidates);
  3385. // If the conversion following the call to the conversion function
  3386. // is interesting, add it as a separate step.
  3387. if (Best->FinalConversion.First || Best->FinalConversion.Second ||
  3388. Best->FinalConversion.Third) {
  3389. ImplicitConversionSequence ICS;
  3390. ICS.setStandard();
  3391. ICS.Standard = Best->FinalConversion;
  3392. Sequence.AddConversionSequenceStep(ICS, DestType);
  3393. }
  3394. }
  3395. /// The non-zero enum values here are indexes into diagnostic alternatives.
  3396. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
  3397. /// Determines whether this expression is an acceptable ICR source.
  3398. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
  3399. bool isAddressOf) {
  3400. // Skip parens.
  3401. e = e->IgnoreParens();
  3402. // Skip address-of nodes.
  3403. if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
  3404. if (op->getOpcode() == UO_AddrOf)
  3405. return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
  3406. // Skip certain casts.
  3407. } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
  3408. switch (ce->getCastKind()) {
  3409. case CK_Dependent:
  3410. case CK_BitCast:
  3411. case CK_LValueBitCast:
  3412. case CK_NoOp:
  3413. return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
  3414. case CK_ArrayToPointerDecay:
  3415. return IIK_nonscalar;
  3416. case CK_NullToPointer:
  3417. return IIK_okay;
  3418. default:
  3419. break;
  3420. }
  3421. // If we have a declaration reference, it had better be a local variable.
  3422. } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
  3423. if (!isAddressOf) return IIK_nonlocal;
  3424. VarDecl *var;
  3425. if (isa<DeclRefExpr>(e)) {
  3426. var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
  3427. if (!var) return IIK_nonlocal;
  3428. } else {
  3429. var = cast<BlockDeclRefExpr>(e)->getDecl();
  3430. }
  3431. return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
  3432. // If we have a conditional operator, check both sides.
  3433. } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
  3434. if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
  3435. return iik;
  3436. return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
  3437. // These are never scalar.
  3438. } else if (isa<ArraySubscriptExpr>(e)) {
  3439. return IIK_nonscalar;
  3440. // Otherwise, it needs to be a null pointer constant.
  3441. } else {
  3442. return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
  3443. ? IIK_okay : IIK_nonlocal);
  3444. }
  3445. return IIK_nonlocal;
  3446. }
  3447. /// Check whether the given expression is a valid operand for an
  3448. /// indirect copy/restore.
  3449. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
  3450. assert(src->isRValue());
  3451. InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
  3452. if (iik == IIK_okay) return;
  3453. S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
  3454. << ((unsigned) iik - 1) // shift index into diagnostic explanations
  3455. << src->getSourceRange();
  3456. }
  3457. /// \brief Determine whether we have compatible array types for the
  3458. /// purposes of GNU by-copy array initialization.
  3459. static bool hasCompatibleArrayTypes(ASTContext &Context,
  3460. const ArrayType *Dest,
  3461. const ArrayType *Source) {
  3462. // If the source and destination array types are equivalent, we're
  3463. // done.
  3464. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
  3465. return true;
  3466. // Make sure that the element types are the same.
  3467. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
  3468. return false;
  3469. // The only mismatch we allow is when the destination is an
  3470. // incomplete array type and the source is a constant array type.
  3471. return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
  3472. }
  3473. static bool tryObjCWritebackConversion(Sema &S,
  3474. InitializationSequence &Sequence,
  3475. const InitializedEntity &Entity,
  3476. Expr *Initializer) {
  3477. bool ArrayDecay = false;
  3478. QualType ArgType = Initializer->getType();
  3479. QualType ArgPointee;
  3480. if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
  3481. ArrayDecay = true;
  3482. ArgPointee = ArgArrayType->getElementType();
  3483. ArgType = S.Context.getPointerType(ArgPointee);
  3484. }
  3485. // Handle write-back conversion.
  3486. QualType ConvertedArgType;
  3487. if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
  3488. ConvertedArgType))
  3489. return false;
  3490. // We should copy unless we're passing to an argument explicitly
  3491. // marked 'out'.
  3492. bool ShouldCopy = true;
  3493. if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  3494. ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  3495. // Do we need an lvalue conversion?
  3496. if (ArrayDecay || Initializer->isGLValue()) {
  3497. ImplicitConversionSequence ICS;
  3498. ICS.setStandard();
  3499. ICS.Standard.setAsIdentityConversion();
  3500. QualType ResultType;
  3501. if (ArrayDecay) {
  3502. ICS.Standard.First = ICK_Array_To_Pointer;
  3503. ResultType = S.Context.getPointerType(ArgPointee);
  3504. } else {
  3505. ICS.Standard.First = ICK_Lvalue_To_Rvalue;
  3506. ResultType = Initializer->getType().getNonLValueExprType(S.Context);
  3507. }
  3508. Sequence.AddConversionSequenceStep(ICS, ResultType);
  3509. }
  3510. Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  3511. return true;
  3512. }
  3513. InitializationSequence::InitializationSequence(Sema &S,
  3514. const InitializedEntity &Entity,
  3515. const InitializationKind &Kind,
  3516. Expr **Args,
  3517. unsigned NumArgs)
  3518. : FailedCandidateSet(Kind.getLocation()) {
  3519. ASTContext &Context = S.Context;
  3520. // C++0x [dcl.init]p16:
  3521. // The semantics of initializers are as follows. The destination type is
  3522. // the type of the object or reference being initialized and the source
  3523. // type is the type of the initializer expression. The source type is not
  3524. // defined when the initializer is a braced-init-list or when it is a
  3525. // parenthesized list of expressions.
  3526. QualType DestType = Entity.getType();
  3527. if (DestType->isDependentType() ||
  3528. Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
  3529. SequenceKind = DependentSequence;
  3530. return;
  3531. }
  3532. // Almost everything is a normal sequence.
  3533. setSequenceKind(NormalSequence);
  3534. for (unsigned I = 0; I != NumArgs; ++I)
  3535. if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
  3536. // FIXME: should we be doing this here?
  3537. ExprResult result = S.CheckPlaceholderExpr(Args[I]);
  3538. if (result.isInvalid()) {
  3539. SetFailed(FK_PlaceholderType);
  3540. return;
  3541. }
  3542. Args[I] = result.take();
  3543. }
  3544. QualType SourceType;
  3545. Expr *Initializer = 0;
  3546. if (NumArgs == 1) {
  3547. Initializer = Args[0];
  3548. if (!isa<InitListExpr>(Initializer))
  3549. SourceType = Initializer->getType();
  3550. }
  3551. // - If the initializer is a (non-parenthesized) braced-init-list, the
  3552. // object is list-initialized (8.5.4).
  3553. if (Kind.getKind() != InitializationKind::IK_Direct) {
  3554. if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
  3555. TryListInitialization(S, Entity, Kind, InitList, *this);
  3556. return;
  3557. }
  3558. }
  3559. // - If the destination type is a reference type, see 8.5.3.
  3560. if (DestType->isReferenceType()) {
  3561. // C++0x [dcl.init.ref]p1:
  3562. // A variable declared to be a T& or T&&, that is, "reference to type T"
  3563. // (8.3.2), shall be initialized by an object, or function, of type T or
  3564. // by an object that can be converted into a T.
  3565. // (Therefore, multiple arguments are not permitted.)
  3566. if (NumArgs != 1)
  3567. SetFailed(FK_TooManyInitsForReference);
  3568. else
  3569. TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
  3570. return;
  3571. }
  3572. // - If the initializer is (), the object is value-initialized.
  3573. if (Kind.getKind() == InitializationKind::IK_Value ||
  3574. (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
  3575. TryValueInitialization(S, Entity, Kind, *this);
  3576. return;
  3577. }
  3578. // Handle default initialization.
  3579. if (Kind.getKind() == InitializationKind::IK_Default) {
  3580. TryDefaultInitialization(S, Entity, Kind, *this);
  3581. return;
  3582. }
  3583. // - If the destination type is an array of characters, an array of
  3584. // char16_t, an array of char32_t, or an array of wchar_t, and the
  3585. // initializer is a string literal, see 8.5.2.
  3586. // - Otherwise, if the destination type is an array, the program is
  3587. // ill-formed.
  3588. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
  3589. if (Initializer && isa<VariableArrayType>(DestAT)) {
  3590. SetFailed(FK_VariableLengthArrayHasInitializer);
  3591. return;
  3592. }
  3593. if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
  3594. TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
  3595. return;
  3596. }
  3597. // Note: as an GNU C extension, we allow initialization of an
  3598. // array from a compound literal that creates an array of the same
  3599. // type, so long as the initializer has no side effects.
  3600. if (!S.getLangOptions().CPlusPlus && Initializer &&
  3601. isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
  3602. Initializer->getType()->isArrayType()) {
  3603. const ArrayType *SourceAT
  3604. = Context.getAsArrayType(Initializer->getType());
  3605. if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
  3606. SetFailed(FK_ArrayTypeMismatch);
  3607. else if (Initializer->HasSideEffects(S.Context))
  3608. SetFailed(FK_NonConstantArrayInit);
  3609. else {
  3610. AddArrayInitStep(DestType);
  3611. }
  3612. } else if (DestAT->getElementType()->isAnyCharacterType())
  3613. SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
  3614. else
  3615. SetFailed(FK_ArrayNeedsInitList);
  3616. return;
  3617. }
  3618. // Determine whether we should consider writeback conversions for
  3619. // Objective-C ARC.
  3620. bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
  3621. Entity.getKind() == InitializedEntity::EK_Parameter;
  3622. // We're at the end of the line for C: it's either a write-back conversion
  3623. // or it's a C assignment. There's no need to check anything else.
  3624. if (!S.getLangOptions().CPlusPlus) {
  3625. // If allowed, check whether this is an Objective-C writeback conversion.
  3626. if (allowObjCWritebackConversion &&
  3627. tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
  3628. return;
  3629. }
  3630. // Handle initialization in C
  3631. AddCAssignmentStep(DestType);
  3632. MaybeProduceObjCObject(S, *this, Entity);
  3633. return;
  3634. }
  3635. assert(S.getLangOptions().CPlusPlus);
  3636. // - If the destination type is a (possibly cv-qualified) class type:
  3637. if (DestType->isRecordType()) {
  3638. // - If the initialization is direct-initialization, or if it is
  3639. // copy-initialization where the cv-unqualified version of the
  3640. // source type is the same class as, or a derived class of, the
  3641. // class of the destination, constructors are considered. [...]
  3642. if (Kind.getKind() == InitializationKind::IK_Direct ||
  3643. (Kind.getKind() == InitializationKind::IK_Copy &&
  3644. (Context.hasSameUnqualifiedType(SourceType, DestType) ||
  3645. S.IsDerivedFrom(SourceType, DestType))))
  3646. TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
  3647. Entity.getType(), *this);
  3648. // - Otherwise (i.e., for the remaining copy-initialization cases),
  3649. // user-defined conversion sequences that can convert from the source
  3650. // type to the destination type or (when a conversion function is
  3651. // used) to a derived class thereof are enumerated as described in
  3652. // 13.3.1.4, and the best one is chosen through overload resolution
  3653. // (13.3).
  3654. else
  3655. TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
  3656. return;
  3657. }
  3658. if (NumArgs > 1) {
  3659. SetFailed(FK_TooManyInitsForScalar);
  3660. return;
  3661. }
  3662. assert(NumArgs == 1 && "Zero-argument case handled above");
  3663. // - Otherwise, if the source type is a (possibly cv-qualified) class
  3664. // type, conversion functions are considered.
  3665. if (!SourceType.isNull() && SourceType->isRecordType()) {
  3666. TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
  3667. MaybeProduceObjCObject(S, *this, Entity);
  3668. return;
  3669. }
  3670. // - Otherwise, the initial value of the object being initialized is the
  3671. // (possibly converted) value of the initializer expression. Standard
  3672. // conversions (Clause 4) will be used, if necessary, to convert the
  3673. // initializer expression to the cv-unqualified version of the
  3674. // destination type; no user-defined conversions are considered.
  3675. ImplicitConversionSequence ICS
  3676. = S.TryImplicitConversion(Initializer, Entity.getType(),
  3677. /*SuppressUserConversions*/true,
  3678. /*AllowExplicitConversions*/ false,
  3679. /*InOverloadResolution*/ false,
  3680. /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
  3681. allowObjCWritebackConversion);
  3682. if (ICS.isStandard() &&
  3683. ICS.Standard.Second == ICK_Writeback_Conversion) {
  3684. // Objective-C ARC writeback conversion.
  3685. // We should copy unless we're passing to an argument explicitly
  3686. // marked 'out'.
  3687. bool ShouldCopy = true;
  3688. if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
  3689. ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
  3690. // If there was an lvalue adjustment, add it as a separate conversion.
  3691. if (ICS.Standard.First == ICK_Array_To_Pointer ||
  3692. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  3693. ImplicitConversionSequence LvalueICS;
  3694. LvalueICS.setStandard();
  3695. LvalueICS.Standard.setAsIdentityConversion();
  3696. LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
  3697. LvalueICS.Standard.First = ICS.Standard.First;
  3698. AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
  3699. }
  3700. AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
  3701. } else if (ICS.isBad()) {
  3702. DeclAccessPair dap;
  3703. if (Initializer->getType() == Context.OverloadTy &&
  3704. !S.ResolveAddressOfOverloadedFunction(Initializer
  3705. , DestType, false, dap))
  3706. SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
  3707. else
  3708. SetFailed(InitializationSequence::FK_ConversionFailed);
  3709. } else {
  3710. AddConversionSequenceStep(ICS, Entity.getType());
  3711. MaybeProduceObjCObject(S, *this, Entity);
  3712. }
  3713. }
  3714. InitializationSequence::~InitializationSequence() {
  3715. for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
  3716. StepEnd = Steps.end();
  3717. Step != StepEnd; ++Step)
  3718. Step->Destroy();
  3719. }
  3720. //===----------------------------------------------------------------------===//
  3721. // Perform initialization
  3722. //===----------------------------------------------------------------------===//
  3723. static Sema::AssignmentAction
  3724. getAssignmentAction(const InitializedEntity &Entity) {
  3725. switch(Entity.getKind()) {
  3726. case InitializedEntity::EK_Variable:
  3727. case InitializedEntity::EK_New:
  3728. case InitializedEntity::EK_Exception:
  3729. case InitializedEntity::EK_Base:
  3730. case InitializedEntity::EK_Delegating:
  3731. return Sema::AA_Initializing;
  3732. case InitializedEntity::EK_Parameter:
  3733. if (Entity.getDecl() &&
  3734. isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
  3735. return Sema::AA_Sending;
  3736. return Sema::AA_Passing;
  3737. case InitializedEntity::EK_Result:
  3738. return Sema::AA_Returning;
  3739. case InitializedEntity::EK_Temporary:
  3740. // FIXME: Can we tell apart casting vs. converting?
  3741. return Sema::AA_Casting;
  3742. case InitializedEntity::EK_Member:
  3743. case InitializedEntity::EK_ArrayElement:
  3744. case InitializedEntity::EK_VectorElement:
  3745. case InitializedEntity::EK_ComplexElement:
  3746. case InitializedEntity::EK_BlockElement:
  3747. case InitializedEntity::EK_LambdaCapture:
  3748. return Sema::AA_Initializing;
  3749. }
  3750. llvm_unreachable("Invalid EntityKind!");
  3751. }
  3752. /// \brief Whether we should binding a created object as a temporary when
  3753. /// initializing the given entity.
  3754. static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
  3755. switch (Entity.getKind()) {
  3756. case InitializedEntity::EK_ArrayElement:
  3757. case InitializedEntity::EK_Member:
  3758. case InitializedEntity::EK_Result:
  3759. case InitializedEntity::EK_New:
  3760. case InitializedEntity::EK_Variable:
  3761. case InitializedEntity::EK_Base:
  3762. case InitializedEntity::EK_Delegating:
  3763. case InitializedEntity::EK_VectorElement:
  3764. case InitializedEntity::EK_ComplexElement:
  3765. case InitializedEntity::EK_Exception:
  3766. case InitializedEntity::EK_BlockElement:
  3767. case InitializedEntity::EK_LambdaCapture:
  3768. return false;
  3769. case InitializedEntity::EK_Parameter:
  3770. case InitializedEntity::EK_Temporary:
  3771. return true;
  3772. }
  3773. llvm_unreachable("missed an InitializedEntity kind?");
  3774. }
  3775. /// \brief Whether the given entity, when initialized with an object
  3776. /// created for that initialization, requires destruction.
  3777. static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
  3778. switch (Entity.getKind()) {
  3779. case InitializedEntity::EK_Member:
  3780. case InitializedEntity::EK_Result:
  3781. case InitializedEntity::EK_New:
  3782. case InitializedEntity::EK_Base:
  3783. case InitializedEntity::EK_Delegating:
  3784. case InitializedEntity::EK_VectorElement:
  3785. case InitializedEntity::EK_ComplexElement:
  3786. case InitializedEntity::EK_BlockElement:
  3787. case InitializedEntity::EK_LambdaCapture:
  3788. return false;
  3789. case InitializedEntity::EK_Variable:
  3790. case InitializedEntity::EK_Parameter:
  3791. case InitializedEntity::EK_Temporary:
  3792. case InitializedEntity::EK_ArrayElement:
  3793. case InitializedEntity::EK_Exception:
  3794. return true;
  3795. }
  3796. llvm_unreachable("missed an InitializedEntity kind?");
  3797. }
  3798. /// \brief Look for copy and move constructors and constructor templates, for
  3799. /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
  3800. static void LookupCopyAndMoveConstructors(Sema &S,
  3801. OverloadCandidateSet &CandidateSet,
  3802. CXXRecordDecl *Class,
  3803. Expr *CurInitExpr) {
  3804. DeclContext::lookup_iterator Con, ConEnd;
  3805. for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
  3806. Con != ConEnd; ++Con) {
  3807. CXXConstructorDecl *Constructor = 0;
  3808. if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
  3809. // Handle copy/moveconstructors, only.
  3810. if (!Constructor || Constructor->isInvalidDecl() ||
  3811. !Constructor->isCopyOrMoveConstructor() ||
  3812. !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
  3813. continue;
  3814. DeclAccessPair FoundDecl
  3815. = DeclAccessPair::make(Constructor, Constructor->getAccess());
  3816. S.AddOverloadCandidate(Constructor, FoundDecl,
  3817. &CurInitExpr, 1, CandidateSet);
  3818. continue;
  3819. }
  3820. // Handle constructor templates.
  3821. FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
  3822. if (ConstructorTmpl->isInvalidDecl())
  3823. continue;
  3824. Constructor = cast<CXXConstructorDecl>(
  3825. ConstructorTmpl->getTemplatedDecl());
  3826. if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
  3827. continue;
  3828. // FIXME: Do we need to limit this to copy-constructor-like
  3829. // candidates?
  3830. DeclAccessPair FoundDecl
  3831. = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
  3832. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
  3833. &CurInitExpr, 1, CandidateSet, true);
  3834. }
  3835. }
  3836. /// \brief Get the location at which initialization diagnostics should appear.
  3837. static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
  3838. Expr *Initializer) {
  3839. switch (Entity.getKind()) {
  3840. case InitializedEntity::EK_Result:
  3841. return Entity.getReturnLoc();
  3842. case InitializedEntity::EK_Exception:
  3843. return Entity.getThrowLoc();
  3844. case InitializedEntity::EK_Variable:
  3845. return Entity.getDecl()->getLocation();
  3846. case InitializedEntity::EK_LambdaCapture:
  3847. return Entity.getCaptureLoc();
  3848. case InitializedEntity::EK_ArrayElement:
  3849. case InitializedEntity::EK_Member:
  3850. case InitializedEntity::EK_Parameter:
  3851. case InitializedEntity::EK_Temporary:
  3852. case InitializedEntity::EK_New:
  3853. case InitializedEntity::EK_Base:
  3854. case InitializedEntity::EK_Delegating:
  3855. case InitializedEntity::EK_VectorElement:
  3856. case InitializedEntity::EK_ComplexElement:
  3857. case InitializedEntity::EK_BlockElement:
  3858. return Initializer->getLocStart();
  3859. }
  3860. llvm_unreachable("missed an InitializedEntity kind?");
  3861. }
  3862. /// \brief Make a (potentially elidable) temporary copy of the object
  3863. /// provided by the given initializer by calling the appropriate copy
  3864. /// constructor.
  3865. ///
  3866. /// \param S The Sema object used for type-checking.
  3867. ///
  3868. /// \param T The type of the temporary object, which must either be
  3869. /// the type of the initializer expression or a superclass thereof.
  3870. ///
  3871. /// \param Enter The entity being initialized.
  3872. ///
  3873. /// \param CurInit The initializer expression.
  3874. ///
  3875. /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
  3876. /// is permitted in C++03 (but not C++0x) when binding a reference to
  3877. /// an rvalue.
  3878. ///
  3879. /// \returns An expression that copies the initializer expression into
  3880. /// a temporary object, or an error expression if a copy could not be
  3881. /// created.
  3882. static ExprResult CopyObject(Sema &S,
  3883. QualType T,
  3884. const InitializedEntity &Entity,
  3885. ExprResult CurInit,
  3886. bool IsExtraneousCopy) {
  3887. // Determine which class type we're copying to.
  3888. Expr *CurInitExpr = (Expr *)CurInit.get();
  3889. CXXRecordDecl *Class = 0;
  3890. if (const RecordType *Record = T->getAs<RecordType>())
  3891. Class = cast<CXXRecordDecl>(Record->getDecl());
  3892. if (!Class)
  3893. return move(CurInit);
  3894. // C++0x [class.copy]p32:
  3895. // When certain criteria are met, an implementation is allowed to
  3896. // omit the copy/move construction of a class object, even if the
  3897. // copy/move constructor and/or destructor for the object have
  3898. // side effects. [...]
  3899. // - when a temporary class object that has not been bound to a
  3900. // reference (12.2) would be copied/moved to a class object
  3901. // with the same cv-unqualified type, the copy/move operation
  3902. // can be omitted by constructing the temporary object
  3903. // directly into the target of the omitted copy/move
  3904. //
  3905. // Note that the other three bullets are handled elsewhere. Copy
  3906. // elision for return statements and throw expressions are handled as part
  3907. // of constructor initialization, while copy elision for exception handlers
  3908. // is handled by the run-time.
  3909. bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
  3910. SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
  3911. // Make sure that the type we are copying is complete.
  3912. if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
  3913. return move(CurInit);
  3914. // Perform overload resolution using the class's copy/move constructors.
  3915. // Only consider constructors and constructor templates. Per
  3916. // C++0x [dcl.init]p16, second bullet to class types, this initialization
  3917. // is direct-initialization.
  3918. OverloadCandidateSet CandidateSet(Loc);
  3919. LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
  3920. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3921. OverloadCandidateSet::iterator Best;
  3922. switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
  3923. case OR_Success:
  3924. break;
  3925. case OR_No_Viable_Function:
  3926. S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
  3927. ? diag::ext_rvalue_to_reference_temp_copy_no_viable
  3928. : diag::err_temp_copy_no_viable)
  3929. << (int)Entity.getKind() << CurInitExpr->getType()
  3930. << CurInitExpr->getSourceRange();
  3931. CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
  3932. if (!IsExtraneousCopy || S.isSFINAEContext())
  3933. return ExprError();
  3934. return move(CurInit);
  3935. case OR_Ambiguous:
  3936. S.Diag(Loc, diag::err_temp_copy_ambiguous)
  3937. << (int)Entity.getKind() << CurInitExpr->getType()
  3938. << CurInitExpr->getSourceRange();
  3939. CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
  3940. return ExprError();
  3941. case OR_Deleted:
  3942. S.Diag(Loc, diag::err_temp_copy_deleted)
  3943. << (int)Entity.getKind() << CurInitExpr->getType()
  3944. << CurInitExpr->getSourceRange();
  3945. S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
  3946. << 1 << Best->Function->isDeleted();
  3947. return ExprError();
  3948. }
  3949. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  3950. ASTOwningVector<Expr*> ConstructorArgs(S);
  3951. CurInit.release(); // Ownership transferred into MultiExprArg, below.
  3952. S.CheckConstructorAccess(Loc, Constructor, Entity,
  3953. Best->FoundDecl.getAccess(), IsExtraneousCopy);
  3954. if (IsExtraneousCopy) {
  3955. // If this is a totally extraneous copy for C++03 reference
  3956. // binding purposes, just return the original initialization
  3957. // expression. We don't generate an (elided) copy operation here
  3958. // because doing so would require us to pass down a flag to avoid
  3959. // infinite recursion, where each step adds another extraneous,
  3960. // elidable copy.
  3961. // Instantiate the default arguments of any extra parameters in
  3962. // the selected copy constructor, as if we were going to create a
  3963. // proper call to the copy constructor.
  3964. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
  3965. ParmVarDecl *Parm = Constructor->getParamDecl(I);
  3966. if (S.RequireCompleteType(Loc, Parm->getType(),
  3967. S.PDiag(diag::err_call_incomplete_argument)))
  3968. break;
  3969. // Build the default argument expression; we don't actually care
  3970. // if this succeeds or not, because this routine will complain
  3971. // if there was a problem.
  3972. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
  3973. }
  3974. return S.Owned(CurInitExpr);
  3975. }
  3976. S.MarkFunctionReferenced(Loc, Constructor);
  3977. // Determine the arguments required to actually perform the
  3978. // constructor call (we might have derived-to-base conversions, or
  3979. // the copy constructor may have default arguments).
  3980. if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
  3981. Loc, ConstructorArgs))
  3982. return ExprError();
  3983. // Actually perform the constructor call.
  3984. CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
  3985. move_arg(ConstructorArgs),
  3986. HadMultipleCandidates,
  3987. /*ZeroInit*/ false,
  3988. CXXConstructExpr::CK_Complete,
  3989. SourceRange());
  3990. // If we're supposed to bind temporaries, do so.
  3991. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
  3992. CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
  3993. return move(CurInit);
  3994. }
  3995. /// \brief Check whether elidable copy construction for binding a reference to
  3996. /// a temporary would have succeeded if we were building in C++98 mode, for
  3997. /// -Wc++98-compat.
  3998. static void CheckCXX98CompatAccessibleCopy(Sema &S,
  3999. const InitializedEntity &Entity,
  4000. Expr *CurInitExpr) {
  4001. assert(S.getLangOptions().CPlusPlus0x);
  4002. const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
  4003. if (!Record)
  4004. return;
  4005. SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
  4006. if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
  4007. == DiagnosticsEngine::Ignored)
  4008. return;
  4009. // Find constructors which would have been considered.
  4010. OverloadCandidateSet CandidateSet(Loc);
  4011. LookupCopyAndMoveConstructors(
  4012. S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
  4013. // Perform overload resolution.
  4014. OverloadCandidateSet::iterator Best;
  4015. OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
  4016. PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
  4017. << OR << (int)Entity.getKind() << CurInitExpr->getType()
  4018. << CurInitExpr->getSourceRange();
  4019. switch (OR) {
  4020. case OR_Success:
  4021. S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
  4022. Best->FoundDecl.getAccess(), Diag);
  4023. // FIXME: Check default arguments as far as that's possible.
  4024. break;
  4025. case OR_No_Viable_Function:
  4026. S.Diag(Loc, Diag);
  4027. CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
  4028. break;
  4029. case OR_Ambiguous:
  4030. S.Diag(Loc, Diag);
  4031. CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
  4032. break;
  4033. case OR_Deleted:
  4034. S.Diag(Loc, Diag);
  4035. S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
  4036. << 1 << Best->Function->isDeleted();
  4037. break;
  4038. }
  4039. }
  4040. void InitializationSequence::PrintInitLocationNote(Sema &S,
  4041. const InitializedEntity &Entity) {
  4042. if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
  4043. if (Entity.getDecl()->getLocation().isInvalid())
  4044. return;
  4045. if (Entity.getDecl()->getDeclName())
  4046. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
  4047. << Entity.getDecl()->getDeclName();
  4048. else
  4049. S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
  4050. }
  4051. }
  4052. static bool isReferenceBinding(const InitializationSequence::Step &s) {
  4053. return s.Kind == InitializationSequence::SK_BindReference ||
  4054. s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
  4055. }
  4056. static ExprResult
  4057. PerformConstructorInitialization(Sema &S,
  4058. const InitializedEntity &Entity,
  4059. const InitializationKind &Kind,
  4060. MultiExprArg Args,
  4061. const InitializationSequence::Step& Step,
  4062. bool &ConstructorInitRequiresZeroInit) {
  4063. unsigned NumArgs = Args.size();
  4064. CXXConstructorDecl *Constructor
  4065. = cast<CXXConstructorDecl>(Step.Function.Function);
  4066. bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
  4067. // Build a call to the selected constructor.
  4068. ASTOwningVector<Expr*> ConstructorArgs(S);
  4069. SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
  4070. ? Kind.getEqualLoc()
  4071. : Kind.getLocation();
  4072. if (Kind.getKind() == InitializationKind::IK_Default) {
  4073. // Force even a trivial, implicit default constructor to be
  4074. // semantically checked. We do this explicitly because we don't build
  4075. // the definition for completely trivial constructors.
  4076. CXXRecordDecl *ClassDecl = Constructor->getParent();
  4077. assert(ClassDecl && "No parent class for constructor.");
  4078. if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  4079. ClassDecl->hasTrivialDefaultConstructor() &&
  4080. !Constructor->isUsed(false))
  4081. S.DefineImplicitDefaultConstructor(Loc, Constructor);
  4082. }
  4083. ExprResult CurInit = S.Owned((Expr *)0);
  4084. // Determine the arguments required to actually perform the constructor
  4085. // call.
  4086. if (S.CompleteConstructorCall(Constructor, move(Args),
  4087. Loc, ConstructorArgs))
  4088. return ExprError();
  4089. if (Entity.getKind() == InitializedEntity::EK_Temporary &&
  4090. NumArgs != 1 && // FIXME: Hack to work around cast weirdness
  4091. (Kind.getKind() == InitializationKind::IK_Direct ||
  4092. Kind.getKind() == InitializationKind::IK_Value)) {
  4093. // An explicitly-constructed temporary, e.g., X(1, 2).
  4094. unsigned NumExprs = ConstructorArgs.size();
  4095. Expr **Exprs = (Expr **)ConstructorArgs.take();
  4096. S.MarkFunctionReferenced(Loc, Constructor);
  4097. S.DiagnoseUseOfDecl(Constructor, Loc);
  4098. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  4099. if (!TSInfo)
  4100. TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
  4101. CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
  4102. Constructor,
  4103. TSInfo,
  4104. Exprs,
  4105. NumExprs,
  4106. Kind.getParenRange(),
  4107. HadMultipleCandidates,
  4108. ConstructorInitRequiresZeroInit));
  4109. } else {
  4110. CXXConstructExpr::ConstructionKind ConstructKind =
  4111. CXXConstructExpr::CK_Complete;
  4112. if (Entity.getKind() == InitializedEntity::EK_Base) {
  4113. ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
  4114. CXXConstructExpr::CK_VirtualBase :
  4115. CXXConstructExpr::CK_NonVirtualBase;
  4116. } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
  4117. ConstructKind = CXXConstructExpr::CK_Delegating;
  4118. }
  4119. // Only get the parenthesis range if it is a direct construction.
  4120. SourceRange parenRange =
  4121. Kind.getKind() == InitializationKind::IK_Direct ?
  4122. Kind.getParenRange() : SourceRange();
  4123. // If the entity allows NRVO, mark the construction as elidable
  4124. // unconditionally.
  4125. if (Entity.allowsNRVO())
  4126. CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
  4127. Constructor, /*Elidable=*/true,
  4128. move_arg(ConstructorArgs),
  4129. HadMultipleCandidates,
  4130. ConstructorInitRequiresZeroInit,
  4131. ConstructKind,
  4132. parenRange);
  4133. else
  4134. CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
  4135. Constructor,
  4136. move_arg(ConstructorArgs),
  4137. HadMultipleCandidates,
  4138. ConstructorInitRequiresZeroInit,
  4139. ConstructKind,
  4140. parenRange);
  4141. }
  4142. if (CurInit.isInvalid())
  4143. return ExprError();
  4144. // Only check access if all of that succeeded.
  4145. S.CheckConstructorAccess(Loc, Constructor, Entity,
  4146. Step.Function.FoundDecl.getAccess());
  4147. S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
  4148. if (shouldBindAsTemporary(Entity))
  4149. CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
  4150. return move(CurInit);
  4151. }
  4152. ExprResult
  4153. InitializationSequence::Perform(Sema &S,
  4154. const InitializedEntity &Entity,
  4155. const InitializationKind &Kind,
  4156. MultiExprArg Args,
  4157. QualType *ResultType) {
  4158. if (Failed()) {
  4159. unsigned NumArgs = Args.size();
  4160. Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
  4161. return ExprError();
  4162. }
  4163. if (getKind() == DependentSequence) {
  4164. // If the declaration is a non-dependent, incomplete array type
  4165. // that has an initializer, then its type will be completed once
  4166. // the initializer is instantiated.
  4167. if (ResultType && !Entity.getType()->isDependentType() &&
  4168. Args.size() == 1) {
  4169. QualType DeclType = Entity.getType();
  4170. if (const IncompleteArrayType *ArrayT
  4171. = S.Context.getAsIncompleteArrayType(DeclType)) {
  4172. // FIXME: We don't currently have the ability to accurately
  4173. // compute the length of an initializer list without
  4174. // performing full type-checking of the initializer list
  4175. // (since we have to determine where braces are implicitly
  4176. // introduced and such). So, we fall back to making the array
  4177. // type a dependently-sized array type with no specified
  4178. // bound.
  4179. if (isa<InitListExpr>((Expr *)Args.get()[0])) {
  4180. SourceRange Brackets;
  4181. // Scavange the location of the brackets from the entity, if we can.
  4182. if (DeclaratorDecl *DD = Entity.getDecl()) {
  4183. if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
  4184. TypeLoc TL = TInfo->getTypeLoc();
  4185. if (IncompleteArrayTypeLoc *ArrayLoc
  4186. = dyn_cast<IncompleteArrayTypeLoc>(&TL))
  4187. Brackets = ArrayLoc->getBracketsRange();
  4188. }
  4189. }
  4190. *ResultType
  4191. = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
  4192. /*NumElts=*/0,
  4193. ArrayT->getSizeModifier(),
  4194. ArrayT->getIndexTypeCVRQualifiers(),
  4195. Brackets);
  4196. }
  4197. }
  4198. }
  4199. if (Kind.getKind() == InitializationKind::IK_Direct &&
  4200. !Kind.isExplicitCast()) {
  4201. // Rebuild the ParenListExpr.
  4202. SourceRange ParenRange = Kind.getParenRange();
  4203. return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
  4204. move(Args));
  4205. }
  4206. assert(Kind.getKind() == InitializationKind::IK_Copy ||
  4207. Kind.isExplicitCast());
  4208. return ExprResult(Args.release()[0]);
  4209. }
  4210. // No steps means no initialization.
  4211. if (Steps.empty())
  4212. return S.Owned((Expr *)0);
  4213. QualType DestType = Entity.getType().getNonReferenceType();
  4214. // FIXME: Ugly hack around the fact that Entity.getType() is not
  4215. // the same as Entity.getDecl()->getType() in cases involving type merging,
  4216. // and we want latter when it makes sense.
  4217. if (ResultType)
  4218. *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
  4219. Entity.getType();
  4220. ExprResult CurInit = S.Owned((Expr *)0);
  4221. // For initialization steps that start with a single initializer,
  4222. // grab the only argument out the Args and place it into the "current"
  4223. // initializer.
  4224. switch (Steps.front().Kind) {
  4225. case SK_ResolveAddressOfOverloadedFunction:
  4226. case SK_CastDerivedToBaseRValue:
  4227. case SK_CastDerivedToBaseXValue:
  4228. case SK_CastDerivedToBaseLValue:
  4229. case SK_BindReference:
  4230. case SK_BindReferenceToTemporary:
  4231. case SK_ExtraneousCopyToTemporary:
  4232. case SK_UserConversion:
  4233. case SK_QualificationConversionLValue:
  4234. case SK_QualificationConversionXValue:
  4235. case SK_QualificationConversionRValue:
  4236. case SK_ConversionSequence:
  4237. case SK_ListConstructorCall:
  4238. case SK_ListInitialization:
  4239. case SK_UnwrapInitList:
  4240. case SK_RewrapInitList:
  4241. case SK_CAssignment:
  4242. case SK_StringInit:
  4243. case SK_ObjCObjectConversion:
  4244. case SK_ArrayInit:
  4245. case SK_PassByIndirectCopyRestore:
  4246. case SK_PassByIndirectRestore:
  4247. case SK_ProduceObjCObject:
  4248. case SK_StdInitializerList: {
  4249. assert(Args.size() == 1);
  4250. CurInit = Args.get()[0];
  4251. if (!CurInit.get()) return ExprError();
  4252. break;
  4253. }
  4254. case SK_ConstructorInitialization:
  4255. case SK_ZeroInitialization:
  4256. break;
  4257. }
  4258. // Walk through the computed steps for the initialization sequence,
  4259. // performing the specified conversions along the way.
  4260. bool ConstructorInitRequiresZeroInit = false;
  4261. for (step_iterator Step = step_begin(), StepEnd = step_end();
  4262. Step != StepEnd; ++Step) {
  4263. if (CurInit.isInvalid())
  4264. return ExprError();
  4265. QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
  4266. switch (Step->Kind) {
  4267. case SK_ResolveAddressOfOverloadedFunction:
  4268. // Overload resolution determined which function invoke; update the
  4269. // initializer to reflect that choice.
  4270. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
  4271. S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
  4272. CurInit = S.FixOverloadedFunctionReference(move(CurInit),
  4273. Step->Function.FoundDecl,
  4274. Step->Function.Function);
  4275. break;
  4276. case SK_CastDerivedToBaseRValue:
  4277. case SK_CastDerivedToBaseXValue:
  4278. case SK_CastDerivedToBaseLValue: {
  4279. // We have a derived-to-base cast that produces either an rvalue or an
  4280. // lvalue. Perform that cast.
  4281. CXXCastPath BasePath;
  4282. // Casts to inaccessible base classes are allowed with C-style casts.
  4283. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
  4284. if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
  4285. CurInit.get()->getLocStart(),
  4286. CurInit.get()->getSourceRange(),
  4287. &BasePath, IgnoreBaseAccess))
  4288. return ExprError();
  4289. if (S.BasePathInvolvesVirtualBase(BasePath)) {
  4290. QualType T = SourceType;
  4291. if (const PointerType *Pointer = T->getAs<PointerType>())
  4292. T = Pointer->getPointeeType();
  4293. if (const RecordType *RecordTy = T->getAs<RecordType>())
  4294. S.MarkVTableUsed(CurInit.get()->getLocStart(),
  4295. cast<CXXRecordDecl>(RecordTy->getDecl()));
  4296. }
  4297. ExprValueKind VK =
  4298. Step->Kind == SK_CastDerivedToBaseLValue ?
  4299. VK_LValue :
  4300. (Step->Kind == SK_CastDerivedToBaseXValue ?
  4301. VK_XValue :
  4302. VK_RValue);
  4303. CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
  4304. Step->Type,
  4305. CK_DerivedToBase,
  4306. CurInit.get(),
  4307. &BasePath, VK));
  4308. break;
  4309. }
  4310. case SK_BindReference:
  4311. if (FieldDecl *BitField = CurInit.get()->getBitField()) {
  4312. // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
  4313. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
  4314. << Entity.getType().isVolatileQualified()
  4315. << BitField->getDeclName()
  4316. << CurInit.get()->getSourceRange();
  4317. S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
  4318. return ExprError();
  4319. }
  4320. if (CurInit.get()->refersToVectorElement()) {
  4321. // References cannot bind to vector elements.
  4322. S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
  4323. << Entity.getType().isVolatileQualified()
  4324. << CurInit.get()->getSourceRange();
  4325. PrintInitLocationNote(S, Entity);
  4326. return ExprError();
  4327. }
  4328. // Reference binding does not have any corresponding ASTs.
  4329. // Check exception specifications
  4330. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  4331. return ExprError();
  4332. break;
  4333. case SK_BindReferenceToTemporary:
  4334. // Check exception specifications
  4335. if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
  4336. return ExprError();
  4337. // Materialize the temporary into memory.
  4338. CurInit = new (S.Context) MaterializeTemporaryExpr(
  4339. Entity.getType().getNonReferenceType(),
  4340. CurInit.get(),
  4341. Entity.getType()->isLValueReferenceType());
  4342. // If we're binding to an Objective-C object that has lifetime, we
  4343. // need cleanups.
  4344. if (S.getLangOptions().ObjCAutoRefCount &&
  4345. CurInit.get()->getType()->isObjCLifetimeType())
  4346. S.ExprNeedsCleanups = true;
  4347. break;
  4348. case SK_ExtraneousCopyToTemporary:
  4349. CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
  4350. /*IsExtraneousCopy=*/true);
  4351. break;
  4352. case SK_UserConversion: {
  4353. // We have a user-defined conversion that invokes either a constructor
  4354. // or a conversion function.
  4355. CastKind CastKind;
  4356. bool IsCopy = false;
  4357. FunctionDecl *Fn = Step->Function.Function;
  4358. DeclAccessPair FoundFn = Step->Function.FoundDecl;
  4359. bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
  4360. bool CreatedObject = false;
  4361. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
  4362. // Build a call to the selected constructor.
  4363. ASTOwningVector<Expr*> ConstructorArgs(S);
  4364. SourceLocation Loc = CurInit.get()->getLocStart();
  4365. CurInit.release(); // Ownership transferred into MultiExprArg, below.
  4366. // Determine the arguments required to actually perform the constructor
  4367. // call.
  4368. Expr *Arg = CurInit.get();
  4369. if (S.CompleteConstructorCall(Constructor,
  4370. MultiExprArg(&Arg, 1),
  4371. Loc, ConstructorArgs))
  4372. return ExprError();
  4373. // Build an expression that constructs a temporary.
  4374. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
  4375. move_arg(ConstructorArgs),
  4376. HadMultipleCandidates,
  4377. /*ZeroInit*/ false,
  4378. CXXConstructExpr::CK_Complete,
  4379. SourceRange());
  4380. if (CurInit.isInvalid())
  4381. return ExprError();
  4382. S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
  4383. FoundFn.getAccess());
  4384. S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
  4385. CastKind = CK_ConstructorConversion;
  4386. QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
  4387. if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
  4388. S.IsDerivedFrom(SourceType, Class))
  4389. IsCopy = true;
  4390. CreatedObject = true;
  4391. } else {
  4392. // Build a call to the conversion function.
  4393. CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
  4394. S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
  4395. FoundFn);
  4396. S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
  4397. // FIXME: Should we move this initialization into a separate
  4398. // derived-to-base conversion? I believe the answer is "no", because
  4399. // we don't want to turn off access control here for c-style casts.
  4400. ExprResult CurInitExprRes =
  4401. S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
  4402. FoundFn, Conversion);
  4403. if(CurInitExprRes.isInvalid())
  4404. return ExprError();
  4405. CurInit = move(CurInitExprRes);
  4406. // Build the actual call to the conversion function.
  4407. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
  4408. HadMultipleCandidates);
  4409. if (CurInit.isInvalid() || !CurInit.get())
  4410. return ExprError();
  4411. CastKind = CK_UserDefinedConversion;
  4412. CreatedObject = Conversion->getResultType()->isRecordType();
  4413. }
  4414. bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
  4415. bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
  4416. if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
  4417. QualType T = CurInit.get()->getType();
  4418. if (const RecordType *Record = T->getAs<RecordType>()) {
  4419. CXXDestructorDecl *Destructor
  4420. = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
  4421. S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
  4422. S.PDiag(diag::err_access_dtor_temp) << T);
  4423. S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
  4424. S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
  4425. }
  4426. }
  4427. CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
  4428. CurInit.get()->getType(),
  4429. CastKind, CurInit.get(), 0,
  4430. CurInit.get()->getValueKind()));
  4431. if (MaybeBindToTemp)
  4432. CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
  4433. if (RequiresCopy)
  4434. CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
  4435. move(CurInit), /*IsExtraneousCopy=*/false);
  4436. break;
  4437. }
  4438. case SK_QualificationConversionLValue:
  4439. case SK_QualificationConversionXValue:
  4440. case SK_QualificationConversionRValue: {
  4441. // Perform a qualification conversion; these can never go wrong.
  4442. ExprValueKind VK =
  4443. Step->Kind == SK_QualificationConversionLValue ?
  4444. VK_LValue :
  4445. (Step->Kind == SK_QualificationConversionXValue ?
  4446. VK_XValue :
  4447. VK_RValue);
  4448. CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
  4449. break;
  4450. }
  4451. case SK_ConversionSequence: {
  4452. Sema::CheckedConversionKind CCK
  4453. = Kind.isCStyleCast()? Sema::CCK_CStyleCast
  4454. : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
  4455. : Kind.isExplicitCast()? Sema::CCK_OtherCast
  4456. : Sema::CCK_ImplicitConversion;
  4457. ExprResult CurInitExprRes =
  4458. S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
  4459. getAssignmentAction(Entity), CCK);
  4460. if (CurInitExprRes.isInvalid())
  4461. return ExprError();
  4462. CurInit = move(CurInitExprRes);
  4463. break;
  4464. }
  4465. case SK_ListInitialization: {
  4466. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  4467. // Hack: We must pass *ResultType if available in order to set the type
  4468. // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
  4469. // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
  4470. // temporary, not a reference, so we should pass Ty.
  4471. // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
  4472. // Since this step is never used for a reference directly, we explicitly
  4473. // unwrap references here and rewrap them afterwards.
  4474. // We also need to create a InitializeTemporary entity for this.
  4475. QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
  4476. bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
  4477. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
  4478. InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
  4479. InitList, Ty, /*VerifyOnly=*/false,
  4480. Kind.getKind() != InitializationKind::IK_DirectList ||
  4481. !S.getLangOptions().CPlusPlus0x);
  4482. if (PerformInitList.HadError())
  4483. return ExprError();
  4484. if (ResultType) {
  4485. if ((*ResultType)->isRValueReferenceType())
  4486. Ty = S.Context.getRValueReferenceType(Ty);
  4487. else if ((*ResultType)->isLValueReferenceType())
  4488. Ty = S.Context.getLValueReferenceType(Ty,
  4489. (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
  4490. *ResultType = Ty;
  4491. }
  4492. InitListExpr *StructuredInitList =
  4493. PerformInitList.getFullyStructuredList();
  4494. CurInit.release();
  4495. CurInit = S.Owned(StructuredInitList);
  4496. break;
  4497. }
  4498. case SK_ListConstructorCall: {
  4499. // When an initializer list is passed for a parameter of type "reference
  4500. // to object", we don't get an EK_Temporary entity, but instead an
  4501. // EK_Parameter entity with reference type.
  4502. // FIXME: This is a hack. Why is this necessary here, but not in other
  4503. // places where implicit temporaries are created?
  4504. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
  4505. Entity.getType().getNonReferenceType());
  4506. bool UseTemporary = Entity.getType()->isReferenceType();
  4507. InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
  4508. MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
  4509. CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
  4510. Entity,
  4511. Kind, move(Arg), *Step,
  4512. ConstructorInitRequiresZeroInit);
  4513. break;
  4514. }
  4515. case SK_UnwrapInitList:
  4516. CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
  4517. break;
  4518. case SK_RewrapInitList: {
  4519. Expr *E = CurInit.take();
  4520. InitListExpr *Syntactic = Step->WrappingSyntacticList;
  4521. InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
  4522. Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
  4523. ILE->setSyntacticForm(Syntactic);
  4524. ILE->setType(E->getType());
  4525. ILE->setValueKind(E->getValueKind());
  4526. CurInit = S.Owned(ILE);
  4527. break;
  4528. }
  4529. case SK_ConstructorInitialization:
  4530. CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
  4531. *Step,
  4532. ConstructorInitRequiresZeroInit);
  4533. break;
  4534. case SK_ZeroInitialization: {
  4535. step_iterator NextStep = Step;
  4536. ++NextStep;
  4537. if (NextStep != StepEnd &&
  4538. NextStep->Kind == SK_ConstructorInitialization) {
  4539. // The need for zero-initialization is recorded directly into
  4540. // the call to the object's constructor within the next step.
  4541. ConstructorInitRequiresZeroInit = true;
  4542. } else if (Kind.getKind() == InitializationKind::IK_Value &&
  4543. S.getLangOptions().CPlusPlus &&
  4544. !Kind.isImplicitValueInit()) {
  4545. TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
  4546. if (!TSInfo)
  4547. TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
  4548. Kind.getRange().getBegin());
  4549. CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
  4550. TSInfo->getType().getNonLValueExprType(S.Context),
  4551. TSInfo,
  4552. Kind.getRange().getEnd()));
  4553. } else {
  4554. CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
  4555. }
  4556. break;
  4557. }
  4558. case SK_CAssignment: {
  4559. QualType SourceType = CurInit.get()->getType();
  4560. ExprResult Result = move(CurInit);
  4561. Sema::AssignConvertType ConvTy =
  4562. S.CheckSingleAssignmentConstraints(Step->Type, Result);
  4563. if (Result.isInvalid())
  4564. return ExprError();
  4565. CurInit = move(Result);
  4566. // If this is a call, allow conversion to a transparent union.
  4567. ExprResult CurInitExprRes = move(CurInit);
  4568. if (ConvTy != Sema::Compatible &&
  4569. Entity.getKind() == InitializedEntity::EK_Parameter &&
  4570. S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
  4571. == Sema::Compatible)
  4572. ConvTy = Sema::Compatible;
  4573. if (CurInitExprRes.isInvalid())
  4574. return ExprError();
  4575. CurInit = move(CurInitExprRes);
  4576. bool Complained;
  4577. if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
  4578. Step->Type, SourceType,
  4579. CurInit.get(),
  4580. getAssignmentAction(Entity),
  4581. &Complained)) {
  4582. PrintInitLocationNote(S, Entity);
  4583. return ExprError();
  4584. } else if (Complained)
  4585. PrintInitLocationNote(S, Entity);
  4586. break;
  4587. }
  4588. case SK_StringInit: {
  4589. QualType Ty = Step->Type;
  4590. CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
  4591. S.Context.getAsArrayType(Ty), S);
  4592. break;
  4593. }
  4594. case SK_ObjCObjectConversion:
  4595. CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
  4596. CK_ObjCObjectLValueCast,
  4597. CurInit.get()->getValueKind());
  4598. break;
  4599. case SK_ArrayInit:
  4600. // Okay: we checked everything before creating this step. Note that
  4601. // this is a GNU extension.
  4602. S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
  4603. << Step->Type << CurInit.get()->getType()
  4604. << CurInit.get()->getSourceRange();
  4605. // If the destination type is an incomplete array type, update the
  4606. // type accordingly.
  4607. if (ResultType) {
  4608. if (const IncompleteArrayType *IncompleteDest
  4609. = S.Context.getAsIncompleteArrayType(Step->Type)) {
  4610. if (const ConstantArrayType *ConstantSource
  4611. = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
  4612. *ResultType = S.Context.getConstantArrayType(
  4613. IncompleteDest->getElementType(),
  4614. ConstantSource->getSize(),
  4615. ArrayType::Normal, 0);
  4616. }
  4617. }
  4618. }
  4619. break;
  4620. case SK_PassByIndirectCopyRestore:
  4621. case SK_PassByIndirectRestore:
  4622. checkIndirectCopyRestoreSource(S, CurInit.get());
  4623. CurInit = S.Owned(new (S.Context)
  4624. ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
  4625. Step->Kind == SK_PassByIndirectCopyRestore));
  4626. break;
  4627. case SK_ProduceObjCObject:
  4628. CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
  4629. CK_ARCProduceObject,
  4630. CurInit.take(), 0, VK_RValue));
  4631. break;
  4632. case SK_StdInitializerList: {
  4633. QualType Dest = Step->Type;
  4634. QualType E;
  4635. bool Success = S.isStdInitializerList(Dest, &E);
  4636. (void)Success;
  4637. assert(Success && "Destination type changed?");
  4638. InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
  4639. unsigned NumInits = ILE->getNumInits();
  4640. SmallVector<Expr*, 16> Converted(NumInits);
  4641. InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
  4642. S.Context.getConstantArrayType(E,
  4643. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  4644. NumInits),
  4645. ArrayType::Normal, 0));
  4646. InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
  4647. 0, HiddenArray);
  4648. for (unsigned i = 0; i < NumInits; ++i) {
  4649. Element.setElementIndex(i);
  4650. ExprResult Init = S.Owned(ILE->getInit(i));
  4651. ExprResult Res = S.PerformCopyInitialization(Element,
  4652. Init.get()->getExprLoc(),
  4653. Init);
  4654. assert(!Res.isInvalid() && "Result changed since try phase.");
  4655. Converted[i] = Res.take();
  4656. }
  4657. InitListExpr *Semantic = new (S.Context)
  4658. InitListExpr(S.Context, ILE->getLBraceLoc(),
  4659. Converted.data(), NumInits, ILE->getRBraceLoc());
  4660. Semantic->setSyntacticForm(ILE);
  4661. Semantic->setType(Dest);
  4662. CurInit = S.Owned(Semantic);
  4663. break;
  4664. }
  4665. }
  4666. }
  4667. // Diagnose non-fatal problems with the completed initialization.
  4668. if (Entity.getKind() == InitializedEntity::EK_Member &&
  4669. cast<FieldDecl>(Entity.getDecl())->isBitField())
  4670. S.CheckBitFieldInitialization(Kind.getLocation(),
  4671. cast<FieldDecl>(Entity.getDecl()),
  4672. CurInit.get());
  4673. return move(CurInit);
  4674. }
  4675. /// \brief Provide some notes that detail why a function was implicitly
  4676. /// deleted.
  4677. static void diagnoseImplicitlyDeletedFunction(Sema &S, CXXMethodDecl *Method) {
  4678. // FIXME: This is a work in progress. It should dig deeper to figure out
  4679. // why the function was deleted (e.g., because one of its members doesn't
  4680. // have a copy constructor, for the copy-constructor case).
  4681. if (!Method->isImplicit()) {
  4682. S.Diag(Method->getLocation(), diag::note_callee_decl)
  4683. << Method->getDeclName();
  4684. }
  4685. if (Method->getParent()->isLambda()) {
  4686. S.Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
  4687. return;
  4688. }
  4689. S.Diag(Method->getParent()->getLocation(), diag::note_defined_here)
  4690. << Method->getParent();
  4691. }
  4692. //===----------------------------------------------------------------------===//
  4693. // Diagnose initialization failures
  4694. //===----------------------------------------------------------------------===//
  4695. bool InitializationSequence::Diagnose(Sema &S,
  4696. const InitializedEntity &Entity,
  4697. const InitializationKind &Kind,
  4698. Expr **Args, unsigned NumArgs) {
  4699. if (!Failed())
  4700. return false;
  4701. QualType DestType = Entity.getType();
  4702. switch (Failure) {
  4703. case FK_TooManyInitsForReference:
  4704. // FIXME: Customize for the initialized entity?
  4705. if (NumArgs == 0)
  4706. S.Diag(Kind.getLocation(), diag::err_reference_without_init)
  4707. << DestType.getNonReferenceType();
  4708. else // FIXME: diagnostic below could be better!
  4709. S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
  4710. << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
  4711. break;
  4712. case FK_ArrayNeedsInitList:
  4713. case FK_ArrayNeedsInitListOrStringLiteral:
  4714. S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
  4715. << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
  4716. break;
  4717. case FK_ArrayTypeMismatch:
  4718. case FK_NonConstantArrayInit:
  4719. S.Diag(Kind.getLocation(),
  4720. (Failure == FK_ArrayTypeMismatch
  4721. ? diag::err_array_init_different_type
  4722. : diag::err_array_init_non_constant_array))
  4723. << DestType.getNonReferenceType()
  4724. << Args[0]->getType()
  4725. << Args[0]->getSourceRange();
  4726. break;
  4727. case FK_VariableLengthArrayHasInitializer:
  4728. S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
  4729. << Args[0]->getSourceRange();
  4730. break;
  4731. case FK_AddressOfOverloadFailed: {
  4732. DeclAccessPair Found;
  4733. S.ResolveAddressOfOverloadedFunction(Args[0],
  4734. DestType.getNonReferenceType(),
  4735. true,
  4736. Found);
  4737. break;
  4738. }
  4739. case FK_ReferenceInitOverloadFailed:
  4740. case FK_UserConversionOverloadFailed:
  4741. switch (FailedOverloadResult) {
  4742. case OR_Ambiguous:
  4743. if (Failure == FK_UserConversionOverloadFailed)
  4744. S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
  4745. << Args[0]->getType() << DestType
  4746. << Args[0]->getSourceRange();
  4747. else
  4748. S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
  4749. << DestType << Args[0]->getType()
  4750. << Args[0]->getSourceRange();
  4751. FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
  4752. break;
  4753. case OR_No_Viable_Function:
  4754. S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
  4755. << Args[0]->getType() << DestType.getNonReferenceType()
  4756. << Args[0]->getSourceRange();
  4757. FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
  4758. break;
  4759. case OR_Deleted: {
  4760. S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
  4761. << Args[0]->getType() << DestType.getNonReferenceType()
  4762. << Args[0]->getSourceRange();
  4763. OverloadCandidateSet::iterator Best;
  4764. OverloadingResult Ovl
  4765. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
  4766. true);
  4767. if (Ovl == OR_Deleted) {
  4768. S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
  4769. << 1 << Best->Function->isDeleted();
  4770. } else {
  4771. llvm_unreachable("Inconsistent overload resolution?");
  4772. }
  4773. break;
  4774. }
  4775. case OR_Success:
  4776. llvm_unreachable("Conversion did not fail!");
  4777. }
  4778. break;
  4779. case FK_NonConstLValueReferenceBindingToTemporary:
  4780. if (isa<InitListExpr>(Args[0])) {
  4781. S.Diag(Kind.getLocation(),
  4782. diag::err_lvalue_reference_bind_to_initlist)
  4783. << DestType.getNonReferenceType().isVolatileQualified()
  4784. << DestType.getNonReferenceType()
  4785. << Args[0]->getSourceRange();
  4786. break;
  4787. }
  4788. // Intentional fallthrough
  4789. case FK_NonConstLValueReferenceBindingToUnrelated:
  4790. S.Diag(Kind.getLocation(),
  4791. Failure == FK_NonConstLValueReferenceBindingToTemporary
  4792. ? diag::err_lvalue_reference_bind_to_temporary
  4793. : diag::err_lvalue_reference_bind_to_unrelated)
  4794. << DestType.getNonReferenceType().isVolatileQualified()
  4795. << DestType.getNonReferenceType()
  4796. << Args[0]->getType()
  4797. << Args[0]->getSourceRange();
  4798. break;
  4799. case FK_RValueReferenceBindingToLValue:
  4800. S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
  4801. << DestType.getNonReferenceType() << Args[0]->getType()
  4802. << Args[0]->getSourceRange();
  4803. break;
  4804. case FK_ReferenceInitDropsQualifiers:
  4805. S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
  4806. << DestType.getNonReferenceType()
  4807. << Args[0]->getType()
  4808. << Args[0]->getSourceRange();
  4809. break;
  4810. case FK_ReferenceInitFailed:
  4811. S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
  4812. << DestType.getNonReferenceType()
  4813. << Args[0]->isLValue()
  4814. << Args[0]->getType()
  4815. << Args[0]->getSourceRange();
  4816. if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
  4817. Args[0]->getType()->isObjCObjectPointerType())
  4818. S.EmitRelatedResultTypeNote(Args[0]);
  4819. break;
  4820. case FK_ConversionFailed: {
  4821. QualType FromType = Args[0]->getType();
  4822. PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
  4823. << (int)Entity.getKind()
  4824. << DestType
  4825. << Args[0]->isLValue()
  4826. << FromType
  4827. << Args[0]->getSourceRange();
  4828. S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
  4829. S.Diag(Kind.getLocation(), PDiag);
  4830. if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
  4831. Args[0]->getType()->isObjCObjectPointerType())
  4832. S.EmitRelatedResultTypeNote(Args[0]);
  4833. break;
  4834. }
  4835. case FK_ConversionFromPropertyFailed:
  4836. // No-op. This error has already been reported.
  4837. break;
  4838. case FK_TooManyInitsForScalar: {
  4839. SourceRange R;
  4840. if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
  4841. R = SourceRange(InitList->getInit(0)->getLocEnd(),
  4842. InitList->getLocEnd());
  4843. else
  4844. R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
  4845. R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
  4846. if (Kind.isCStyleOrFunctionalCast())
  4847. S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
  4848. << R;
  4849. else
  4850. S.Diag(Kind.getLocation(), diag::err_excess_initializers)
  4851. << /*scalar=*/2 << R;
  4852. break;
  4853. }
  4854. case FK_ReferenceBindingToInitList:
  4855. S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
  4856. << DestType.getNonReferenceType() << Args[0]->getSourceRange();
  4857. break;
  4858. case FK_InitListBadDestinationType:
  4859. S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
  4860. << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
  4861. break;
  4862. case FK_ListConstructorOverloadFailed:
  4863. case FK_ConstructorOverloadFailed: {
  4864. SourceRange ArgsRange;
  4865. if (NumArgs)
  4866. ArgsRange = SourceRange(Args[0]->getLocStart(),
  4867. Args[NumArgs - 1]->getLocEnd());
  4868. if (Failure == FK_ListConstructorOverloadFailed) {
  4869. assert(NumArgs == 1 && "List construction from other than 1 argument.");
  4870. InitListExpr *InitList = cast<InitListExpr>(Args[0]);
  4871. Args = InitList->getInits();
  4872. NumArgs = InitList->getNumInits();
  4873. }
  4874. // FIXME: Using "DestType" for the entity we're printing is probably
  4875. // bad.
  4876. switch (FailedOverloadResult) {
  4877. case OR_Ambiguous:
  4878. S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
  4879. << DestType << ArgsRange;
  4880. FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
  4881. Args, NumArgs);
  4882. break;
  4883. case OR_No_Viable_Function:
  4884. if (Kind.getKind() == InitializationKind::IK_Default &&
  4885. (Entity.getKind() == InitializedEntity::EK_Base ||
  4886. Entity.getKind() == InitializedEntity::EK_Member) &&
  4887. isa<CXXConstructorDecl>(S.CurContext)) {
  4888. // This is implicit default initialization of a member or
  4889. // base within a constructor. If no viable function was
  4890. // found, notify the user that she needs to explicitly
  4891. // initialize this base/member.
  4892. CXXConstructorDecl *Constructor
  4893. = cast<CXXConstructorDecl>(S.CurContext);
  4894. if (Entity.getKind() == InitializedEntity::EK_Base) {
  4895. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  4896. << Constructor->isImplicit()
  4897. << S.Context.getTypeDeclType(Constructor->getParent())
  4898. << /*base=*/0
  4899. << Entity.getType();
  4900. RecordDecl *BaseDecl
  4901. = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
  4902. ->getDecl();
  4903. S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  4904. << S.Context.getTagDeclType(BaseDecl);
  4905. } else {
  4906. S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
  4907. << Constructor->isImplicit()
  4908. << S.Context.getTypeDeclType(Constructor->getParent())
  4909. << /*member=*/1
  4910. << Entity.getName();
  4911. S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
  4912. if (const RecordType *Record
  4913. = Entity.getType()->getAs<RecordType>())
  4914. S.Diag(Record->getDecl()->getLocation(),
  4915. diag::note_previous_decl)
  4916. << S.Context.getTagDeclType(Record->getDecl());
  4917. }
  4918. break;
  4919. }
  4920. S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
  4921. << DestType << ArgsRange;
  4922. FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
  4923. break;
  4924. case OR_Deleted: {
  4925. OverloadCandidateSet::iterator Best;
  4926. OverloadingResult Ovl
  4927. = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
  4928. if (Ovl != OR_Deleted) {
  4929. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  4930. << true << DestType << ArgsRange;
  4931. llvm_unreachable("Inconsistent overload resolution?");
  4932. break;
  4933. }
  4934. // If this is a defaulted or implicitly-declared function, then
  4935. // it was implicitly deleted. Make it clear that the deletion was
  4936. // implicit.
  4937. if (S.isImplicitlyDeleted(Best->Function)) {
  4938. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
  4939. << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
  4940. << DestType << ArgsRange;
  4941. diagnoseImplicitlyDeletedFunction(S,
  4942. cast<CXXMethodDecl>(Best->Function));
  4943. break;
  4944. }
  4945. S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
  4946. << true << DestType << ArgsRange;
  4947. S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
  4948. << 1 << Best->Function->isDeleted();
  4949. break;
  4950. }
  4951. case OR_Success:
  4952. llvm_unreachable("Conversion did not fail!");
  4953. }
  4954. }
  4955. break;
  4956. case FK_DefaultInitOfConst:
  4957. if (Entity.getKind() == InitializedEntity::EK_Member &&
  4958. isa<CXXConstructorDecl>(S.CurContext)) {
  4959. // This is implicit default-initialization of a const member in
  4960. // a constructor. Complain that it needs to be explicitly
  4961. // initialized.
  4962. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
  4963. S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
  4964. << Constructor->isImplicit()
  4965. << S.Context.getTypeDeclType(Constructor->getParent())
  4966. << /*const=*/1
  4967. << Entity.getName();
  4968. S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
  4969. << Entity.getName();
  4970. } else {
  4971. S.Diag(Kind.getLocation(), diag::err_default_init_const)
  4972. << DestType << (bool)DestType->getAs<RecordType>();
  4973. }
  4974. break;
  4975. case FK_Incomplete:
  4976. S.RequireCompleteType(Kind.getLocation(), DestType,
  4977. diag::err_init_incomplete_type);
  4978. break;
  4979. case FK_ListInitializationFailed: {
  4980. // Run the init list checker again to emit diagnostics.
  4981. InitListExpr* InitList = cast<InitListExpr>(Args[0]);
  4982. QualType DestType = Entity.getType();
  4983. InitListChecker DiagnoseInitList(S, Entity, InitList,
  4984. DestType, /*VerifyOnly=*/false,
  4985. Kind.getKind() != InitializationKind::IK_DirectList ||
  4986. !S.getLangOptions().CPlusPlus0x);
  4987. assert(DiagnoseInitList.HadError() &&
  4988. "Inconsistent init list check result.");
  4989. break;
  4990. }
  4991. case FK_PlaceholderType: {
  4992. // FIXME: Already diagnosed!
  4993. break;
  4994. }
  4995. case FK_InitListElementCopyFailure: {
  4996. // Try to perform all copies again.
  4997. InitListExpr* InitList = cast<InitListExpr>(Args[0]);
  4998. unsigned NumInits = InitList->getNumInits();
  4999. QualType DestType = Entity.getType();
  5000. QualType E;
  5001. bool Success = S.isStdInitializerList(DestType, &E);
  5002. (void)Success;
  5003. assert(Success && "Where did the std::initializer_list go?");
  5004. InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
  5005. S.Context.getConstantArrayType(E,
  5006. llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
  5007. NumInits),
  5008. ArrayType::Normal, 0));
  5009. InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
  5010. 0, HiddenArray);
  5011. // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
  5012. // where the init list type is wrong, e.g.
  5013. // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
  5014. // FIXME: Emit a note if we hit the limit?
  5015. int ErrorCount = 0;
  5016. for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
  5017. Element.setElementIndex(i);
  5018. ExprResult Init = S.Owned(InitList->getInit(i));
  5019. if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
  5020. .isInvalid())
  5021. ++ErrorCount;
  5022. }
  5023. break;
  5024. }
  5025. }
  5026. PrintInitLocationNote(S, Entity);
  5027. return true;
  5028. }
  5029. void InitializationSequence::dump(raw_ostream &OS) const {
  5030. switch (SequenceKind) {
  5031. case FailedSequence: {
  5032. OS << "Failed sequence: ";
  5033. switch (Failure) {
  5034. case FK_TooManyInitsForReference:
  5035. OS << "too many initializers for reference";
  5036. break;
  5037. case FK_ArrayNeedsInitList:
  5038. OS << "array requires initializer list";
  5039. break;
  5040. case FK_ArrayNeedsInitListOrStringLiteral:
  5041. OS << "array requires initializer list or string literal";
  5042. break;
  5043. case FK_ArrayTypeMismatch:
  5044. OS << "array type mismatch";
  5045. break;
  5046. case FK_NonConstantArrayInit:
  5047. OS << "non-constant array initializer";
  5048. break;
  5049. case FK_AddressOfOverloadFailed:
  5050. OS << "address of overloaded function failed";
  5051. break;
  5052. case FK_ReferenceInitOverloadFailed:
  5053. OS << "overload resolution for reference initialization failed";
  5054. break;
  5055. case FK_NonConstLValueReferenceBindingToTemporary:
  5056. OS << "non-const lvalue reference bound to temporary";
  5057. break;
  5058. case FK_NonConstLValueReferenceBindingToUnrelated:
  5059. OS << "non-const lvalue reference bound to unrelated type";
  5060. break;
  5061. case FK_RValueReferenceBindingToLValue:
  5062. OS << "rvalue reference bound to an lvalue";
  5063. break;
  5064. case FK_ReferenceInitDropsQualifiers:
  5065. OS << "reference initialization drops qualifiers";
  5066. break;
  5067. case FK_ReferenceInitFailed:
  5068. OS << "reference initialization failed";
  5069. break;
  5070. case FK_ConversionFailed:
  5071. OS << "conversion failed";
  5072. break;
  5073. case FK_ConversionFromPropertyFailed:
  5074. OS << "conversion from property failed";
  5075. break;
  5076. case FK_TooManyInitsForScalar:
  5077. OS << "too many initializers for scalar";
  5078. break;
  5079. case FK_ReferenceBindingToInitList:
  5080. OS << "referencing binding to initializer list";
  5081. break;
  5082. case FK_InitListBadDestinationType:
  5083. OS << "initializer list for non-aggregate, non-scalar type";
  5084. break;
  5085. case FK_UserConversionOverloadFailed:
  5086. OS << "overloading failed for user-defined conversion";
  5087. break;
  5088. case FK_ConstructorOverloadFailed:
  5089. OS << "constructor overloading failed";
  5090. break;
  5091. case FK_DefaultInitOfConst:
  5092. OS << "default initialization of a const variable";
  5093. break;
  5094. case FK_Incomplete:
  5095. OS << "initialization of incomplete type";
  5096. break;
  5097. case FK_ListInitializationFailed:
  5098. OS << "list initialization checker failure";
  5099. break;
  5100. case FK_VariableLengthArrayHasInitializer:
  5101. OS << "variable length array has an initializer";
  5102. break;
  5103. case FK_PlaceholderType:
  5104. OS << "initializer expression isn't contextually valid";
  5105. break;
  5106. case FK_ListConstructorOverloadFailed:
  5107. OS << "list constructor overloading failed";
  5108. break;
  5109. case FK_InitListElementCopyFailure:
  5110. OS << "copy construction of initializer list element failed";
  5111. break;
  5112. }
  5113. OS << '\n';
  5114. return;
  5115. }
  5116. case DependentSequence:
  5117. OS << "Dependent sequence\n";
  5118. return;
  5119. case NormalSequence:
  5120. OS << "Normal sequence: ";
  5121. break;
  5122. }
  5123. for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
  5124. if (S != step_begin()) {
  5125. OS << " -> ";
  5126. }
  5127. switch (S->Kind) {
  5128. case SK_ResolveAddressOfOverloadedFunction:
  5129. OS << "resolve address of overloaded function";
  5130. break;
  5131. case SK_CastDerivedToBaseRValue:
  5132. OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
  5133. break;
  5134. case SK_CastDerivedToBaseXValue:
  5135. OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
  5136. break;
  5137. case SK_CastDerivedToBaseLValue:
  5138. OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
  5139. break;
  5140. case SK_BindReference:
  5141. OS << "bind reference to lvalue";
  5142. break;
  5143. case SK_BindReferenceToTemporary:
  5144. OS << "bind reference to a temporary";
  5145. break;
  5146. case SK_ExtraneousCopyToTemporary:
  5147. OS << "extraneous C++03 copy to temporary";
  5148. break;
  5149. case SK_UserConversion:
  5150. OS << "user-defined conversion via " << *S->Function.Function;
  5151. break;
  5152. case SK_QualificationConversionRValue:
  5153. OS << "qualification conversion (rvalue)";
  5154. break;
  5155. case SK_QualificationConversionXValue:
  5156. OS << "qualification conversion (xvalue)";
  5157. break;
  5158. case SK_QualificationConversionLValue:
  5159. OS << "qualification conversion (lvalue)";
  5160. break;
  5161. case SK_ConversionSequence:
  5162. OS << "implicit conversion sequence (";
  5163. S->ICS->DebugPrint(); // FIXME: use OS
  5164. OS << ")";
  5165. break;
  5166. case SK_ListInitialization:
  5167. OS << "list aggregate initialization";
  5168. break;
  5169. case SK_ListConstructorCall:
  5170. OS << "list initialization via constructor";
  5171. break;
  5172. case SK_UnwrapInitList:
  5173. OS << "unwrap reference initializer list";
  5174. break;
  5175. case SK_RewrapInitList:
  5176. OS << "rewrap reference initializer list";
  5177. break;
  5178. case SK_ConstructorInitialization:
  5179. OS << "constructor initialization";
  5180. break;
  5181. case SK_ZeroInitialization:
  5182. OS << "zero initialization";
  5183. break;
  5184. case SK_CAssignment:
  5185. OS << "C assignment";
  5186. break;
  5187. case SK_StringInit:
  5188. OS << "string initialization";
  5189. break;
  5190. case SK_ObjCObjectConversion:
  5191. OS << "Objective-C object conversion";
  5192. break;
  5193. case SK_ArrayInit:
  5194. OS << "array initialization";
  5195. break;
  5196. case SK_PassByIndirectCopyRestore:
  5197. OS << "pass by indirect copy and restore";
  5198. break;
  5199. case SK_PassByIndirectRestore:
  5200. OS << "pass by indirect restore";
  5201. break;
  5202. case SK_ProduceObjCObject:
  5203. OS << "Objective-C object retension";
  5204. break;
  5205. case SK_StdInitializerList:
  5206. OS << "std::initializer_list from initializer list";
  5207. break;
  5208. }
  5209. }
  5210. }
  5211. void InitializationSequence::dump() const {
  5212. dump(llvm::errs());
  5213. }
  5214. static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
  5215. QualType EntityType,
  5216. const Expr *PreInit,
  5217. const Expr *PostInit) {
  5218. if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
  5219. return;
  5220. // A narrowing conversion can only appear as the final implicit conversion in
  5221. // an initialization sequence.
  5222. const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
  5223. if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
  5224. return;
  5225. const ImplicitConversionSequence &ICS = *LastStep.ICS;
  5226. const StandardConversionSequence *SCS = 0;
  5227. switch (ICS.getKind()) {
  5228. case ImplicitConversionSequence::StandardConversion:
  5229. SCS = &ICS.Standard;
  5230. break;
  5231. case ImplicitConversionSequence::UserDefinedConversion:
  5232. SCS = &ICS.UserDefined.After;
  5233. break;
  5234. case ImplicitConversionSequence::AmbiguousConversion:
  5235. case ImplicitConversionSequence::EllipsisConversion:
  5236. case ImplicitConversionSequence::BadConversion:
  5237. return;
  5238. }
  5239. // Determine the type prior to the narrowing conversion. If a conversion
  5240. // operator was used, this may be different from both the type of the entity
  5241. // and of the pre-initialization expression.
  5242. QualType PreNarrowingType = PreInit->getType();
  5243. if (Seq.step_begin() + 1 != Seq.step_end())
  5244. PreNarrowingType = Seq.step_end()[-2].Type;
  5245. // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
  5246. APValue ConstantValue;
  5247. switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
  5248. case NK_Not_Narrowing:
  5249. // No narrowing occurred.
  5250. return;
  5251. case NK_Type_Narrowing:
  5252. // This was a floating-to-integer conversion, which is always considered a
  5253. // narrowing conversion even if the value is a constant and can be
  5254. // represented exactly as an integer.
  5255. S.Diag(PostInit->getLocStart(),
  5256. S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
  5257. diag::warn_init_list_type_narrowing
  5258. : S.isSFINAEContext()?
  5259. diag::err_init_list_type_narrowing_sfinae
  5260. : diag::err_init_list_type_narrowing)
  5261. << PostInit->getSourceRange()
  5262. << PreNarrowingType.getLocalUnqualifiedType()
  5263. << EntityType.getLocalUnqualifiedType();
  5264. break;
  5265. case NK_Constant_Narrowing:
  5266. // A constant value was narrowed.
  5267. S.Diag(PostInit->getLocStart(),
  5268. S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
  5269. diag::warn_init_list_constant_narrowing
  5270. : S.isSFINAEContext()?
  5271. diag::err_init_list_constant_narrowing_sfinae
  5272. : diag::err_init_list_constant_narrowing)
  5273. << PostInit->getSourceRange()
  5274. << ConstantValue.getAsString(S.getASTContext(), EntityType)
  5275. << EntityType.getLocalUnqualifiedType();
  5276. break;
  5277. case NK_Variable_Narrowing:
  5278. // A variable's value may have been narrowed.
  5279. S.Diag(PostInit->getLocStart(),
  5280. S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
  5281. diag::warn_init_list_variable_narrowing
  5282. : S.isSFINAEContext()?
  5283. diag::err_init_list_variable_narrowing_sfinae
  5284. : diag::err_init_list_variable_narrowing)
  5285. << PostInit->getSourceRange()
  5286. << PreNarrowingType.getLocalUnqualifiedType()
  5287. << EntityType.getLocalUnqualifiedType();
  5288. break;
  5289. }
  5290. SmallString<128> StaticCast;
  5291. llvm::raw_svector_ostream OS(StaticCast);
  5292. OS << "static_cast<";
  5293. if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
  5294. // It's important to use the typedef's name if there is one so that the
  5295. // fixit doesn't break code using types like int64_t.
  5296. //
  5297. // FIXME: This will break if the typedef requires qualification. But
  5298. // getQualifiedNameAsString() includes non-machine-parsable components.
  5299. OS << *TT->getDecl();
  5300. } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
  5301. OS << BT->getName(S.getLangOptions());
  5302. else {
  5303. // Oops, we didn't find the actual type of the variable. Don't emit a fixit
  5304. // with a broken cast.
  5305. return;
  5306. }
  5307. OS << ">(";
  5308. S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
  5309. << PostInit->getSourceRange()
  5310. << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
  5311. << FixItHint::CreateInsertion(
  5312. S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
  5313. }
  5314. //===----------------------------------------------------------------------===//
  5315. // Initialization helper functions
  5316. //===----------------------------------------------------------------------===//
  5317. bool
  5318. Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
  5319. ExprResult Init) {
  5320. if (Init.isInvalid())
  5321. return false;
  5322. Expr *InitE = Init.get();
  5323. assert(InitE && "No initialization expression");
  5324. InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
  5325. SourceLocation());
  5326. InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
  5327. return !Seq.Failed();
  5328. }
  5329. ExprResult
  5330. Sema::PerformCopyInitialization(const InitializedEntity &Entity,
  5331. SourceLocation EqualLoc,
  5332. ExprResult Init,
  5333. bool TopLevelOfInitList) {
  5334. if (Init.isInvalid())
  5335. return ExprError();
  5336. Expr *InitE = Init.get();
  5337. assert(InitE && "No initialization expression?");
  5338. if (EqualLoc.isInvalid())
  5339. EqualLoc = InitE->getLocStart();
  5340. InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
  5341. EqualLoc);
  5342. InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
  5343. Init.release();
  5344. ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
  5345. if (!Result.isInvalid() && TopLevelOfInitList)
  5346. DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
  5347. InitE, Result.get());
  5348. return Result;
  5349. }