SemaInit.cpp 338 KB

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