SemaInit.cpp 366 KB

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