SemaInit.cpp 401 KB

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