SemaDecl.cpp 671 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/Basic/Builtins.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  30. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  31. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/Lookup.h"
  38. #include "clang/Sema/ParsedTemplate.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.h"
  41. #include "clang/Sema/SemaInternal.h"
  42. #include "clang/Sema/Template.h"
  43. #include "llvm/ADT/SmallString.h"
  44. #include "llvm/ADT/Triple.h"
  45. #include <algorithm>
  46. #include <cstring>
  47. #include <functional>
  48. using namespace clang;
  49. using namespace sema;
  50. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  51. if (OwnedType) {
  52. Decl *Group[2] = { OwnedType, Ptr };
  53. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  54. }
  55. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  56. }
  57. namespace {
  58. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  59. public:
  60. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  61. bool AllowTemplates = false,
  62. bool AllowNonTemplates = true)
  63. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  64. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  65. WantExpressionKeywords = false;
  66. WantCXXNamedCasts = false;
  67. WantRemainingKeywords = false;
  68. }
  69. bool ValidateCandidate(const TypoCorrection &candidate) override {
  70. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  71. if (!AllowInvalidDecl && ND->isInvalidDecl())
  72. return false;
  73. if (getAsTypeTemplateDecl(ND))
  74. return AllowTemplates;
  75. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  76. if (!IsType)
  77. return false;
  78. if (AllowNonTemplates)
  79. return true;
  80. // An injected-class-name of a class template (specialization) is valid
  81. // as a template or as a non-template.
  82. if (AllowTemplates) {
  83. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  84. if (!RD || !RD->isInjectedClassName())
  85. return false;
  86. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  87. return RD->getDescribedClassTemplate() ||
  88. isa<ClassTemplateSpecializationDecl>(RD);
  89. }
  90. return false;
  91. }
  92. return !WantClassName && candidate.isKeyword();
  93. }
  94. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  95. return std::make_unique<TypeNameValidatorCCC>(*this);
  96. }
  97. private:
  98. bool AllowInvalidDecl;
  99. bool WantClassName;
  100. bool AllowTemplates;
  101. bool AllowNonTemplates;
  102. };
  103. } // end anonymous namespace
  104. /// Determine whether the token kind starts a simple-type-specifier.
  105. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  106. switch (Kind) {
  107. // FIXME: Take into account the current language when deciding whether a
  108. // token kind is a valid type specifier
  109. case tok::kw_short:
  110. case tok::kw_long:
  111. case tok::kw___int64:
  112. case tok::kw___int128:
  113. case tok::kw_signed:
  114. case tok::kw_unsigned:
  115. case tok::kw_void:
  116. case tok::kw_char:
  117. case tok::kw_int:
  118. case tok::kw_half:
  119. case tok::kw_float:
  120. case tok::kw_double:
  121. case tok::kw__Float16:
  122. case tok::kw___float128:
  123. case tok::kw_wchar_t:
  124. case tok::kw_bool:
  125. case tok::kw___underlying_type:
  126. case tok::kw___auto_type:
  127. return true;
  128. case tok::annot_typename:
  129. case tok::kw_char16_t:
  130. case tok::kw_char32_t:
  131. case tok::kw_typeof:
  132. case tok::annot_decltype:
  133. case tok::kw_decltype:
  134. return getLangOpts().CPlusPlus;
  135. case tok::kw_char8_t:
  136. return getLangOpts().Char8;
  137. default:
  138. break;
  139. }
  140. return false;
  141. }
  142. namespace {
  143. enum class UnqualifiedTypeNameLookupResult {
  144. NotFound,
  145. FoundNonType,
  146. FoundType
  147. };
  148. } // end anonymous namespace
  149. /// Tries to perform unqualified lookup of the type decls in bases for
  150. /// dependent class.
  151. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  152. /// type decl, \a FoundType if only type decls are found.
  153. static UnqualifiedTypeNameLookupResult
  154. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  155. SourceLocation NameLoc,
  156. const CXXRecordDecl *RD) {
  157. if (!RD->hasDefinition())
  158. return UnqualifiedTypeNameLookupResult::NotFound;
  159. // Look for type decls in base classes.
  160. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  161. UnqualifiedTypeNameLookupResult::NotFound;
  162. for (const auto &Base : RD->bases()) {
  163. const CXXRecordDecl *BaseRD = nullptr;
  164. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  165. BaseRD = BaseTT->getAsCXXRecordDecl();
  166. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  167. // Look for type decls in dependent base classes that have known primary
  168. // templates.
  169. if (!TST || !TST->isDependentType())
  170. continue;
  171. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  172. if (!TD)
  173. continue;
  174. if (auto *BasePrimaryTemplate =
  175. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  176. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  177. BaseRD = BasePrimaryTemplate;
  178. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  179. if (const ClassTemplatePartialSpecializationDecl *PS =
  180. CTD->findPartialSpecialization(Base.getType()))
  181. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  182. BaseRD = PS;
  183. }
  184. }
  185. }
  186. if (BaseRD) {
  187. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  188. if (!isa<TypeDecl>(ND))
  189. return UnqualifiedTypeNameLookupResult::FoundNonType;
  190. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  191. }
  192. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  193. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  194. case UnqualifiedTypeNameLookupResult::FoundNonType:
  195. return UnqualifiedTypeNameLookupResult::FoundNonType;
  196. case UnqualifiedTypeNameLookupResult::FoundType:
  197. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  198. break;
  199. case UnqualifiedTypeNameLookupResult::NotFound:
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. return FoundTypeDecl;
  206. }
  207. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  208. const IdentifierInfo &II,
  209. SourceLocation NameLoc) {
  210. // Lookup in the parent class template context, if any.
  211. const CXXRecordDecl *RD = nullptr;
  212. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  213. UnqualifiedTypeNameLookupResult::NotFound;
  214. for (DeclContext *DC = S.CurContext;
  215. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  216. DC = DC->getParent()) {
  217. // Look for type decls in dependent base classes that have known primary
  218. // templates.
  219. RD = dyn_cast<CXXRecordDecl>(DC);
  220. if (RD && RD->getDescribedClassTemplate())
  221. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  222. }
  223. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  224. return nullptr;
  225. // We found some types in dependent base classes. Recover as if the user
  226. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  227. // lookup during template instantiation.
  228. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  229. ASTContext &Context = S.Context;
  230. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  231. cast<Type>(Context.getRecordType(RD)));
  232. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  233. CXXScopeSpec SS;
  234. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  235. TypeLocBuilder Builder;
  236. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  237. DepTL.setNameLoc(NameLoc);
  238. DepTL.setElaboratedKeywordLoc(SourceLocation());
  239. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  240. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  241. }
  242. /// If the identifier refers to a type name within this scope,
  243. /// return the declaration of that type.
  244. ///
  245. /// This routine performs ordinary name lookup of the identifier II
  246. /// within the given scope, with optional C++ scope specifier SS, to
  247. /// determine whether the name refers to a type. If so, returns an
  248. /// opaque pointer (actually a QualType) corresponding to that
  249. /// type. Otherwise, returns NULL.
  250. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  251. Scope *S, CXXScopeSpec *SS,
  252. bool isClassName, bool HasTrailingDot,
  253. ParsedType ObjectTypePtr,
  254. bool IsCtorOrDtorName,
  255. bool WantNontrivialTypeSourceInfo,
  256. bool IsClassTemplateDeductionContext,
  257. IdentifierInfo **CorrectedII) {
  258. // FIXME: Consider allowing this outside C++1z mode as an extension.
  259. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  260. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  261. !isClassName && !HasTrailingDot;
  262. // Determine where we will perform name lookup.
  263. DeclContext *LookupCtx = nullptr;
  264. if (ObjectTypePtr) {
  265. QualType ObjectType = ObjectTypePtr.get();
  266. if (ObjectType->isRecordType())
  267. LookupCtx = computeDeclContext(ObjectType);
  268. } else if (SS && SS->isNotEmpty()) {
  269. LookupCtx = computeDeclContext(*SS, false);
  270. if (!LookupCtx) {
  271. if (isDependentScopeSpecifier(*SS)) {
  272. // C++ [temp.res]p3:
  273. // A qualified-id that refers to a type and in which the
  274. // nested-name-specifier depends on a template-parameter (14.6.2)
  275. // shall be prefixed by the keyword typename to indicate that the
  276. // qualified-id denotes a type, forming an
  277. // elaborated-type-specifier (7.1.5.3).
  278. //
  279. // We therefore do not perform any name lookup if the result would
  280. // refer to a member of an unknown specialization.
  281. if (!isClassName && !IsCtorOrDtorName)
  282. return nullptr;
  283. // We know from the grammar that this name refers to a type,
  284. // so build a dependent node to describe the type.
  285. if (WantNontrivialTypeSourceInfo)
  286. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  287. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  288. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  289. II, NameLoc);
  290. return ParsedType::make(T);
  291. }
  292. return nullptr;
  293. }
  294. if (!LookupCtx->isDependentContext() &&
  295. RequireCompleteDeclContext(*SS, LookupCtx))
  296. return nullptr;
  297. }
  298. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  299. // lookup for class-names.
  300. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  301. LookupOrdinaryName;
  302. LookupResult Result(*this, &II, NameLoc, Kind);
  303. if (LookupCtx) {
  304. // Perform "qualified" name lookup into the declaration context we
  305. // computed, which is either the type of the base of a member access
  306. // expression or the declaration context associated with a prior
  307. // nested-name-specifier.
  308. LookupQualifiedName(Result, LookupCtx);
  309. if (ObjectTypePtr && Result.empty()) {
  310. // C++ [basic.lookup.classref]p3:
  311. // If the unqualified-id is ~type-name, the type-name is looked up
  312. // in the context of the entire postfix-expression. If the type T of
  313. // the object expression is of a class type C, the type-name is also
  314. // looked up in the scope of class C. At least one of the lookups shall
  315. // find a name that refers to (possibly cv-qualified) T.
  316. LookupName(Result, S);
  317. }
  318. } else {
  319. // Perform unqualified name lookup.
  320. LookupName(Result, S);
  321. // For unqualified lookup in a class template in MSVC mode, look into
  322. // dependent base classes where the primary class template is known.
  323. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  324. if (ParsedType TypeInBase =
  325. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  326. return TypeInBase;
  327. }
  328. }
  329. NamedDecl *IIDecl = nullptr;
  330. switch (Result.getResultKind()) {
  331. case LookupResult::NotFound:
  332. case LookupResult::NotFoundInCurrentInstantiation:
  333. if (CorrectedII) {
  334. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  335. AllowDeducedTemplate);
  336. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  337. S, SS, CCC, CTK_ErrorRecovery);
  338. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  339. TemplateTy Template;
  340. bool MemberOfUnknownSpecialization;
  341. UnqualifiedId TemplateName;
  342. TemplateName.setIdentifier(NewII, NameLoc);
  343. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  344. CXXScopeSpec NewSS, *NewSSPtr = SS;
  345. if (SS && NNS) {
  346. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  347. NewSSPtr = &NewSS;
  348. }
  349. if (Correction && (NNS || NewII != &II) &&
  350. // Ignore a correction to a template type as the to-be-corrected
  351. // identifier is not a template (typo correction for template names
  352. // is handled elsewhere).
  353. !(getLangOpts().CPlusPlus && NewSSPtr &&
  354. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  355. Template, MemberOfUnknownSpecialization))) {
  356. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  357. isClassName, HasTrailingDot, ObjectTypePtr,
  358. IsCtorOrDtorName,
  359. WantNontrivialTypeSourceInfo,
  360. IsClassTemplateDeductionContext);
  361. if (Ty) {
  362. diagnoseTypo(Correction,
  363. PDiag(diag::err_unknown_type_or_class_name_suggest)
  364. << Result.getLookupName() << isClassName);
  365. if (SS && NNS)
  366. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  367. *CorrectedII = NewII;
  368. return Ty;
  369. }
  370. }
  371. }
  372. // If typo correction failed or was not performed, fall through
  373. LLVM_FALLTHROUGH;
  374. case LookupResult::FoundOverloaded:
  375. case LookupResult::FoundUnresolvedValue:
  376. Result.suppressDiagnostics();
  377. return nullptr;
  378. case LookupResult::Ambiguous:
  379. // Recover from type-hiding ambiguities by hiding the type. We'll
  380. // do the lookup again when looking for an object, and we can
  381. // diagnose the error then. If we don't do this, then the error
  382. // about hiding the type will be immediately followed by an error
  383. // that only makes sense if the identifier was treated like a type.
  384. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  385. Result.suppressDiagnostics();
  386. return nullptr;
  387. }
  388. // Look to see if we have a type anywhere in the list of results.
  389. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  390. Res != ResEnd; ++Res) {
  391. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  392. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  393. if (!IIDecl ||
  394. (*Res)->getLocation().getRawEncoding() <
  395. IIDecl->getLocation().getRawEncoding())
  396. IIDecl = *Res;
  397. }
  398. }
  399. if (!IIDecl) {
  400. // None of the entities we found is a type, so there is no way
  401. // to even assume that the result is a type. In this case, don't
  402. // complain about the ambiguity. The parser will either try to
  403. // perform this lookup again (e.g., as an object name), which
  404. // will produce the ambiguity, or will complain that it expected
  405. // a type name.
  406. Result.suppressDiagnostics();
  407. return nullptr;
  408. }
  409. // We found a type within the ambiguous lookup; diagnose the
  410. // ambiguity and then return that type. This might be the right
  411. // answer, or it might not be, but it suppresses any attempt to
  412. // perform the name lookup again.
  413. break;
  414. case LookupResult::Found:
  415. IIDecl = Result.getFoundDecl();
  416. break;
  417. }
  418. assert(IIDecl && "Didn't find decl");
  419. QualType T;
  420. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  421. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  422. // instead names the constructors of the class, except when naming a class.
  423. // This is ill-formed when we're not actually forming a ctor or dtor name.
  424. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  425. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  426. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  427. FoundRD->isInjectedClassName() &&
  428. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  429. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  430. << &II << /*Type*/1;
  431. DiagnoseUseOfDecl(IIDecl, NameLoc);
  432. T = Context.getTypeDeclType(TD);
  433. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  434. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  435. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  436. if (!HasTrailingDot)
  437. T = Context.getObjCInterfaceType(IDecl);
  438. } else if (AllowDeducedTemplate) {
  439. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  440. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  441. QualType(), false);
  442. }
  443. if (T.isNull()) {
  444. // If it's not plausibly a type, suppress diagnostics.
  445. Result.suppressDiagnostics();
  446. return nullptr;
  447. }
  448. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  449. // constructor or destructor name (in such a case, the scope specifier
  450. // will be attached to the enclosing Expr or Decl node).
  451. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  452. !isa<ObjCInterfaceDecl>(IIDecl)) {
  453. if (WantNontrivialTypeSourceInfo) {
  454. // Construct a type with type-source information.
  455. TypeLocBuilder Builder;
  456. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  457. T = getElaboratedType(ETK_None, *SS, T);
  458. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  459. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  460. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  461. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  462. } else {
  463. T = getElaboratedType(ETK_None, *SS, T);
  464. }
  465. }
  466. return ParsedType::make(T);
  467. }
  468. // Builds a fake NNS for the given decl context.
  469. static NestedNameSpecifier *
  470. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  471. for (;; DC = DC->getLookupParent()) {
  472. DC = DC->getPrimaryContext();
  473. auto *ND = dyn_cast<NamespaceDecl>(DC);
  474. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  475. return NestedNameSpecifier::Create(Context, nullptr, ND);
  476. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  477. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  478. RD->getTypeForDecl());
  479. else if (isa<TranslationUnitDecl>(DC))
  480. return NestedNameSpecifier::GlobalSpecifier(Context);
  481. }
  482. llvm_unreachable("something isn't in TU scope?");
  483. }
  484. /// Find the parent class with dependent bases of the innermost enclosing method
  485. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  486. /// up allowing unqualified dependent type names at class-level, which MSVC
  487. /// correctly rejects.
  488. static const CXXRecordDecl *
  489. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  490. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  491. DC = DC->getPrimaryContext();
  492. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  493. if (MD->getParent()->hasAnyDependentBases())
  494. return MD->getParent();
  495. }
  496. return nullptr;
  497. }
  498. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  499. SourceLocation NameLoc,
  500. bool IsTemplateTypeArg) {
  501. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  502. NestedNameSpecifier *NNS = nullptr;
  503. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  504. // If we weren't able to parse a default template argument, delay lookup
  505. // until instantiation time by making a non-dependent DependentTypeName. We
  506. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  507. // lookup is retried.
  508. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  509. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  510. // name specifiers.
  511. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  512. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  513. } else if (const CXXRecordDecl *RD =
  514. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  515. // Build a DependentNameType that will perform lookup into RD at
  516. // instantiation time.
  517. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  518. RD->getTypeForDecl());
  519. // Diagnose that this identifier was undeclared, and retry the lookup during
  520. // template instantiation.
  521. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  522. << RD;
  523. } else {
  524. // This is not a situation that we should recover from.
  525. return ParsedType();
  526. }
  527. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  528. // Build type location information. We synthesized the qualifier, so we have
  529. // to build a fake NestedNameSpecifierLoc.
  530. NestedNameSpecifierLocBuilder NNSLocBuilder;
  531. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  532. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  533. TypeLocBuilder Builder;
  534. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  535. DepTL.setNameLoc(NameLoc);
  536. DepTL.setElaboratedKeywordLoc(SourceLocation());
  537. DepTL.setQualifierLoc(QualifierLoc);
  538. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  539. }
  540. /// isTagName() - This method is called *for error recovery purposes only*
  541. /// to determine if the specified name is a valid tag name ("struct foo"). If
  542. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  543. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  544. /// cases in C where the user forgot to specify the tag.
  545. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  546. // Do a tag name lookup in this scope.
  547. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  548. LookupName(R, S, false);
  549. R.suppressDiagnostics();
  550. if (R.getResultKind() == LookupResult::Found)
  551. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  552. switch (TD->getTagKind()) {
  553. case TTK_Struct: return DeclSpec::TST_struct;
  554. case TTK_Interface: return DeclSpec::TST_interface;
  555. case TTK_Union: return DeclSpec::TST_union;
  556. case TTK_Class: return DeclSpec::TST_class;
  557. case TTK_Enum: return DeclSpec::TST_enum;
  558. }
  559. }
  560. return DeclSpec::TST_unspecified;
  561. }
  562. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  563. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  564. /// then downgrade the missing typename error to a warning.
  565. /// This is needed for MSVC compatibility; Example:
  566. /// @code
  567. /// template<class T> class A {
  568. /// public:
  569. /// typedef int TYPE;
  570. /// };
  571. /// template<class T> class B : public A<T> {
  572. /// public:
  573. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  574. /// };
  575. /// @endcode
  576. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  577. if (CurContext->isRecord()) {
  578. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  579. return true;
  580. const Type *Ty = SS->getScopeRep()->getAsType();
  581. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  582. for (const auto &Base : RD->bases())
  583. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  584. return true;
  585. return S->isFunctionPrototypeScope();
  586. }
  587. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  588. }
  589. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  590. SourceLocation IILoc,
  591. Scope *S,
  592. CXXScopeSpec *SS,
  593. ParsedType &SuggestedType,
  594. bool IsTemplateName) {
  595. // Don't report typename errors for editor placeholders.
  596. if (II->isEditorPlaceholder())
  597. return;
  598. // We don't have anything to suggest (yet).
  599. SuggestedType = nullptr;
  600. // There may have been a typo in the name of the type. Look up typo
  601. // results, in case we have something that we can suggest.
  602. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  603. /*AllowTemplates=*/IsTemplateName,
  604. /*AllowNonTemplates=*/!IsTemplateName);
  605. if (TypoCorrection Corrected =
  606. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  607. CCC, CTK_ErrorRecovery)) {
  608. // FIXME: Support error recovery for the template-name case.
  609. bool CanRecover = !IsTemplateName;
  610. if (Corrected.isKeyword()) {
  611. // We corrected to a keyword.
  612. diagnoseTypo(Corrected,
  613. PDiag(IsTemplateName ? diag::err_no_template_suggest
  614. : diag::err_unknown_typename_suggest)
  615. << II);
  616. II = Corrected.getCorrectionAsIdentifierInfo();
  617. } else {
  618. // We found a similarly-named type or interface; suggest that.
  619. if (!SS || !SS->isSet()) {
  620. diagnoseTypo(Corrected,
  621. PDiag(IsTemplateName ? diag::err_no_template_suggest
  622. : diag::err_unknown_typename_suggest)
  623. << II, CanRecover);
  624. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  625. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  626. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  627. II->getName().equals(CorrectedStr);
  628. diagnoseTypo(Corrected,
  629. PDiag(IsTemplateName
  630. ? diag::err_no_member_template_suggest
  631. : diag::err_unknown_nested_typename_suggest)
  632. << II << DC << DroppedSpecifier << SS->getRange(),
  633. CanRecover);
  634. } else {
  635. llvm_unreachable("could not have corrected a typo here");
  636. }
  637. if (!CanRecover)
  638. return;
  639. CXXScopeSpec tmpSS;
  640. if (Corrected.getCorrectionSpecifier())
  641. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  642. SourceRange(IILoc));
  643. // FIXME: Support class template argument deduction here.
  644. SuggestedType =
  645. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  646. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  647. /*IsCtorOrDtorName=*/false,
  648. /*WantNontrivialTypeSourceInfo=*/true);
  649. }
  650. return;
  651. }
  652. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  653. // See if II is a class template that the user forgot to pass arguments to.
  654. UnqualifiedId Name;
  655. Name.setIdentifier(II, IILoc);
  656. CXXScopeSpec EmptySS;
  657. TemplateTy TemplateResult;
  658. bool MemberOfUnknownSpecialization;
  659. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  660. Name, nullptr, true, TemplateResult,
  661. MemberOfUnknownSpecialization) == TNK_Type_template) {
  662. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  663. return;
  664. }
  665. }
  666. // FIXME: Should we move the logic that tries to recover from a missing tag
  667. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  668. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  669. Diag(IILoc, IsTemplateName ? diag::err_no_template
  670. : diag::err_unknown_typename)
  671. << II;
  672. else if (DeclContext *DC = computeDeclContext(*SS, false))
  673. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  674. : diag::err_typename_nested_not_found)
  675. << II << DC << SS->getRange();
  676. else if (isDependentScopeSpecifier(*SS)) {
  677. unsigned DiagID = diag::err_typename_missing;
  678. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  679. DiagID = diag::ext_typename_missing;
  680. Diag(SS->getRange().getBegin(), DiagID)
  681. << SS->getScopeRep() << II->getName()
  682. << SourceRange(SS->getRange().getBegin(), IILoc)
  683. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  684. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  685. *SS, *II, IILoc).get();
  686. } else {
  687. assert(SS && SS->isInvalid() &&
  688. "Invalid scope specifier has already been diagnosed");
  689. }
  690. }
  691. /// Determine whether the given result set contains either a type name
  692. /// or
  693. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  694. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  695. NextToken.is(tok::less);
  696. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  697. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  698. return true;
  699. if (CheckTemplate && isa<TemplateDecl>(*I))
  700. return true;
  701. }
  702. return false;
  703. }
  704. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  705. Scope *S, CXXScopeSpec &SS,
  706. IdentifierInfo *&Name,
  707. SourceLocation NameLoc) {
  708. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  709. SemaRef.LookupParsedName(R, S, &SS);
  710. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  711. StringRef FixItTagName;
  712. switch (Tag->getTagKind()) {
  713. case TTK_Class:
  714. FixItTagName = "class ";
  715. break;
  716. case TTK_Enum:
  717. FixItTagName = "enum ";
  718. break;
  719. case TTK_Struct:
  720. FixItTagName = "struct ";
  721. break;
  722. case TTK_Interface:
  723. FixItTagName = "__interface ";
  724. break;
  725. case TTK_Union:
  726. FixItTagName = "union ";
  727. break;
  728. }
  729. StringRef TagName = FixItTagName.drop_back();
  730. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  731. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  732. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  733. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  734. I != IEnd; ++I)
  735. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  736. << Name << TagName;
  737. // Replace lookup results with just the tag decl.
  738. Result.clear(Sema::LookupTagName);
  739. SemaRef.LookupParsedName(Result, S, &SS);
  740. return true;
  741. }
  742. return false;
  743. }
  744. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  745. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  746. QualType T, SourceLocation NameLoc) {
  747. ASTContext &Context = S.Context;
  748. TypeLocBuilder Builder;
  749. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  750. T = S.getElaboratedType(ETK_None, SS, T);
  751. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  752. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  753. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  754. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  755. }
  756. Sema::NameClassification
  757. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  758. SourceLocation NameLoc, const Token &NextToken,
  759. bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
  760. DeclarationNameInfo NameInfo(Name, NameLoc);
  761. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  762. if (NextToken.is(tok::coloncolon)) {
  763. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  764. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  765. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  766. isCurrentClassName(*Name, S, &SS)) {
  767. // Per [class.qual]p2, this names the constructors of SS, not the
  768. // injected-class-name. We don't have a classification for that.
  769. // There's not much point caching this result, since the parser
  770. // will reject it later.
  771. return NameClassification::Unknown();
  772. }
  773. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  774. LookupParsedName(Result, S, &SS, !CurMethod);
  775. // For unqualified lookup in a class template in MSVC mode, look into
  776. // dependent base classes where the primary class template is known.
  777. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  778. if (ParsedType TypeInBase =
  779. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  780. return TypeInBase;
  781. }
  782. // Perform lookup for Objective-C instance variables (including automatically
  783. // synthesized instance variables), if we're in an Objective-C method.
  784. // FIXME: This lookup really, really needs to be folded in to the normal
  785. // unqualified lookup mechanism.
  786. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  787. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  788. if (E.get() || E.isInvalid())
  789. return E;
  790. }
  791. bool SecondTry = false;
  792. bool IsFilteredTemplateName = false;
  793. Corrected:
  794. switch (Result.getResultKind()) {
  795. case LookupResult::NotFound:
  796. // If an unqualified-id is followed by a '(', then we have a function
  797. // call.
  798. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  799. // In C++, this is an ADL-only call.
  800. // FIXME: Reference?
  801. if (getLangOpts().CPlusPlus)
  802. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  803. // C90 6.3.2.2:
  804. // If the expression that precedes the parenthesized argument list in a
  805. // function call consists solely of an identifier, and if no
  806. // declaration is visible for this identifier, the identifier is
  807. // implicitly declared exactly as if, in the innermost block containing
  808. // the function call, the declaration
  809. //
  810. // extern int identifier ();
  811. //
  812. // appeared.
  813. //
  814. // We also allow this in C99 as an extension.
  815. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  816. Result.addDecl(D);
  817. Result.resolveKind();
  818. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  819. }
  820. }
  821. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  822. // In C++20 onwards, this could be an ADL-only call to a function
  823. // template, and we're required to assume that this is a template name.
  824. //
  825. // FIXME: Find a way to still do typo correction in this case.
  826. TemplateName Template =
  827. Context.getAssumedTemplateName(NameInfo.getName());
  828. return NameClassification::UndeclaredTemplate(Template);
  829. }
  830. // In C, we first see whether there is a tag type by the same name, in
  831. // which case it's likely that the user just forgot to write "enum",
  832. // "struct", or "union".
  833. if (!getLangOpts().CPlusPlus && !SecondTry &&
  834. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  835. break;
  836. }
  837. // Perform typo correction to determine if there is another name that is
  838. // close to this name.
  839. if (!SecondTry && CCC) {
  840. SecondTry = true;
  841. if (TypoCorrection Corrected =
  842. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  843. &SS, *CCC, CTK_ErrorRecovery)) {
  844. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  845. unsigned QualifiedDiag = diag::err_no_member_suggest;
  846. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  847. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  848. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  849. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  850. UnqualifiedDiag = diag::err_no_template_suggest;
  851. QualifiedDiag = diag::err_no_member_template_suggest;
  852. } else if (UnderlyingFirstDecl &&
  853. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  854. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  855. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  856. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  857. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  858. }
  859. if (SS.isEmpty()) {
  860. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  861. } else {// FIXME: is this even reachable? Test it.
  862. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  863. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  864. Name->getName().equals(CorrectedStr);
  865. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  866. << Name << computeDeclContext(SS, false)
  867. << DroppedSpecifier << SS.getRange());
  868. }
  869. // Update the name, so that the caller has the new name.
  870. Name = Corrected.getCorrectionAsIdentifierInfo();
  871. // Typo correction corrected to a keyword.
  872. if (Corrected.isKeyword())
  873. return Name;
  874. // Also update the LookupResult...
  875. // FIXME: This should probably go away at some point
  876. Result.clear();
  877. Result.setLookupName(Corrected.getCorrection());
  878. if (FirstDecl)
  879. Result.addDecl(FirstDecl);
  880. // If we found an Objective-C instance variable, let
  881. // LookupInObjCMethod build the appropriate expression to
  882. // reference the ivar.
  883. // FIXME: This is a gross hack.
  884. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  885. Result.clear();
  886. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  887. return E;
  888. }
  889. goto Corrected;
  890. }
  891. }
  892. // We failed to correct; just fall through and let the parser deal with it.
  893. Result.suppressDiagnostics();
  894. return NameClassification::Unknown();
  895. case LookupResult::NotFoundInCurrentInstantiation: {
  896. // We performed name lookup into the current instantiation, and there were
  897. // dependent bases, so we treat this result the same way as any other
  898. // dependent nested-name-specifier.
  899. // C++ [temp.res]p2:
  900. // A name used in a template declaration or definition and that is
  901. // dependent on a template-parameter is assumed not to name a type
  902. // unless the applicable name lookup finds a type name or the name is
  903. // qualified by the keyword typename.
  904. //
  905. // FIXME: If the next token is '<', we might want to ask the parser to
  906. // perform some heroics to see if we actually have a
  907. // template-argument-list, which would indicate a missing 'template'
  908. // keyword here.
  909. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  910. NameInfo, IsAddressOfOperand,
  911. /*TemplateArgs=*/nullptr);
  912. }
  913. case LookupResult::Found:
  914. case LookupResult::FoundOverloaded:
  915. case LookupResult::FoundUnresolvedValue:
  916. break;
  917. case LookupResult::Ambiguous:
  918. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  919. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  920. /*AllowDependent=*/false)) {
  921. // C++ [temp.local]p3:
  922. // A lookup that finds an injected-class-name (10.2) can result in an
  923. // ambiguity in certain cases (for example, if it is found in more than
  924. // one base class). If all of the injected-class-names that are found
  925. // refer to specializations of the same class template, and if the name
  926. // is followed by a template-argument-list, the reference refers to the
  927. // class template itself and not a specialization thereof, and is not
  928. // ambiguous.
  929. //
  930. // This filtering can make an ambiguous result into an unambiguous one,
  931. // so try again after filtering out template names.
  932. FilterAcceptableTemplateNames(Result);
  933. if (!Result.isAmbiguous()) {
  934. IsFilteredTemplateName = true;
  935. break;
  936. }
  937. }
  938. // Diagnose the ambiguity and return an error.
  939. return NameClassification::Error();
  940. }
  941. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  942. (IsFilteredTemplateName ||
  943. hasAnyAcceptableTemplateNames(
  944. Result, /*AllowFunctionTemplates=*/true,
  945. /*AllowDependent=*/false,
  946. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  947. getLangOpts().CPlusPlus2a))) {
  948. // C++ [temp.names]p3:
  949. // After name lookup (3.4) finds that a name is a template-name or that
  950. // an operator-function-id or a literal- operator-id refers to a set of
  951. // overloaded functions any member of which is a function template if
  952. // this is followed by a <, the < is always taken as the delimiter of a
  953. // template-argument-list and never as the less-than operator.
  954. // C++2a [temp.names]p2:
  955. // A name is also considered to refer to a template if it is an
  956. // unqualified-id followed by a < and name lookup finds either one
  957. // or more functions or finds nothing.
  958. if (!IsFilteredTemplateName)
  959. FilterAcceptableTemplateNames(Result);
  960. bool IsFunctionTemplate;
  961. bool IsVarTemplate;
  962. TemplateName Template;
  963. if (Result.end() - Result.begin() > 1) {
  964. IsFunctionTemplate = true;
  965. Template = Context.getOverloadedTemplateName(Result.begin(),
  966. Result.end());
  967. } else if (!Result.empty()) {
  968. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  969. *Result.begin(), /*AllowFunctionTemplates=*/true,
  970. /*AllowDependent=*/false));
  971. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  972. IsVarTemplate = isa<VarTemplateDecl>(TD);
  973. if (SS.isSet() && !SS.isInvalid())
  974. Template =
  975. Context.getQualifiedTemplateName(SS.getScopeRep(),
  976. /*TemplateKeyword=*/false, TD);
  977. else
  978. Template = TemplateName(TD);
  979. } else {
  980. // All results were non-template functions. This is a function template
  981. // name.
  982. IsFunctionTemplate = true;
  983. Template = Context.getAssumedTemplateName(NameInfo.getName());
  984. }
  985. if (IsFunctionTemplate) {
  986. // Function templates always go through overload resolution, at which
  987. // point we'll perform the various checks (e.g., accessibility) we need
  988. // to based on which function we selected.
  989. Result.suppressDiagnostics();
  990. return NameClassification::FunctionTemplate(Template);
  991. }
  992. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  993. : NameClassification::TypeTemplate(Template);
  994. }
  995. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  996. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  997. DiagnoseUseOfDecl(Type, NameLoc);
  998. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  999. QualType T = Context.getTypeDeclType(Type);
  1000. if (SS.isNotEmpty())
  1001. return buildNestedType(*this, SS, T, NameLoc);
  1002. return ParsedType::make(T);
  1003. }
  1004. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1005. if (!Class) {
  1006. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1007. if (ObjCCompatibleAliasDecl *Alias =
  1008. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1009. Class = Alias->getClassInterface();
  1010. }
  1011. if (Class) {
  1012. DiagnoseUseOfDecl(Class, NameLoc);
  1013. if (NextToken.is(tok::period)) {
  1014. // Interface. <something> is parsed as a property reference expression.
  1015. // Just return "unknown" as a fall-through for now.
  1016. Result.suppressDiagnostics();
  1017. return NameClassification::Unknown();
  1018. }
  1019. QualType T = Context.getObjCInterfaceType(Class);
  1020. return ParsedType::make(T);
  1021. }
  1022. // We can have a type template here if we're classifying a template argument.
  1023. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1024. !isa<VarTemplateDecl>(FirstDecl))
  1025. return NameClassification::TypeTemplate(
  1026. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1027. // Check for a tag type hidden by a non-type decl in a few cases where it
  1028. // seems likely a type is wanted instead of the non-type that was found.
  1029. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1030. if ((NextToken.is(tok::identifier) ||
  1031. (NextIsOp &&
  1032. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1033. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1034. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1035. DiagnoseUseOfDecl(Type, NameLoc);
  1036. QualType T = Context.getTypeDeclType(Type);
  1037. if (SS.isNotEmpty())
  1038. return buildNestedType(*this, SS, T, NameLoc);
  1039. return ParsedType::make(T);
  1040. }
  1041. if (FirstDecl->isCXXClassMember())
  1042. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1043. nullptr, S);
  1044. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1045. return BuildDeclarationNameExpr(SS, Result, ADL);
  1046. }
  1047. Sema::TemplateNameKindForDiagnostics
  1048. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1049. auto *TD = Name.getAsTemplateDecl();
  1050. if (!TD)
  1051. return TemplateNameKindForDiagnostics::DependentTemplate;
  1052. if (isa<ClassTemplateDecl>(TD))
  1053. return TemplateNameKindForDiagnostics::ClassTemplate;
  1054. if (isa<FunctionTemplateDecl>(TD))
  1055. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1056. if (isa<VarTemplateDecl>(TD))
  1057. return TemplateNameKindForDiagnostics::VarTemplate;
  1058. if (isa<TypeAliasTemplateDecl>(TD))
  1059. return TemplateNameKindForDiagnostics::AliasTemplate;
  1060. if (isa<TemplateTemplateParmDecl>(TD))
  1061. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1062. if (isa<ConceptDecl>(TD))
  1063. return TemplateNameKindForDiagnostics::Concept;
  1064. return TemplateNameKindForDiagnostics::DependentTemplate;
  1065. }
  1066. // Determines the context to return to after temporarily entering a
  1067. // context. This depends in an unnecessarily complicated way on the
  1068. // exact ordering of callbacks from the parser.
  1069. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1070. // Functions defined inline within classes aren't parsed until we've
  1071. // finished parsing the top-level class, so the top-level class is
  1072. // the context we'll need to return to.
  1073. // A Lambda call operator whose parent is a class must not be treated
  1074. // as an inline member function. A Lambda can be used legally
  1075. // either as an in-class member initializer or a default argument. These
  1076. // are parsed once the class has been marked complete and so the containing
  1077. // context would be the nested class (when the lambda is defined in one);
  1078. // If the class is not complete, then the lambda is being used in an
  1079. // ill-formed fashion (such as to specify the width of a bit-field, or
  1080. // in an array-bound) - in which case we still want to return the
  1081. // lexically containing DC (which could be a nested class).
  1082. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1083. DC = DC->getLexicalParent();
  1084. // A function not defined within a class will always return to its
  1085. // lexical context.
  1086. if (!isa<CXXRecordDecl>(DC))
  1087. return DC;
  1088. // A C++ inline method/friend is parsed *after* the topmost class
  1089. // it was declared in is fully parsed ("complete"); the topmost
  1090. // class is the context we need to return to.
  1091. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1092. DC = RD;
  1093. // Return the declaration context of the topmost class the inline method is
  1094. // declared in.
  1095. return DC;
  1096. }
  1097. return DC->getLexicalParent();
  1098. }
  1099. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1100. assert(getContainingDC(DC) == CurContext &&
  1101. "The next DeclContext should be lexically contained in the current one.");
  1102. CurContext = DC;
  1103. S->setEntity(DC);
  1104. }
  1105. void Sema::PopDeclContext() {
  1106. assert(CurContext && "DeclContext imbalance!");
  1107. CurContext = getContainingDC(CurContext);
  1108. assert(CurContext && "Popped translation unit!");
  1109. }
  1110. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1111. Decl *D) {
  1112. // Unlike PushDeclContext, the context to which we return is not necessarily
  1113. // the containing DC of TD, because the new context will be some pre-existing
  1114. // TagDecl definition instead of a fresh one.
  1115. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1116. CurContext = cast<TagDecl>(D)->getDefinition();
  1117. assert(CurContext && "skipping definition of undefined tag");
  1118. // Start lookups from the parent of the current context; we don't want to look
  1119. // into the pre-existing complete definition.
  1120. S->setEntity(CurContext->getLookupParent());
  1121. return Result;
  1122. }
  1123. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1124. CurContext = static_cast<decltype(CurContext)>(Context);
  1125. }
  1126. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1127. /// of a declarator's nested name specifier.
  1128. ///
  1129. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1130. // C++0x [basic.lookup.unqual]p13:
  1131. // A name used in the definition of a static data member of class
  1132. // X (after the qualified-id of the static member) is looked up as
  1133. // if the name was used in a member function of X.
  1134. // C++0x [basic.lookup.unqual]p14:
  1135. // If a variable member of a namespace is defined outside of the
  1136. // scope of its namespace then any name used in the definition of
  1137. // the variable member (after the declarator-id) is looked up as
  1138. // if the definition of the variable member occurred in its
  1139. // namespace.
  1140. // Both of these imply that we should push a scope whose context
  1141. // is the semantic context of the declaration. We can't use
  1142. // PushDeclContext here because that context is not necessarily
  1143. // lexically contained in the current context. Fortunately,
  1144. // the containing scope should have the appropriate information.
  1145. assert(!S->getEntity() && "scope already has entity");
  1146. #ifndef NDEBUG
  1147. Scope *Ancestor = S->getParent();
  1148. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1149. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1150. #endif
  1151. CurContext = DC;
  1152. S->setEntity(DC);
  1153. }
  1154. void Sema::ExitDeclaratorContext(Scope *S) {
  1155. assert(S->getEntity() == CurContext && "Context imbalance!");
  1156. // Switch back to the lexical context. The safety of this is
  1157. // enforced by an assert in EnterDeclaratorContext.
  1158. Scope *Ancestor = S->getParent();
  1159. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1160. CurContext = Ancestor->getEntity();
  1161. // We don't need to do anything with the scope, which is going to
  1162. // disappear.
  1163. }
  1164. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1165. // We assume that the caller has already called
  1166. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1167. FunctionDecl *FD = D->getAsFunction();
  1168. if (!FD)
  1169. return;
  1170. // Same implementation as PushDeclContext, but enters the context
  1171. // from the lexical parent, rather than the top-level class.
  1172. assert(CurContext == FD->getLexicalParent() &&
  1173. "The next DeclContext should be lexically contained in the current one.");
  1174. CurContext = FD;
  1175. S->setEntity(CurContext);
  1176. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1177. ParmVarDecl *Param = FD->getParamDecl(P);
  1178. // If the parameter has an identifier, then add it to the scope
  1179. if (Param->getIdentifier()) {
  1180. S->AddDecl(Param);
  1181. IdResolver.AddDecl(Param);
  1182. }
  1183. }
  1184. }
  1185. void Sema::ActOnExitFunctionContext() {
  1186. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1187. // rather than the top-level class.
  1188. assert(CurContext && "DeclContext imbalance!");
  1189. CurContext = CurContext->getLexicalParent();
  1190. assert(CurContext && "Popped translation unit!");
  1191. }
  1192. /// Determine whether we allow overloading of the function
  1193. /// PrevDecl with another declaration.
  1194. ///
  1195. /// This routine determines whether overloading is possible, not
  1196. /// whether some new function is actually an overload. It will return
  1197. /// true in C++ (where we can always provide overloads) or, as an
  1198. /// extension, in C when the previous function is already an
  1199. /// overloaded function declaration or has the "overloadable"
  1200. /// attribute.
  1201. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1202. ASTContext &Context,
  1203. const FunctionDecl *New) {
  1204. if (Context.getLangOpts().CPlusPlus)
  1205. return true;
  1206. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1207. return true;
  1208. return Previous.getResultKind() == LookupResult::Found &&
  1209. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1210. New->hasAttr<OverloadableAttr>());
  1211. }
  1212. /// Add this decl to the scope shadowed decl chains.
  1213. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1214. // Move up the scope chain until we find the nearest enclosing
  1215. // non-transparent context. The declaration will be introduced into this
  1216. // scope.
  1217. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1218. S = S->getParent();
  1219. // Add scoped declarations into their context, so that they can be
  1220. // found later. Declarations without a context won't be inserted
  1221. // into any context.
  1222. if (AddToContext)
  1223. CurContext->addDecl(D);
  1224. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1225. // are function-local declarations.
  1226. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1227. !D->getDeclContext()->getRedeclContext()->Equals(
  1228. D->getLexicalDeclContext()->getRedeclContext()) &&
  1229. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1230. return;
  1231. // Template instantiations should also not be pushed into scope.
  1232. if (isa<FunctionDecl>(D) &&
  1233. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1234. return;
  1235. // If this replaces anything in the current scope,
  1236. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1237. IEnd = IdResolver.end();
  1238. for (; I != IEnd; ++I) {
  1239. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1240. S->RemoveDecl(*I);
  1241. IdResolver.RemoveDecl(*I);
  1242. // Should only need to replace one decl.
  1243. break;
  1244. }
  1245. }
  1246. S->AddDecl(D);
  1247. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1248. // Implicitly-generated labels may end up getting generated in an order that
  1249. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1250. // the label at the appropriate place in the identifier chain.
  1251. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1252. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1253. if (IDC == CurContext) {
  1254. if (!S->isDeclScope(*I))
  1255. continue;
  1256. } else if (IDC->Encloses(CurContext))
  1257. break;
  1258. }
  1259. IdResolver.InsertDeclAfter(I, D);
  1260. } else {
  1261. IdResolver.AddDecl(D);
  1262. }
  1263. }
  1264. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1265. bool AllowInlineNamespace) {
  1266. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1267. }
  1268. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1269. DeclContext *TargetDC = DC->getPrimaryContext();
  1270. do {
  1271. if (DeclContext *ScopeDC = S->getEntity())
  1272. if (ScopeDC->getPrimaryContext() == TargetDC)
  1273. return S;
  1274. } while ((S = S->getParent()));
  1275. return nullptr;
  1276. }
  1277. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1278. DeclContext*,
  1279. ASTContext&);
  1280. /// Filters out lookup results that don't fall within the given scope
  1281. /// as determined by isDeclInScope.
  1282. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1283. bool ConsiderLinkage,
  1284. bool AllowInlineNamespace) {
  1285. LookupResult::Filter F = R.makeFilter();
  1286. while (F.hasNext()) {
  1287. NamedDecl *D = F.next();
  1288. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1289. continue;
  1290. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1291. continue;
  1292. F.erase();
  1293. }
  1294. F.done();
  1295. }
  1296. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1297. /// have compatible owning modules.
  1298. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1299. // FIXME: The Modules TS is not clear about how friend declarations are
  1300. // to be treated. It's not meaningful to have different owning modules for
  1301. // linkage in redeclarations of the same entity, so for now allow the
  1302. // redeclaration and change the owning modules to match.
  1303. if (New->getFriendObjectKind() &&
  1304. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1305. New->setLocalOwningModule(Old->getOwningModule());
  1306. makeMergedDefinitionVisible(New);
  1307. return false;
  1308. }
  1309. Module *NewM = New->getOwningModule();
  1310. Module *OldM = Old->getOwningModule();
  1311. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1312. NewM = NewM->Parent;
  1313. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1314. OldM = OldM->Parent;
  1315. if (NewM == OldM)
  1316. return false;
  1317. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1318. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1319. if (NewIsModuleInterface || OldIsModuleInterface) {
  1320. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1321. // if a declaration of D [...] appears in the purview of a module, all
  1322. // other such declarations shall appear in the purview of the same module
  1323. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1324. << New
  1325. << NewIsModuleInterface
  1326. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1327. << OldIsModuleInterface
  1328. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1329. Diag(Old->getLocation(), diag::note_previous_declaration);
  1330. New->setInvalidDecl();
  1331. return true;
  1332. }
  1333. return false;
  1334. }
  1335. static bool isUsingDecl(NamedDecl *D) {
  1336. return isa<UsingShadowDecl>(D) ||
  1337. isa<UnresolvedUsingTypenameDecl>(D) ||
  1338. isa<UnresolvedUsingValueDecl>(D);
  1339. }
  1340. /// Removes using shadow declarations from the lookup results.
  1341. static void RemoveUsingDecls(LookupResult &R) {
  1342. LookupResult::Filter F = R.makeFilter();
  1343. while (F.hasNext())
  1344. if (isUsingDecl(F.next()))
  1345. F.erase();
  1346. F.done();
  1347. }
  1348. /// Check for this common pattern:
  1349. /// @code
  1350. /// class S {
  1351. /// S(const S&); // DO NOT IMPLEMENT
  1352. /// void operator=(const S&); // DO NOT IMPLEMENT
  1353. /// };
  1354. /// @endcode
  1355. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1356. // FIXME: Should check for private access too but access is set after we get
  1357. // the decl here.
  1358. if (D->doesThisDeclarationHaveABody())
  1359. return false;
  1360. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1361. return CD->isCopyConstructor();
  1362. return D->isCopyAssignmentOperator();
  1363. }
  1364. // We need this to handle
  1365. //
  1366. // typedef struct {
  1367. // void *foo() { return 0; }
  1368. // } A;
  1369. //
  1370. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1371. // for example. If 'A', foo will have external linkage. If we have '*A',
  1372. // foo will have no linkage. Since we can't know until we get to the end
  1373. // of the typedef, this function finds out if D might have non-external linkage.
  1374. // Callers should verify at the end of the TU if it D has external linkage or
  1375. // not.
  1376. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1377. const DeclContext *DC = D->getDeclContext();
  1378. while (!DC->isTranslationUnit()) {
  1379. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1380. if (!RD->hasNameForLinkage())
  1381. return true;
  1382. }
  1383. DC = DC->getParent();
  1384. }
  1385. return !D->isExternallyVisible();
  1386. }
  1387. // FIXME: This needs to be refactored; some other isInMainFile users want
  1388. // these semantics.
  1389. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1390. if (S.TUKind != TU_Complete)
  1391. return false;
  1392. return S.SourceMgr.isInMainFile(Loc);
  1393. }
  1394. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1395. assert(D);
  1396. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1397. return false;
  1398. // Ignore all entities declared within templates, and out-of-line definitions
  1399. // of members of class templates.
  1400. if (D->getDeclContext()->isDependentContext() ||
  1401. D->getLexicalDeclContext()->isDependentContext())
  1402. return false;
  1403. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1404. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1405. return false;
  1406. // A non-out-of-line declaration of a member specialization was implicitly
  1407. // instantiated; it's the out-of-line declaration that we're interested in.
  1408. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1409. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1410. return false;
  1411. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1412. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1413. return false;
  1414. } else {
  1415. // 'static inline' functions are defined in headers; don't warn.
  1416. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1417. return false;
  1418. }
  1419. if (FD->doesThisDeclarationHaveABody() &&
  1420. Context.DeclMustBeEmitted(FD))
  1421. return false;
  1422. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1423. // Constants and utility variables are defined in headers with internal
  1424. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1425. // like "inline".)
  1426. if (!isMainFileLoc(*this, VD->getLocation()))
  1427. return false;
  1428. if (Context.DeclMustBeEmitted(VD))
  1429. return false;
  1430. if (VD->isStaticDataMember() &&
  1431. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1432. return false;
  1433. if (VD->isStaticDataMember() &&
  1434. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1435. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1436. return false;
  1437. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1438. return false;
  1439. } else {
  1440. return false;
  1441. }
  1442. // Only warn for unused decls internal to the translation unit.
  1443. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1444. // for inline functions defined in the main source file, for instance.
  1445. return mightHaveNonExternalLinkage(D);
  1446. }
  1447. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1448. if (!D)
  1449. return;
  1450. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1451. const FunctionDecl *First = FD->getFirstDecl();
  1452. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1453. return; // First should already be in the vector.
  1454. }
  1455. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1456. const VarDecl *First = VD->getFirstDecl();
  1457. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1458. return; // First should already be in the vector.
  1459. }
  1460. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1461. UnusedFileScopedDecls.push_back(D);
  1462. }
  1463. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1464. if (D->isInvalidDecl())
  1465. return false;
  1466. bool Referenced = false;
  1467. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1468. // For a decomposition declaration, warn if none of the bindings are
  1469. // referenced, instead of if the variable itself is referenced (which
  1470. // it is, by the bindings' expressions).
  1471. for (auto *BD : DD->bindings()) {
  1472. if (BD->isReferenced()) {
  1473. Referenced = true;
  1474. break;
  1475. }
  1476. }
  1477. } else if (!D->getDeclName()) {
  1478. return false;
  1479. } else if (D->isReferenced() || D->isUsed()) {
  1480. Referenced = true;
  1481. }
  1482. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1483. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1484. return false;
  1485. if (isa<LabelDecl>(D))
  1486. return true;
  1487. // Except for labels, we only care about unused decls that are local to
  1488. // functions.
  1489. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1490. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1491. // For dependent types, the diagnostic is deferred.
  1492. WithinFunction =
  1493. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1494. if (!WithinFunction)
  1495. return false;
  1496. if (isa<TypedefNameDecl>(D))
  1497. return true;
  1498. // White-list anything that isn't a local variable.
  1499. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1500. return false;
  1501. // Types of valid local variables should be complete, so this should succeed.
  1502. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1503. // White-list anything with an __attribute__((unused)) type.
  1504. const auto *Ty = VD->getType().getTypePtr();
  1505. // Only look at the outermost level of typedef.
  1506. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1507. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1508. return false;
  1509. }
  1510. // If we failed to complete the type for some reason, or if the type is
  1511. // dependent, don't diagnose the variable.
  1512. if (Ty->isIncompleteType() || Ty->isDependentType())
  1513. return false;
  1514. // Look at the element type to ensure that the warning behaviour is
  1515. // consistent for both scalars and arrays.
  1516. Ty = Ty->getBaseElementTypeUnsafe();
  1517. if (const TagType *TT = Ty->getAs<TagType>()) {
  1518. const TagDecl *Tag = TT->getDecl();
  1519. if (Tag->hasAttr<UnusedAttr>())
  1520. return false;
  1521. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1522. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1523. return false;
  1524. if (const Expr *Init = VD->getInit()) {
  1525. if (const ExprWithCleanups *Cleanups =
  1526. dyn_cast<ExprWithCleanups>(Init))
  1527. Init = Cleanups->getSubExpr();
  1528. const CXXConstructExpr *Construct =
  1529. dyn_cast<CXXConstructExpr>(Init);
  1530. if (Construct && !Construct->isElidable()) {
  1531. CXXConstructorDecl *CD = Construct->getConstructor();
  1532. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1533. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1534. return false;
  1535. }
  1536. }
  1537. }
  1538. }
  1539. // TODO: __attribute__((unused)) templates?
  1540. }
  1541. return true;
  1542. }
  1543. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1544. FixItHint &Hint) {
  1545. if (isa<LabelDecl>(D)) {
  1546. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1547. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1548. true);
  1549. if (AfterColon.isInvalid())
  1550. return;
  1551. Hint = FixItHint::CreateRemoval(
  1552. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1553. }
  1554. }
  1555. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1556. if (D->getTypeForDecl()->isDependentType())
  1557. return;
  1558. for (auto *TmpD : D->decls()) {
  1559. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1560. DiagnoseUnusedDecl(T);
  1561. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1562. DiagnoseUnusedNestedTypedefs(R);
  1563. }
  1564. }
  1565. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1566. /// unless they are marked attr(unused).
  1567. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1568. if (!ShouldDiagnoseUnusedDecl(D))
  1569. return;
  1570. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1571. // typedefs can be referenced later on, so the diagnostics are emitted
  1572. // at end-of-translation-unit.
  1573. UnusedLocalTypedefNameCandidates.insert(TD);
  1574. return;
  1575. }
  1576. FixItHint Hint;
  1577. GenerateFixForUnusedDecl(D, Context, Hint);
  1578. unsigned DiagID;
  1579. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1580. DiagID = diag::warn_unused_exception_param;
  1581. else if (isa<LabelDecl>(D))
  1582. DiagID = diag::warn_unused_label;
  1583. else
  1584. DiagID = diag::warn_unused_variable;
  1585. Diag(D->getLocation(), DiagID) << D << Hint;
  1586. }
  1587. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1588. // Verify that we have no forward references left. If so, there was a goto
  1589. // or address of a label taken, but no definition of it. Label fwd
  1590. // definitions are indicated with a null substmt which is also not a resolved
  1591. // MS inline assembly label name.
  1592. bool Diagnose = false;
  1593. if (L->isMSAsmLabel())
  1594. Diagnose = !L->isResolvedMSAsmLabel();
  1595. else
  1596. Diagnose = L->getStmt() == nullptr;
  1597. if (Diagnose)
  1598. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1599. }
  1600. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1601. S->mergeNRVOIntoParent();
  1602. if (S->decl_empty()) return;
  1603. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1604. "Scope shouldn't contain decls!");
  1605. for (auto *TmpD : S->decls()) {
  1606. assert(TmpD && "This decl didn't get pushed??");
  1607. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1608. NamedDecl *D = cast<NamedDecl>(TmpD);
  1609. // Diagnose unused variables in this scope.
  1610. if (!S->hasUnrecoverableErrorOccurred()) {
  1611. DiagnoseUnusedDecl(D);
  1612. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1613. DiagnoseUnusedNestedTypedefs(RD);
  1614. }
  1615. if (!D->getDeclName()) continue;
  1616. // If this was a forward reference to a label, verify it was defined.
  1617. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1618. CheckPoppedLabel(LD, *this);
  1619. // Remove this name from our lexical scope, and warn on it if we haven't
  1620. // already.
  1621. IdResolver.RemoveDecl(D);
  1622. auto ShadowI = ShadowingDecls.find(D);
  1623. if (ShadowI != ShadowingDecls.end()) {
  1624. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1625. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1626. << D << FD << FD->getParent();
  1627. Diag(FD->getLocation(), diag::note_previous_declaration);
  1628. }
  1629. ShadowingDecls.erase(ShadowI);
  1630. }
  1631. }
  1632. }
  1633. /// Look for an Objective-C class in the translation unit.
  1634. ///
  1635. /// \param Id The name of the Objective-C class we're looking for. If
  1636. /// typo-correction fixes this name, the Id will be updated
  1637. /// to the fixed name.
  1638. ///
  1639. /// \param IdLoc The location of the name in the translation unit.
  1640. ///
  1641. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1642. /// if there is no class with the given name.
  1643. ///
  1644. /// \returns The declaration of the named Objective-C class, or NULL if the
  1645. /// class could not be found.
  1646. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1647. SourceLocation IdLoc,
  1648. bool DoTypoCorrection) {
  1649. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1650. // creation from this context.
  1651. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1652. if (!IDecl && DoTypoCorrection) {
  1653. // Perform typo correction at the given location, but only if we
  1654. // find an Objective-C class name.
  1655. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1656. if (TypoCorrection C =
  1657. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1658. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1659. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1660. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1661. Id = IDecl->getIdentifier();
  1662. }
  1663. }
  1664. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1665. // This routine must always return a class definition, if any.
  1666. if (Def && Def->getDefinition())
  1667. Def = Def->getDefinition();
  1668. return Def;
  1669. }
  1670. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1671. /// from S, where a non-field would be declared. This routine copes
  1672. /// with the difference between C and C++ scoping rules in structs and
  1673. /// unions. For example, the following code is well-formed in C but
  1674. /// ill-formed in C++:
  1675. /// @code
  1676. /// struct S6 {
  1677. /// enum { BAR } e;
  1678. /// };
  1679. ///
  1680. /// void test_S6() {
  1681. /// struct S6 a;
  1682. /// a.e = BAR;
  1683. /// }
  1684. /// @endcode
  1685. /// For the declaration of BAR, this routine will return a different
  1686. /// scope. The scope S will be the scope of the unnamed enumeration
  1687. /// within S6. In C++, this routine will return the scope associated
  1688. /// with S6, because the enumeration's scope is a transparent
  1689. /// context but structures can contain non-field names. In C, this
  1690. /// routine will return the translation unit scope, since the
  1691. /// enumeration's scope is a transparent context and structures cannot
  1692. /// contain non-field names.
  1693. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1694. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1695. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1696. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1697. S = S->getParent();
  1698. return S;
  1699. }
  1700. /// Looks up the declaration of "struct objc_super" and
  1701. /// saves it for later use in building builtin declaration of
  1702. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1703. /// pre-existing declaration exists no action takes place.
  1704. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1705. IdentifierInfo *II) {
  1706. if (!II->isStr("objc_msgSendSuper"))
  1707. return;
  1708. ASTContext &Context = ThisSema.Context;
  1709. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1710. SourceLocation(), Sema::LookupTagName);
  1711. ThisSema.LookupName(Result, S);
  1712. if (Result.getResultKind() == LookupResult::Found)
  1713. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1714. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1715. }
  1716. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1717. ASTContext::GetBuiltinTypeError Error) {
  1718. switch (Error) {
  1719. case ASTContext::GE_None:
  1720. return "";
  1721. case ASTContext::GE_Missing_type:
  1722. return BuiltinInfo.getHeaderName(ID);
  1723. case ASTContext::GE_Missing_stdio:
  1724. return "stdio.h";
  1725. case ASTContext::GE_Missing_setjmp:
  1726. return "setjmp.h";
  1727. case ASTContext::GE_Missing_ucontext:
  1728. return "ucontext.h";
  1729. }
  1730. llvm_unreachable("unhandled error kind");
  1731. }
  1732. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1733. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1734. /// if we're creating this built-in in anticipation of redeclaring the
  1735. /// built-in.
  1736. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1737. Scope *S, bool ForRedeclaration,
  1738. SourceLocation Loc) {
  1739. LookupPredefedObjCSuperType(*this, S, II);
  1740. ASTContext::GetBuiltinTypeError Error;
  1741. QualType R = Context.GetBuiltinType(ID, Error);
  1742. if (Error) {
  1743. if (!ForRedeclaration)
  1744. return nullptr;
  1745. // If we have a builtin without an associated type we should not emit a
  1746. // warning when we were not able to find a type for it.
  1747. if (Error == ASTContext::GE_Missing_type)
  1748. return nullptr;
  1749. // If we could not find a type for setjmp it is because the jmp_buf type was
  1750. // not defined prior to the setjmp declaration.
  1751. if (Error == ASTContext::GE_Missing_setjmp) {
  1752. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  1753. << Context.BuiltinInfo.getName(ID);
  1754. return nullptr;
  1755. }
  1756. // Generally, we emit a warning that the declaration requires the
  1757. // appropriate header.
  1758. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1759. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1760. << Context.BuiltinInfo.getName(ID);
  1761. return nullptr;
  1762. }
  1763. if (!ForRedeclaration &&
  1764. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1765. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1766. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1767. << Context.BuiltinInfo.getName(ID) << R;
  1768. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1769. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1770. Diag(Loc, diag::note_include_header_or_declare)
  1771. << Context.BuiltinInfo.getHeaderName(ID)
  1772. << Context.BuiltinInfo.getName(ID);
  1773. }
  1774. if (R.isNull())
  1775. return nullptr;
  1776. DeclContext *Parent = Context.getTranslationUnitDecl();
  1777. if (getLangOpts().CPlusPlus) {
  1778. LinkageSpecDecl *CLinkageDecl =
  1779. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1780. LinkageSpecDecl::lang_c, false);
  1781. CLinkageDecl->setImplicit();
  1782. Parent->addDecl(CLinkageDecl);
  1783. Parent = CLinkageDecl;
  1784. }
  1785. FunctionDecl *New = FunctionDecl::Create(Context,
  1786. Parent,
  1787. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1788. SC_Extern,
  1789. false,
  1790. R->isFunctionProtoType());
  1791. New->setImplicit();
  1792. // Create Decl objects for each parameter, adding them to the
  1793. // FunctionDecl.
  1794. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1795. SmallVector<ParmVarDecl*, 16> Params;
  1796. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1797. ParmVarDecl *parm =
  1798. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1799. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1800. SC_None, nullptr);
  1801. parm->setScopeInfo(0, i);
  1802. Params.push_back(parm);
  1803. }
  1804. New->setParams(Params);
  1805. }
  1806. AddKnownFunctionAttributes(New);
  1807. RegisterLocallyScopedExternCDecl(New, S);
  1808. // TUScope is the translation-unit scope to insert this function into.
  1809. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1810. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1811. // entirely, but we're not there yet.
  1812. DeclContext *SavedContext = CurContext;
  1813. CurContext = Parent;
  1814. PushOnScopeChains(New, TUScope);
  1815. CurContext = SavedContext;
  1816. return New;
  1817. }
  1818. /// Typedef declarations don't have linkage, but they still denote the same
  1819. /// entity if their types are the same.
  1820. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1821. /// isSameEntity.
  1822. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1823. TypedefNameDecl *Decl,
  1824. LookupResult &Previous) {
  1825. // This is only interesting when modules are enabled.
  1826. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1827. return;
  1828. // Empty sets are uninteresting.
  1829. if (Previous.empty())
  1830. return;
  1831. LookupResult::Filter Filter = Previous.makeFilter();
  1832. while (Filter.hasNext()) {
  1833. NamedDecl *Old = Filter.next();
  1834. // Non-hidden declarations are never ignored.
  1835. if (S.isVisible(Old))
  1836. continue;
  1837. // Declarations of the same entity are not ignored, even if they have
  1838. // different linkages.
  1839. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1840. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1841. Decl->getUnderlyingType()))
  1842. continue;
  1843. // If both declarations give a tag declaration a typedef name for linkage
  1844. // purposes, then they declare the same entity.
  1845. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1846. Decl->getAnonDeclWithTypedefName())
  1847. continue;
  1848. }
  1849. Filter.erase();
  1850. }
  1851. Filter.done();
  1852. }
  1853. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1854. QualType OldType;
  1855. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1856. OldType = OldTypedef->getUnderlyingType();
  1857. else
  1858. OldType = Context.getTypeDeclType(Old);
  1859. QualType NewType = New->getUnderlyingType();
  1860. if (NewType->isVariablyModifiedType()) {
  1861. // Must not redefine a typedef with a variably-modified type.
  1862. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1863. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1864. << Kind << NewType;
  1865. if (Old->getLocation().isValid())
  1866. notePreviousDefinition(Old, New->getLocation());
  1867. New->setInvalidDecl();
  1868. return true;
  1869. }
  1870. if (OldType != NewType &&
  1871. !OldType->isDependentType() &&
  1872. !NewType->isDependentType() &&
  1873. !Context.hasSameType(OldType, NewType)) {
  1874. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1875. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1876. << Kind << NewType << OldType;
  1877. if (Old->getLocation().isValid())
  1878. notePreviousDefinition(Old, New->getLocation());
  1879. New->setInvalidDecl();
  1880. return true;
  1881. }
  1882. return false;
  1883. }
  1884. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1885. /// same name and scope as a previous declaration 'Old'. Figure out
  1886. /// how to resolve this situation, merging decls or emitting
  1887. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1888. ///
  1889. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1890. LookupResult &OldDecls) {
  1891. // If the new decl is known invalid already, don't bother doing any
  1892. // merging checks.
  1893. if (New->isInvalidDecl()) return;
  1894. // Allow multiple definitions for ObjC built-in typedefs.
  1895. // FIXME: Verify the underlying types are equivalent!
  1896. if (getLangOpts().ObjC) {
  1897. const IdentifierInfo *TypeID = New->getIdentifier();
  1898. switch (TypeID->getLength()) {
  1899. default: break;
  1900. case 2:
  1901. {
  1902. if (!TypeID->isStr("id"))
  1903. break;
  1904. QualType T = New->getUnderlyingType();
  1905. if (!T->isPointerType())
  1906. break;
  1907. if (!T->isVoidPointerType()) {
  1908. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1909. if (!PT->isStructureType())
  1910. break;
  1911. }
  1912. Context.setObjCIdRedefinitionType(T);
  1913. // Install the built-in type for 'id', ignoring the current definition.
  1914. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1915. return;
  1916. }
  1917. case 5:
  1918. if (!TypeID->isStr("Class"))
  1919. break;
  1920. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1921. // Install the built-in type for 'Class', ignoring the current definition.
  1922. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1923. return;
  1924. case 3:
  1925. if (!TypeID->isStr("SEL"))
  1926. break;
  1927. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1928. // Install the built-in type for 'SEL', ignoring the current definition.
  1929. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1930. return;
  1931. }
  1932. // Fall through - the typedef name was not a builtin type.
  1933. }
  1934. // Verify the old decl was also a type.
  1935. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1936. if (!Old) {
  1937. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1938. << New->getDeclName();
  1939. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1940. if (OldD->getLocation().isValid())
  1941. notePreviousDefinition(OldD, New->getLocation());
  1942. return New->setInvalidDecl();
  1943. }
  1944. // If the old declaration is invalid, just give up here.
  1945. if (Old->isInvalidDecl())
  1946. return New->setInvalidDecl();
  1947. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1948. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1949. auto *NewTag = New->getAnonDeclWithTypedefName();
  1950. NamedDecl *Hidden = nullptr;
  1951. if (OldTag && NewTag &&
  1952. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1953. !hasVisibleDefinition(OldTag, &Hidden)) {
  1954. // There is a definition of this tag, but it is not visible. Use it
  1955. // instead of our tag.
  1956. New->setTypeForDecl(OldTD->getTypeForDecl());
  1957. if (OldTD->isModed())
  1958. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1959. OldTD->getUnderlyingType());
  1960. else
  1961. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1962. // Make the old tag definition visible.
  1963. makeMergedDefinitionVisible(Hidden);
  1964. // If this was an unscoped enumeration, yank all of its enumerators
  1965. // out of the scope.
  1966. if (isa<EnumDecl>(NewTag)) {
  1967. Scope *EnumScope = getNonFieldDeclScope(S);
  1968. for (auto *D : NewTag->decls()) {
  1969. auto *ED = cast<EnumConstantDecl>(D);
  1970. assert(EnumScope->isDeclScope(ED));
  1971. EnumScope->RemoveDecl(ED);
  1972. IdResolver.RemoveDecl(ED);
  1973. ED->getLexicalDeclContext()->removeDecl(ED);
  1974. }
  1975. }
  1976. }
  1977. }
  1978. // If the typedef types are not identical, reject them in all languages and
  1979. // with any extensions enabled.
  1980. if (isIncompatibleTypedef(Old, New))
  1981. return;
  1982. // The types match. Link up the redeclaration chain and merge attributes if
  1983. // the old declaration was a typedef.
  1984. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1985. New->setPreviousDecl(Typedef);
  1986. mergeDeclAttributes(New, Old);
  1987. }
  1988. if (getLangOpts().MicrosoftExt)
  1989. return;
  1990. if (getLangOpts().CPlusPlus) {
  1991. // C++ [dcl.typedef]p2:
  1992. // In a given non-class scope, a typedef specifier can be used to
  1993. // redefine the name of any type declared in that scope to refer
  1994. // to the type to which it already refers.
  1995. if (!isa<CXXRecordDecl>(CurContext))
  1996. return;
  1997. // C++0x [dcl.typedef]p4:
  1998. // In a given class scope, a typedef specifier can be used to redefine
  1999. // any class-name declared in that scope that is not also a typedef-name
  2000. // to refer to the type to which it already refers.
  2001. //
  2002. // This wording came in via DR424, which was a correction to the
  2003. // wording in DR56, which accidentally banned code like:
  2004. //
  2005. // struct S {
  2006. // typedef struct A { } A;
  2007. // };
  2008. //
  2009. // in the C++03 standard. We implement the C++0x semantics, which
  2010. // allow the above but disallow
  2011. //
  2012. // struct S {
  2013. // typedef int I;
  2014. // typedef int I;
  2015. // };
  2016. //
  2017. // since that was the intent of DR56.
  2018. if (!isa<TypedefNameDecl>(Old))
  2019. return;
  2020. Diag(New->getLocation(), diag::err_redefinition)
  2021. << New->getDeclName();
  2022. notePreviousDefinition(Old, New->getLocation());
  2023. return New->setInvalidDecl();
  2024. }
  2025. // Modules always permit redefinition of typedefs, as does C11.
  2026. if (getLangOpts().Modules || getLangOpts().C11)
  2027. return;
  2028. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2029. // is normally mapped to an error, but can be controlled with
  2030. // -Wtypedef-redefinition. If either the original or the redefinition is
  2031. // in a system header, don't emit this for compatibility with GCC.
  2032. if (getDiagnostics().getSuppressSystemWarnings() &&
  2033. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2034. (Old->isImplicit() ||
  2035. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2036. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2037. return;
  2038. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2039. << New->getDeclName();
  2040. notePreviousDefinition(Old, New->getLocation());
  2041. }
  2042. /// DeclhasAttr - returns true if decl Declaration already has the target
  2043. /// attribute.
  2044. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2045. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2046. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2047. for (const auto *i : D->attrs())
  2048. if (i->getKind() == A->getKind()) {
  2049. if (Ann) {
  2050. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2051. return true;
  2052. continue;
  2053. }
  2054. // FIXME: Don't hardcode this check
  2055. if (OA && isa<OwnershipAttr>(i))
  2056. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2057. return true;
  2058. }
  2059. return false;
  2060. }
  2061. static bool isAttributeTargetADefinition(Decl *D) {
  2062. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2063. return VD->isThisDeclarationADefinition();
  2064. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2065. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2066. return true;
  2067. }
  2068. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2069. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2070. ///
  2071. /// \return \c true if any attributes were added to \p New.
  2072. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2073. // Look for alignas attributes on Old, and pick out whichever attribute
  2074. // specifies the strictest alignment requirement.
  2075. AlignedAttr *OldAlignasAttr = nullptr;
  2076. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2077. unsigned OldAlign = 0;
  2078. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2079. // FIXME: We have no way of representing inherited dependent alignments
  2080. // in a case like:
  2081. // template<int A, int B> struct alignas(A) X;
  2082. // template<int A, int B> struct alignas(B) X {};
  2083. // For now, we just ignore any alignas attributes which are not on the
  2084. // definition in such a case.
  2085. if (I->isAlignmentDependent())
  2086. return false;
  2087. if (I->isAlignas())
  2088. OldAlignasAttr = I;
  2089. unsigned Align = I->getAlignment(S.Context);
  2090. if (Align > OldAlign) {
  2091. OldAlign = Align;
  2092. OldStrictestAlignAttr = I;
  2093. }
  2094. }
  2095. // Look for alignas attributes on New.
  2096. AlignedAttr *NewAlignasAttr = nullptr;
  2097. unsigned NewAlign = 0;
  2098. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2099. if (I->isAlignmentDependent())
  2100. return false;
  2101. if (I->isAlignas())
  2102. NewAlignasAttr = I;
  2103. unsigned Align = I->getAlignment(S.Context);
  2104. if (Align > NewAlign)
  2105. NewAlign = Align;
  2106. }
  2107. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2108. // Both declarations have 'alignas' attributes. We require them to match.
  2109. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2110. // fall short. (If two declarations both have alignas, they must both match
  2111. // every definition, and so must match each other if there is a definition.)
  2112. // If either declaration only contains 'alignas(0)' specifiers, then it
  2113. // specifies the natural alignment for the type.
  2114. if (OldAlign == 0 || NewAlign == 0) {
  2115. QualType Ty;
  2116. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2117. Ty = VD->getType();
  2118. else
  2119. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2120. if (OldAlign == 0)
  2121. OldAlign = S.Context.getTypeAlign(Ty);
  2122. if (NewAlign == 0)
  2123. NewAlign = S.Context.getTypeAlign(Ty);
  2124. }
  2125. if (OldAlign != NewAlign) {
  2126. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2127. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2128. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2129. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2130. }
  2131. }
  2132. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2133. // C++11 [dcl.align]p6:
  2134. // if any declaration of an entity has an alignment-specifier,
  2135. // every defining declaration of that entity shall specify an
  2136. // equivalent alignment.
  2137. // C11 6.7.5/7:
  2138. // If the definition of an object does not have an alignment
  2139. // specifier, any other declaration of that object shall also
  2140. // have no alignment specifier.
  2141. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2142. << OldAlignasAttr;
  2143. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2144. << OldAlignasAttr;
  2145. }
  2146. bool AnyAdded = false;
  2147. // Ensure we have an attribute representing the strictest alignment.
  2148. if (OldAlign > NewAlign) {
  2149. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2150. Clone->setInherited(true);
  2151. New->addAttr(Clone);
  2152. AnyAdded = true;
  2153. }
  2154. // Ensure we have an alignas attribute if the old declaration had one.
  2155. if (OldAlignasAttr && !NewAlignasAttr &&
  2156. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2157. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2158. Clone->setInherited(true);
  2159. New->addAttr(Clone);
  2160. AnyAdded = true;
  2161. }
  2162. return AnyAdded;
  2163. }
  2164. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2165. const InheritableAttr *Attr,
  2166. Sema::AvailabilityMergeKind AMK) {
  2167. // This function copies an attribute Attr from a previous declaration to the
  2168. // new declaration D if the new declaration doesn't itself have that attribute
  2169. // yet or if that attribute allows duplicates.
  2170. // If you're adding a new attribute that requires logic different from
  2171. // "use explicit attribute on decl if present, else use attribute from
  2172. // previous decl", for example if the attribute needs to be consistent
  2173. // between redeclarations, you need to call a custom merge function here.
  2174. InheritableAttr *NewAttr = nullptr;
  2175. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2176. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2177. NewAttr = S.mergeAvailabilityAttr(
  2178. D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
  2179. AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
  2180. AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
  2181. AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
  2182. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2183. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2184. AttrSpellingListIndex);
  2185. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2186. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2187. AttrSpellingListIndex);
  2188. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2189. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2190. AttrSpellingListIndex);
  2191. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2192. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2193. AttrSpellingListIndex);
  2194. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2195. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2196. FA->getFormatIdx(), FA->getFirstArg(),
  2197. AttrSpellingListIndex);
  2198. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2199. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2200. AttrSpellingListIndex);
  2201. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2202. NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
  2203. AttrSpellingListIndex);
  2204. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2205. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2206. AttrSpellingListIndex,
  2207. IA->getSemanticSpelling());
  2208. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2209. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2210. &S.Context.Idents.get(AA->getSpelling()),
  2211. AttrSpellingListIndex);
  2212. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2213. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2214. isa<CUDAGlobalAttr>(Attr))) {
  2215. // CUDA target attributes are part of function signature for
  2216. // overloading purposes and must not be merged.
  2217. return false;
  2218. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2219. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2220. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2221. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2222. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2223. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2224. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2225. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2226. else if (isa<AlignedAttr>(Attr))
  2227. // AlignedAttrs are handled separately, because we need to handle all
  2228. // such attributes on a declaration at the same time.
  2229. NewAttr = nullptr;
  2230. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2231. (AMK == Sema::AMK_Override ||
  2232. AMK == Sema::AMK_ProtocolImplementation))
  2233. NewAttr = nullptr;
  2234. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2235. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2236. UA->getGuid());
  2237. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2238. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2239. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2240. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2241. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2242. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2243. if (NewAttr) {
  2244. NewAttr->setInherited(true);
  2245. D->addAttr(NewAttr);
  2246. if (isa<MSInheritanceAttr>(NewAttr))
  2247. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2248. return true;
  2249. }
  2250. return false;
  2251. }
  2252. static const NamedDecl *getDefinition(const Decl *D) {
  2253. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2254. return TD->getDefinition();
  2255. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2256. const VarDecl *Def = VD->getDefinition();
  2257. if (Def)
  2258. return Def;
  2259. return VD->getActingDefinition();
  2260. }
  2261. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2262. return FD->getDefinition();
  2263. return nullptr;
  2264. }
  2265. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2266. for (const auto *Attribute : D->attrs())
  2267. if (Attribute->getKind() == Kind)
  2268. return true;
  2269. return false;
  2270. }
  2271. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2272. /// there are no new attributes in this declaration.
  2273. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2274. if (!New->hasAttrs())
  2275. return;
  2276. const NamedDecl *Def = getDefinition(Old);
  2277. if (!Def || Def == New)
  2278. return;
  2279. AttrVec &NewAttributes = New->getAttrs();
  2280. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2281. const Attr *NewAttribute = NewAttributes[I];
  2282. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2283. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2284. Sema::SkipBodyInfo SkipBody;
  2285. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2286. // If we're skipping this definition, drop the "alias" attribute.
  2287. if (SkipBody.ShouldSkip) {
  2288. NewAttributes.erase(NewAttributes.begin() + I);
  2289. --E;
  2290. continue;
  2291. }
  2292. } else {
  2293. VarDecl *VD = cast<VarDecl>(New);
  2294. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2295. VarDecl::TentativeDefinition
  2296. ? diag::err_alias_after_tentative
  2297. : diag::err_redefinition;
  2298. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2299. if (Diag == diag::err_redefinition)
  2300. S.notePreviousDefinition(Def, VD->getLocation());
  2301. else
  2302. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2303. VD->setInvalidDecl();
  2304. }
  2305. ++I;
  2306. continue;
  2307. }
  2308. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2309. // Tentative definitions are only interesting for the alias check above.
  2310. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2311. ++I;
  2312. continue;
  2313. }
  2314. }
  2315. if (hasAttribute(Def, NewAttribute->getKind())) {
  2316. ++I;
  2317. continue; // regular attr merging will take care of validating this.
  2318. }
  2319. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2320. // C's _Noreturn is allowed to be added to a function after it is defined.
  2321. ++I;
  2322. continue;
  2323. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2324. if (AA->isAlignas()) {
  2325. // C++11 [dcl.align]p6:
  2326. // if any declaration of an entity has an alignment-specifier,
  2327. // every defining declaration of that entity shall specify an
  2328. // equivalent alignment.
  2329. // C11 6.7.5/7:
  2330. // If the definition of an object does not have an alignment
  2331. // specifier, any other declaration of that object shall also
  2332. // have no alignment specifier.
  2333. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2334. << AA;
  2335. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2336. << AA;
  2337. NewAttributes.erase(NewAttributes.begin() + I);
  2338. --E;
  2339. continue;
  2340. }
  2341. }
  2342. S.Diag(NewAttribute->getLocation(),
  2343. diag::warn_attribute_precede_definition);
  2344. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2345. NewAttributes.erase(NewAttributes.begin() + I);
  2346. --E;
  2347. }
  2348. }
  2349. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2350. const ConstInitAttr *CIAttr,
  2351. bool AttrBeforeInit) {
  2352. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2353. // Figure out a good way to write this specifier on the old declaration.
  2354. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2355. // enough of the attribute list spelling information to extract that without
  2356. // heroics.
  2357. std::string SuitableSpelling;
  2358. if (S.getLangOpts().CPlusPlus2a)
  2359. SuitableSpelling =
  2360. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
  2361. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2362. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2363. InsertLoc,
  2364. {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
  2365. tok::coloncolon,
  2366. S.PP.getIdentifierInfo("require_constant_initialization"),
  2367. tok::r_square, tok::r_square});
  2368. if (SuitableSpelling.empty())
  2369. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2370. InsertLoc,
  2371. {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2372. S.PP.getIdentifierInfo("require_constant_initialization"),
  2373. tok::r_paren, tok::r_paren});
  2374. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
  2375. SuitableSpelling = "constinit";
  2376. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2377. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2378. if (SuitableSpelling.empty())
  2379. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2380. SuitableSpelling += " ";
  2381. if (AttrBeforeInit) {
  2382. // extern constinit int a;
  2383. // int a = 0; // error (missing 'constinit'), accepted as extension
  2384. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2385. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2386. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2387. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2388. } else {
  2389. // int a = 0;
  2390. // constinit extern int a; // error (missing 'constinit')
  2391. S.Diag(CIAttr->getLocation(),
  2392. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2393. : diag::warn_require_const_init_added_too_late)
  2394. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2395. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2396. << CIAttr->isConstinit()
  2397. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2398. }
  2399. }
  2400. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2401. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2402. AvailabilityMergeKind AMK) {
  2403. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2404. UsedAttr *NewAttr = OldAttr->clone(Context);
  2405. NewAttr->setInherited(true);
  2406. New->addAttr(NewAttr);
  2407. }
  2408. if (!Old->hasAttrs() && !New->hasAttrs())
  2409. return;
  2410. // [dcl.constinit]p1:
  2411. // If the [constinit] specifier is applied to any declaration of a
  2412. // variable, it shall be applied to the initializing declaration.
  2413. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2414. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2415. if (bool(OldConstInit) != bool(NewConstInit)) {
  2416. const auto *OldVD = cast<VarDecl>(Old);
  2417. auto *NewVD = cast<VarDecl>(New);
  2418. // Find the initializing declaration. Note that we might not have linked
  2419. // the new declaration into the redeclaration chain yet.
  2420. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2421. if (!InitDecl &&
  2422. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2423. InitDecl = NewVD;
  2424. if (InitDecl == NewVD) {
  2425. // This is the initializing declaration. If it would inherit 'constinit',
  2426. // that's ill-formed. (Note that we do not apply this to the attribute
  2427. // form).
  2428. if (OldConstInit && OldConstInit->isConstinit())
  2429. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2430. /*AttrBeforeInit=*/true);
  2431. } else if (NewConstInit) {
  2432. // This is the first time we've been told that this declaration should
  2433. // have a constant initializer. If we already saw the initializing
  2434. // declaration, this is too late.
  2435. if (InitDecl && InitDecl != NewVD) {
  2436. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2437. /*AttrBeforeInit=*/false);
  2438. NewVD->dropAttr<ConstInitAttr>();
  2439. }
  2440. }
  2441. }
  2442. // Attributes declared post-definition are currently ignored.
  2443. checkNewAttributesAfterDef(*this, New, Old);
  2444. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2445. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2446. if (OldA->getLabel() != NewA->getLabel()) {
  2447. // This redeclaration changes __asm__ label.
  2448. Diag(New->getLocation(), diag::err_different_asm_label);
  2449. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2450. }
  2451. } else if (Old->isUsed()) {
  2452. // This redeclaration adds an __asm__ label to a declaration that has
  2453. // already been ODR-used.
  2454. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2455. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2456. }
  2457. }
  2458. // Re-declaration cannot add abi_tag's.
  2459. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2460. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2461. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2462. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2463. NewTag) == OldAbiTagAttr->tags_end()) {
  2464. Diag(NewAbiTagAttr->getLocation(),
  2465. diag::err_new_abi_tag_on_redeclaration)
  2466. << NewTag;
  2467. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2468. }
  2469. }
  2470. } else {
  2471. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2472. Diag(Old->getLocation(), diag::note_previous_declaration);
  2473. }
  2474. }
  2475. // This redeclaration adds a section attribute.
  2476. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2477. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2478. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2479. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2480. Diag(Old->getLocation(), diag::note_previous_declaration);
  2481. }
  2482. }
  2483. }
  2484. // Redeclaration adds code-seg attribute.
  2485. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2486. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2487. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2488. Diag(New->getLocation(), diag::warn_mismatched_section)
  2489. << 0 /*codeseg*/;
  2490. Diag(Old->getLocation(), diag::note_previous_declaration);
  2491. }
  2492. if (!Old->hasAttrs())
  2493. return;
  2494. bool foundAny = New->hasAttrs();
  2495. // Ensure that any moving of objects within the allocated map is done before
  2496. // we process them.
  2497. if (!foundAny) New->setAttrs(AttrVec());
  2498. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2499. // Ignore deprecated/unavailable/availability attributes if requested.
  2500. AvailabilityMergeKind LocalAMK = AMK_None;
  2501. if (isa<DeprecatedAttr>(I) ||
  2502. isa<UnavailableAttr>(I) ||
  2503. isa<AvailabilityAttr>(I)) {
  2504. switch (AMK) {
  2505. case AMK_None:
  2506. continue;
  2507. case AMK_Redeclaration:
  2508. case AMK_Override:
  2509. case AMK_ProtocolImplementation:
  2510. LocalAMK = AMK;
  2511. break;
  2512. }
  2513. }
  2514. // Already handled.
  2515. if (isa<UsedAttr>(I))
  2516. continue;
  2517. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2518. foundAny = true;
  2519. }
  2520. if (mergeAlignedAttrs(*this, New, Old))
  2521. foundAny = true;
  2522. if (!foundAny) New->dropAttrs();
  2523. }
  2524. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2525. /// to the new one.
  2526. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2527. const ParmVarDecl *oldDecl,
  2528. Sema &S) {
  2529. // C++11 [dcl.attr.depend]p2:
  2530. // The first declaration of a function shall specify the
  2531. // carries_dependency attribute for its declarator-id if any declaration
  2532. // of the function specifies the carries_dependency attribute.
  2533. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2534. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2535. S.Diag(CDA->getLocation(),
  2536. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2537. // Find the first declaration of the parameter.
  2538. // FIXME: Should we build redeclaration chains for function parameters?
  2539. const FunctionDecl *FirstFD =
  2540. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2541. const ParmVarDecl *FirstVD =
  2542. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2543. S.Diag(FirstVD->getLocation(),
  2544. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2545. }
  2546. if (!oldDecl->hasAttrs())
  2547. return;
  2548. bool foundAny = newDecl->hasAttrs();
  2549. // Ensure that any moving of objects within the allocated map is
  2550. // done before we process them.
  2551. if (!foundAny) newDecl->setAttrs(AttrVec());
  2552. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2553. if (!DeclHasAttr(newDecl, I)) {
  2554. InheritableAttr *newAttr =
  2555. cast<InheritableParamAttr>(I->clone(S.Context));
  2556. newAttr->setInherited(true);
  2557. newDecl->addAttr(newAttr);
  2558. foundAny = true;
  2559. }
  2560. }
  2561. if (!foundAny) newDecl->dropAttrs();
  2562. }
  2563. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2564. const ParmVarDecl *OldParam,
  2565. Sema &S) {
  2566. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2567. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2568. if (*Oldnullability != *Newnullability) {
  2569. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2570. << DiagNullabilityKind(
  2571. *Newnullability,
  2572. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2573. != 0))
  2574. << DiagNullabilityKind(
  2575. *Oldnullability,
  2576. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2577. != 0));
  2578. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2579. }
  2580. } else {
  2581. QualType NewT = NewParam->getType();
  2582. NewT = S.Context.getAttributedType(
  2583. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2584. NewT, NewT);
  2585. NewParam->setType(NewT);
  2586. }
  2587. }
  2588. }
  2589. namespace {
  2590. /// Used in MergeFunctionDecl to keep track of function parameters in
  2591. /// C.
  2592. struct GNUCompatibleParamWarning {
  2593. ParmVarDecl *OldParm;
  2594. ParmVarDecl *NewParm;
  2595. QualType PromotedType;
  2596. };
  2597. } // end anonymous namespace
  2598. /// getSpecialMember - get the special member enum for a method.
  2599. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2600. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2601. if (Ctor->isDefaultConstructor())
  2602. return Sema::CXXDefaultConstructor;
  2603. if (Ctor->isCopyConstructor())
  2604. return Sema::CXXCopyConstructor;
  2605. if (Ctor->isMoveConstructor())
  2606. return Sema::CXXMoveConstructor;
  2607. } else if (isa<CXXDestructorDecl>(MD)) {
  2608. return Sema::CXXDestructor;
  2609. } else if (MD->isCopyAssignmentOperator()) {
  2610. return Sema::CXXCopyAssignment;
  2611. } else if (MD->isMoveAssignmentOperator()) {
  2612. return Sema::CXXMoveAssignment;
  2613. }
  2614. return Sema::CXXInvalid;
  2615. }
  2616. // Determine whether the previous declaration was a definition, implicit
  2617. // declaration, or a declaration.
  2618. template <typename T>
  2619. static std::pair<diag::kind, SourceLocation>
  2620. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2621. diag::kind PrevDiag;
  2622. SourceLocation OldLocation = Old->getLocation();
  2623. if (Old->isThisDeclarationADefinition())
  2624. PrevDiag = diag::note_previous_definition;
  2625. else if (Old->isImplicit()) {
  2626. PrevDiag = diag::note_previous_implicit_declaration;
  2627. if (OldLocation.isInvalid())
  2628. OldLocation = New->getLocation();
  2629. } else
  2630. PrevDiag = diag::note_previous_declaration;
  2631. return std::make_pair(PrevDiag, OldLocation);
  2632. }
  2633. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2634. /// only extern inline functions can be redefined, and even then only in
  2635. /// GNU89 mode.
  2636. static bool canRedefineFunction(const FunctionDecl *FD,
  2637. const LangOptions& LangOpts) {
  2638. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2639. !LangOpts.CPlusPlus &&
  2640. FD->isInlineSpecified() &&
  2641. FD->getStorageClass() == SC_Extern);
  2642. }
  2643. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2644. const AttributedType *AT = T->getAs<AttributedType>();
  2645. while (AT && !AT->isCallingConv())
  2646. AT = AT->getModifiedType()->getAs<AttributedType>();
  2647. return AT;
  2648. }
  2649. template <typename T>
  2650. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2651. const DeclContext *DC = Old->getDeclContext();
  2652. if (DC->isRecord())
  2653. return false;
  2654. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2655. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2656. return true;
  2657. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2658. return true;
  2659. return false;
  2660. }
  2661. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2662. static bool isExternC(VarTemplateDecl *) { return false; }
  2663. /// Check whether a redeclaration of an entity introduced by a
  2664. /// using-declaration is valid, given that we know it's not an overload
  2665. /// (nor a hidden tag declaration).
  2666. template<typename ExpectedDecl>
  2667. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2668. ExpectedDecl *New) {
  2669. // C++11 [basic.scope.declarative]p4:
  2670. // Given a set of declarations in a single declarative region, each of
  2671. // which specifies the same unqualified name,
  2672. // -- they shall all refer to the same entity, or all refer to functions
  2673. // and function templates; or
  2674. // -- exactly one declaration shall declare a class name or enumeration
  2675. // name that is not a typedef name and the other declarations shall all
  2676. // refer to the same variable or enumerator, or all refer to functions
  2677. // and function templates; in this case the class name or enumeration
  2678. // name is hidden (3.3.10).
  2679. // C++11 [namespace.udecl]p14:
  2680. // If a function declaration in namespace scope or block scope has the
  2681. // same name and the same parameter-type-list as a function introduced
  2682. // by a using-declaration, and the declarations do not declare the same
  2683. // function, the program is ill-formed.
  2684. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2685. if (Old &&
  2686. !Old->getDeclContext()->getRedeclContext()->Equals(
  2687. New->getDeclContext()->getRedeclContext()) &&
  2688. !(isExternC(Old) && isExternC(New)))
  2689. Old = nullptr;
  2690. if (!Old) {
  2691. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2692. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2693. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2694. return true;
  2695. }
  2696. return false;
  2697. }
  2698. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2699. const FunctionDecl *B) {
  2700. assert(A->getNumParams() == B->getNumParams());
  2701. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2702. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2703. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2704. if (AttrA == AttrB)
  2705. return true;
  2706. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2707. AttrA->isDynamic() == AttrB->isDynamic();
  2708. };
  2709. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2710. }
  2711. /// If necessary, adjust the semantic declaration context for a qualified
  2712. /// declaration to name the correct inline namespace within the qualifier.
  2713. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2714. DeclaratorDecl *OldD) {
  2715. // The only case where we need to update the DeclContext is when
  2716. // redeclaration lookup for a qualified name finds a declaration
  2717. // in an inline namespace within the context named by the qualifier:
  2718. //
  2719. // inline namespace N { int f(); }
  2720. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2721. //
  2722. // For unqualified declarations, the semantic context *can* change
  2723. // along the redeclaration chain (for local extern declarations,
  2724. // extern "C" declarations, and friend declarations in particular).
  2725. if (!NewD->getQualifier())
  2726. return;
  2727. // NewD is probably already in the right context.
  2728. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2729. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2730. if (NamedDC->Equals(SemaDC))
  2731. return;
  2732. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2733. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2734. "unexpected context for redeclaration");
  2735. auto *LexDC = NewD->getLexicalDeclContext();
  2736. auto FixSemaDC = [=](NamedDecl *D) {
  2737. if (!D)
  2738. return;
  2739. D->setDeclContext(SemaDC);
  2740. D->setLexicalDeclContext(LexDC);
  2741. };
  2742. FixSemaDC(NewD);
  2743. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2744. FixSemaDC(FD->getDescribedFunctionTemplate());
  2745. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2746. FixSemaDC(VD->getDescribedVarTemplate());
  2747. }
  2748. /// MergeFunctionDecl - We just parsed a function 'New' from
  2749. /// declarator D which has the same name and scope as a previous
  2750. /// declaration 'Old'. Figure out how to resolve this situation,
  2751. /// merging decls or emitting diagnostics as appropriate.
  2752. ///
  2753. /// In C++, New and Old must be declarations that are not
  2754. /// overloaded. Use IsOverload to determine whether New and Old are
  2755. /// overloaded, and to select the Old declaration that New should be
  2756. /// merged with.
  2757. ///
  2758. /// Returns true if there was an error, false otherwise.
  2759. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2760. Scope *S, bool MergeTypeWithOld) {
  2761. // Verify the old decl was also a function.
  2762. FunctionDecl *Old = OldD->getAsFunction();
  2763. if (!Old) {
  2764. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2765. if (New->getFriendObjectKind()) {
  2766. Diag(New->getLocation(), diag::err_using_decl_friend);
  2767. Diag(Shadow->getTargetDecl()->getLocation(),
  2768. diag::note_using_decl_target);
  2769. Diag(Shadow->getUsingDecl()->getLocation(),
  2770. diag::note_using_decl) << 0;
  2771. return true;
  2772. }
  2773. // Check whether the two declarations might declare the same function.
  2774. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2775. return true;
  2776. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2777. } else {
  2778. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2779. << New->getDeclName();
  2780. notePreviousDefinition(OldD, New->getLocation());
  2781. return true;
  2782. }
  2783. }
  2784. // If the old declaration is invalid, just give up here.
  2785. if (Old->isInvalidDecl())
  2786. return true;
  2787. // Disallow redeclaration of some builtins.
  2788. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2789. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2790. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2791. << Old << Old->getType();
  2792. return true;
  2793. }
  2794. diag::kind PrevDiag;
  2795. SourceLocation OldLocation;
  2796. std::tie(PrevDiag, OldLocation) =
  2797. getNoteDiagForInvalidRedeclaration(Old, New);
  2798. // Don't complain about this if we're in GNU89 mode and the old function
  2799. // is an extern inline function.
  2800. // Don't complain about specializations. They are not supposed to have
  2801. // storage classes.
  2802. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2803. New->getStorageClass() == SC_Static &&
  2804. Old->hasExternalFormalLinkage() &&
  2805. !New->getTemplateSpecializationInfo() &&
  2806. !canRedefineFunction(Old, getLangOpts())) {
  2807. if (getLangOpts().MicrosoftExt) {
  2808. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2809. Diag(OldLocation, PrevDiag);
  2810. } else {
  2811. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2812. Diag(OldLocation, PrevDiag);
  2813. return true;
  2814. }
  2815. }
  2816. if (New->hasAttr<InternalLinkageAttr>() &&
  2817. !Old->hasAttr<InternalLinkageAttr>()) {
  2818. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2819. << New->getDeclName();
  2820. notePreviousDefinition(Old, New->getLocation());
  2821. New->dropAttr<InternalLinkageAttr>();
  2822. }
  2823. if (CheckRedeclarationModuleOwnership(New, Old))
  2824. return true;
  2825. if (!getLangOpts().CPlusPlus) {
  2826. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2827. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2828. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2829. << New << OldOvl;
  2830. // Try our best to find a decl that actually has the overloadable
  2831. // attribute for the note. In most cases (e.g. programs with only one
  2832. // broken declaration/definition), this won't matter.
  2833. //
  2834. // FIXME: We could do this if we juggled some extra state in
  2835. // OverloadableAttr, rather than just removing it.
  2836. const Decl *DiagOld = Old;
  2837. if (OldOvl) {
  2838. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2839. const auto *A = D->getAttr<OverloadableAttr>();
  2840. return A && !A->isImplicit();
  2841. });
  2842. // If we've implicitly added *all* of the overloadable attrs to this
  2843. // chain, emitting a "previous redecl" note is pointless.
  2844. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2845. }
  2846. if (DiagOld)
  2847. Diag(DiagOld->getLocation(),
  2848. diag::note_attribute_overloadable_prev_overload)
  2849. << OldOvl;
  2850. if (OldOvl)
  2851. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2852. else
  2853. New->dropAttr<OverloadableAttr>();
  2854. }
  2855. }
  2856. // If a function is first declared with a calling convention, but is later
  2857. // declared or defined without one, all following decls assume the calling
  2858. // convention of the first.
  2859. //
  2860. // It's OK if a function is first declared without a calling convention,
  2861. // but is later declared or defined with the default calling convention.
  2862. //
  2863. // To test if either decl has an explicit calling convention, we look for
  2864. // AttributedType sugar nodes on the type as written. If they are missing or
  2865. // were canonicalized away, we assume the calling convention was implicit.
  2866. //
  2867. // Note also that we DO NOT return at this point, because we still have
  2868. // other tests to run.
  2869. QualType OldQType = Context.getCanonicalType(Old->getType());
  2870. QualType NewQType = Context.getCanonicalType(New->getType());
  2871. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2872. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2873. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2874. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2875. bool RequiresAdjustment = false;
  2876. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2877. FunctionDecl *First = Old->getFirstDecl();
  2878. const FunctionType *FT =
  2879. First->getType().getCanonicalType()->castAs<FunctionType>();
  2880. FunctionType::ExtInfo FI = FT->getExtInfo();
  2881. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2882. if (!NewCCExplicit) {
  2883. // Inherit the CC from the previous declaration if it was specified
  2884. // there but not here.
  2885. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2886. RequiresAdjustment = true;
  2887. } else if (New->getBuiltinID()) {
  2888. // Calling Conventions on a Builtin aren't really useful and setting a
  2889. // default calling convention and cdecl'ing some builtin redeclarations is
  2890. // common, so warn and ignore the calling convention on the redeclaration.
  2891. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  2892. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2893. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2894. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2895. RequiresAdjustment = true;
  2896. } else {
  2897. // Calling conventions aren't compatible, so complain.
  2898. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2899. Diag(New->getLocation(), diag::err_cconv_change)
  2900. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2901. << !FirstCCExplicit
  2902. << (!FirstCCExplicit ? "" :
  2903. FunctionType::getNameForCallConv(FI.getCC()));
  2904. // Put the note on the first decl, since it is the one that matters.
  2905. Diag(First->getLocation(), diag::note_previous_declaration);
  2906. return true;
  2907. }
  2908. }
  2909. // FIXME: diagnose the other way around?
  2910. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2911. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2912. RequiresAdjustment = true;
  2913. }
  2914. // Merge regparm attribute.
  2915. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2916. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2917. if (NewTypeInfo.getHasRegParm()) {
  2918. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2919. << NewType->getRegParmType()
  2920. << OldType->getRegParmType();
  2921. Diag(OldLocation, diag::note_previous_declaration);
  2922. return true;
  2923. }
  2924. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2925. RequiresAdjustment = true;
  2926. }
  2927. // Merge ns_returns_retained attribute.
  2928. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2929. if (NewTypeInfo.getProducesResult()) {
  2930. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2931. << "'ns_returns_retained'";
  2932. Diag(OldLocation, diag::note_previous_declaration);
  2933. return true;
  2934. }
  2935. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2936. RequiresAdjustment = true;
  2937. }
  2938. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2939. NewTypeInfo.getNoCallerSavedRegs()) {
  2940. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2941. AnyX86NoCallerSavedRegistersAttr *Attr =
  2942. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2943. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2944. Diag(OldLocation, diag::note_previous_declaration);
  2945. return true;
  2946. }
  2947. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2948. RequiresAdjustment = true;
  2949. }
  2950. if (RequiresAdjustment) {
  2951. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2952. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2953. New->setType(QualType(AdjustedType, 0));
  2954. NewQType = Context.getCanonicalType(New->getType());
  2955. }
  2956. // If this redeclaration makes the function inline, we may need to add it to
  2957. // UndefinedButUsed.
  2958. if (!Old->isInlined() && New->isInlined() &&
  2959. !New->hasAttr<GNUInlineAttr>() &&
  2960. !getLangOpts().GNUInline &&
  2961. Old->isUsed(false) &&
  2962. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2963. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2964. SourceLocation()));
  2965. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2966. // about it.
  2967. if (New->hasAttr<GNUInlineAttr>() &&
  2968. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2969. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2970. }
  2971. // If pass_object_size params don't match up perfectly, this isn't a valid
  2972. // redeclaration.
  2973. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2974. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2975. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2976. << New->getDeclName();
  2977. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2978. return true;
  2979. }
  2980. if (getLangOpts().CPlusPlus) {
  2981. // C++1z [over.load]p2
  2982. // Certain function declarations cannot be overloaded:
  2983. // -- Function declarations that differ only in the return type,
  2984. // the exception specification, or both cannot be overloaded.
  2985. // Check the exception specifications match. This may recompute the type of
  2986. // both Old and New if it resolved exception specifications, so grab the
  2987. // types again after this. Because this updates the type, we do this before
  2988. // any of the other checks below, which may update the "de facto" NewQType
  2989. // but do not necessarily update the type of New.
  2990. if (CheckEquivalentExceptionSpec(Old, New))
  2991. return true;
  2992. OldQType = Context.getCanonicalType(Old->getType());
  2993. NewQType = Context.getCanonicalType(New->getType());
  2994. // Go back to the type source info to compare the declared return types,
  2995. // per C++1y [dcl.type.auto]p13:
  2996. // Redeclarations or specializations of a function or function template
  2997. // with a declared return type that uses a placeholder type shall also
  2998. // use that placeholder, not a deduced type.
  2999. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  3000. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3001. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3002. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3003. OldDeclaredReturnType)) {
  3004. QualType ResQT;
  3005. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3006. OldDeclaredReturnType->isObjCObjectPointerType())
  3007. // FIXME: This does the wrong thing for a deduced return type.
  3008. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3009. if (ResQT.isNull()) {
  3010. if (New->isCXXClassMember() && New->isOutOfLine())
  3011. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3012. << New << New->getReturnTypeSourceRange();
  3013. else
  3014. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3015. << New->getReturnTypeSourceRange();
  3016. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3017. << Old->getReturnTypeSourceRange();
  3018. return true;
  3019. }
  3020. else
  3021. NewQType = ResQT;
  3022. }
  3023. QualType OldReturnType = OldType->getReturnType();
  3024. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3025. if (OldReturnType != NewReturnType) {
  3026. // If this function has a deduced return type and has already been
  3027. // defined, copy the deduced value from the old declaration.
  3028. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3029. if (OldAT && OldAT->isDeduced()) {
  3030. New->setType(
  3031. SubstAutoType(New->getType(),
  3032. OldAT->isDependentType() ? Context.DependentTy
  3033. : OldAT->getDeducedType()));
  3034. NewQType = Context.getCanonicalType(
  3035. SubstAutoType(NewQType,
  3036. OldAT->isDependentType() ? Context.DependentTy
  3037. : OldAT->getDeducedType()));
  3038. }
  3039. }
  3040. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3041. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3042. if (OldMethod && NewMethod) {
  3043. // Preserve triviality.
  3044. NewMethod->setTrivial(OldMethod->isTrivial());
  3045. // MSVC allows explicit template specialization at class scope:
  3046. // 2 CXXMethodDecls referring to the same function will be injected.
  3047. // We don't want a redeclaration error.
  3048. bool IsClassScopeExplicitSpecialization =
  3049. OldMethod->isFunctionTemplateSpecialization() &&
  3050. NewMethod->isFunctionTemplateSpecialization();
  3051. bool isFriend = NewMethod->getFriendObjectKind();
  3052. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3053. !IsClassScopeExplicitSpecialization) {
  3054. // -- Member function declarations with the same name and the
  3055. // same parameter types cannot be overloaded if any of them
  3056. // is a static member function declaration.
  3057. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3058. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3059. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3060. return true;
  3061. }
  3062. // C++ [class.mem]p1:
  3063. // [...] A member shall not be declared twice in the
  3064. // member-specification, except that a nested class or member
  3065. // class template can be declared and then later defined.
  3066. if (!inTemplateInstantiation()) {
  3067. unsigned NewDiag;
  3068. if (isa<CXXConstructorDecl>(OldMethod))
  3069. NewDiag = diag::err_constructor_redeclared;
  3070. else if (isa<CXXDestructorDecl>(NewMethod))
  3071. NewDiag = diag::err_destructor_redeclared;
  3072. else if (isa<CXXConversionDecl>(NewMethod))
  3073. NewDiag = diag::err_conv_function_redeclared;
  3074. else
  3075. NewDiag = diag::err_member_redeclared;
  3076. Diag(New->getLocation(), NewDiag);
  3077. } else {
  3078. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3079. << New << New->getType();
  3080. }
  3081. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3082. return true;
  3083. // Complain if this is an explicit declaration of a special
  3084. // member that was initially declared implicitly.
  3085. //
  3086. // As an exception, it's okay to befriend such methods in order
  3087. // to permit the implicit constructor/destructor/operator calls.
  3088. } else if (OldMethod->isImplicit()) {
  3089. if (isFriend) {
  3090. NewMethod->setImplicit();
  3091. } else {
  3092. Diag(NewMethod->getLocation(),
  3093. diag::err_definition_of_implicitly_declared_member)
  3094. << New << getSpecialMember(OldMethod);
  3095. return true;
  3096. }
  3097. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3098. Diag(NewMethod->getLocation(),
  3099. diag::err_definition_of_explicitly_defaulted_member)
  3100. << getSpecialMember(OldMethod);
  3101. return true;
  3102. }
  3103. }
  3104. // C++11 [dcl.attr.noreturn]p1:
  3105. // The first declaration of a function shall specify the noreturn
  3106. // attribute if any declaration of that function specifies the noreturn
  3107. // attribute.
  3108. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3109. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3110. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3111. Diag(Old->getFirstDecl()->getLocation(),
  3112. diag::note_noreturn_missing_first_decl);
  3113. }
  3114. // C++11 [dcl.attr.depend]p2:
  3115. // The first declaration of a function shall specify the
  3116. // carries_dependency attribute for its declarator-id if any declaration
  3117. // of the function specifies the carries_dependency attribute.
  3118. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3119. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3120. Diag(CDA->getLocation(),
  3121. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3122. Diag(Old->getFirstDecl()->getLocation(),
  3123. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3124. }
  3125. // (C++98 8.3.5p3):
  3126. // All declarations for a function shall agree exactly in both the
  3127. // return type and the parameter-type-list.
  3128. // We also want to respect all the extended bits except noreturn.
  3129. // noreturn should now match unless the old type info didn't have it.
  3130. QualType OldQTypeForComparison = OldQType;
  3131. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3132. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3133. const FunctionType *OldTypeForComparison
  3134. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3135. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3136. assert(OldQTypeForComparison.isCanonical());
  3137. }
  3138. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3139. // As a special case, retain the language linkage from previous
  3140. // declarations of a friend function as an extension.
  3141. //
  3142. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3143. // and is useful because there's otherwise no way to specify language
  3144. // linkage within class scope.
  3145. //
  3146. // Check cautiously as the friend object kind isn't yet complete.
  3147. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3148. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3149. Diag(OldLocation, PrevDiag);
  3150. } else {
  3151. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3152. Diag(OldLocation, PrevDiag);
  3153. return true;
  3154. }
  3155. }
  3156. if (OldQTypeForComparison == NewQType)
  3157. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3158. // If the types are imprecise (due to dependent constructs in friends or
  3159. // local extern declarations), it's OK if they differ. We'll check again
  3160. // during instantiation.
  3161. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3162. return false;
  3163. // Fall through for conflicting redeclarations and redefinitions.
  3164. }
  3165. // C: Function types need to be compatible, not identical. This handles
  3166. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3167. if (!getLangOpts().CPlusPlus &&
  3168. Context.typesAreCompatible(OldQType, NewQType)) {
  3169. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3170. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3171. const FunctionProtoType *OldProto = nullptr;
  3172. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3173. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3174. // The old declaration provided a function prototype, but the
  3175. // new declaration does not. Merge in the prototype.
  3176. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3177. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3178. NewQType =
  3179. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3180. OldProto->getExtProtoInfo());
  3181. New->setType(NewQType);
  3182. New->setHasInheritedPrototype();
  3183. // Synthesize parameters with the same types.
  3184. SmallVector<ParmVarDecl*, 16> Params;
  3185. for (const auto &ParamType : OldProto->param_types()) {
  3186. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3187. SourceLocation(), nullptr,
  3188. ParamType, /*TInfo=*/nullptr,
  3189. SC_None, nullptr);
  3190. Param->setScopeInfo(0, Params.size());
  3191. Param->setImplicit();
  3192. Params.push_back(Param);
  3193. }
  3194. New->setParams(Params);
  3195. }
  3196. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3197. }
  3198. // GNU C permits a K&R definition to follow a prototype declaration
  3199. // if the declared types of the parameters in the K&R definition
  3200. // match the types in the prototype declaration, even when the
  3201. // promoted types of the parameters from the K&R definition differ
  3202. // from the types in the prototype. GCC then keeps the types from
  3203. // the prototype.
  3204. //
  3205. // If a variadic prototype is followed by a non-variadic K&R definition,
  3206. // the K&R definition becomes variadic. This is sort of an edge case, but
  3207. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3208. // C99 6.9.1p8.
  3209. if (!getLangOpts().CPlusPlus &&
  3210. Old->hasPrototype() && !New->hasPrototype() &&
  3211. New->getType()->getAs<FunctionProtoType>() &&
  3212. Old->getNumParams() == New->getNumParams()) {
  3213. SmallVector<QualType, 16> ArgTypes;
  3214. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3215. const FunctionProtoType *OldProto
  3216. = Old->getType()->getAs<FunctionProtoType>();
  3217. const FunctionProtoType *NewProto
  3218. = New->getType()->getAs<FunctionProtoType>();
  3219. // Determine whether this is the GNU C extension.
  3220. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3221. NewProto->getReturnType());
  3222. bool LooseCompatible = !MergedReturn.isNull();
  3223. for (unsigned Idx = 0, End = Old->getNumParams();
  3224. LooseCompatible && Idx != End; ++Idx) {
  3225. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3226. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3227. if (Context.typesAreCompatible(OldParm->getType(),
  3228. NewProto->getParamType(Idx))) {
  3229. ArgTypes.push_back(NewParm->getType());
  3230. } else if (Context.typesAreCompatible(OldParm->getType(),
  3231. NewParm->getType(),
  3232. /*CompareUnqualified=*/true)) {
  3233. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3234. NewProto->getParamType(Idx) };
  3235. Warnings.push_back(Warn);
  3236. ArgTypes.push_back(NewParm->getType());
  3237. } else
  3238. LooseCompatible = false;
  3239. }
  3240. if (LooseCompatible) {
  3241. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3242. Diag(Warnings[Warn].NewParm->getLocation(),
  3243. diag::ext_param_promoted_not_compatible_with_prototype)
  3244. << Warnings[Warn].PromotedType
  3245. << Warnings[Warn].OldParm->getType();
  3246. if (Warnings[Warn].OldParm->getLocation().isValid())
  3247. Diag(Warnings[Warn].OldParm->getLocation(),
  3248. diag::note_previous_declaration);
  3249. }
  3250. if (MergeTypeWithOld)
  3251. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3252. OldProto->getExtProtoInfo()));
  3253. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3254. }
  3255. // Fall through to diagnose conflicting types.
  3256. }
  3257. // A function that has already been declared has been redeclared or
  3258. // defined with a different type; show an appropriate diagnostic.
  3259. // If the previous declaration was an implicitly-generated builtin
  3260. // declaration, then at the very least we should use a specialized note.
  3261. unsigned BuiltinID;
  3262. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3263. // If it's actually a library-defined builtin function like 'malloc'
  3264. // or 'printf', just warn about the incompatible redeclaration.
  3265. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3266. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3267. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3268. << Old << Old->getType();
  3269. // If this is a global redeclaration, just forget hereafter
  3270. // about the "builtin-ness" of the function.
  3271. //
  3272. // Doing this for local extern declarations is problematic. If
  3273. // the builtin declaration remains visible, a second invalid
  3274. // local declaration will produce a hard error; if it doesn't
  3275. // remain visible, a single bogus local redeclaration (which is
  3276. // actually only a warning) could break all the downstream code.
  3277. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3278. New->getIdentifier()->revertBuiltin();
  3279. return false;
  3280. }
  3281. PrevDiag = diag::note_previous_builtin_declaration;
  3282. }
  3283. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3284. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3285. return true;
  3286. }
  3287. /// Completes the merge of two function declarations that are
  3288. /// known to be compatible.
  3289. ///
  3290. /// This routine handles the merging of attributes and other
  3291. /// properties of function declarations from the old declaration to
  3292. /// the new declaration, once we know that New is in fact a
  3293. /// redeclaration of Old.
  3294. ///
  3295. /// \returns false
  3296. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3297. Scope *S, bool MergeTypeWithOld) {
  3298. // Merge the attributes
  3299. mergeDeclAttributes(New, Old);
  3300. // Merge "pure" flag.
  3301. if (Old->isPure())
  3302. New->setPure();
  3303. // Merge "used" flag.
  3304. if (Old->getMostRecentDecl()->isUsed(false))
  3305. New->setIsUsed();
  3306. // Merge attributes from the parameters. These can mismatch with K&R
  3307. // declarations.
  3308. if (New->getNumParams() == Old->getNumParams())
  3309. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3310. ParmVarDecl *NewParam = New->getParamDecl(i);
  3311. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3312. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3313. mergeParamDeclTypes(NewParam, OldParam, *this);
  3314. }
  3315. if (getLangOpts().CPlusPlus)
  3316. return MergeCXXFunctionDecl(New, Old, S);
  3317. // Merge the function types so the we get the composite types for the return
  3318. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3319. // was visible.
  3320. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3321. if (!Merged.isNull() && MergeTypeWithOld)
  3322. New->setType(Merged);
  3323. return false;
  3324. }
  3325. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3326. ObjCMethodDecl *oldMethod) {
  3327. // Merge the attributes, including deprecated/unavailable
  3328. AvailabilityMergeKind MergeKind =
  3329. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3330. ? AMK_ProtocolImplementation
  3331. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3332. : AMK_Override;
  3333. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3334. // Merge attributes from the parameters.
  3335. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3336. oe = oldMethod->param_end();
  3337. for (ObjCMethodDecl::param_iterator
  3338. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3339. ni != ne && oi != oe; ++ni, ++oi)
  3340. mergeParamDeclAttributes(*ni, *oi, *this);
  3341. CheckObjCMethodOverride(newMethod, oldMethod);
  3342. }
  3343. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3344. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3345. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3346. ? diag::err_redefinition_different_type
  3347. : diag::err_redeclaration_different_type)
  3348. << New->getDeclName() << New->getType() << Old->getType();
  3349. diag::kind PrevDiag;
  3350. SourceLocation OldLocation;
  3351. std::tie(PrevDiag, OldLocation)
  3352. = getNoteDiagForInvalidRedeclaration(Old, New);
  3353. S.Diag(OldLocation, PrevDiag);
  3354. New->setInvalidDecl();
  3355. }
  3356. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3357. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3358. /// emitting diagnostics as appropriate.
  3359. ///
  3360. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3361. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3362. /// is attached.
  3363. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3364. bool MergeTypeWithOld) {
  3365. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3366. return;
  3367. QualType MergedT;
  3368. if (getLangOpts().CPlusPlus) {
  3369. if (New->getType()->isUndeducedType()) {
  3370. // We don't know what the new type is until the initializer is attached.
  3371. return;
  3372. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3373. // These could still be something that needs exception specs checked.
  3374. return MergeVarDeclExceptionSpecs(New, Old);
  3375. }
  3376. // C++ [basic.link]p10:
  3377. // [...] the types specified by all declarations referring to a given
  3378. // object or function shall be identical, except that declarations for an
  3379. // array object can specify array types that differ by the presence or
  3380. // absence of a major array bound (8.3.4).
  3381. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3382. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3383. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3384. // We are merging a variable declaration New into Old. If it has an array
  3385. // bound, and that bound differs from Old's bound, we should diagnose the
  3386. // mismatch.
  3387. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3388. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3389. PrevVD = PrevVD->getPreviousDecl()) {
  3390. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3391. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3392. continue;
  3393. if (!Context.hasSameType(NewArray, PrevVDTy))
  3394. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3395. }
  3396. }
  3397. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3398. if (Context.hasSameType(OldArray->getElementType(),
  3399. NewArray->getElementType()))
  3400. MergedT = New->getType();
  3401. }
  3402. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3403. // has no array bound, it should not inherit one from Old, if Old is not
  3404. // visible.
  3405. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3406. if (Context.hasSameType(OldArray->getElementType(),
  3407. NewArray->getElementType()))
  3408. MergedT = Old->getType();
  3409. }
  3410. }
  3411. else if (New->getType()->isObjCObjectPointerType() &&
  3412. Old->getType()->isObjCObjectPointerType()) {
  3413. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3414. Old->getType());
  3415. }
  3416. } else {
  3417. // C 6.2.7p2:
  3418. // All declarations that refer to the same object or function shall have
  3419. // compatible type.
  3420. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3421. }
  3422. if (MergedT.isNull()) {
  3423. // It's OK if we couldn't merge types if either type is dependent, for a
  3424. // block-scope variable. In other cases (static data members of class
  3425. // templates, variable templates, ...), we require the types to be
  3426. // equivalent.
  3427. // FIXME: The C++ standard doesn't say anything about this.
  3428. if ((New->getType()->isDependentType() ||
  3429. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3430. // If the old type was dependent, we can't merge with it, so the new type
  3431. // becomes dependent for now. We'll reproduce the original type when we
  3432. // instantiate the TypeSourceInfo for the variable.
  3433. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3434. New->setType(Context.DependentTy);
  3435. return;
  3436. }
  3437. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3438. }
  3439. // Don't actually update the type on the new declaration if the old
  3440. // declaration was an extern declaration in a different scope.
  3441. if (MergeTypeWithOld)
  3442. New->setType(MergedT);
  3443. }
  3444. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3445. LookupResult &Previous) {
  3446. // C11 6.2.7p4:
  3447. // For an identifier with internal or external linkage declared
  3448. // in a scope in which a prior declaration of that identifier is
  3449. // visible, if the prior declaration specifies internal or
  3450. // external linkage, the type of the identifier at the later
  3451. // declaration becomes the composite type.
  3452. //
  3453. // If the variable isn't visible, we do not merge with its type.
  3454. if (Previous.isShadowed())
  3455. return false;
  3456. if (S.getLangOpts().CPlusPlus) {
  3457. // C++11 [dcl.array]p3:
  3458. // If there is a preceding declaration of the entity in the same
  3459. // scope in which the bound was specified, an omitted array bound
  3460. // is taken to be the same as in that earlier declaration.
  3461. return NewVD->isPreviousDeclInSameBlockScope() ||
  3462. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3463. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3464. } else {
  3465. // If the old declaration was function-local, don't merge with its
  3466. // type unless we're in the same function.
  3467. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3468. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3469. }
  3470. }
  3471. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3472. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3473. /// situation, merging decls or emitting diagnostics as appropriate.
  3474. ///
  3475. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3476. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3477. /// definitions here, since the initializer hasn't been attached.
  3478. ///
  3479. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3480. // If the new decl is already invalid, don't do any other checking.
  3481. if (New->isInvalidDecl())
  3482. return;
  3483. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3484. return;
  3485. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3486. // Verify the old decl was also a variable or variable template.
  3487. VarDecl *Old = nullptr;
  3488. VarTemplateDecl *OldTemplate = nullptr;
  3489. if (Previous.isSingleResult()) {
  3490. if (NewTemplate) {
  3491. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3492. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3493. if (auto *Shadow =
  3494. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3495. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3496. return New->setInvalidDecl();
  3497. } else {
  3498. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3499. if (auto *Shadow =
  3500. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3501. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3502. return New->setInvalidDecl();
  3503. }
  3504. }
  3505. if (!Old) {
  3506. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3507. << New->getDeclName();
  3508. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3509. New->getLocation());
  3510. return New->setInvalidDecl();
  3511. }
  3512. // Ensure the template parameters are compatible.
  3513. if (NewTemplate &&
  3514. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3515. OldTemplate->getTemplateParameters(),
  3516. /*Complain=*/true, TPL_TemplateMatch))
  3517. return New->setInvalidDecl();
  3518. // C++ [class.mem]p1:
  3519. // A member shall not be declared twice in the member-specification [...]
  3520. //
  3521. // Here, we need only consider static data members.
  3522. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3523. Diag(New->getLocation(), diag::err_duplicate_member)
  3524. << New->getIdentifier();
  3525. Diag(Old->getLocation(), diag::note_previous_declaration);
  3526. New->setInvalidDecl();
  3527. }
  3528. mergeDeclAttributes(New, Old);
  3529. // Warn if an already-declared variable is made a weak_import in a subsequent
  3530. // declaration
  3531. if (New->hasAttr<WeakImportAttr>() &&
  3532. Old->getStorageClass() == SC_None &&
  3533. !Old->hasAttr<WeakImportAttr>()) {
  3534. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3535. notePreviousDefinition(Old, New->getLocation());
  3536. // Remove weak_import attribute on new declaration.
  3537. New->dropAttr<WeakImportAttr>();
  3538. }
  3539. if (New->hasAttr<InternalLinkageAttr>() &&
  3540. !Old->hasAttr<InternalLinkageAttr>()) {
  3541. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3542. << New->getDeclName();
  3543. notePreviousDefinition(Old, New->getLocation());
  3544. New->dropAttr<InternalLinkageAttr>();
  3545. }
  3546. // Merge the types.
  3547. VarDecl *MostRecent = Old->getMostRecentDecl();
  3548. if (MostRecent != Old) {
  3549. MergeVarDeclTypes(New, MostRecent,
  3550. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3551. if (New->isInvalidDecl())
  3552. return;
  3553. }
  3554. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3555. if (New->isInvalidDecl())
  3556. return;
  3557. diag::kind PrevDiag;
  3558. SourceLocation OldLocation;
  3559. std::tie(PrevDiag, OldLocation) =
  3560. getNoteDiagForInvalidRedeclaration(Old, New);
  3561. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3562. if (New->getStorageClass() == SC_Static &&
  3563. !New->isStaticDataMember() &&
  3564. Old->hasExternalFormalLinkage()) {
  3565. if (getLangOpts().MicrosoftExt) {
  3566. Diag(New->getLocation(), diag::ext_static_non_static)
  3567. << New->getDeclName();
  3568. Diag(OldLocation, PrevDiag);
  3569. } else {
  3570. Diag(New->getLocation(), diag::err_static_non_static)
  3571. << New->getDeclName();
  3572. Diag(OldLocation, PrevDiag);
  3573. return New->setInvalidDecl();
  3574. }
  3575. }
  3576. // C99 6.2.2p4:
  3577. // For an identifier declared with the storage-class specifier
  3578. // extern in a scope in which a prior declaration of that
  3579. // identifier is visible,23) if the prior declaration specifies
  3580. // internal or external linkage, the linkage of the identifier at
  3581. // the later declaration is the same as the linkage specified at
  3582. // the prior declaration. If no prior declaration is visible, or
  3583. // if the prior declaration specifies no linkage, then the
  3584. // identifier has external linkage.
  3585. if (New->hasExternalStorage() && Old->hasLinkage())
  3586. /* Okay */;
  3587. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3588. !New->isStaticDataMember() &&
  3589. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3590. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3591. Diag(OldLocation, PrevDiag);
  3592. return New->setInvalidDecl();
  3593. }
  3594. // Check if extern is followed by non-extern and vice-versa.
  3595. if (New->hasExternalStorage() &&
  3596. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3597. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3598. Diag(OldLocation, PrevDiag);
  3599. return New->setInvalidDecl();
  3600. }
  3601. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3602. !New->hasExternalStorage()) {
  3603. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3604. Diag(OldLocation, PrevDiag);
  3605. return New->setInvalidDecl();
  3606. }
  3607. if (CheckRedeclarationModuleOwnership(New, Old))
  3608. return;
  3609. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3610. // FIXME: The test for external storage here seems wrong? We still
  3611. // need to check for mismatches.
  3612. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3613. // Don't complain about out-of-line definitions of static members.
  3614. !(Old->getLexicalDeclContext()->isRecord() &&
  3615. !New->getLexicalDeclContext()->isRecord())) {
  3616. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3617. Diag(OldLocation, PrevDiag);
  3618. return New->setInvalidDecl();
  3619. }
  3620. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3621. if (VarDecl *Def = Old->getDefinition()) {
  3622. // C++1z [dcl.fcn.spec]p4:
  3623. // If the definition of a variable appears in a translation unit before
  3624. // its first declaration as inline, the program is ill-formed.
  3625. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3626. Diag(Def->getLocation(), diag::note_previous_definition);
  3627. }
  3628. }
  3629. // If this redeclaration makes the variable inline, we may need to add it to
  3630. // UndefinedButUsed.
  3631. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3632. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3633. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3634. SourceLocation()));
  3635. if (New->getTLSKind() != Old->getTLSKind()) {
  3636. if (!Old->getTLSKind()) {
  3637. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3638. Diag(OldLocation, PrevDiag);
  3639. } else if (!New->getTLSKind()) {
  3640. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3641. Diag(OldLocation, PrevDiag);
  3642. } else {
  3643. // Do not allow redeclaration to change the variable between requiring
  3644. // static and dynamic initialization.
  3645. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3646. // declaration to determine the kind. Do we need to be compatible here?
  3647. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3648. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3649. Diag(OldLocation, PrevDiag);
  3650. }
  3651. }
  3652. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3653. if (getLangOpts().CPlusPlus &&
  3654. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3655. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3656. Old->getCanonicalDecl()->isConstexpr()) {
  3657. // This definition won't be a definition any more once it's been merged.
  3658. Diag(New->getLocation(),
  3659. diag::warn_deprecated_redundant_constexpr_static_def);
  3660. } else if (VarDecl *Def = Old->getDefinition()) {
  3661. if (checkVarDeclRedefinition(Def, New))
  3662. return;
  3663. }
  3664. }
  3665. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3666. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3667. Diag(OldLocation, PrevDiag);
  3668. New->setInvalidDecl();
  3669. return;
  3670. }
  3671. // Merge "used" flag.
  3672. if (Old->getMostRecentDecl()->isUsed(false))
  3673. New->setIsUsed();
  3674. // Keep a chain of previous declarations.
  3675. New->setPreviousDecl(Old);
  3676. if (NewTemplate)
  3677. NewTemplate->setPreviousDecl(OldTemplate);
  3678. adjustDeclContextForDeclaratorDecl(New, Old);
  3679. // Inherit access appropriately.
  3680. New->setAccess(Old->getAccess());
  3681. if (NewTemplate)
  3682. NewTemplate->setAccess(New->getAccess());
  3683. if (Old->isInline())
  3684. New->setImplicitlyInline();
  3685. }
  3686. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3687. SourceManager &SrcMgr = getSourceManager();
  3688. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3689. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3690. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3691. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3692. auto &HSI = PP.getHeaderSearchInfo();
  3693. StringRef HdrFilename =
  3694. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3695. auto noteFromModuleOrInclude = [&](Module *Mod,
  3696. SourceLocation IncLoc) -> bool {
  3697. // Redefinition errors with modules are common with non modular mapped
  3698. // headers, example: a non-modular header H in module A that also gets
  3699. // included directly in a TU. Pointing twice to the same header/definition
  3700. // is confusing, try to get better diagnostics when modules is on.
  3701. if (IncLoc.isValid()) {
  3702. if (Mod) {
  3703. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3704. << HdrFilename.str() << Mod->getFullModuleName();
  3705. if (!Mod->DefinitionLoc.isInvalid())
  3706. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3707. << Mod->getFullModuleName();
  3708. } else {
  3709. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3710. << HdrFilename.str();
  3711. }
  3712. return true;
  3713. }
  3714. return false;
  3715. };
  3716. // Is it the same file and same offset? Provide more information on why
  3717. // this leads to a redefinition error.
  3718. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3719. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3720. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3721. bool EmittedDiag =
  3722. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3723. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3724. // If the header has no guards, emit a note suggesting one.
  3725. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3726. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3727. if (EmittedDiag)
  3728. return;
  3729. }
  3730. // Redefinition coming from different files or couldn't do better above.
  3731. if (Old->getLocation().isValid())
  3732. Diag(Old->getLocation(), diag::note_previous_definition);
  3733. }
  3734. /// We've just determined that \p Old and \p New both appear to be definitions
  3735. /// of the same variable. Either diagnose or fix the problem.
  3736. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3737. if (!hasVisibleDefinition(Old) &&
  3738. (New->getFormalLinkage() == InternalLinkage ||
  3739. New->isInline() ||
  3740. New->getDescribedVarTemplate() ||
  3741. New->getNumTemplateParameterLists() ||
  3742. New->getDeclContext()->isDependentContext())) {
  3743. // The previous definition is hidden, and multiple definitions are
  3744. // permitted (in separate TUs). Demote this to a declaration.
  3745. New->demoteThisDefinitionToDeclaration();
  3746. // Make the canonical definition visible.
  3747. if (auto *OldTD = Old->getDescribedVarTemplate())
  3748. makeMergedDefinitionVisible(OldTD);
  3749. makeMergedDefinitionVisible(Old);
  3750. return false;
  3751. } else {
  3752. Diag(New->getLocation(), diag::err_redefinition) << New;
  3753. notePreviousDefinition(Old, New->getLocation());
  3754. New->setInvalidDecl();
  3755. return true;
  3756. }
  3757. }
  3758. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3759. /// no declarator (e.g. "struct foo;") is parsed.
  3760. Decl *
  3761. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3762. RecordDecl *&AnonRecord) {
  3763. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3764. AnonRecord);
  3765. }
  3766. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3767. // disambiguate entities defined in different scopes.
  3768. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3769. // compatibility.
  3770. // We will pick our mangling number depending on which version of MSVC is being
  3771. // targeted.
  3772. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3773. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3774. ? S->getMSCurManglingNumber()
  3775. : S->getMSLastManglingNumber();
  3776. }
  3777. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3778. if (!Context.getLangOpts().CPlusPlus)
  3779. return;
  3780. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3781. // If this tag is the direct child of a class, number it if
  3782. // it is anonymous.
  3783. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3784. return;
  3785. MangleNumberingContext &MCtx =
  3786. Context.getManglingNumberContext(Tag->getParent());
  3787. Context.setManglingNumber(
  3788. Tag, MCtx.getManglingNumber(
  3789. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3790. return;
  3791. }
  3792. // If this tag isn't a direct child of a class, number it if it is local.
  3793. Decl *ManglingContextDecl;
  3794. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3795. Tag->getDeclContext(), ManglingContextDecl)) {
  3796. Context.setManglingNumber(
  3797. Tag, MCtx->getManglingNumber(
  3798. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3799. }
  3800. }
  3801. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3802. TypedefNameDecl *NewTD) {
  3803. if (TagFromDeclSpec->isInvalidDecl())
  3804. return;
  3805. // Do nothing if the tag already has a name for linkage purposes.
  3806. if (TagFromDeclSpec->hasNameForLinkage())
  3807. return;
  3808. // A well-formed anonymous tag must always be a TUK_Definition.
  3809. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3810. // The type must match the tag exactly; no qualifiers allowed.
  3811. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3812. Context.getTagDeclType(TagFromDeclSpec))) {
  3813. if (getLangOpts().CPlusPlus)
  3814. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3815. return;
  3816. }
  3817. // If we've already computed linkage for the anonymous tag, then
  3818. // adding a typedef name for the anonymous decl can change that
  3819. // linkage, which might be a serious problem. Diagnose this as
  3820. // unsupported and ignore the typedef name. TODO: we should
  3821. // pursue this as a language defect and establish a formal rule
  3822. // for how to handle it.
  3823. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3824. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3825. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3826. tagLoc = getLocForEndOfToken(tagLoc);
  3827. llvm::SmallString<40> textToInsert;
  3828. textToInsert += ' ';
  3829. textToInsert += NewTD->getIdentifier()->getName();
  3830. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3831. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3832. return;
  3833. }
  3834. // Otherwise, set this is the anon-decl typedef for the tag.
  3835. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3836. }
  3837. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3838. switch (T) {
  3839. case DeclSpec::TST_class:
  3840. return 0;
  3841. case DeclSpec::TST_struct:
  3842. return 1;
  3843. case DeclSpec::TST_interface:
  3844. return 2;
  3845. case DeclSpec::TST_union:
  3846. return 3;
  3847. case DeclSpec::TST_enum:
  3848. return 4;
  3849. default:
  3850. llvm_unreachable("unexpected type specifier");
  3851. }
  3852. }
  3853. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3854. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3855. /// parameters to cope with template friend declarations.
  3856. Decl *
  3857. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3858. MultiTemplateParamsArg TemplateParams,
  3859. bool IsExplicitInstantiation,
  3860. RecordDecl *&AnonRecord) {
  3861. Decl *TagD = nullptr;
  3862. TagDecl *Tag = nullptr;
  3863. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3864. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3865. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3866. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3867. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3868. TagD = DS.getRepAsDecl();
  3869. if (!TagD) // We probably had an error
  3870. return nullptr;
  3871. // Note that the above type specs guarantee that the
  3872. // type rep is a Decl, whereas in many of the others
  3873. // it's a Type.
  3874. if (isa<TagDecl>(TagD))
  3875. Tag = cast<TagDecl>(TagD);
  3876. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3877. Tag = CTD->getTemplatedDecl();
  3878. }
  3879. if (Tag) {
  3880. handleTagNumbering(Tag, S);
  3881. Tag->setFreeStanding();
  3882. if (Tag->isInvalidDecl())
  3883. return Tag;
  3884. }
  3885. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3886. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3887. // or incomplete types shall not be restrict-qualified."
  3888. if (TypeQuals & DeclSpec::TQ_restrict)
  3889. Diag(DS.getRestrictSpecLoc(),
  3890. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3891. << DS.getSourceRange();
  3892. }
  3893. if (DS.isInlineSpecified())
  3894. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3895. << getLangOpts().CPlusPlus17;
  3896. if (DS.hasConstexprSpecifier()) {
  3897. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3898. // and definitions of functions and variables.
  3899. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3900. // the declaration of a function or function template
  3901. if (Tag)
  3902. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3903. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  3904. << DS.getConstexprSpecifier();
  3905. else
  3906. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3907. << DS.getConstexprSpecifier();
  3908. // Don't emit warnings after this error.
  3909. return TagD;
  3910. }
  3911. DiagnoseFunctionSpecifiers(DS);
  3912. if (DS.isFriendSpecified()) {
  3913. // If we're dealing with a decl but not a TagDecl, assume that
  3914. // whatever routines created it handled the friendship aspect.
  3915. if (TagD && !Tag)
  3916. return nullptr;
  3917. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3918. }
  3919. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3920. bool IsExplicitSpecialization =
  3921. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3922. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3923. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3924. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3925. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3926. // nested-name-specifier unless it is an explicit instantiation
  3927. // or an explicit specialization.
  3928. //
  3929. // FIXME: We allow class template partial specializations here too, per the
  3930. // obvious intent of DR1819.
  3931. //
  3932. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3933. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3934. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3935. return nullptr;
  3936. }
  3937. // Track whether this decl-specifier declares anything.
  3938. bool DeclaresAnything = true;
  3939. // Handle anonymous struct definitions.
  3940. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3941. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3942. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3943. if (getLangOpts().CPlusPlus ||
  3944. Record->getDeclContext()->isRecord()) {
  3945. // If CurContext is a DeclContext that can contain statements,
  3946. // RecursiveASTVisitor won't visit the decls that
  3947. // BuildAnonymousStructOrUnion() will put into CurContext.
  3948. // Also store them here so that they can be part of the
  3949. // DeclStmt that gets created in this case.
  3950. // FIXME: Also return the IndirectFieldDecls created by
  3951. // BuildAnonymousStructOr union, for the same reason?
  3952. if (CurContext->isFunctionOrMethod())
  3953. AnonRecord = Record;
  3954. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3955. Context.getPrintingPolicy());
  3956. }
  3957. DeclaresAnything = false;
  3958. }
  3959. }
  3960. // C11 6.7.2.1p2:
  3961. // A struct-declaration that does not declare an anonymous structure or
  3962. // anonymous union shall contain a struct-declarator-list.
  3963. //
  3964. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3965. // did not permit a struct-declaration without a struct-declarator-list.
  3966. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3967. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3968. // Check for Microsoft C extension: anonymous struct/union member.
  3969. // Handle 2 kinds of anonymous struct/union:
  3970. // struct STRUCT;
  3971. // union UNION;
  3972. // and
  3973. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3974. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3975. if ((Tag && Tag->getDeclName()) ||
  3976. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3977. RecordDecl *Record = nullptr;
  3978. if (Tag)
  3979. Record = dyn_cast<RecordDecl>(Tag);
  3980. else if (const RecordType *RT =
  3981. DS.getRepAsType().get()->getAsStructureType())
  3982. Record = RT->getDecl();
  3983. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3984. Record = UT->getDecl();
  3985. if (Record && getLangOpts().MicrosoftExt) {
  3986. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3987. << Record->isUnion() << DS.getSourceRange();
  3988. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3989. }
  3990. DeclaresAnything = false;
  3991. }
  3992. }
  3993. // Skip all the checks below if we have a type error.
  3994. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3995. (TagD && TagD->isInvalidDecl()))
  3996. return TagD;
  3997. if (getLangOpts().CPlusPlus &&
  3998. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3999. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4000. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4001. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4002. DeclaresAnything = false;
  4003. if (!DS.isMissingDeclaratorOk()) {
  4004. // Customize diagnostic for a typedef missing a name.
  4005. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4006. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4007. << DS.getSourceRange();
  4008. else
  4009. DeclaresAnything = false;
  4010. }
  4011. if (DS.isModulePrivateSpecified() &&
  4012. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4013. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4014. << Tag->getTagKind()
  4015. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4016. ActOnDocumentableDecl(TagD);
  4017. // C 6.7/2:
  4018. // A declaration [...] shall declare at least a declarator [...], a tag,
  4019. // or the members of an enumeration.
  4020. // C++ [dcl.dcl]p3:
  4021. // [If there are no declarators], and except for the declaration of an
  4022. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4023. // names into the program, or shall redeclare a name introduced by a
  4024. // previous declaration.
  4025. if (!DeclaresAnything) {
  4026. // In C, we allow this as a (popular) extension / bug. Don't bother
  4027. // producing further diagnostics for redundant qualifiers after this.
  4028. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4029. return TagD;
  4030. }
  4031. // C++ [dcl.stc]p1:
  4032. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4033. // init-declarator-list of the declaration shall not be empty.
  4034. // C++ [dcl.fct.spec]p1:
  4035. // If a cv-qualifier appears in a decl-specifier-seq, the
  4036. // init-declarator-list of the declaration shall not be empty.
  4037. //
  4038. // Spurious qualifiers here appear to be valid in C.
  4039. unsigned DiagID = diag::warn_standalone_specifier;
  4040. if (getLangOpts().CPlusPlus)
  4041. DiagID = diag::ext_standalone_specifier;
  4042. // Note that a linkage-specification sets a storage class, but
  4043. // 'extern "C" struct foo;' is actually valid and not theoretically
  4044. // useless.
  4045. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4046. if (SCS == DeclSpec::SCS_mutable)
  4047. // Since mutable is not a viable storage class specifier in C, there is
  4048. // no reason to treat it as an extension. Instead, diagnose as an error.
  4049. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4050. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4051. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4052. << DeclSpec::getSpecifierName(SCS);
  4053. }
  4054. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4055. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4056. << DeclSpec::getSpecifierName(TSCS);
  4057. if (DS.getTypeQualifiers()) {
  4058. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4059. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4060. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4061. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4062. // Restrict is covered above.
  4063. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4064. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4065. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4066. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4067. }
  4068. // Warn about ignored type attributes, for example:
  4069. // __attribute__((aligned)) struct A;
  4070. // Attributes should be placed after tag to apply to type declaration.
  4071. if (!DS.getAttributes().empty()) {
  4072. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4073. if (TypeSpecType == DeclSpec::TST_class ||
  4074. TypeSpecType == DeclSpec::TST_struct ||
  4075. TypeSpecType == DeclSpec::TST_interface ||
  4076. TypeSpecType == DeclSpec::TST_union ||
  4077. TypeSpecType == DeclSpec::TST_enum) {
  4078. for (const ParsedAttr &AL : DS.getAttributes())
  4079. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4080. << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4081. }
  4082. }
  4083. return TagD;
  4084. }
  4085. /// We are trying to inject an anonymous member into the given scope;
  4086. /// check if there's an existing declaration that can't be overloaded.
  4087. ///
  4088. /// \return true if this is a forbidden redeclaration
  4089. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4090. Scope *S,
  4091. DeclContext *Owner,
  4092. DeclarationName Name,
  4093. SourceLocation NameLoc,
  4094. bool IsUnion) {
  4095. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4096. Sema::ForVisibleRedeclaration);
  4097. if (!SemaRef.LookupName(R, S)) return false;
  4098. // Pick a representative declaration.
  4099. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4100. assert(PrevDecl && "Expected a non-null Decl");
  4101. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4102. return false;
  4103. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4104. << IsUnion << Name;
  4105. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4106. return true;
  4107. }
  4108. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4109. /// anonymous struct or union AnonRecord into the owning context Owner
  4110. /// and scope S. This routine will be invoked just after we realize
  4111. /// that an unnamed union or struct is actually an anonymous union or
  4112. /// struct, e.g.,
  4113. ///
  4114. /// @code
  4115. /// union {
  4116. /// int i;
  4117. /// float f;
  4118. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4119. /// // f into the surrounding scope.x
  4120. /// @endcode
  4121. ///
  4122. /// This routine is recursive, injecting the names of nested anonymous
  4123. /// structs/unions into the owning context and scope as well.
  4124. static bool
  4125. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4126. RecordDecl *AnonRecord, AccessSpecifier AS,
  4127. SmallVectorImpl<NamedDecl *> &Chaining) {
  4128. bool Invalid = false;
  4129. // Look every FieldDecl and IndirectFieldDecl with a name.
  4130. for (auto *D : AnonRecord->decls()) {
  4131. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4132. cast<NamedDecl>(D)->getDeclName()) {
  4133. ValueDecl *VD = cast<ValueDecl>(D);
  4134. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4135. VD->getLocation(),
  4136. AnonRecord->isUnion())) {
  4137. // C++ [class.union]p2:
  4138. // The names of the members of an anonymous union shall be
  4139. // distinct from the names of any other entity in the
  4140. // scope in which the anonymous union is declared.
  4141. Invalid = true;
  4142. } else {
  4143. // C++ [class.union]p2:
  4144. // For the purpose of name lookup, after the anonymous union
  4145. // definition, the members of the anonymous union are
  4146. // considered to have been defined in the scope in which the
  4147. // anonymous union is declared.
  4148. unsigned OldChainingSize = Chaining.size();
  4149. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4150. Chaining.append(IF->chain_begin(), IF->chain_end());
  4151. else
  4152. Chaining.push_back(VD);
  4153. assert(Chaining.size() >= 2);
  4154. NamedDecl **NamedChain =
  4155. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4156. for (unsigned i = 0; i < Chaining.size(); i++)
  4157. NamedChain[i] = Chaining[i];
  4158. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4159. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4160. VD->getType(), {NamedChain, Chaining.size()});
  4161. for (const auto *Attr : VD->attrs())
  4162. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4163. IndirectField->setAccess(AS);
  4164. IndirectField->setImplicit();
  4165. SemaRef.PushOnScopeChains(IndirectField, S);
  4166. // That includes picking up the appropriate access specifier.
  4167. if (AS != AS_none) IndirectField->setAccess(AS);
  4168. Chaining.resize(OldChainingSize);
  4169. }
  4170. }
  4171. }
  4172. return Invalid;
  4173. }
  4174. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4175. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4176. /// illegal input values are mapped to SC_None.
  4177. static StorageClass
  4178. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4179. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4180. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4181. "Parser allowed 'typedef' as storage class VarDecl.");
  4182. switch (StorageClassSpec) {
  4183. case DeclSpec::SCS_unspecified: return SC_None;
  4184. case DeclSpec::SCS_extern:
  4185. if (DS.isExternInLinkageSpec())
  4186. return SC_None;
  4187. return SC_Extern;
  4188. case DeclSpec::SCS_static: return SC_Static;
  4189. case DeclSpec::SCS_auto: return SC_Auto;
  4190. case DeclSpec::SCS_register: return SC_Register;
  4191. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4192. // Illegal SCSs map to None: error reporting is up to the caller.
  4193. case DeclSpec::SCS_mutable: // Fall through.
  4194. case DeclSpec::SCS_typedef: return SC_None;
  4195. }
  4196. llvm_unreachable("unknown storage class specifier");
  4197. }
  4198. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4199. assert(Record->hasInClassInitializer());
  4200. for (const auto *I : Record->decls()) {
  4201. const auto *FD = dyn_cast<FieldDecl>(I);
  4202. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4203. FD = IFD->getAnonField();
  4204. if (FD && FD->hasInClassInitializer())
  4205. return FD->getLocation();
  4206. }
  4207. llvm_unreachable("couldn't find in-class initializer");
  4208. }
  4209. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4210. SourceLocation DefaultInitLoc) {
  4211. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4212. return;
  4213. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4214. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4215. }
  4216. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4217. CXXRecordDecl *AnonUnion) {
  4218. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4219. return;
  4220. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4221. }
  4222. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4223. /// anonymous structure or union. Anonymous unions are a C++ feature
  4224. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4225. /// are a C11 feature and GNU C++ extension.
  4226. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4227. AccessSpecifier AS,
  4228. RecordDecl *Record,
  4229. const PrintingPolicy &Policy) {
  4230. DeclContext *Owner = Record->getDeclContext();
  4231. // Diagnose whether this anonymous struct/union is an extension.
  4232. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4233. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4234. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4235. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4236. else if (!Record->isUnion() && !getLangOpts().C11)
  4237. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4238. // C and C++ require different kinds of checks for anonymous
  4239. // structs/unions.
  4240. bool Invalid = false;
  4241. if (getLangOpts().CPlusPlus) {
  4242. const char *PrevSpec = nullptr;
  4243. if (Record->isUnion()) {
  4244. // C++ [class.union]p6:
  4245. // C++17 [class.union.anon]p2:
  4246. // Anonymous unions declared in a named namespace or in the
  4247. // global namespace shall be declared static.
  4248. unsigned DiagID;
  4249. DeclContext *OwnerScope = Owner->getRedeclContext();
  4250. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4251. (OwnerScope->isTranslationUnit() ||
  4252. (OwnerScope->isNamespace() &&
  4253. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4254. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4255. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4256. // Recover by adding 'static'.
  4257. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4258. PrevSpec, DiagID, Policy);
  4259. }
  4260. // C++ [class.union]p6:
  4261. // A storage class is not allowed in a declaration of an
  4262. // anonymous union in a class scope.
  4263. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4264. isa<RecordDecl>(Owner)) {
  4265. Diag(DS.getStorageClassSpecLoc(),
  4266. diag::err_anonymous_union_with_storage_spec)
  4267. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4268. // Recover by removing the storage specifier.
  4269. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4270. SourceLocation(),
  4271. PrevSpec, DiagID, Context.getPrintingPolicy());
  4272. }
  4273. }
  4274. // Ignore const/volatile/restrict qualifiers.
  4275. if (DS.getTypeQualifiers()) {
  4276. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4277. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4278. << Record->isUnion() << "const"
  4279. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4280. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4281. Diag(DS.getVolatileSpecLoc(),
  4282. diag::ext_anonymous_struct_union_qualified)
  4283. << Record->isUnion() << "volatile"
  4284. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4285. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4286. Diag(DS.getRestrictSpecLoc(),
  4287. diag::ext_anonymous_struct_union_qualified)
  4288. << Record->isUnion() << "restrict"
  4289. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4290. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4291. Diag(DS.getAtomicSpecLoc(),
  4292. diag::ext_anonymous_struct_union_qualified)
  4293. << Record->isUnion() << "_Atomic"
  4294. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4295. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4296. Diag(DS.getUnalignedSpecLoc(),
  4297. diag::ext_anonymous_struct_union_qualified)
  4298. << Record->isUnion() << "__unaligned"
  4299. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4300. DS.ClearTypeQualifiers();
  4301. }
  4302. // C++ [class.union]p2:
  4303. // The member-specification of an anonymous union shall only
  4304. // define non-static data members. [Note: nested types and
  4305. // functions cannot be declared within an anonymous union. ]
  4306. for (auto *Mem : Record->decls()) {
  4307. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4308. // C++ [class.union]p3:
  4309. // An anonymous union shall not have private or protected
  4310. // members (clause 11).
  4311. assert(FD->getAccess() != AS_none);
  4312. if (FD->getAccess() != AS_public) {
  4313. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4314. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4315. Invalid = true;
  4316. }
  4317. // C++ [class.union]p1
  4318. // An object of a class with a non-trivial constructor, a non-trivial
  4319. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4320. // assignment operator cannot be a member of a union, nor can an
  4321. // array of such objects.
  4322. if (CheckNontrivialField(FD))
  4323. Invalid = true;
  4324. } else if (Mem->isImplicit()) {
  4325. // Any implicit members are fine.
  4326. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4327. // This is a type that showed up in an
  4328. // elaborated-type-specifier inside the anonymous struct or
  4329. // union, but which actually declares a type outside of the
  4330. // anonymous struct or union. It's okay.
  4331. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4332. if (!MemRecord->isAnonymousStructOrUnion() &&
  4333. MemRecord->getDeclName()) {
  4334. // Visual C++ allows type definition in anonymous struct or union.
  4335. if (getLangOpts().MicrosoftExt)
  4336. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4337. << Record->isUnion();
  4338. else {
  4339. // This is a nested type declaration.
  4340. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4341. << Record->isUnion();
  4342. Invalid = true;
  4343. }
  4344. } else {
  4345. // This is an anonymous type definition within another anonymous type.
  4346. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4347. // not part of standard C++.
  4348. Diag(MemRecord->getLocation(),
  4349. diag::ext_anonymous_record_with_anonymous_type)
  4350. << Record->isUnion();
  4351. }
  4352. } else if (isa<AccessSpecDecl>(Mem)) {
  4353. // Any access specifier is fine.
  4354. } else if (isa<StaticAssertDecl>(Mem)) {
  4355. // In C++1z, static_assert declarations are also fine.
  4356. } else {
  4357. // We have something that isn't a non-static data
  4358. // member. Complain about it.
  4359. unsigned DK = diag::err_anonymous_record_bad_member;
  4360. if (isa<TypeDecl>(Mem))
  4361. DK = diag::err_anonymous_record_with_type;
  4362. else if (isa<FunctionDecl>(Mem))
  4363. DK = diag::err_anonymous_record_with_function;
  4364. else if (isa<VarDecl>(Mem))
  4365. DK = diag::err_anonymous_record_with_static;
  4366. // Visual C++ allows type definition in anonymous struct or union.
  4367. if (getLangOpts().MicrosoftExt &&
  4368. DK == diag::err_anonymous_record_with_type)
  4369. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4370. << Record->isUnion();
  4371. else {
  4372. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4373. Invalid = true;
  4374. }
  4375. }
  4376. }
  4377. // C++11 [class.union]p8 (DR1460):
  4378. // At most one variant member of a union may have a
  4379. // brace-or-equal-initializer.
  4380. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4381. Owner->isRecord())
  4382. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4383. cast<CXXRecordDecl>(Record));
  4384. }
  4385. if (!Record->isUnion() && !Owner->isRecord()) {
  4386. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4387. << getLangOpts().CPlusPlus;
  4388. Invalid = true;
  4389. }
  4390. // C++ [dcl.dcl]p3:
  4391. // [If there are no declarators], and except for the declaration of an
  4392. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4393. // names into the program
  4394. // C++ [class.mem]p2:
  4395. // each such member-declaration shall either declare at least one member
  4396. // name of the class or declare at least one unnamed bit-field
  4397. //
  4398. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4399. if (getLangOpts().CPlusPlus && Record->field_empty())
  4400. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4401. // Mock up a declarator.
  4402. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4403. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4404. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4405. // Create a declaration for this anonymous struct/union.
  4406. NamedDecl *Anon = nullptr;
  4407. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4408. Anon = FieldDecl::Create(
  4409. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4410. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4411. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4412. /*InitStyle=*/ICIS_NoInit);
  4413. Anon->setAccess(AS);
  4414. if (getLangOpts().CPlusPlus)
  4415. FieldCollector->Add(cast<FieldDecl>(Anon));
  4416. } else {
  4417. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4418. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4419. if (SCSpec == DeclSpec::SCS_mutable) {
  4420. // mutable can only appear on non-static class members, so it's always
  4421. // an error here
  4422. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4423. Invalid = true;
  4424. SC = SC_None;
  4425. }
  4426. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4427. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4428. Context.getTypeDeclType(Record), TInfo, SC);
  4429. // Default-initialize the implicit variable. This initialization will be
  4430. // trivial in almost all cases, except if a union member has an in-class
  4431. // initializer:
  4432. // union { int n = 0; };
  4433. ActOnUninitializedDecl(Anon);
  4434. }
  4435. Anon->setImplicit();
  4436. // Mark this as an anonymous struct/union type.
  4437. Record->setAnonymousStructOrUnion(true);
  4438. // Add the anonymous struct/union object to the current
  4439. // context. We'll be referencing this object when we refer to one of
  4440. // its members.
  4441. Owner->addDecl(Anon);
  4442. // Inject the members of the anonymous struct/union into the owning
  4443. // context and into the identifier resolver chain for name lookup
  4444. // purposes.
  4445. SmallVector<NamedDecl*, 2> Chain;
  4446. Chain.push_back(Anon);
  4447. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4448. Invalid = true;
  4449. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4450. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4451. Decl *ManglingContextDecl;
  4452. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4453. NewVD->getDeclContext(), ManglingContextDecl)) {
  4454. Context.setManglingNumber(
  4455. NewVD, MCtx->getManglingNumber(
  4456. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4457. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4458. }
  4459. }
  4460. }
  4461. if (Invalid)
  4462. Anon->setInvalidDecl();
  4463. return Anon;
  4464. }
  4465. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4466. /// Microsoft C anonymous structure.
  4467. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4468. /// Example:
  4469. ///
  4470. /// struct A { int a; };
  4471. /// struct B { struct A; int b; };
  4472. ///
  4473. /// void foo() {
  4474. /// B var;
  4475. /// var.a = 3;
  4476. /// }
  4477. ///
  4478. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4479. RecordDecl *Record) {
  4480. assert(Record && "expected a record!");
  4481. // Mock up a declarator.
  4482. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4483. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4484. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4485. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4486. QualType RecTy = Context.getTypeDeclType(Record);
  4487. // Create a declaration for this anonymous struct.
  4488. NamedDecl *Anon =
  4489. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4490. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4491. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4492. /*InitStyle=*/ICIS_NoInit);
  4493. Anon->setImplicit();
  4494. // Add the anonymous struct object to the current context.
  4495. CurContext->addDecl(Anon);
  4496. // Inject the members of the anonymous struct into the current
  4497. // context and into the identifier resolver chain for name lookup
  4498. // purposes.
  4499. SmallVector<NamedDecl*, 2> Chain;
  4500. Chain.push_back(Anon);
  4501. RecordDecl *RecordDef = Record->getDefinition();
  4502. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4503. diag::err_field_incomplete) ||
  4504. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4505. AS_none, Chain)) {
  4506. Anon->setInvalidDecl();
  4507. ParentDecl->setInvalidDecl();
  4508. }
  4509. return Anon;
  4510. }
  4511. /// GetNameForDeclarator - Determine the full declaration name for the
  4512. /// given Declarator.
  4513. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4514. return GetNameFromUnqualifiedId(D.getName());
  4515. }
  4516. /// Retrieves the declaration name from a parsed unqualified-id.
  4517. DeclarationNameInfo
  4518. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4519. DeclarationNameInfo NameInfo;
  4520. NameInfo.setLoc(Name.StartLocation);
  4521. switch (Name.getKind()) {
  4522. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4523. case UnqualifiedIdKind::IK_Identifier:
  4524. NameInfo.setName(Name.Identifier);
  4525. return NameInfo;
  4526. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4527. // C++ [temp.deduct.guide]p3:
  4528. // The simple-template-id shall name a class template specialization.
  4529. // The template-name shall be the same identifier as the template-name
  4530. // of the simple-template-id.
  4531. // These together intend to imply that the template-name shall name a
  4532. // class template.
  4533. // FIXME: template<typename T> struct X {};
  4534. // template<typename T> using Y = X<T>;
  4535. // Y(int) -> Y<int>;
  4536. // satisfies these rules but does not name a class template.
  4537. TemplateName TN = Name.TemplateName.get().get();
  4538. auto *Template = TN.getAsTemplateDecl();
  4539. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4540. Diag(Name.StartLocation,
  4541. diag::err_deduction_guide_name_not_class_template)
  4542. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4543. if (Template)
  4544. Diag(Template->getLocation(), diag::note_template_decl_here);
  4545. return DeclarationNameInfo();
  4546. }
  4547. NameInfo.setName(
  4548. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4549. return NameInfo;
  4550. }
  4551. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4552. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4553. Name.OperatorFunctionId.Operator));
  4554. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4555. = Name.OperatorFunctionId.SymbolLocations[0];
  4556. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4557. = Name.EndLocation.getRawEncoding();
  4558. return NameInfo;
  4559. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4560. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4561. Name.Identifier));
  4562. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4563. return NameInfo;
  4564. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4565. TypeSourceInfo *TInfo;
  4566. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4567. if (Ty.isNull())
  4568. return DeclarationNameInfo();
  4569. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4570. Context.getCanonicalType(Ty)));
  4571. NameInfo.setNamedTypeInfo(TInfo);
  4572. return NameInfo;
  4573. }
  4574. case UnqualifiedIdKind::IK_ConstructorName: {
  4575. TypeSourceInfo *TInfo;
  4576. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4577. if (Ty.isNull())
  4578. return DeclarationNameInfo();
  4579. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4580. Context.getCanonicalType(Ty)));
  4581. NameInfo.setNamedTypeInfo(TInfo);
  4582. return NameInfo;
  4583. }
  4584. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4585. // In well-formed code, we can only have a constructor
  4586. // template-id that refers to the current context, so go there
  4587. // to find the actual type being constructed.
  4588. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4589. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4590. return DeclarationNameInfo();
  4591. // Determine the type of the class being constructed.
  4592. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4593. // FIXME: Check two things: that the template-id names the same type as
  4594. // CurClassType, and that the template-id does not occur when the name
  4595. // was qualified.
  4596. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4597. Context.getCanonicalType(CurClassType)));
  4598. // FIXME: should we retrieve TypeSourceInfo?
  4599. NameInfo.setNamedTypeInfo(nullptr);
  4600. return NameInfo;
  4601. }
  4602. case UnqualifiedIdKind::IK_DestructorName: {
  4603. TypeSourceInfo *TInfo;
  4604. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4605. if (Ty.isNull())
  4606. return DeclarationNameInfo();
  4607. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4608. Context.getCanonicalType(Ty)));
  4609. NameInfo.setNamedTypeInfo(TInfo);
  4610. return NameInfo;
  4611. }
  4612. case UnqualifiedIdKind::IK_TemplateId: {
  4613. TemplateName TName = Name.TemplateId->Template.get();
  4614. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4615. return Context.getNameForTemplate(TName, TNameLoc);
  4616. }
  4617. } // switch (Name.getKind())
  4618. llvm_unreachable("Unknown name kind");
  4619. }
  4620. static QualType getCoreType(QualType Ty) {
  4621. do {
  4622. if (Ty->isPointerType() || Ty->isReferenceType())
  4623. Ty = Ty->getPointeeType();
  4624. else if (Ty->isArrayType())
  4625. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4626. else
  4627. return Ty.withoutLocalFastQualifiers();
  4628. } while (true);
  4629. }
  4630. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4631. /// and Definition have "nearly" matching parameters. This heuristic is
  4632. /// used to improve diagnostics in the case where an out-of-line function
  4633. /// definition doesn't match any declaration within the class or namespace.
  4634. /// Also sets Params to the list of indices to the parameters that differ
  4635. /// between the declaration and the definition. If hasSimilarParameters
  4636. /// returns true and Params is empty, then all of the parameters match.
  4637. static bool hasSimilarParameters(ASTContext &Context,
  4638. FunctionDecl *Declaration,
  4639. FunctionDecl *Definition,
  4640. SmallVectorImpl<unsigned> &Params) {
  4641. Params.clear();
  4642. if (Declaration->param_size() != Definition->param_size())
  4643. return false;
  4644. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4645. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4646. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4647. // The parameter types are identical
  4648. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4649. continue;
  4650. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4651. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4652. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4653. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4654. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4655. (DeclTyName && DeclTyName == DefTyName))
  4656. Params.push_back(Idx);
  4657. else // The two parameters aren't even close
  4658. return false;
  4659. }
  4660. return true;
  4661. }
  4662. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4663. /// declarator needs to be rebuilt in the current instantiation.
  4664. /// Any bits of declarator which appear before the name are valid for
  4665. /// consideration here. That's specifically the type in the decl spec
  4666. /// and the base type in any member-pointer chunks.
  4667. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4668. DeclarationName Name) {
  4669. // The types we specifically need to rebuild are:
  4670. // - typenames, typeofs, and decltypes
  4671. // - types which will become injected class names
  4672. // Of course, we also need to rebuild any type referencing such a
  4673. // type. It's safest to just say "dependent", but we call out a
  4674. // few cases here.
  4675. DeclSpec &DS = D.getMutableDeclSpec();
  4676. switch (DS.getTypeSpecType()) {
  4677. case DeclSpec::TST_typename:
  4678. case DeclSpec::TST_typeofType:
  4679. case DeclSpec::TST_underlyingType:
  4680. case DeclSpec::TST_atomic: {
  4681. // Grab the type from the parser.
  4682. TypeSourceInfo *TSI = nullptr;
  4683. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4684. if (T.isNull() || !T->isDependentType()) break;
  4685. // Make sure there's a type source info. This isn't really much
  4686. // of a waste; most dependent types should have type source info
  4687. // attached already.
  4688. if (!TSI)
  4689. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4690. // Rebuild the type in the current instantiation.
  4691. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4692. if (!TSI) return true;
  4693. // Store the new type back in the decl spec.
  4694. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4695. DS.UpdateTypeRep(LocType);
  4696. break;
  4697. }
  4698. case DeclSpec::TST_decltype:
  4699. case DeclSpec::TST_typeofExpr: {
  4700. Expr *E = DS.getRepAsExpr();
  4701. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4702. if (Result.isInvalid()) return true;
  4703. DS.UpdateExprRep(Result.get());
  4704. break;
  4705. }
  4706. default:
  4707. // Nothing to do for these decl specs.
  4708. break;
  4709. }
  4710. // It doesn't matter what order we do this in.
  4711. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4712. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4713. // The only type information in the declarator which can come
  4714. // before the declaration name is the base type of a member
  4715. // pointer.
  4716. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4717. continue;
  4718. // Rebuild the scope specifier in-place.
  4719. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4720. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4721. return true;
  4722. }
  4723. return false;
  4724. }
  4725. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4726. D.setFunctionDefinitionKind(FDK_Declaration);
  4727. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4728. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4729. Dcl && Dcl->getDeclContext()->isFileContext())
  4730. Dcl->setTopLevelDeclInObjCContainer();
  4731. if (getLangOpts().OpenCL)
  4732. setCurrentOpenCLExtensionForDecl(Dcl);
  4733. return Dcl;
  4734. }
  4735. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4736. /// If T is the name of a class, then each of the following shall have a
  4737. /// name different from T:
  4738. /// - every static data member of class T;
  4739. /// - every member function of class T
  4740. /// - every member of class T that is itself a type;
  4741. /// \returns true if the declaration name violates these rules.
  4742. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4743. DeclarationNameInfo NameInfo) {
  4744. DeclarationName Name = NameInfo.getName();
  4745. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4746. while (Record && Record->isAnonymousStructOrUnion())
  4747. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4748. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4749. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4750. return true;
  4751. }
  4752. return false;
  4753. }
  4754. /// Diagnose a declaration whose declarator-id has the given
  4755. /// nested-name-specifier.
  4756. ///
  4757. /// \param SS The nested-name-specifier of the declarator-id.
  4758. ///
  4759. /// \param DC The declaration context to which the nested-name-specifier
  4760. /// resolves.
  4761. ///
  4762. /// \param Name The name of the entity being declared.
  4763. ///
  4764. /// \param Loc The location of the name of the entity being declared.
  4765. ///
  4766. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4767. /// we're declaring an explicit / partial specialization / instantiation.
  4768. ///
  4769. /// \returns true if we cannot safely recover from this error, false otherwise.
  4770. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4771. DeclarationName Name,
  4772. SourceLocation Loc, bool IsTemplateId) {
  4773. DeclContext *Cur = CurContext;
  4774. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4775. Cur = Cur->getParent();
  4776. // If the user provided a superfluous scope specifier that refers back to the
  4777. // class in which the entity is already declared, diagnose and ignore it.
  4778. //
  4779. // class X {
  4780. // void X::f();
  4781. // };
  4782. //
  4783. // Note, it was once ill-formed to give redundant qualification in all
  4784. // contexts, but that rule was removed by DR482.
  4785. if (Cur->Equals(DC)) {
  4786. if (Cur->isRecord()) {
  4787. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4788. : diag::err_member_extra_qualification)
  4789. << Name << FixItHint::CreateRemoval(SS.getRange());
  4790. SS.clear();
  4791. } else {
  4792. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4793. }
  4794. return false;
  4795. }
  4796. // Check whether the qualifying scope encloses the scope of the original
  4797. // declaration. For a template-id, we perform the checks in
  4798. // CheckTemplateSpecializationScope.
  4799. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4800. if (Cur->isRecord())
  4801. Diag(Loc, diag::err_member_qualification)
  4802. << Name << SS.getRange();
  4803. else if (isa<TranslationUnitDecl>(DC))
  4804. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4805. << Name << SS.getRange();
  4806. else if (isa<FunctionDecl>(Cur))
  4807. Diag(Loc, diag::err_invalid_declarator_in_function)
  4808. << Name << SS.getRange();
  4809. else if (isa<BlockDecl>(Cur))
  4810. Diag(Loc, diag::err_invalid_declarator_in_block)
  4811. << Name << SS.getRange();
  4812. else
  4813. Diag(Loc, diag::err_invalid_declarator_scope)
  4814. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4815. return true;
  4816. }
  4817. if (Cur->isRecord()) {
  4818. // Cannot qualify members within a class.
  4819. Diag(Loc, diag::err_member_qualification)
  4820. << Name << SS.getRange();
  4821. SS.clear();
  4822. // C++ constructors and destructors with incorrect scopes can break
  4823. // our AST invariants by having the wrong underlying types. If
  4824. // that's the case, then drop this declaration entirely.
  4825. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4826. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4827. !Context.hasSameType(Name.getCXXNameType(),
  4828. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4829. return true;
  4830. return false;
  4831. }
  4832. // C++11 [dcl.meaning]p1:
  4833. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4834. // not begin with a decltype-specifer"
  4835. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4836. while (SpecLoc.getPrefix())
  4837. SpecLoc = SpecLoc.getPrefix();
  4838. if (dyn_cast_or_null<DecltypeType>(
  4839. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4840. Diag(Loc, diag::err_decltype_in_declarator)
  4841. << SpecLoc.getTypeLoc().getSourceRange();
  4842. return false;
  4843. }
  4844. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4845. MultiTemplateParamsArg TemplateParamLists) {
  4846. // TODO: consider using NameInfo for diagnostic.
  4847. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4848. DeclarationName Name = NameInfo.getName();
  4849. // All of these full declarators require an identifier. If it doesn't have
  4850. // one, the ParsedFreeStandingDeclSpec action should be used.
  4851. if (D.isDecompositionDeclarator()) {
  4852. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4853. } else if (!Name) {
  4854. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4855. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4856. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4857. return nullptr;
  4858. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4859. return nullptr;
  4860. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4861. // we find one that is.
  4862. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4863. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4864. S = S->getParent();
  4865. DeclContext *DC = CurContext;
  4866. if (D.getCXXScopeSpec().isInvalid())
  4867. D.setInvalidType();
  4868. else if (D.getCXXScopeSpec().isSet()) {
  4869. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4870. UPPC_DeclarationQualifier))
  4871. return nullptr;
  4872. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4873. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4874. if (!DC || isa<EnumDecl>(DC)) {
  4875. // If we could not compute the declaration context, it's because the
  4876. // declaration context is dependent but does not refer to a class,
  4877. // class template, or class template partial specialization. Complain
  4878. // and return early, to avoid the coming semantic disaster.
  4879. Diag(D.getIdentifierLoc(),
  4880. diag::err_template_qualified_declarator_no_match)
  4881. << D.getCXXScopeSpec().getScopeRep()
  4882. << D.getCXXScopeSpec().getRange();
  4883. return nullptr;
  4884. }
  4885. bool IsDependentContext = DC->isDependentContext();
  4886. if (!IsDependentContext &&
  4887. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4888. return nullptr;
  4889. // If a class is incomplete, do not parse entities inside it.
  4890. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4891. Diag(D.getIdentifierLoc(),
  4892. diag::err_member_def_undefined_record)
  4893. << Name << DC << D.getCXXScopeSpec().getRange();
  4894. return nullptr;
  4895. }
  4896. if (!D.getDeclSpec().isFriendSpecified()) {
  4897. if (diagnoseQualifiedDeclaration(
  4898. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4899. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4900. if (DC->isRecord())
  4901. return nullptr;
  4902. D.setInvalidType();
  4903. }
  4904. }
  4905. // Check whether we need to rebuild the type of the given
  4906. // declaration in the current instantiation.
  4907. if (EnteringContext && IsDependentContext &&
  4908. TemplateParamLists.size() != 0) {
  4909. ContextRAII SavedContext(*this, DC);
  4910. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4911. D.setInvalidType();
  4912. }
  4913. }
  4914. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4915. QualType R = TInfo->getType();
  4916. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4917. UPPC_DeclarationType))
  4918. D.setInvalidType();
  4919. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4920. forRedeclarationInCurContext());
  4921. // See if this is a redefinition of a variable in the same scope.
  4922. if (!D.getCXXScopeSpec().isSet()) {
  4923. bool IsLinkageLookup = false;
  4924. bool CreateBuiltins = false;
  4925. // If the declaration we're planning to build will be a function
  4926. // or object with linkage, then look for another declaration with
  4927. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4928. //
  4929. // If the declaration we're planning to build will be declared with
  4930. // external linkage in the translation unit, create any builtin with
  4931. // the same name.
  4932. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4933. /* Do nothing*/;
  4934. else if (CurContext->isFunctionOrMethod() &&
  4935. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4936. R->isFunctionType())) {
  4937. IsLinkageLookup = true;
  4938. CreateBuiltins =
  4939. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4940. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4941. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4942. CreateBuiltins = true;
  4943. if (IsLinkageLookup) {
  4944. Previous.clear(LookupRedeclarationWithLinkage);
  4945. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4946. }
  4947. LookupName(Previous, S, CreateBuiltins);
  4948. } else { // Something like "int foo::x;"
  4949. LookupQualifiedName(Previous, DC);
  4950. // C++ [dcl.meaning]p1:
  4951. // When the declarator-id is qualified, the declaration shall refer to a
  4952. // previously declared member of the class or namespace to which the
  4953. // qualifier refers (or, in the case of a namespace, of an element of the
  4954. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4955. // thereof; [...]
  4956. //
  4957. // Note that we already checked the context above, and that we do not have
  4958. // enough information to make sure that Previous contains the declaration
  4959. // we want to match. For example, given:
  4960. //
  4961. // class X {
  4962. // void f();
  4963. // void f(float);
  4964. // };
  4965. //
  4966. // void X::f(int) { } // ill-formed
  4967. //
  4968. // In this case, Previous will point to the overload set
  4969. // containing the two f's declared in X, but neither of them
  4970. // matches.
  4971. // C++ [dcl.meaning]p1:
  4972. // [...] the member shall not merely have been introduced by a
  4973. // using-declaration in the scope of the class or namespace nominated by
  4974. // the nested-name-specifier of the declarator-id.
  4975. RemoveUsingDecls(Previous);
  4976. }
  4977. if (Previous.isSingleResult() &&
  4978. Previous.getFoundDecl()->isTemplateParameter()) {
  4979. // Maybe we will complain about the shadowed template parameter.
  4980. if (!D.isInvalidType())
  4981. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4982. Previous.getFoundDecl());
  4983. // Just pretend that we didn't see the previous declaration.
  4984. Previous.clear();
  4985. }
  4986. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4987. // Forget that the previous declaration is the injected-class-name.
  4988. Previous.clear();
  4989. // In C++, the previous declaration we find might be a tag type
  4990. // (class or enum). In this case, the new declaration will hide the
  4991. // tag type. Note that this applies to functions, function templates, and
  4992. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4993. if (Previous.isSingleTagDecl() &&
  4994. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4995. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4996. Previous.clear();
  4997. // Check that there are no default arguments other than in the parameters
  4998. // of a function declaration (C++ only).
  4999. if (getLangOpts().CPlusPlus)
  5000. CheckExtraCXXDefaultArguments(D);
  5001. NamedDecl *New;
  5002. bool AddToScope = true;
  5003. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5004. if (TemplateParamLists.size()) {
  5005. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5006. return nullptr;
  5007. }
  5008. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5009. } else if (R->isFunctionType()) {
  5010. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5011. TemplateParamLists,
  5012. AddToScope);
  5013. } else {
  5014. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5015. AddToScope);
  5016. }
  5017. if (!New)
  5018. return nullptr;
  5019. // If this has an identifier and is not a function template specialization,
  5020. // add it to the scope stack.
  5021. if (New->getDeclName() && AddToScope)
  5022. PushOnScopeChains(New, S);
  5023. if (isInOpenMPDeclareTargetContext())
  5024. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5025. return New;
  5026. }
  5027. /// Helper method to turn variable array types into constant array
  5028. /// types in certain situations which would otherwise be errors (for
  5029. /// GCC compatibility).
  5030. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5031. ASTContext &Context,
  5032. bool &SizeIsNegative,
  5033. llvm::APSInt &Oversized) {
  5034. // This method tries to turn a variable array into a constant
  5035. // array even when the size isn't an ICE. This is necessary
  5036. // for compatibility with code that depends on gcc's buggy
  5037. // constant expression folding, like struct {char x[(int)(char*)2];}
  5038. SizeIsNegative = false;
  5039. Oversized = 0;
  5040. if (T->isDependentType())
  5041. return QualType();
  5042. QualifierCollector Qs;
  5043. const Type *Ty = Qs.strip(T);
  5044. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5045. QualType Pointee = PTy->getPointeeType();
  5046. QualType FixedType =
  5047. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5048. Oversized);
  5049. if (FixedType.isNull()) return FixedType;
  5050. FixedType = Context.getPointerType(FixedType);
  5051. return Qs.apply(Context, FixedType);
  5052. }
  5053. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5054. QualType Inner = PTy->getInnerType();
  5055. QualType FixedType =
  5056. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5057. Oversized);
  5058. if (FixedType.isNull()) return FixedType;
  5059. FixedType = Context.getParenType(FixedType);
  5060. return Qs.apply(Context, FixedType);
  5061. }
  5062. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5063. if (!VLATy)
  5064. return QualType();
  5065. // FIXME: We should probably handle this case
  5066. if (VLATy->getElementType()->isVariablyModifiedType())
  5067. return QualType();
  5068. Expr::EvalResult Result;
  5069. if (!VLATy->getSizeExpr() ||
  5070. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5071. return QualType();
  5072. llvm::APSInt Res = Result.Val.getInt();
  5073. // Check whether the array size is negative.
  5074. if (Res.isSigned() && Res.isNegative()) {
  5075. SizeIsNegative = true;
  5076. return QualType();
  5077. }
  5078. // Check whether the array is too large to be addressed.
  5079. unsigned ActiveSizeBits
  5080. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  5081. Res);
  5082. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5083. Oversized = Res;
  5084. return QualType();
  5085. }
  5086. return Context.getConstantArrayType(VLATy->getElementType(),
  5087. Res, ArrayType::Normal, 0);
  5088. }
  5089. static void
  5090. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5091. SrcTL = SrcTL.getUnqualifiedLoc();
  5092. DstTL = DstTL.getUnqualifiedLoc();
  5093. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5094. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5095. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5096. DstPTL.getPointeeLoc());
  5097. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5098. return;
  5099. }
  5100. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5101. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5102. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5103. DstPTL.getInnerLoc());
  5104. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5105. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5106. return;
  5107. }
  5108. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5109. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5110. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5111. TypeLoc DstElemTL = DstATL.getElementLoc();
  5112. DstElemTL.initializeFullCopy(SrcElemTL);
  5113. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5114. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5115. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5116. }
  5117. /// Helper method to turn variable array types into constant array
  5118. /// types in certain situations which would otherwise be errors (for
  5119. /// GCC compatibility).
  5120. static TypeSourceInfo*
  5121. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5122. ASTContext &Context,
  5123. bool &SizeIsNegative,
  5124. llvm::APSInt &Oversized) {
  5125. QualType FixedTy
  5126. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5127. SizeIsNegative, Oversized);
  5128. if (FixedTy.isNull())
  5129. return nullptr;
  5130. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5131. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5132. FixedTInfo->getTypeLoc());
  5133. return FixedTInfo;
  5134. }
  5135. /// Register the given locally-scoped extern "C" declaration so
  5136. /// that it can be found later for redeclarations. We include any extern "C"
  5137. /// declaration that is not visible in the translation unit here, not just
  5138. /// function-scope declarations.
  5139. void
  5140. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5141. if (!getLangOpts().CPlusPlus &&
  5142. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5143. // Don't need to track declarations in the TU in C.
  5144. return;
  5145. // Note that we have a locally-scoped external with this name.
  5146. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5147. }
  5148. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5149. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5150. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5151. return Result.empty() ? nullptr : *Result.begin();
  5152. }
  5153. /// Diagnose function specifiers on a declaration of an identifier that
  5154. /// does not identify a function.
  5155. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5156. // FIXME: We should probably indicate the identifier in question to avoid
  5157. // confusion for constructs like "virtual int a(), b;"
  5158. if (DS.isVirtualSpecified())
  5159. Diag(DS.getVirtualSpecLoc(),
  5160. diag::err_virtual_non_function);
  5161. if (DS.hasExplicitSpecifier())
  5162. Diag(DS.getExplicitSpecLoc(),
  5163. diag::err_explicit_non_function);
  5164. if (DS.isNoreturnSpecified())
  5165. Diag(DS.getNoreturnSpecLoc(),
  5166. diag::err_noreturn_non_function);
  5167. }
  5168. NamedDecl*
  5169. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5170. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5171. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5172. if (D.getCXXScopeSpec().isSet()) {
  5173. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5174. << D.getCXXScopeSpec().getRange();
  5175. D.setInvalidType();
  5176. // Pretend we didn't see the scope specifier.
  5177. DC = CurContext;
  5178. Previous.clear();
  5179. }
  5180. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5181. if (D.getDeclSpec().isInlineSpecified())
  5182. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5183. << getLangOpts().CPlusPlus17;
  5184. if (D.getDeclSpec().hasConstexprSpecifier())
  5185. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5186. << 1 << D.getDeclSpec().getConstexprSpecifier();
  5187. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5188. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5189. Diag(D.getName().StartLocation,
  5190. diag::err_deduction_guide_invalid_specifier)
  5191. << "typedef";
  5192. else
  5193. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5194. << D.getName().getSourceRange();
  5195. return nullptr;
  5196. }
  5197. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5198. if (!NewTD) return nullptr;
  5199. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5200. ProcessDeclAttributes(S, NewTD, D);
  5201. CheckTypedefForVariablyModifiedType(S, NewTD);
  5202. bool Redeclaration = D.isRedeclaration();
  5203. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5204. D.setRedeclaration(Redeclaration);
  5205. return ND;
  5206. }
  5207. void
  5208. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5209. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5210. // then it shall have block scope.
  5211. // Note that variably modified types must be fixed before merging the decl so
  5212. // that redeclarations will match.
  5213. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5214. QualType T = TInfo->getType();
  5215. if (T->isVariablyModifiedType()) {
  5216. setFunctionHasBranchProtectedScope();
  5217. if (S->getFnParent() == nullptr) {
  5218. bool SizeIsNegative;
  5219. llvm::APSInt Oversized;
  5220. TypeSourceInfo *FixedTInfo =
  5221. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5222. SizeIsNegative,
  5223. Oversized);
  5224. if (FixedTInfo) {
  5225. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5226. NewTD->setTypeSourceInfo(FixedTInfo);
  5227. } else {
  5228. if (SizeIsNegative)
  5229. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5230. else if (T->isVariableArrayType())
  5231. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5232. else if (Oversized.getBoolValue())
  5233. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5234. << Oversized.toString(10);
  5235. else
  5236. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5237. NewTD->setInvalidDecl();
  5238. }
  5239. }
  5240. }
  5241. }
  5242. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5243. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5244. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5245. NamedDecl*
  5246. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5247. LookupResult &Previous, bool &Redeclaration) {
  5248. // Find the shadowed declaration before filtering for scope.
  5249. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5250. // Merge the decl with the existing one if appropriate. If the decl is
  5251. // in an outer scope, it isn't the same thing.
  5252. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5253. /*AllowInlineNamespace*/false);
  5254. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5255. if (!Previous.empty()) {
  5256. Redeclaration = true;
  5257. MergeTypedefNameDecl(S, NewTD, Previous);
  5258. } else {
  5259. inferGslPointerAttribute(NewTD);
  5260. }
  5261. if (ShadowedDecl && !Redeclaration)
  5262. CheckShadow(NewTD, ShadowedDecl, Previous);
  5263. // If this is the C FILE type, notify the AST context.
  5264. if (IdentifierInfo *II = NewTD->getIdentifier())
  5265. if (!NewTD->isInvalidDecl() &&
  5266. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5267. if (II->isStr("FILE"))
  5268. Context.setFILEDecl(NewTD);
  5269. else if (II->isStr("jmp_buf"))
  5270. Context.setjmp_bufDecl(NewTD);
  5271. else if (II->isStr("sigjmp_buf"))
  5272. Context.setsigjmp_bufDecl(NewTD);
  5273. else if (II->isStr("ucontext_t"))
  5274. Context.setucontext_tDecl(NewTD);
  5275. }
  5276. return NewTD;
  5277. }
  5278. /// Determines whether the given declaration is an out-of-scope
  5279. /// previous declaration.
  5280. ///
  5281. /// This routine should be invoked when name lookup has found a
  5282. /// previous declaration (PrevDecl) that is not in the scope where a
  5283. /// new declaration by the same name is being introduced. If the new
  5284. /// declaration occurs in a local scope, previous declarations with
  5285. /// linkage may still be considered previous declarations (C99
  5286. /// 6.2.2p4-5, C++ [basic.link]p6).
  5287. ///
  5288. /// \param PrevDecl the previous declaration found by name
  5289. /// lookup
  5290. ///
  5291. /// \param DC the context in which the new declaration is being
  5292. /// declared.
  5293. ///
  5294. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5295. /// for a new delcaration with the same name.
  5296. static bool
  5297. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5298. ASTContext &Context) {
  5299. if (!PrevDecl)
  5300. return false;
  5301. if (!PrevDecl->hasLinkage())
  5302. return false;
  5303. if (Context.getLangOpts().CPlusPlus) {
  5304. // C++ [basic.link]p6:
  5305. // If there is a visible declaration of an entity with linkage
  5306. // having the same name and type, ignoring entities declared
  5307. // outside the innermost enclosing namespace scope, the block
  5308. // scope declaration declares that same entity and receives the
  5309. // linkage of the previous declaration.
  5310. DeclContext *OuterContext = DC->getRedeclContext();
  5311. if (!OuterContext->isFunctionOrMethod())
  5312. // This rule only applies to block-scope declarations.
  5313. return false;
  5314. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5315. if (PrevOuterContext->isRecord())
  5316. // We found a member function: ignore it.
  5317. return false;
  5318. // Find the innermost enclosing namespace for the new and
  5319. // previous declarations.
  5320. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5321. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5322. // The previous declaration is in a different namespace, so it
  5323. // isn't the same function.
  5324. if (!OuterContext->Equals(PrevOuterContext))
  5325. return false;
  5326. }
  5327. return true;
  5328. }
  5329. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5330. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5331. if (!SS.isSet()) return;
  5332. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5333. }
  5334. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5335. QualType type = decl->getType();
  5336. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5337. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5338. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5339. unsigned kind = -1U;
  5340. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5341. if (var->hasAttr<BlocksAttr>())
  5342. kind = 0; // __block
  5343. else if (!var->hasLocalStorage())
  5344. kind = 1; // global
  5345. } else if (isa<ObjCIvarDecl>(decl)) {
  5346. kind = 3; // ivar
  5347. } else if (isa<FieldDecl>(decl)) {
  5348. kind = 2; // field
  5349. }
  5350. if (kind != -1U) {
  5351. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5352. << kind;
  5353. }
  5354. } else if (lifetime == Qualifiers::OCL_None) {
  5355. // Try to infer lifetime.
  5356. if (!type->isObjCLifetimeType())
  5357. return false;
  5358. lifetime = type->getObjCARCImplicitLifetime();
  5359. type = Context.getLifetimeQualifiedType(type, lifetime);
  5360. decl->setType(type);
  5361. }
  5362. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5363. // Thread-local variables cannot have lifetime.
  5364. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5365. var->getTLSKind()) {
  5366. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5367. << var->getType();
  5368. return true;
  5369. }
  5370. }
  5371. return false;
  5372. }
  5373. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5374. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5375. // the wrong linkage.
  5376. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5377. // 'weak' only applies to declarations with external linkage.
  5378. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5379. if (!ND.isExternallyVisible()) {
  5380. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5381. ND.dropAttr<WeakAttr>();
  5382. }
  5383. }
  5384. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5385. if (ND.isExternallyVisible()) {
  5386. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5387. ND.dropAttr<WeakRefAttr>();
  5388. ND.dropAttr<AliasAttr>();
  5389. }
  5390. }
  5391. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5392. if (VD->hasInit()) {
  5393. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5394. assert(VD->isThisDeclarationADefinition() &&
  5395. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5396. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5397. VD->dropAttr<AliasAttr>();
  5398. }
  5399. }
  5400. }
  5401. // 'selectany' only applies to externally visible variable declarations.
  5402. // It does not apply to functions.
  5403. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5404. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5405. S.Diag(Attr->getLocation(),
  5406. diag::err_attribute_selectany_non_extern_data);
  5407. ND.dropAttr<SelectAnyAttr>();
  5408. }
  5409. }
  5410. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5411. auto *VD = dyn_cast<VarDecl>(&ND);
  5412. bool IsAnonymousNS = false;
  5413. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5414. if (VD) {
  5415. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5416. while (NS && !IsAnonymousNS) {
  5417. IsAnonymousNS = NS->isAnonymousNamespace();
  5418. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5419. }
  5420. }
  5421. // dll attributes require external linkage. Static locals may have external
  5422. // linkage but still cannot be explicitly imported or exported.
  5423. // In Microsoft mode, a variable defined in anonymous namespace must have
  5424. // external linkage in order to be exported.
  5425. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5426. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5427. (!AnonNSInMicrosoftMode &&
  5428. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5429. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5430. << &ND << Attr;
  5431. ND.setInvalidDecl();
  5432. }
  5433. }
  5434. // Virtual functions cannot be marked as 'notail'.
  5435. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5436. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5437. if (MD->isVirtual()) {
  5438. S.Diag(ND.getLocation(),
  5439. diag::err_invalid_attribute_on_virtual_function)
  5440. << Attr;
  5441. ND.dropAttr<NotTailCalledAttr>();
  5442. }
  5443. // Check the attributes on the function type, if any.
  5444. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5445. // Don't declare this variable in the second operand of the for-statement;
  5446. // GCC miscompiles that by ending its lifetime before evaluating the
  5447. // third operand. See gcc.gnu.org/PR86769.
  5448. AttributedTypeLoc ATL;
  5449. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5450. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5451. TL = ATL.getModifiedLoc()) {
  5452. // The [[lifetimebound]] attribute can be applied to the implicit object
  5453. // parameter of a non-static member function (other than a ctor or dtor)
  5454. // by applying it to the function type.
  5455. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5456. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5457. if (!MD || MD->isStatic()) {
  5458. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5459. << !MD << A->getRange();
  5460. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5461. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5462. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5463. }
  5464. }
  5465. }
  5466. }
  5467. }
  5468. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5469. NamedDecl *NewDecl,
  5470. bool IsSpecialization,
  5471. bool IsDefinition) {
  5472. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5473. return;
  5474. bool IsTemplate = false;
  5475. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5476. OldDecl = OldTD->getTemplatedDecl();
  5477. IsTemplate = true;
  5478. if (!IsSpecialization)
  5479. IsDefinition = false;
  5480. }
  5481. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5482. NewDecl = NewTD->getTemplatedDecl();
  5483. IsTemplate = true;
  5484. }
  5485. if (!OldDecl || !NewDecl)
  5486. return;
  5487. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5488. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5489. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5490. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5491. // dllimport and dllexport are inheritable attributes so we have to exclude
  5492. // inherited attribute instances.
  5493. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5494. (NewExportAttr && !NewExportAttr->isInherited());
  5495. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5496. // the only exception being explicit specializations.
  5497. // Implicitly generated declarations are also excluded for now because there
  5498. // is no other way to switch these to use dllimport or dllexport.
  5499. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5500. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5501. // Allow with a warning for free functions and global variables.
  5502. bool JustWarn = false;
  5503. if (!OldDecl->isCXXClassMember()) {
  5504. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5505. if (VD && !VD->getDescribedVarTemplate())
  5506. JustWarn = true;
  5507. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5508. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5509. JustWarn = true;
  5510. }
  5511. // We cannot change a declaration that's been used because IR has already
  5512. // been emitted. Dllimported functions will still work though (modulo
  5513. // address equality) as they can use the thunk.
  5514. if (OldDecl->isUsed())
  5515. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5516. JustWarn = false;
  5517. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5518. : diag::err_attribute_dll_redeclaration;
  5519. S.Diag(NewDecl->getLocation(), DiagID)
  5520. << NewDecl
  5521. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5522. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5523. if (!JustWarn) {
  5524. NewDecl->setInvalidDecl();
  5525. return;
  5526. }
  5527. }
  5528. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5529. // exceptions being inline function definitions (except for function
  5530. // templates), local extern declarations, qualified friend declarations or
  5531. // special MSVC extension: in the last case, the declaration is treated as if
  5532. // it were marked dllexport.
  5533. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5534. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5535. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5536. // Ignore static data because out-of-line definitions are diagnosed
  5537. // separately.
  5538. IsStaticDataMember = VD->isStaticDataMember();
  5539. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5540. VarDecl::DeclarationOnly;
  5541. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5542. IsInline = FD->isInlined();
  5543. IsQualifiedFriend = FD->getQualifier() &&
  5544. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5545. }
  5546. if (OldImportAttr && !HasNewAttr &&
  5547. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5548. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5549. if (IsMicrosoft && IsDefinition) {
  5550. S.Diag(NewDecl->getLocation(),
  5551. diag::warn_redeclaration_without_import_attribute)
  5552. << NewDecl;
  5553. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5554. NewDecl->dropAttr<DLLImportAttr>();
  5555. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5556. NewImportAttr->getRange(), S.Context,
  5557. NewImportAttr->getSpellingListIndex()));
  5558. } else {
  5559. S.Diag(NewDecl->getLocation(),
  5560. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5561. << NewDecl << OldImportAttr;
  5562. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5563. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5564. OldDecl->dropAttr<DLLImportAttr>();
  5565. NewDecl->dropAttr<DLLImportAttr>();
  5566. }
  5567. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5568. // In MinGW, seeing a function declared inline drops the dllimport
  5569. // attribute.
  5570. OldDecl->dropAttr<DLLImportAttr>();
  5571. NewDecl->dropAttr<DLLImportAttr>();
  5572. S.Diag(NewDecl->getLocation(),
  5573. diag::warn_dllimport_dropped_from_inline_function)
  5574. << NewDecl << OldImportAttr;
  5575. }
  5576. // A specialization of a class template member function is processed here
  5577. // since it's a redeclaration. If the parent class is dllexport, the
  5578. // specialization inherits that attribute. This doesn't happen automatically
  5579. // since the parent class isn't instantiated until later.
  5580. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5581. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5582. !NewImportAttr && !NewExportAttr) {
  5583. if (const DLLExportAttr *ParentExportAttr =
  5584. MD->getParent()->getAttr<DLLExportAttr>()) {
  5585. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5586. NewAttr->setInherited(true);
  5587. NewDecl->addAttr(NewAttr);
  5588. }
  5589. }
  5590. }
  5591. }
  5592. /// Given that we are within the definition of the given function,
  5593. /// will that definition behave like C99's 'inline', where the
  5594. /// definition is discarded except for optimization purposes?
  5595. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5596. // Try to avoid calling GetGVALinkageForFunction.
  5597. // All cases of this require the 'inline' keyword.
  5598. if (!FD->isInlined()) return false;
  5599. // This is only possible in C++ with the gnu_inline attribute.
  5600. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5601. return false;
  5602. // Okay, go ahead and call the relatively-more-expensive function.
  5603. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5604. }
  5605. /// Determine whether a variable is extern "C" prior to attaching
  5606. /// an initializer. We can't just call isExternC() here, because that
  5607. /// will also compute and cache whether the declaration is externally
  5608. /// visible, which might change when we attach the initializer.
  5609. ///
  5610. /// This can only be used if the declaration is known to not be a
  5611. /// redeclaration of an internal linkage declaration.
  5612. ///
  5613. /// For instance:
  5614. ///
  5615. /// auto x = []{};
  5616. ///
  5617. /// Attaching the initializer here makes this declaration not externally
  5618. /// visible, because its type has internal linkage.
  5619. ///
  5620. /// FIXME: This is a hack.
  5621. template<typename T>
  5622. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5623. if (S.getLangOpts().CPlusPlus) {
  5624. // In C++, the overloadable attribute negates the effects of extern "C".
  5625. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5626. return false;
  5627. // So do CUDA's host/device attributes.
  5628. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5629. D->template hasAttr<CUDAHostAttr>()))
  5630. return false;
  5631. }
  5632. return D->isExternC();
  5633. }
  5634. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5635. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5636. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5637. isa<OMPDeclareMapperDecl>(DC))
  5638. return VD->hasExternalStorage();
  5639. if (DC->isFileContext())
  5640. return true;
  5641. if (DC->isRecord())
  5642. return false;
  5643. llvm_unreachable("Unexpected context");
  5644. }
  5645. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5646. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5647. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5648. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5649. return true;
  5650. if (DC->isRecord())
  5651. return false;
  5652. llvm_unreachable("Unexpected context");
  5653. }
  5654. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5655. ParsedAttr::Kind Kind) {
  5656. // Check decl attributes on the DeclSpec.
  5657. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5658. return true;
  5659. // Walk the declarator structure, checking decl attributes that were in a type
  5660. // position to the decl itself.
  5661. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5662. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5663. return true;
  5664. }
  5665. // Finally, check attributes on the decl itself.
  5666. return PD.getAttributes().hasAttribute(Kind);
  5667. }
  5668. /// Adjust the \c DeclContext for a function or variable that might be a
  5669. /// function-local external declaration.
  5670. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5671. if (!DC->isFunctionOrMethod())
  5672. return false;
  5673. // If this is a local extern function or variable declared within a function
  5674. // template, don't add it into the enclosing namespace scope until it is
  5675. // instantiated; it might have a dependent type right now.
  5676. if (DC->isDependentContext())
  5677. return true;
  5678. // C++11 [basic.link]p7:
  5679. // When a block scope declaration of an entity with linkage is not found to
  5680. // refer to some other declaration, then that entity is a member of the
  5681. // innermost enclosing namespace.
  5682. //
  5683. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5684. // semantically-enclosing namespace, not a lexically-enclosing one.
  5685. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5686. DC = DC->getParent();
  5687. return true;
  5688. }
  5689. /// Returns true if given declaration has external C language linkage.
  5690. static bool isDeclExternC(const Decl *D) {
  5691. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5692. return FD->isExternC();
  5693. if (const auto *VD = dyn_cast<VarDecl>(D))
  5694. return VD->isExternC();
  5695. llvm_unreachable("Unknown type of decl!");
  5696. }
  5697. NamedDecl *Sema::ActOnVariableDeclarator(
  5698. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5699. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5700. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5701. QualType R = TInfo->getType();
  5702. DeclarationName Name = GetNameForDeclarator(D).getName();
  5703. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5704. if (D.isDecompositionDeclarator()) {
  5705. // Take the name of the first declarator as our name for diagnostic
  5706. // purposes.
  5707. auto &Decomp = D.getDecompositionDeclarator();
  5708. if (!Decomp.bindings().empty()) {
  5709. II = Decomp.bindings()[0].Name;
  5710. Name = II;
  5711. }
  5712. } else if (!II) {
  5713. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5714. return nullptr;
  5715. }
  5716. if (getLangOpts().OpenCL) {
  5717. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5718. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5719. // argument.
  5720. if (R->isImageType() || R->isPipeType()) {
  5721. Diag(D.getIdentifierLoc(),
  5722. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5723. << R;
  5724. D.setInvalidType();
  5725. return nullptr;
  5726. }
  5727. // OpenCL v1.2 s6.9.r:
  5728. // The event type cannot be used to declare a program scope variable.
  5729. // OpenCL v2.0 s6.9.q:
  5730. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5731. if (NULL == S->getParent()) {
  5732. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5733. Diag(D.getIdentifierLoc(),
  5734. diag::err_invalid_type_for_program_scope_var) << R;
  5735. D.setInvalidType();
  5736. return nullptr;
  5737. }
  5738. }
  5739. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5740. QualType NR = R;
  5741. while (NR->isPointerType()) {
  5742. if (NR->isFunctionPointerType()) {
  5743. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5744. D.setInvalidType();
  5745. break;
  5746. }
  5747. NR = NR->getPointeeType();
  5748. }
  5749. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5750. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5751. // half array type (unless the cl_khr_fp16 extension is enabled).
  5752. if (Context.getBaseElementType(R)->isHalfType()) {
  5753. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5754. D.setInvalidType();
  5755. }
  5756. }
  5757. if (R->isSamplerT()) {
  5758. // OpenCL v1.2 s6.9.b p4:
  5759. // The sampler type cannot be used with the __local and __global address
  5760. // space qualifiers.
  5761. if (R.getAddressSpace() == LangAS::opencl_local ||
  5762. R.getAddressSpace() == LangAS::opencl_global) {
  5763. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5764. }
  5765. // OpenCL v1.2 s6.12.14.1:
  5766. // A global sampler must be declared with either the constant address
  5767. // space qualifier or with the const qualifier.
  5768. if (DC->isTranslationUnit() &&
  5769. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5770. R.isConstQualified())) {
  5771. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5772. D.setInvalidType();
  5773. }
  5774. }
  5775. // OpenCL v1.2 s6.9.r:
  5776. // The event type cannot be used with the __local, __constant and __global
  5777. // address space qualifiers.
  5778. if (R->isEventT()) {
  5779. if (R.getAddressSpace() != LangAS::opencl_private) {
  5780. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5781. D.setInvalidType();
  5782. }
  5783. }
  5784. // C++ for OpenCL does not allow the thread_local storage qualifier.
  5785. // OpenCL C does not support thread_local either, and
  5786. // also reject all other thread storage class specifiers.
  5787. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5788. if (TSC != TSCS_unspecified) {
  5789. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5790. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5791. diag::err_opencl_unknown_type_specifier)
  5792. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5793. << DeclSpec::getSpecifierName(TSC) << 1;
  5794. D.setInvalidType();
  5795. return nullptr;
  5796. }
  5797. }
  5798. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5799. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5800. // dllimport globals without explicit storage class are treated as extern. We
  5801. // have to change the storage class this early to get the right DeclContext.
  5802. if (SC == SC_None && !DC->isRecord() &&
  5803. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5804. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5805. SC = SC_Extern;
  5806. DeclContext *OriginalDC = DC;
  5807. bool IsLocalExternDecl = SC == SC_Extern &&
  5808. adjustContextForLocalExternDecl(DC);
  5809. if (SCSpec == DeclSpec::SCS_mutable) {
  5810. // mutable can only appear on non-static class members, so it's always
  5811. // an error here
  5812. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5813. D.setInvalidType();
  5814. SC = SC_None;
  5815. }
  5816. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5817. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5818. D.getDeclSpec().getStorageClassSpecLoc())) {
  5819. // In C++11, the 'register' storage class specifier is deprecated.
  5820. // Suppress the warning in system macros, it's used in macros in some
  5821. // popular C system headers, such as in glibc's htonl() macro.
  5822. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5823. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5824. : diag::warn_deprecated_register)
  5825. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5826. }
  5827. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5828. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5829. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5830. // appear in the declaration specifiers in an external declaration.
  5831. // Global Register+Asm is a GNU extension we support.
  5832. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5833. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5834. D.setInvalidType();
  5835. }
  5836. }
  5837. bool IsMemberSpecialization = false;
  5838. bool IsVariableTemplateSpecialization = false;
  5839. bool IsPartialSpecialization = false;
  5840. bool IsVariableTemplate = false;
  5841. VarDecl *NewVD = nullptr;
  5842. VarTemplateDecl *NewTemplate = nullptr;
  5843. TemplateParameterList *TemplateParams = nullptr;
  5844. if (!getLangOpts().CPlusPlus) {
  5845. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5846. II, R, TInfo, SC);
  5847. if (R->getContainedDeducedType())
  5848. ParsingInitForAutoVars.insert(NewVD);
  5849. if (D.isInvalidType())
  5850. NewVD->setInvalidDecl();
  5851. } else {
  5852. bool Invalid = false;
  5853. if (DC->isRecord() && !CurContext->isRecord()) {
  5854. // This is an out-of-line definition of a static data member.
  5855. switch (SC) {
  5856. case SC_None:
  5857. break;
  5858. case SC_Static:
  5859. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5860. diag::err_static_out_of_line)
  5861. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5862. break;
  5863. case SC_Auto:
  5864. case SC_Register:
  5865. case SC_Extern:
  5866. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5867. // to names of variables declared in a block or to function parameters.
  5868. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5869. // of class members
  5870. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5871. diag::err_storage_class_for_static_member)
  5872. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5873. break;
  5874. case SC_PrivateExtern:
  5875. llvm_unreachable("C storage class in c++!");
  5876. }
  5877. }
  5878. if (SC == SC_Static && CurContext->isRecord()) {
  5879. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5880. if (RD->isLocalClass())
  5881. Diag(D.getIdentifierLoc(),
  5882. diag::err_static_data_member_not_allowed_in_local_class)
  5883. << Name << RD->getDeclName();
  5884. // C++98 [class.union]p1: If a union contains a static data member,
  5885. // the program is ill-formed. C++11 drops this restriction.
  5886. if (RD->isUnion())
  5887. Diag(D.getIdentifierLoc(),
  5888. getLangOpts().CPlusPlus11
  5889. ? diag::warn_cxx98_compat_static_data_member_in_union
  5890. : diag::ext_static_data_member_in_union) << Name;
  5891. // We conservatively disallow static data members in anonymous structs.
  5892. else if (!RD->getDeclName())
  5893. Diag(D.getIdentifierLoc(),
  5894. diag::err_static_data_member_not_allowed_in_anon_struct)
  5895. << Name << RD->isUnion();
  5896. }
  5897. }
  5898. // Match up the template parameter lists with the scope specifier, then
  5899. // determine whether we have a template or a template specialization.
  5900. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5901. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5902. D.getCXXScopeSpec(),
  5903. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5904. ? D.getName().TemplateId
  5905. : nullptr,
  5906. TemplateParamLists,
  5907. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5908. if (TemplateParams) {
  5909. if (!TemplateParams->size() &&
  5910. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5911. // There is an extraneous 'template<>' for this variable. Complain
  5912. // about it, but allow the declaration of the variable.
  5913. Diag(TemplateParams->getTemplateLoc(),
  5914. diag::err_template_variable_noparams)
  5915. << II
  5916. << SourceRange(TemplateParams->getTemplateLoc(),
  5917. TemplateParams->getRAngleLoc());
  5918. TemplateParams = nullptr;
  5919. } else {
  5920. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5921. // This is an explicit specialization or a partial specialization.
  5922. // FIXME: Check that we can declare a specialization here.
  5923. IsVariableTemplateSpecialization = true;
  5924. IsPartialSpecialization = TemplateParams->size() > 0;
  5925. } else { // if (TemplateParams->size() > 0)
  5926. // This is a template declaration.
  5927. IsVariableTemplate = true;
  5928. // Check that we can declare a template here.
  5929. if (CheckTemplateDeclScope(S, TemplateParams))
  5930. return nullptr;
  5931. // Only C++1y supports variable templates (N3651).
  5932. Diag(D.getIdentifierLoc(),
  5933. getLangOpts().CPlusPlus14
  5934. ? diag::warn_cxx11_compat_variable_template
  5935. : diag::ext_variable_template);
  5936. }
  5937. }
  5938. } else {
  5939. assert((Invalid ||
  5940. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5941. "should have a 'template<>' for this decl");
  5942. }
  5943. if (IsVariableTemplateSpecialization) {
  5944. SourceLocation TemplateKWLoc =
  5945. TemplateParamLists.size() > 0
  5946. ? TemplateParamLists[0]->getTemplateLoc()
  5947. : SourceLocation();
  5948. DeclResult Res = ActOnVarTemplateSpecialization(
  5949. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5950. IsPartialSpecialization);
  5951. if (Res.isInvalid())
  5952. return nullptr;
  5953. NewVD = cast<VarDecl>(Res.get());
  5954. AddToScope = false;
  5955. } else if (D.isDecompositionDeclarator()) {
  5956. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5957. D.getIdentifierLoc(), R, TInfo, SC,
  5958. Bindings);
  5959. } else
  5960. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5961. D.getIdentifierLoc(), II, R, TInfo, SC);
  5962. // If this is supposed to be a variable template, create it as such.
  5963. if (IsVariableTemplate) {
  5964. NewTemplate =
  5965. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5966. TemplateParams, NewVD);
  5967. NewVD->setDescribedVarTemplate(NewTemplate);
  5968. }
  5969. // If this decl has an auto type in need of deduction, make a note of the
  5970. // Decl so we can diagnose uses of it in its own initializer.
  5971. if (R->getContainedDeducedType())
  5972. ParsingInitForAutoVars.insert(NewVD);
  5973. if (D.isInvalidType() || Invalid) {
  5974. NewVD->setInvalidDecl();
  5975. if (NewTemplate)
  5976. NewTemplate->setInvalidDecl();
  5977. }
  5978. SetNestedNameSpecifier(*this, NewVD, D);
  5979. // If we have any template parameter lists that don't directly belong to
  5980. // the variable (matching the scope specifier), store them.
  5981. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5982. if (TemplateParamLists.size() > VDTemplateParamLists)
  5983. NewVD->setTemplateParameterListsInfo(
  5984. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5985. }
  5986. if (D.getDeclSpec().isInlineSpecified()) {
  5987. if (!getLangOpts().CPlusPlus) {
  5988. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5989. << 0;
  5990. } else if (CurContext->isFunctionOrMethod()) {
  5991. // 'inline' is not allowed on block scope variable declaration.
  5992. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5993. diag::err_inline_declaration_block_scope) << Name
  5994. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5995. } else {
  5996. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5997. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5998. : diag::ext_inline_variable);
  5999. NewVD->setInlineSpecified();
  6000. }
  6001. }
  6002. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6003. // lexical context will be different from the semantic context.
  6004. NewVD->setLexicalDeclContext(CurContext);
  6005. if (NewTemplate)
  6006. NewTemplate->setLexicalDeclContext(CurContext);
  6007. if (IsLocalExternDecl) {
  6008. if (D.isDecompositionDeclarator())
  6009. for (auto *B : Bindings)
  6010. B->setLocalExternDecl();
  6011. else
  6012. NewVD->setLocalExternDecl();
  6013. }
  6014. bool EmitTLSUnsupportedError = false;
  6015. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6016. // C++11 [dcl.stc]p4:
  6017. // When thread_local is applied to a variable of block scope the
  6018. // storage-class-specifier static is implied if it does not appear
  6019. // explicitly.
  6020. // Core issue: 'static' is not implied if the variable is declared
  6021. // 'extern'.
  6022. if (NewVD->hasLocalStorage() &&
  6023. (SCSpec != DeclSpec::SCS_unspecified ||
  6024. TSCS != DeclSpec::TSCS_thread_local ||
  6025. !DC->isFunctionOrMethod()))
  6026. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6027. diag::err_thread_non_global)
  6028. << DeclSpec::getSpecifierName(TSCS);
  6029. else if (!Context.getTargetInfo().isTLSSupported()) {
  6030. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6031. // Postpone error emission until we've collected attributes required to
  6032. // figure out whether it's a host or device variable and whether the
  6033. // error should be ignored.
  6034. EmitTLSUnsupportedError = true;
  6035. // We still need to mark the variable as TLS so it shows up in AST with
  6036. // proper storage class for other tools to use even if we're not going
  6037. // to emit any code for it.
  6038. NewVD->setTSCSpec(TSCS);
  6039. } else
  6040. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6041. diag::err_thread_unsupported);
  6042. } else
  6043. NewVD->setTSCSpec(TSCS);
  6044. }
  6045. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6046. case CSK_unspecified:
  6047. break;
  6048. case CSK_consteval:
  6049. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6050. diag::err_constexpr_wrong_decl_kind)
  6051. << D.getDeclSpec().getConstexprSpecifier();
  6052. LLVM_FALLTHROUGH;
  6053. case CSK_constexpr:
  6054. NewVD->setConstexpr(true);
  6055. // C++1z [dcl.spec.constexpr]p1:
  6056. // A static data member declared with the constexpr specifier is
  6057. // implicitly an inline variable.
  6058. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  6059. NewVD->setImplicitlyInline();
  6060. break;
  6061. case CSK_constinit:
  6062. if (!NewVD->hasGlobalStorage())
  6063. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6064. diag::err_constinit_local_variable);
  6065. else
  6066. NewVD->addAttr(::new (Context) ConstInitAttr(
  6067. SourceRange(D.getDeclSpec().getConstexprSpecLoc()), Context,
  6068. ConstInitAttr::Keyword_constinit));
  6069. break;
  6070. }
  6071. // C99 6.7.4p3
  6072. // An inline definition of a function with external linkage shall
  6073. // not contain a definition of a modifiable object with static or
  6074. // thread storage duration...
  6075. // We only apply this when the function is required to be defined
  6076. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6077. // that a local variable with thread storage duration still has to
  6078. // be marked 'static'. Also note that it's possible to get these
  6079. // semantics in C++ using __attribute__((gnu_inline)).
  6080. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6081. !NewVD->getType().isConstQualified()) {
  6082. FunctionDecl *CurFD = getCurFunctionDecl();
  6083. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6084. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6085. diag::warn_static_local_in_extern_inline);
  6086. MaybeSuggestAddingStaticToDecl(CurFD);
  6087. }
  6088. }
  6089. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6090. if (IsVariableTemplateSpecialization)
  6091. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6092. << (IsPartialSpecialization ? 1 : 0)
  6093. << FixItHint::CreateRemoval(
  6094. D.getDeclSpec().getModulePrivateSpecLoc());
  6095. else if (IsMemberSpecialization)
  6096. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6097. << 2
  6098. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6099. else if (NewVD->hasLocalStorage())
  6100. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6101. << 0 << NewVD->getDeclName()
  6102. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6103. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6104. else {
  6105. NewVD->setModulePrivate();
  6106. if (NewTemplate)
  6107. NewTemplate->setModulePrivate();
  6108. for (auto *B : Bindings)
  6109. B->setModulePrivate();
  6110. }
  6111. }
  6112. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6113. ProcessDeclAttributes(S, NewVD, D);
  6114. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6115. if (EmitTLSUnsupportedError &&
  6116. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6117. (getLangOpts().OpenMPIsDevice &&
  6118. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6119. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6120. diag::err_thread_unsupported);
  6121. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6122. // storage [duration]."
  6123. if (SC == SC_None && S->getFnParent() != nullptr &&
  6124. (NewVD->hasAttr<CUDASharedAttr>() ||
  6125. NewVD->hasAttr<CUDAConstantAttr>())) {
  6126. NewVD->setStorageClass(SC_Static);
  6127. }
  6128. }
  6129. // Ensure that dllimport globals without explicit storage class are treated as
  6130. // extern. The storage class is set above using parsed attributes. Now we can
  6131. // check the VarDecl itself.
  6132. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6133. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6134. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6135. // In auto-retain/release, infer strong retension for variables of
  6136. // retainable type.
  6137. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6138. NewVD->setInvalidDecl();
  6139. // Handle GNU asm-label extension (encoded as an attribute).
  6140. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6141. // The parser guarantees this is a string.
  6142. StringLiteral *SE = cast<StringLiteral>(E);
  6143. StringRef Label = SE->getString();
  6144. if (S->getFnParent() != nullptr) {
  6145. switch (SC) {
  6146. case SC_None:
  6147. case SC_Auto:
  6148. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6149. break;
  6150. case SC_Register:
  6151. // Local Named register
  6152. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6153. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6154. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6155. break;
  6156. case SC_Static:
  6157. case SC_Extern:
  6158. case SC_PrivateExtern:
  6159. break;
  6160. }
  6161. } else if (SC == SC_Register) {
  6162. // Global Named register
  6163. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6164. const auto &TI = Context.getTargetInfo();
  6165. bool HasSizeMismatch;
  6166. if (!TI.isValidGCCRegisterName(Label))
  6167. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6168. else if (!TI.validateGlobalRegisterVariable(Label,
  6169. Context.getTypeSize(R),
  6170. HasSizeMismatch))
  6171. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6172. else if (HasSizeMismatch)
  6173. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6174. }
  6175. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6176. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6177. NewVD->setInvalidDecl(true);
  6178. }
  6179. }
  6180. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6181. Context, Label, 0));
  6182. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6183. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6184. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6185. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6186. if (isDeclExternC(NewVD)) {
  6187. NewVD->addAttr(I->second);
  6188. ExtnameUndeclaredIdentifiers.erase(I);
  6189. } else
  6190. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6191. << /*Variable*/1 << NewVD;
  6192. }
  6193. }
  6194. // Find the shadowed declaration before filtering for scope.
  6195. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6196. ? getShadowedDeclaration(NewVD, Previous)
  6197. : nullptr;
  6198. // Don't consider existing declarations that are in a different
  6199. // scope and are out-of-semantic-context declarations (if the new
  6200. // declaration has linkage).
  6201. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6202. D.getCXXScopeSpec().isNotEmpty() ||
  6203. IsMemberSpecialization ||
  6204. IsVariableTemplateSpecialization);
  6205. // Check whether the previous declaration is in the same block scope. This
  6206. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6207. if (getLangOpts().CPlusPlus &&
  6208. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6209. NewVD->setPreviousDeclInSameBlockScope(
  6210. Previous.isSingleResult() && !Previous.isShadowed() &&
  6211. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6212. if (!getLangOpts().CPlusPlus) {
  6213. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6214. } else {
  6215. // If this is an explicit specialization of a static data member, check it.
  6216. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6217. CheckMemberSpecialization(NewVD, Previous))
  6218. NewVD->setInvalidDecl();
  6219. // Merge the decl with the existing one if appropriate.
  6220. if (!Previous.empty()) {
  6221. if (Previous.isSingleResult() &&
  6222. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6223. D.getCXXScopeSpec().isSet()) {
  6224. // The user tried to define a non-static data member
  6225. // out-of-line (C++ [dcl.meaning]p1).
  6226. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6227. << D.getCXXScopeSpec().getRange();
  6228. Previous.clear();
  6229. NewVD->setInvalidDecl();
  6230. }
  6231. } else if (D.getCXXScopeSpec().isSet()) {
  6232. // No previous declaration in the qualifying scope.
  6233. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6234. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6235. << D.getCXXScopeSpec().getRange();
  6236. NewVD->setInvalidDecl();
  6237. }
  6238. if (!IsVariableTemplateSpecialization)
  6239. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6240. if (NewTemplate) {
  6241. VarTemplateDecl *PrevVarTemplate =
  6242. NewVD->getPreviousDecl()
  6243. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6244. : nullptr;
  6245. // Check the template parameter list of this declaration, possibly
  6246. // merging in the template parameter list from the previous variable
  6247. // template declaration.
  6248. if (CheckTemplateParameterList(
  6249. TemplateParams,
  6250. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6251. : nullptr,
  6252. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6253. DC->isDependentContext())
  6254. ? TPC_ClassTemplateMember
  6255. : TPC_VarTemplate))
  6256. NewVD->setInvalidDecl();
  6257. // If we are providing an explicit specialization of a static variable
  6258. // template, make a note of that.
  6259. if (PrevVarTemplate &&
  6260. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6261. PrevVarTemplate->setMemberSpecialization();
  6262. }
  6263. }
  6264. // Diagnose shadowed variables iff this isn't a redeclaration.
  6265. if (ShadowedDecl && !D.isRedeclaration())
  6266. CheckShadow(NewVD, ShadowedDecl, Previous);
  6267. ProcessPragmaWeak(S, NewVD);
  6268. // If this is the first declaration of an extern C variable, update
  6269. // the map of such variables.
  6270. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6271. isIncompleteDeclExternC(*this, NewVD))
  6272. RegisterLocallyScopedExternCDecl(NewVD, S);
  6273. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6274. Decl *ManglingContextDecl;
  6275. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6276. NewVD->getDeclContext(), ManglingContextDecl)) {
  6277. Context.setManglingNumber(
  6278. NewVD, MCtx->getManglingNumber(
  6279. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6280. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6281. }
  6282. }
  6283. // Special handling of variable named 'main'.
  6284. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6285. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6286. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6287. // C++ [basic.start.main]p3
  6288. // A program that declares a variable main at global scope is ill-formed.
  6289. if (getLangOpts().CPlusPlus)
  6290. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6291. // In C, and external-linkage variable named main results in undefined
  6292. // behavior.
  6293. else if (NewVD->hasExternalFormalLinkage())
  6294. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6295. }
  6296. if (D.isRedeclaration() && !Previous.empty()) {
  6297. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6298. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6299. D.isFunctionDefinition());
  6300. }
  6301. if (NewTemplate) {
  6302. if (NewVD->isInvalidDecl())
  6303. NewTemplate->setInvalidDecl();
  6304. ActOnDocumentableDecl(NewTemplate);
  6305. return NewTemplate;
  6306. }
  6307. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6308. CompleteMemberSpecialization(NewVD, Previous);
  6309. return NewVD;
  6310. }
  6311. /// Enum describing the %select options in diag::warn_decl_shadow.
  6312. enum ShadowedDeclKind {
  6313. SDK_Local,
  6314. SDK_Global,
  6315. SDK_StaticMember,
  6316. SDK_Field,
  6317. SDK_Typedef,
  6318. SDK_Using
  6319. };
  6320. /// Determine what kind of declaration we're shadowing.
  6321. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6322. const DeclContext *OldDC) {
  6323. if (isa<TypeAliasDecl>(ShadowedDecl))
  6324. return SDK_Using;
  6325. else if (isa<TypedefDecl>(ShadowedDecl))
  6326. return SDK_Typedef;
  6327. else if (isa<RecordDecl>(OldDC))
  6328. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6329. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6330. }
  6331. /// Return the location of the capture if the given lambda captures the given
  6332. /// variable \p VD, or an invalid source location otherwise.
  6333. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6334. const VarDecl *VD) {
  6335. for (const Capture &Capture : LSI->Captures) {
  6336. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6337. return Capture.getLocation();
  6338. }
  6339. return SourceLocation();
  6340. }
  6341. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6342. const LookupResult &R) {
  6343. // Only diagnose if we're shadowing an unambiguous field or variable.
  6344. if (R.getResultKind() != LookupResult::Found)
  6345. return false;
  6346. // Return false if warning is ignored.
  6347. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6348. }
  6349. /// Return the declaration shadowed by the given variable \p D, or null
  6350. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6351. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6352. const LookupResult &R) {
  6353. if (!shouldWarnIfShadowedDecl(Diags, R))
  6354. return nullptr;
  6355. // Don't diagnose declarations at file scope.
  6356. if (D->hasGlobalStorage())
  6357. return nullptr;
  6358. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6359. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6360. ? ShadowedDecl
  6361. : nullptr;
  6362. }
  6363. /// Return the declaration shadowed by the given typedef \p D, or null
  6364. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6365. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6366. const LookupResult &R) {
  6367. // Don't warn if typedef declaration is part of a class
  6368. if (D->getDeclContext()->isRecord())
  6369. return nullptr;
  6370. if (!shouldWarnIfShadowedDecl(Diags, R))
  6371. return nullptr;
  6372. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6373. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6374. }
  6375. /// Diagnose variable or built-in function shadowing. Implements
  6376. /// -Wshadow.
  6377. ///
  6378. /// This method is called whenever a VarDecl is added to a "useful"
  6379. /// scope.
  6380. ///
  6381. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6382. /// \param R the lookup of the name
  6383. ///
  6384. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6385. const LookupResult &R) {
  6386. DeclContext *NewDC = D->getDeclContext();
  6387. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6388. // Fields are not shadowed by variables in C++ static methods.
  6389. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6390. if (MD->isStatic())
  6391. return;
  6392. // Fields shadowed by constructor parameters are a special case. Usually
  6393. // the constructor initializes the field with the parameter.
  6394. if (isa<CXXConstructorDecl>(NewDC))
  6395. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6396. // Remember that this was shadowed so we can either warn about its
  6397. // modification or its existence depending on warning settings.
  6398. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6399. return;
  6400. }
  6401. }
  6402. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6403. if (shadowedVar->isExternC()) {
  6404. // For shadowing external vars, make sure that we point to the global
  6405. // declaration, not a locally scoped extern declaration.
  6406. for (auto I : shadowedVar->redecls())
  6407. if (I->isFileVarDecl()) {
  6408. ShadowedDecl = I;
  6409. break;
  6410. }
  6411. }
  6412. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6413. unsigned WarningDiag = diag::warn_decl_shadow;
  6414. SourceLocation CaptureLoc;
  6415. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6416. isa<CXXMethodDecl>(NewDC)) {
  6417. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6418. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6419. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6420. // Try to avoid warnings for lambdas with an explicit capture list.
  6421. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6422. // Warn only when the lambda captures the shadowed decl explicitly.
  6423. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6424. if (CaptureLoc.isInvalid())
  6425. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6426. } else {
  6427. // Remember that this was shadowed so we can avoid the warning if the
  6428. // shadowed decl isn't captured and the warning settings allow it.
  6429. cast<LambdaScopeInfo>(getCurFunction())
  6430. ->ShadowingDecls.push_back(
  6431. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6432. return;
  6433. }
  6434. }
  6435. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6436. // A variable can't shadow a local variable in an enclosing scope, if
  6437. // they are separated by a non-capturing declaration context.
  6438. for (DeclContext *ParentDC = NewDC;
  6439. ParentDC && !ParentDC->Equals(OldDC);
  6440. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6441. // Only block literals, captured statements, and lambda expressions
  6442. // can capture; other scopes don't.
  6443. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6444. !isLambdaCallOperator(ParentDC)) {
  6445. return;
  6446. }
  6447. }
  6448. }
  6449. }
  6450. }
  6451. // Only warn about certain kinds of shadowing for class members.
  6452. if (NewDC && NewDC->isRecord()) {
  6453. // In particular, don't warn about shadowing non-class members.
  6454. if (!OldDC->isRecord())
  6455. return;
  6456. // TODO: should we warn about static data members shadowing
  6457. // static data members from base classes?
  6458. // TODO: don't diagnose for inaccessible shadowed members.
  6459. // This is hard to do perfectly because we might friend the
  6460. // shadowing context, but that's just a false negative.
  6461. }
  6462. DeclarationName Name = R.getLookupName();
  6463. // Emit warning and note.
  6464. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6465. return;
  6466. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6467. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6468. if (!CaptureLoc.isInvalid())
  6469. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6470. << Name << /*explicitly*/ 1;
  6471. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6472. }
  6473. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6474. /// when these variables are captured by the lambda.
  6475. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6476. for (const auto &Shadow : LSI->ShadowingDecls) {
  6477. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6478. // Try to avoid the warning when the shadowed decl isn't captured.
  6479. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6480. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6481. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6482. ? diag::warn_decl_shadow_uncaptured_local
  6483. : diag::warn_decl_shadow)
  6484. << Shadow.VD->getDeclName()
  6485. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6486. if (!CaptureLoc.isInvalid())
  6487. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6488. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6489. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6490. }
  6491. }
  6492. /// Check -Wshadow without the advantage of a previous lookup.
  6493. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6494. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6495. return;
  6496. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6497. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6498. LookupName(R, S);
  6499. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6500. CheckShadow(D, ShadowedDecl, R);
  6501. }
  6502. /// Check if 'E', which is an expression that is about to be modified, refers
  6503. /// to a constructor parameter that shadows a field.
  6504. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6505. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6506. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6507. return;
  6508. E = E->IgnoreParenImpCasts();
  6509. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6510. if (!DRE)
  6511. return;
  6512. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6513. auto I = ShadowingDecls.find(D);
  6514. if (I == ShadowingDecls.end())
  6515. return;
  6516. const NamedDecl *ShadowedDecl = I->second;
  6517. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6518. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6519. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6520. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6521. // Avoid issuing multiple warnings about the same decl.
  6522. ShadowingDecls.erase(I);
  6523. }
  6524. /// Check for conflict between this global or extern "C" declaration and
  6525. /// previous global or extern "C" declarations. This is only used in C++.
  6526. template<typename T>
  6527. static bool checkGlobalOrExternCConflict(
  6528. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6529. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6530. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6531. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6532. // The common case: this global doesn't conflict with any extern "C"
  6533. // declaration.
  6534. return false;
  6535. }
  6536. if (Prev) {
  6537. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6538. // Both the old and new declarations have C language linkage. This is a
  6539. // redeclaration.
  6540. Previous.clear();
  6541. Previous.addDecl(Prev);
  6542. return true;
  6543. }
  6544. // This is a global, non-extern "C" declaration, and there is a previous
  6545. // non-global extern "C" declaration. Diagnose if this is a variable
  6546. // declaration.
  6547. if (!isa<VarDecl>(ND))
  6548. return false;
  6549. } else {
  6550. // The declaration is extern "C". Check for any declaration in the
  6551. // translation unit which might conflict.
  6552. if (IsGlobal) {
  6553. // We have already performed the lookup into the translation unit.
  6554. IsGlobal = false;
  6555. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6556. I != E; ++I) {
  6557. if (isa<VarDecl>(*I)) {
  6558. Prev = *I;
  6559. break;
  6560. }
  6561. }
  6562. } else {
  6563. DeclContext::lookup_result R =
  6564. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6565. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6566. I != E; ++I) {
  6567. if (isa<VarDecl>(*I)) {
  6568. Prev = *I;
  6569. break;
  6570. }
  6571. // FIXME: If we have any other entity with this name in global scope,
  6572. // the declaration is ill-formed, but that is a defect: it breaks the
  6573. // 'stat' hack, for instance. Only variables can have mangled name
  6574. // clashes with extern "C" declarations, so only they deserve a
  6575. // diagnostic.
  6576. }
  6577. }
  6578. if (!Prev)
  6579. return false;
  6580. }
  6581. // Use the first declaration's location to ensure we point at something which
  6582. // is lexically inside an extern "C" linkage-spec.
  6583. assert(Prev && "should have found a previous declaration to diagnose");
  6584. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6585. Prev = FD->getFirstDecl();
  6586. else
  6587. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6588. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6589. << IsGlobal << ND;
  6590. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6591. << IsGlobal;
  6592. return false;
  6593. }
  6594. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6595. /// if we have found that this is a redeclaration of some prior entity.
  6596. ///
  6597. /// Per C++ [dcl.link]p6:
  6598. /// Two declarations [for a function or variable] with C language linkage
  6599. /// with the same name that appear in different scopes refer to the same
  6600. /// [entity]. An entity with C language linkage shall not be declared with
  6601. /// the same name as an entity in global scope.
  6602. template<typename T>
  6603. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6604. LookupResult &Previous) {
  6605. if (!S.getLangOpts().CPlusPlus) {
  6606. // In C, when declaring a global variable, look for a corresponding 'extern'
  6607. // variable declared in function scope. We don't need this in C++, because
  6608. // we find local extern decls in the surrounding file-scope DeclContext.
  6609. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6610. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6611. Previous.clear();
  6612. Previous.addDecl(Prev);
  6613. return true;
  6614. }
  6615. }
  6616. return false;
  6617. }
  6618. // A declaration in the translation unit can conflict with an extern "C"
  6619. // declaration.
  6620. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6621. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6622. // An extern "C" declaration can conflict with a declaration in the
  6623. // translation unit or can be a redeclaration of an extern "C" declaration
  6624. // in another scope.
  6625. if (isIncompleteDeclExternC(S,ND))
  6626. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6627. // Neither global nor extern "C": nothing to do.
  6628. return false;
  6629. }
  6630. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6631. // If the decl is already known invalid, don't check it.
  6632. if (NewVD->isInvalidDecl())
  6633. return;
  6634. QualType T = NewVD->getType();
  6635. // Defer checking an 'auto' type until its initializer is attached.
  6636. if (T->isUndeducedType())
  6637. return;
  6638. if (NewVD->hasAttrs())
  6639. CheckAlignasUnderalignment(NewVD);
  6640. if (T->isObjCObjectType()) {
  6641. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6642. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6643. T = Context.getObjCObjectPointerType(T);
  6644. NewVD->setType(T);
  6645. }
  6646. // Emit an error if an address space was applied to decl with local storage.
  6647. // This includes arrays of objects with address space qualifiers, but not
  6648. // automatic variables that point to other address spaces.
  6649. // ISO/IEC TR 18037 S5.1.2
  6650. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6651. T.getAddressSpace() != LangAS::Default) {
  6652. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6653. NewVD->setInvalidDecl();
  6654. return;
  6655. }
  6656. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6657. // scope.
  6658. if (getLangOpts().OpenCLVersion == 120 &&
  6659. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6660. NewVD->isStaticLocal()) {
  6661. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6662. NewVD->setInvalidDecl();
  6663. return;
  6664. }
  6665. if (getLangOpts().OpenCL) {
  6666. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6667. if (NewVD->hasAttr<BlocksAttr>()) {
  6668. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6669. return;
  6670. }
  6671. if (T->isBlockPointerType()) {
  6672. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6673. // can't use 'extern' storage class.
  6674. if (!T.isConstQualified()) {
  6675. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6676. << 0 /*const*/;
  6677. NewVD->setInvalidDecl();
  6678. return;
  6679. }
  6680. if (NewVD->hasExternalStorage()) {
  6681. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6682. NewVD->setInvalidDecl();
  6683. return;
  6684. }
  6685. }
  6686. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6687. // __constant address space.
  6688. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6689. // variables inside a function can also be declared in the global
  6690. // address space.
  6691. // C++ for OpenCL inherits rule from OpenCL C v2.0.
  6692. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  6693. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6694. NewVD->hasExternalStorage()) {
  6695. if (!T->isSamplerT() &&
  6696. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6697. (T.getAddressSpace() == LangAS::opencl_global &&
  6698. (getLangOpts().OpenCLVersion == 200 ||
  6699. getLangOpts().OpenCLCPlusPlus)))) {
  6700. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6701. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6702. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6703. << Scope << "global or constant";
  6704. else
  6705. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6706. << Scope << "constant";
  6707. NewVD->setInvalidDecl();
  6708. return;
  6709. }
  6710. } else {
  6711. if (T.getAddressSpace() == LangAS::opencl_global) {
  6712. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6713. << 1 /*is any function*/ << "global";
  6714. NewVD->setInvalidDecl();
  6715. return;
  6716. }
  6717. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6718. T.getAddressSpace() == LangAS::opencl_local) {
  6719. FunctionDecl *FD = getCurFunctionDecl();
  6720. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6721. // in functions.
  6722. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6723. if (T.getAddressSpace() == LangAS::opencl_constant)
  6724. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6725. << 0 /*non-kernel only*/ << "constant";
  6726. else
  6727. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6728. << 0 /*non-kernel only*/ << "local";
  6729. NewVD->setInvalidDecl();
  6730. return;
  6731. }
  6732. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6733. // in the outermost scope of a kernel function.
  6734. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6735. if (!getCurScope()->isFunctionScope()) {
  6736. if (T.getAddressSpace() == LangAS::opencl_constant)
  6737. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6738. << "constant";
  6739. else
  6740. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6741. << "local";
  6742. NewVD->setInvalidDecl();
  6743. return;
  6744. }
  6745. }
  6746. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  6747. // If we are parsing a template we didn't deduce an addr
  6748. // space yet.
  6749. T.getAddressSpace() != LangAS::Default) {
  6750. // Do not allow other address spaces on automatic variable.
  6751. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6752. NewVD->setInvalidDecl();
  6753. return;
  6754. }
  6755. }
  6756. }
  6757. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6758. && !NewVD->hasAttr<BlocksAttr>()) {
  6759. if (getLangOpts().getGC() != LangOptions::NonGC)
  6760. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6761. else {
  6762. assert(!getLangOpts().ObjCAutoRefCount);
  6763. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6764. }
  6765. }
  6766. bool isVM = T->isVariablyModifiedType();
  6767. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6768. NewVD->hasAttr<BlocksAttr>())
  6769. setFunctionHasBranchProtectedScope();
  6770. if ((isVM && NewVD->hasLinkage()) ||
  6771. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6772. bool SizeIsNegative;
  6773. llvm::APSInt Oversized;
  6774. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6775. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6776. QualType FixedT;
  6777. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6778. FixedT = FixedTInfo->getType();
  6779. else if (FixedTInfo) {
  6780. // Type and type-as-written are canonically different. We need to fix up
  6781. // both types separately.
  6782. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6783. Oversized);
  6784. }
  6785. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6786. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6787. // FIXME: This won't give the correct result for
  6788. // int a[10][n];
  6789. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6790. if (NewVD->isFileVarDecl())
  6791. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6792. << SizeRange;
  6793. else if (NewVD->isStaticLocal())
  6794. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6795. << SizeRange;
  6796. else
  6797. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6798. << SizeRange;
  6799. NewVD->setInvalidDecl();
  6800. return;
  6801. }
  6802. if (!FixedTInfo) {
  6803. if (NewVD->isFileVarDecl())
  6804. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6805. else
  6806. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6807. NewVD->setInvalidDecl();
  6808. return;
  6809. }
  6810. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6811. NewVD->setType(FixedT);
  6812. NewVD->setTypeSourceInfo(FixedTInfo);
  6813. }
  6814. if (T->isVoidType()) {
  6815. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6816. // of objects and functions.
  6817. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6818. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6819. << T;
  6820. NewVD->setInvalidDecl();
  6821. return;
  6822. }
  6823. }
  6824. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6825. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6826. NewVD->setInvalidDecl();
  6827. return;
  6828. }
  6829. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6830. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6831. NewVD->setInvalidDecl();
  6832. return;
  6833. }
  6834. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6835. RequireLiteralType(NewVD->getLocation(), T,
  6836. diag::err_constexpr_var_non_literal)) {
  6837. NewVD->setInvalidDecl();
  6838. return;
  6839. }
  6840. }
  6841. /// Perform semantic checking on a newly-created variable
  6842. /// declaration.
  6843. ///
  6844. /// This routine performs all of the type-checking required for a
  6845. /// variable declaration once it has been built. It is used both to
  6846. /// check variables after they have been parsed and their declarators
  6847. /// have been translated into a declaration, and to check variables
  6848. /// that have been instantiated from a template.
  6849. ///
  6850. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6851. ///
  6852. /// Returns true if the variable declaration is a redeclaration.
  6853. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6854. CheckVariableDeclarationType(NewVD);
  6855. // If the decl is already known invalid, don't check it.
  6856. if (NewVD->isInvalidDecl())
  6857. return false;
  6858. // If we did not find anything by this name, look for a non-visible
  6859. // extern "C" declaration with the same name.
  6860. if (Previous.empty() &&
  6861. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6862. Previous.setShadowed();
  6863. if (!Previous.empty()) {
  6864. MergeVarDecl(NewVD, Previous);
  6865. return true;
  6866. }
  6867. return false;
  6868. }
  6869. namespace {
  6870. struct FindOverriddenMethod {
  6871. Sema *S;
  6872. CXXMethodDecl *Method;
  6873. /// Member lookup function that determines whether a given C++
  6874. /// method overrides a method in a base class, to be used with
  6875. /// CXXRecordDecl::lookupInBases().
  6876. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6877. RecordDecl *BaseRecord =
  6878. Specifier->getType()->getAs<RecordType>()->getDecl();
  6879. DeclarationName Name = Method->getDeclName();
  6880. // FIXME: Do we care about other names here too?
  6881. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6882. // We really want to find the base class destructor here.
  6883. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6884. CanQualType CT = S->Context.getCanonicalType(T);
  6885. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6886. }
  6887. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6888. Path.Decls = Path.Decls.slice(1)) {
  6889. NamedDecl *D = Path.Decls.front();
  6890. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6891. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6892. return true;
  6893. }
  6894. }
  6895. return false;
  6896. }
  6897. };
  6898. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6899. } // end anonymous namespace
  6900. /// Report an error regarding overriding, along with any relevant
  6901. /// overridden methods.
  6902. ///
  6903. /// \param DiagID the primary error to report.
  6904. /// \param MD the overriding method.
  6905. /// \param OEK which overrides to include as notes.
  6906. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6907. OverrideErrorKind OEK = OEK_All) {
  6908. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6909. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6910. // This check (& the OEK parameter) could be replaced by a predicate, but
  6911. // without lambdas that would be overkill. This is still nicer than writing
  6912. // out the diag loop 3 times.
  6913. if ((OEK == OEK_All) ||
  6914. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6915. (OEK == OEK_Deleted && O->isDeleted()))
  6916. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6917. }
  6918. }
  6919. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6920. /// and if so, check that it's a valid override and remember it.
  6921. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6922. // Look for methods in base classes that this method might override.
  6923. CXXBasePaths Paths;
  6924. FindOverriddenMethod FOM;
  6925. FOM.Method = MD;
  6926. FOM.S = this;
  6927. bool hasDeletedOverridenMethods = false;
  6928. bool hasNonDeletedOverridenMethods = false;
  6929. bool AddedAny = false;
  6930. if (DC->lookupInBases(FOM, Paths)) {
  6931. for (auto *I : Paths.found_decls()) {
  6932. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6933. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6934. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6935. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6936. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6937. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6938. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6939. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6940. AddedAny = true;
  6941. }
  6942. }
  6943. }
  6944. }
  6945. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6946. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6947. }
  6948. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6949. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6950. }
  6951. return AddedAny;
  6952. }
  6953. namespace {
  6954. // Struct for holding all of the extra arguments needed by
  6955. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6956. struct ActOnFDArgs {
  6957. Scope *S;
  6958. Declarator &D;
  6959. MultiTemplateParamsArg TemplateParamLists;
  6960. bool AddToScope;
  6961. };
  6962. } // end anonymous namespace
  6963. namespace {
  6964. // Callback to only accept typo corrections that have a non-zero edit distance.
  6965. // Also only accept corrections that have the same parent decl.
  6966. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6967. public:
  6968. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6969. CXXRecordDecl *Parent)
  6970. : Context(Context), OriginalFD(TypoFD),
  6971. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6972. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6973. if (candidate.getEditDistance() == 0)
  6974. return false;
  6975. SmallVector<unsigned, 1> MismatchedParams;
  6976. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6977. CDeclEnd = candidate.end();
  6978. CDecl != CDeclEnd; ++CDecl) {
  6979. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6980. if (FD && !FD->hasBody() &&
  6981. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6982. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6983. CXXRecordDecl *Parent = MD->getParent();
  6984. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6985. return true;
  6986. } else if (!ExpectedParent) {
  6987. return true;
  6988. }
  6989. }
  6990. }
  6991. return false;
  6992. }
  6993. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  6994. return std::make_unique<DifferentNameValidatorCCC>(*this);
  6995. }
  6996. private:
  6997. ASTContext &Context;
  6998. FunctionDecl *OriginalFD;
  6999. CXXRecordDecl *ExpectedParent;
  7000. };
  7001. } // end anonymous namespace
  7002. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7003. TypoCorrectedFunctionDefinitions.insert(F);
  7004. }
  7005. /// Generate diagnostics for an invalid function redeclaration.
  7006. ///
  7007. /// This routine handles generating the diagnostic messages for an invalid
  7008. /// function redeclaration, including finding possible similar declarations
  7009. /// or performing typo correction if there are no previous declarations with
  7010. /// the same name.
  7011. ///
  7012. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7013. /// the new declaration name does not cause new errors.
  7014. static NamedDecl *DiagnoseInvalidRedeclaration(
  7015. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7016. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7017. DeclarationName Name = NewFD->getDeclName();
  7018. DeclContext *NewDC = NewFD->getDeclContext();
  7019. SmallVector<unsigned, 1> MismatchedParams;
  7020. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7021. TypoCorrection Correction;
  7022. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7023. unsigned DiagMsg =
  7024. IsLocalFriend ? diag::err_no_matching_local_friend :
  7025. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7026. diag::err_member_decl_does_not_match;
  7027. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7028. IsLocalFriend ? Sema::LookupLocalFriendName
  7029. : Sema::LookupOrdinaryName,
  7030. Sema::ForVisibleRedeclaration);
  7031. NewFD->setInvalidDecl();
  7032. if (IsLocalFriend)
  7033. SemaRef.LookupName(Prev, S);
  7034. else
  7035. SemaRef.LookupQualifiedName(Prev, NewDC);
  7036. assert(!Prev.isAmbiguous() &&
  7037. "Cannot have an ambiguity in previous-declaration lookup");
  7038. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7039. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7040. MD ? MD->getParent() : nullptr);
  7041. if (!Prev.empty()) {
  7042. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7043. Func != FuncEnd; ++Func) {
  7044. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7045. if (FD &&
  7046. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7047. // Add 1 to the index so that 0 can mean the mismatch didn't
  7048. // involve a parameter
  7049. unsigned ParamNum =
  7050. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7051. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7052. }
  7053. }
  7054. // If the qualified name lookup yielded nothing, try typo correction
  7055. } else if ((Correction = SemaRef.CorrectTypo(
  7056. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7057. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7058. IsLocalFriend ? nullptr : NewDC))) {
  7059. // Set up everything for the call to ActOnFunctionDeclarator
  7060. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7061. ExtraArgs.D.getIdentifierLoc());
  7062. Previous.clear();
  7063. Previous.setLookupName(Correction.getCorrection());
  7064. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7065. CDeclEnd = Correction.end();
  7066. CDecl != CDeclEnd; ++CDecl) {
  7067. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7068. if (FD && !FD->hasBody() &&
  7069. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7070. Previous.addDecl(FD);
  7071. }
  7072. }
  7073. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7074. NamedDecl *Result;
  7075. // Retry building the function declaration with the new previous
  7076. // declarations, and with errors suppressed.
  7077. {
  7078. // Trap errors.
  7079. Sema::SFINAETrap Trap(SemaRef);
  7080. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7081. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7082. // eliminate the need for the parameter pack ExtraArgs.
  7083. Result = SemaRef.ActOnFunctionDeclarator(
  7084. ExtraArgs.S, ExtraArgs.D,
  7085. Correction.getCorrectionDecl()->getDeclContext(),
  7086. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7087. ExtraArgs.AddToScope);
  7088. if (Trap.hasErrorOccurred())
  7089. Result = nullptr;
  7090. }
  7091. if (Result) {
  7092. // Determine which correction we picked.
  7093. Decl *Canonical = Result->getCanonicalDecl();
  7094. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7095. I != E; ++I)
  7096. if ((*I)->getCanonicalDecl() == Canonical)
  7097. Correction.setCorrectionDecl(*I);
  7098. // Let Sema know about the correction.
  7099. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7100. SemaRef.diagnoseTypo(
  7101. Correction,
  7102. SemaRef.PDiag(IsLocalFriend
  7103. ? diag::err_no_matching_local_friend_suggest
  7104. : diag::err_member_decl_does_not_match_suggest)
  7105. << Name << NewDC << IsDefinition);
  7106. return Result;
  7107. }
  7108. // Pretend the typo correction never occurred
  7109. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7110. ExtraArgs.D.getIdentifierLoc());
  7111. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7112. Previous.clear();
  7113. Previous.setLookupName(Name);
  7114. }
  7115. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7116. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7117. bool NewFDisConst = false;
  7118. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7119. NewFDisConst = NewMD->isConst();
  7120. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7121. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7122. NearMatch != NearMatchEnd; ++NearMatch) {
  7123. FunctionDecl *FD = NearMatch->first;
  7124. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7125. bool FDisConst = MD && MD->isConst();
  7126. bool IsMember = MD || !IsLocalFriend;
  7127. // FIXME: These notes are poorly worded for the local friend case.
  7128. if (unsigned Idx = NearMatch->second) {
  7129. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7130. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7131. if (Loc.isInvalid()) Loc = FD->getLocation();
  7132. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7133. : diag::note_local_decl_close_param_match)
  7134. << Idx << FDParam->getType()
  7135. << NewFD->getParamDecl(Idx - 1)->getType();
  7136. } else if (FDisConst != NewFDisConst) {
  7137. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7138. << NewFDisConst << FD->getSourceRange().getEnd();
  7139. } else
  7140. SemaRef.Diag(FD->getLocation(),
  7141. IsMember ? diag::note_member_def_close_match
  7142. : diag::note_local_decl_close_match);
  7143. }
  7144. return nullptr;
  7145. }
  7146. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7147. switch (D.getDeclSpec().getStorageClassSpec()) {
  7148. default: llvm_unreachable("Unknown storage class!");
  7149. case DeclSpec::SCS_auto:
  7150. case DeclSpec::SCS_register:
  7151. case DeclSpec::SCS_mutable:
  7152. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7153. diag::err_typecheck_sclass_func);
  7154. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7155. D.setInvalidType();
  7156. break;
  7157. case DeclSpec::SCS_unspecified: break;
  7158. case DeclSpec::SCS_extern:
  7159. if (D.getDeclSpec().isExternInLinkageSpec())
  7160. return SC_None;
  7161. return SC_Extern;
  7162. case DeclSpec::SCS_static: {
  7163. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7164. // C99 6.7.1p5:
  7165. // The declaration of an identifier for a function that has
  7166. // block scope shall have no explicit storage-class specifier
  7167. // other than extern
  7168. // See also (C++ [dcl.stc]p4).
  7169. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7170. diag::err_static_block_func);
  7171. break;
  7172. } else
  7173. return SC_Static;
  7174. }
  7175. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7176. }
  7177. // No explicit storage class has already been returned
  7178. return SC_None;
  7179. }
  7180. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7181. DeclContext *DC, QualType &R,
  7182. TypeSourceInfo *TInfo,
  7183. StorageClass SC,
  7184. bool &IsVirtualOkay) {
  7185. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7186. DeclarationName Name = NameInfo.getName();
  7187. FunctionDecl *NewFD = nullptr;
  7188. bool isInline = D.getDeclSpec().isInlineSpecified();
  7189. if (!SemaRef.getLangOpts().CPlusPlus) {
  7190. // Determine whether the function was written with a
  7191. // prototype. This true when:
  7192. // - there is a prototype in the declarator, or
  7193. // - the type R of the function is some kind of typedef or other non-
  7194. // attributed reference to a type name (which eventually refers to a
  7195. // function type).
  7196. bool HasPrototype =
  7197. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7198. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7199. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7200. R, TInfo, SC, isInline, HasPrototype,
  7201. CSK_unspecified);
  7202. if (D.isInvalidType())
  7203. NewFD->setInvalidDecl();
  7204. return NewFD;
  7205. }
  7206. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7207. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7208. if (ConstexprKind == CSK_constinit) {
  7209. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7210. diag::err_constexpr_wrong_decl_kind)
  7211. << ConstexprKind;
  7212. ConstexprKind = CSK_unspecified;
  7213. D.getMutableDeclSpec().ClearConstexprSpec();
  7214. }
  7215. // Check that the return type is not an abstract class type.
  7216. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7217. // the class has been completely parsed.
  7218. if (!DC->isRecord() &&
  7219. SemaRef.RequireNonAbstractType(
  7220. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7221. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7222. D.setInvalidType();
  7223. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7224. // This is a C++ constructor declaration.
  7225. assert(DC->isRecord() &&
  7226. "Constructors can only be declared in a member context");
  7227. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7228. return CXXConstructorDecl::Create(
  7229. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7230. TInfo, ExplicitSpecifier, isInline,
  7231. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7232. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7233. // This is a C++ destructor declaration.
  7234. if (DC->isRecord()) {
  7235. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7236. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7237. CXXDestructorDecl *NewDD =
  7238. CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
  7239. NameInfo, R, TInfo, isInline,
  7240. /*isImplicitlyDeclared=*/false);
  7241. // If the destructor needs an implicit exception specification, set it
  7242. // now. FIXME: It'd be nice to be able to create the right type to start
  7243. // with, but the type needs to reference the destructor declaration.
  7244. if (SemaRef.getLangOpts().CPlusPlus11)
  7245. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7246. IsVirtualOkay = true;
  7247. return NewDD;
  7248. } else {
  7249. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7250. D.setInvalidType();
  7251. // Create a FunctionDecl to satisfy the function definition parsing
  7252. // code path.
  7253. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7254. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7255. isInline,
  7256. /*hasPrototype=*/true, ConstexprKind);
  7257. }
  7258. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7259. if (!DC->isRecord()) {
  7260. SemaRef.Diag(D.getIdentifierLoc(),
  7261. diag::err_conv_function_not_member);
  7262. return nullptr;
  7263. }
  7264. SemaRef.CheckConversionDeclarator(D, R, SC);
  7265. IsVirtualOkay = true;
  7266. return CXXConversionDecl::Create(
  7267. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7268. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7269. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7270. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7271. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7272. ExplicitSpecifier, NameInfo, R, TInfo,
  7273. D.getEndLoc());
  7274. } else if (DC->isRecord()) {
  7275. // If the name of the function is the same as the name of the record,
  7276. // then this must be an invalid constructor that has a return type.
  7277. // (The parser checks for a return type and makes the declarator a
  7278. // constructor if it has no return type).
  7279. if (Name.getAsIdentifierInfo() &&
  7280. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7281. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7282. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7283. << SourceRange(D.getIdentifierLoc());
  7284. return nullptr;
  7285. }
  7286. // This is a C++ method declaration.
  7287. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7288. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7289. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7290. IsVirtualOkay = !Ret->isStatic();
  7291. return Ret;
  7292. } else {
  7293. bool isFriend =
  7294. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7295. if (!isFriend && SemaRef.CurContext->isRecord())
  7296. return nullptr;
  7297. // Determine whether the function was written with a
  7298. // prototype. This true when:
  7299. // - we're in C++ (where every function has a prototype),
  7300. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7301. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7302. ConstexprKind);
  7303. }
  7304. }
  7305. enum OpenCLParamType {
  7306. ValidKernelParam,
  7307. PtrPtrKernelParam,
  7308. PtrKernelParam,
  7309. InvalidAddrSpacePtrKernelParam,
  7310. InvalidKernelParam,
  7311. RecordKernelParam
  7312. };
  7313. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7314. // Size dependent types are just typedefs to normal integer types
  7315. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7316. // integers other than by their names.
  7317. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7318. // Remove typedefs one by one until we reach a typedef
  7319. // for a size dependent type.
  7320. QualType DesugaredTy = Ty;
  7321. do {
  7322. ArrayRef<StringRef> Names(SizeTypeNames);
  7323. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7324. if (Names.end() != Match)
  7325. return true;
  7326. Ty = DesugaredTy;
  7327. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7328. } while (DesugaredTy != Ty);
  7329. return false;
  7330. }
  7331. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7332. if (PT->isPointerType()) {
  7333. QualType PointeeType = PT->getPointeeType();
  7334. if (PointeeType->isPointerType())
  7335. return PtrPtrKernelParam;
  7336. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7337. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7338. PointeeType.getAddressSpace() == LangAS::Default)
  7339. return InvalidAddrSpacePtrKernelParam;
  7340. return PtrKernelParam;
  7341. }
  7342. // OpenCL v1.2 s6.9.k:
  7343. // Arguments to kernel functions in a program cannot be declared with the
  7344. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7345. // uintptr_t or a struct and/or union that contain fields declared to be one
  7346. // of these built-in scalar types.
  7347. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7348. return InvalidKernelParam;
  7349. if (PT->isImageType())
  7350. return PtrKernelParam;
  7351. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7352. return InvalidKernelParam;
  7353. // OpenCL extension spec v1.2 s9.5:
  7354. // This extension adds support for half scalar and vector types as built-in
  7355. // types that can be used for arithmetic operations, conversions etc.
  7356. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7357. return InvalidKernelParam;
  7358. if (PT->isRecordType())
  7359. return RecordKernelParam;
  7360. // Look into an array argument to check if it has a forbidden type.
  7361. if (PT->isArrayType()) {
  7362. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7363. // Call ourself to check an underlying type of an array. Since the
  7364. // getPointeeOrArrayElementType returns an innermost type which is not an
  7365. // array, this recursive call only happens once.
  7366. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7367. }
  7368. return ValidKernelParam;
  7369. }
  7370. static void checkIsValidOpenCLKernelParameter(
  7371. Sema &S,
  7372. Declarator &D,
  7373. ParmVarDecl *Param,
  7374. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7375. QualType PT = Param->getType();
  7376. // Cache the valid types we encounter to avoid rechecking structs that are
  7377. // used again
  7378. if (ValidTypes.count(PT.getTypePtr()))
  7379. return;
  7380. switch (getOpenCLKernelParameterType(S, PT)) {
  7381. case PtrPtrKernelParam:
  7382. // OpenCL v1.2 s6.9.a:
  7383. // A kernel function argument cannot be declared as a
  7384. // pointer to a pointer type.
  7385. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7386. D.setInvalidType();
  7387. return;
  7388. case InvalidAddrSpacePtrKernelParam:
  7389. // OpenCL v1.0 s6.5:
  7390. // __kernel function arguments declared to be a pointer of a type can point
  7391. // to one of the following address spaces only : __global, __local or
  7392. // __constant.
  7393. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7394. D.setInvalidType();
  7395. return;
  7396. // OpenCL v1.2 s6.9.k:
  7397. // Arguments to kernel functions in a program cannot be declared with the
  7398. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7399. // uintptr_t or a struct and/or union that contain fields declared to be
  7400. // one of these built-in scalar types.
  7401. case InvalidKernelParam:
  7402. // OpenCL v1.2 s6.8 n:
  7403. // A kernel function argument cannot be declared
  7404. // of event_t type.
  7405. // Do not diagnose half type since it is diagnosed as invalid argument
  7406. // type for any function elsewhere.
  7407. if (!PT->isHalfType()) {
  7408. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7409. // Explain what typedefs are involved.
  7410. const TypedefType *Typedef = nullptr;
  7411. while ((Typedef = PT->getAs<TypedefType>())) {
  7412. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7413. // SourceLocation may be invalid for a built-in type.
  7414. if (Loc.isValid())
  7415. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7416. PT = Typedef->desugar();
  7417. }
  7418. }
  7419. D.setInvalidType();
  7420. return;
  7421. case PtrKernelParam:
  7422. case ValidKernelParam:
  7423. ValidTypes.insert(PT.getTypePtr());
  7424. return;
  7425. case RecordKernelParam:
  7426. break;
  7427. }
  7428. // Track nested structs we will inspect
  7429. SmallVector<const Decl *, 4> VisitStack;
  7430. // Track where we are in the nested structs. Items will migrate from
  7431. // VisitStack to HistoryStack as we do the DFS for bad field.
  7432. SmallVector<const FieldDecl *, 4> HistoryStack;
  7433. HistoryStack.push_back(nullptr);
  7434. // At this point we already handled everything except of a RecordType or
  7435. // an ArrayType of a RecordType.
  7436. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7437. const RecordType *RecTy =
  7438. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7439. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7440. VisitStack.push_back(RecTy->getDecl());
  7441. assert(VisitStack.back() && "First decl null?");
  7442. do {
  7443. const Decl *Next = VisitStack.pop_back_val();
  7444. if (!Next) {
  7445. assert(!HistoryStack.empty());
  7446. // Found a marker, we have gone up a level
  7447. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7448. ValidTypes.insert(Hist->getType().getTypePtr());
  7449. continue;
  7450. }
  7451. // Adds everything except the original parameter declaration (which is not a
  7452. // field itself) to the history stack.
  7453. const RecordDecl *RD;
  7454. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7455. HistoryStack.push_back(Field);
  7456. QualType FieldTy = Field->getType();
  7457. // Other field types (known to be valid or invalid) are handled while we
  7458. // walk around RecordDecl::fields().
  7459. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7460. "Unexpected type.");
  7461. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7462. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7463. } else {
  7464. RD = cast<RecordDecl>(Next);
  7465. }
  7466. // Add a null marker so we know when we've gone back up a level
  7467. VisitStack.push_back(nullptr);
  7468. for (const auto *FD : RD->fields()) {
  7469. QualType QT = FD->getType();
  7470. if (ValidTypes.count(QT.getTypePtr()))
  7471. continue;
  7472. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7473. if (ParamType == ValidKernelParam)
  7474. continue;
  7475. if (ParamType == RecordKernelParam) {
  7476. VisitStack.push_back(FD);
  7477. continue;
  7478. }
  7479. // OpenCL v1.2 s6.9.p:
  7480. // Arguments to kernel functions that are declared to be a struct or union
  7481. // do not allow OpenCL objects to be passed as elements of the struct or
  7482. // union.
  7483. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7484. ParamType == InvalidAddrSpacePtrKernelParam) {
  7485. S.Diag(Param->getLocation(),
  7486. diag::err_record_with_pointers_kernel_param)
  7487. << PT->isUnionType()
  7488. << PT;
  7489. } else {
  7490. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7491. }
  7492. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7493. << OrigRecDecl->getDeclName();
  7494. // We have an error, now let's go back up through history and show where
  7495. // the offending field came from
  7496. for (ArrayRef<const FieldDecl *>::const_iterator
  7497. I = HistoryStack.begin() + 1,
  7498. E = HistoryStack.end();
  7499. I != E; ++I) {
  7500. const FieldDecl *OuterField = *I;
  7501. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7502. << OuterField->getType();
  7503. }
  7504. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7505. << QT->isPointerType()
  7506. << QT;
  7507. D.setInvalidType();
  7508. return;
  7509. }
  7510. } while (!VisitStack.empty());
  7511. }
  7512. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7513. /// elaborated type specifier in the specified context, and lookup finds
  7514. /// nothing.
  7515. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7516. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7517. DC = DC->getParent();
  7518. return DC;
  7519. }
  7520. /// Find the Scope in which a tag is implicitly declared if we see an
  7521. /// elaborated type specifier in the specified context, and lookup finds
  7522. /// nothing.
  7523. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7524. while (S->isClassScope() ||
  7525. (LangOpts.CPlusPlus &&
  7526. S->isFunctionPrototypeScope()) ||
  7527. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7528. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7529. S = S->getParent();
  7530. return S;
  7531. }
  7532. NamedDecl*
  7533. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7534. TypeSourceInfo *TInfo, LookupResult &Previous,
  7535. MultiTemplateParamsArg TemplateParamLists,
  7536. bool &AddToScope) {
  7537. QualType R = TInfo->getType();
  7538. assert(R->isFunctionType());
  7539. // TODO: consider using NameInfo for diagnostic.
  7540. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7541. DeclarationName Name = NameInfo.getName();
  7542. StorageClass SC = getFunctionStorageClass(*this, D);
  7543. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7544. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7545. diag::err_invalid_thread)
  7546. << DeclSpec::getSpecifierName(TSCS);
  7547. if (D.isFirstDeclarationOfMember())
  7548. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7549. D.getIdentifierLoc());
  7550. bool isFriend = false;
  7551. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7552. bool isMemberSpecialization = false;
  7553. bool isFunctionTemplateSpecialization = false;
  7554. bool isDependentClassScopeExplicitSpecialization = false;
  7555. bool HasExplicitTemplateArgs = false;
  7556. TemplateArgumentListInfo TemplateArgs;
  7557. bool isVirtualOkay = false;
  7558. DeclContext *OriginalDC = DC;
  7559. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7560. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7561. isVirtualOkay);
  7562. if (!NewFD) return nullptr;
  7563. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7564. NewFD->setTopLevelDeclInObjCContainer();
  7565. // Set the lexical context. If this is a function-scope declaration, or has a
  7566. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7567. // context will be different from the semantic context.
  7568. NewFD->setLexicalDeclContext(CurContext);
  7569. if (IsLocalExternDecl)
  7570. NewFD->setLocalExternDecl();
  7571. if (getLangOpts().CPlusPlus) {
  7572. bool isInline = D.getDeclSpec().isInlineSpecified();
  7573. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7574. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7575. isFriend = D.getDeclSpec().isFriendSpecified();
  7576. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7577. // C++ [class.friend]p5
  7578. // A function can be defined in a friend declaration of a
  7579. // class . . . . Such a function is implicitly inline.
  7580. NewFD->setImplicitlyInline();
  7581. }
  7582. // If this is a method defined in an __interface, and is not a constructor
  7583. // or an overloaded operator, then set the pure flag (isVirtual will already
  7584. // return true).
  7585. if (const CXXRecordDecl *Parent =
  7586. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7587. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7588. NewFD->setPure(true);
  7589. // C++ [class.union]p2
  7590. // A union can have member functions, but not virtual functions.
  7591. if (isVirtual && Parent->isUnion())
  7592. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7593. }
  7594. SetNestedNameSpecifier(*this, NewFD, D);
  7595. isMemberSpecialization = false;
  7596. isFunctionTemplateSpecialization = false;
  7597. if (D.isInvalidType())
  7598. NewFD->setInvalidDecl();
  7599. // Match up the template parameter lists with the scope specifier, then
  7600. // determine whether we have a template or a template specialization.
  7601. bool Invalid = false;
  7602. if (TemplateParameterList *TemplateParams =
  7603. MatchTemplateParametersToScopeSpecifier(
  7604. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7605. D.getCXXScopeSpec(),
  7606. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7607. ? D.getName().TemplateId
  7608. : nullptr,
  7609. TemplateParamLists, isFriend, isMemberSpecialization,
  7610. Invalid)) {
  7611. if (TemplateParams->size() > 0) {
  7612. // This is a function template
  7613. // Check that we can declare a template here.
  7614. if (CheckTemplateDeclScope(S, TemplateParams))
  7615. NewFD->setInvalidDecl();
  7616. // A destructor cannot be a template.
  7617. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7618. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7619. NewFD->setInvalidDecl();
  7620. }
  7621. // If we're adding a template to a dependent context, we may need to
  7622. // rebuilding some of the types used within the template parameter list,
  7623. // now that we know what the current instantiation is.
  7624. if (DC->isDependentContext()) {
  7625. ContextRAII SavedContext(*this, DC);
  7626. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7627. Invalid = true;
  7628. }
  7629. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7630. NewFD->getLocation(),
  7631. Name, TemplateParams,
  7632. NewFD);
  7633. FunctionTemplate->setLexicalDeclContext(CurContext);
  7634. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7635. // For source fidelity, store the other template param lists.
  7636. if (TemplateParamLists.size() > 1) {
  7637. NewFD->setTemplateParameterListsInfo(Context,
  7638. TemplateParamLists.drop_back(1));
  7639. }
  7640. } else {
  7641. // This is a function template specialization.
  7642. isFunctionTemplateSpecialization = true;
  7643. // For source fidelity, store all the template param lists.
  7644. if (TemplateParamLists.size() > 0)
  7645. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7646. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7647. if (isFriend) {
  7648. // We want to remove the "template<>", found here.
  7649. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7650. // If we remove the template<> and the name is not a
  7651. // template-id, we're actually silently creating a problem:
  7652. // the friend declaration will refer to an untemplated decl,
  7653. // and clearly the user wants a template specialization. So
  7654. // we need to insert '<>' after the name.
  7655. SourceLocation InsertLoc;
  7656. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7657. InsertLoc = D.getName().getSourceRange().getEnd();
  7658. InsertLoc = getLocForEndOfToken(InsertLoc);
  7659. }
  7660. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7661. << Name << RemoveRange
  7662. << FixItHint::CreateRemoval(RemoveRange)
  7663. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7664. }
  7665. }
  7666. } else {
  7667. // All template param lists were matched against the scope specifier:
  7668. // this is NOT (an explicit specialization of) a template.
  7669. if (TemplateParamLists.size() > 0)
  7670. // For source fidelity, store all the template param lists.
  7671. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7672. }
  7673. if (Invalid) {
  7674. NewFD->setInvalidDecl();
  7675. if (FunctionTemplate)
  7676. FunctionTemplate->setInvalidDecl();
  7677. }
  7678. // C++ [dcl.fct.spec]p5:
  7679. // The virtual specifier shall only be used in declarations of
  7680. // nonstatic class member functions that appear within a
  7681. // member-specification of a class declaration; see 10.3.
  7682. //
  7683. if (isVirtual && !NewFD->isInvalidDecl()) {
  7684. if (!isVirtualOkay) {
  7685. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7686. diag::err_virtual_non_function);
  7687. } else if (!CurContext->isRecord()) {
  7688. // 'virtual' was specified outside of the class.
  7689. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7690. diag::err_virtual_out_of_class)
  7691. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7692. } else if (NewFD->getDescribedFunctionTemplate()) {
  7693. // C++ [temp.mem]p3:
  7694. // A member function template shall not be virtual.
  7695. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7696. diag::err_virtual_member_function_template)
  7697. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7698. } else {
  7699. // Okay: Add virtual to the method.
  7700. NewFD->setVirtualAsWritten(true);
  7701. }
  7702. if (getLangOpts().CPlusPlus14 &&
  7703. NewFD->getReturnType()->isUndeducedType())
  7704. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7705. }
  7706. if (getLangOpts().CPlusPlus14 &&
  7707. (NewFD->isDependentContext() ||
  7708. (isFriend && CurContext->isDependentContext())) &&
  7709. NewFD->getReturnType()->isUndeducedType()) {
  7710. // If the function template is referenced directly (for instance, as a
  7711. // member of the current instantiation), pretend it has a dependent type.
  7712. // This is not really justified by the standard, but is the only sane
  7713. // thing to do.
  7714. // FIXME: For a friend function, we have not marked the function as being
  7715. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7716. const FunctionProtoType *FPT =
  7717. NewFD->getType()->castAs<FunctionProtoType>();
  7718. QualType Result =
  7719. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7720. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7721. FPT->getExtProtoInfo()));
  7722. }
  7723. // C++ [dcl.fct.spec]p3:
  7724. // The inline specifier shall not appear on a block scope function
  7725. // declaration.
  7726. if (isInline && !NewFD->isInvalidDecl()) {
  7727. if (CurContext->isFunctionOrMethod()) {
  7728. // 'inline' is not allowed on block scope function declaration.
  7729. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7730. diag::err_inline_declaration_block_scope) << Name
  7731. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7732. }
  7733. }
  7734. // C++ [dcl.fct.spec]p6:
  7735. // The explicit specifier shall be used only in the declaration of a
  7736. // constructor or conversion function within its class definition;
  7737. // see 12.3.1 and 12.3.2.
  7738. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7739. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7740. if (!CurContext->isRecord()) {
  7741. // 'explicit' was specified outside of the class.
  7742. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7743. diag::err_explicit_out_of_class)
  7744. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7745. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7746. !isa<CXXConversionDecl>(NewFD)) {
  7747. // 'explicit' was specified on a function that wasn't a constructor
  7748. // or conversion function.
  7749. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7750. diag::err_explicit_non_ctor_or_conv_function)
  7751. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7752. }
  7753. }
  7754. if (ConstexprSpecKind ConstexprKind =
  7755. D.getDeclSpec().getConstexprSpecifier()) {
  7756. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7757. // are implicitly inline.
  7758. NewFD->setImplicitlyInline();
  7759. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7760. // be either constructors or to return a literal type. Therefore,
  7761. // destructors cannot be declared constexpr.
  7762. if (isa<CXXDestructorDecl>(NewFD)) {
  7763. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7764. << ConstexprKind;
  7765. }
  7766. }
  7767. // If __module_private__ was specified, mark the function accordingly.
  7768. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7769. if (isFunctionTemplateSpecialization) {
  7770. SourceLocation ModulePrivateLoc
  7771. = D.getDeclSpec().getModulePrivateSpecLoc();
  7772. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7773. << 0
  7774. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7775. } else {
  7776. NewFD->setModulePrivate();
  7777. if (FunctionTemplate)
  7778. FunctionTemplate->setModulePrivate();
  7779. }
  7780. }
  7781. if (isFriend) {
  7782. if (FunctionTemplate) {
  7783. FunctionTemplate->setObjectOfFriendDecl();
  7784. FunctionTemplate->setAccess(AS_public);
  7785. }
  7786. NewFD->setObjectOfFriendDecl();
  7787. NewFD->setAccess(AS_public);
  7788. }
  7789. // If a function is defined as defaulted or deleted, mark it as such now.
  7790. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7791. // definition kind to FDK_Definition.
  7792. switch (D.getFunctionDefinitionKind()) {
  7793. case FDK_Declaration:
  7794. case FDK_Definition:
  7795. break;
  7796. case FDK_Defaulted:
  7797. NewFD->setDefaulted();
  7798. break;
  7799. case FDK_Deleted:
  7800. NewFD->setDeletedAsWritten();
  7801. break;
  7802. }
  7803. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7804. D.isFunctionDefinition()) {
  7805. // C++ [class.mfct]p2:
  7806. // A member function may be defined (8.4) in its class definition, in
  7807. // which case it is an inline member function (7.1.2)
  7808. NewFD->setImplicitlyInline();
  7809. }
  7810. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7811. !CurContext->isRecord()) {
  7812. // C++ [class.static]p1:
  7813. // A data or function member of a class may be declared static
  7814. // in a class definition, in which case it is a static member of
  7815. // the class.
  7816. // Complain about the 'static' specifier if it's on an out-of-line
  7817. // member function definition.
  7818. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7819. // member function template declaration and class member template
  7820. // declaration (MSVC versions before 2015), warn about this.
  7821. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7822. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7823. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7824. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7825. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7826. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7827. }
  7828. // C++11 [except.spec]p15:
  7829. // A deallocation function with no exception-specification is treated
  7830. // as if it were specified with noexcept(true).
  7831. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7832. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7833. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7834. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7835. NewFD->setType(Context.getFunctionType(
  7836. FPT->getReturnType(), FPT->getParamTypes(),
  7837. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7838. }
  7839. // Filter out previous declarations that don't match the scope.
  7840. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7841. D.getCXXScopeSpec().isNotEmpty() ||
  7842. isMemberSpecialization ||
  7843. isFunctionTemplateSpecialization);
  7844. // Handle GNU asm-label extension (encoded as an attribute).
  7845. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7846. // The parser guarantees this is a string.
  7847. StringLiteral *SE = cast<StringLiteral>(E);
  7848. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7849. SE->getString(), 0));
  7850. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7851. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7852. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7853. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7854. if (isDeclExternC(NewFD)) {
  7855. NewFD->addAttr(I->second);
  7856. ExtnameUndeclaredIdentifiers.erase(I);
  7857. } else
  7858. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7859. << /*Variable*/0 << NewFD;
  7860. }
  7861. }
  7862. // Copy the parameter declarations from the declarator D to the function
  7863. // declaration NewFD, if they are available. First scavenge them into Params.
  7864. SmallVector<ParmVarDecl*, 16> Params;
  7865. unsigned FTIIdx;
  7866. if (D.isFunctionDeclarator(FTIIdx)) {
  7867. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7868. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7869. // function that takes no arguments, not a function that takes a
  7870. // single void argument.
  7871. // We let through "const void" here because Sema::GetTypeForDeclarator
  7872. // already checks for that case.
  7873. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7874. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7875. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7876. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7877. Param->setDeclContext(NewFD);
  7878. Params.push_back(Param);
  7879. if (Param->isInvalidDecl())
  7880. NewFD->setInvalidDecl();
  7881. }
  7882. }
  7883. if (!getLangOpts().CPlusPlus) {
  7884. // In C, find all the tag declarations from the prototype and move them
  7885. // into the function DeclContext. Remove them from the surrounding tag
  7886. // injection context of the function, which is typically but not always
  7887. // the TU.
  7888. DeclContext *PrototypeTagContext =
  7889. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7890. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7891. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7892. // We don't want to reparent enumerators. Look at their parent enum
  7893. // instead.
  7894. if (!TD) {
  7895. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7896. TD = cast<EnumDecl>(ECD->getDeclContext());
  7897. }
  7898. if (!TD)
  7899. continue;
  7900. DeclContext *TagDC = TD->getLexicalDeclContext();
  7901. if (!TagDC->containsDecl(TD))
  7902. continue;
  7903. TagDC->removeDecl(TD);
  7904. TD->setDeclContext(NewFD);
  7905. NewFD->addDecl(TD);
  7906. // Preserve the lexical DeclContext if it is not the surrounding tag
  7907. // injection context of the FD. In this example, the semantic context of
  7908. // E will be f and the lexical context will be S, while both the
  7909. // semantic and lexical contexts of S will be f:
  7910. // void f(struct S { enum E { a } f; } s);
  7911. if (TagDC != PrototypeTagContext)
  7912. TD->setLexicalDeclContext(TagDC);
  7913. }
  7914. }
  7915. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7916. // When we're declaring a function with a typedef, typeof, etc as in the
  7917. // following example, we'll need to synthesize (unnamed)
  7918. // parameters for use in the declaration.
  7919. //
  7920. // @code
  7921. // typedef void fn(int);
  7922. // fn f;
  7923. // @endcode
  7924. // Synthesize a parameter for each argument type.
  7925. for (const auto &AI : FT->param_types()) {
  7926. ParmVarDecl *Param =
  7927. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7928. Param->setScopeInfo(0, Params.size());
  7929. Params.push_back(Param);
  7930. }
  7931. } else {
  7932. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7933. "Should not need args for typedef of non-prototype fn");
  7934. }
  7935. // Finally, we know we have the right number of parameters, install them.
  7936. NewFD->setParams(Params);
  7937. if (D.getDeclSpec().isNoreturnSpecified())
  7938. NewFD->addAttr(
  7939. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7940. Context, 0));
  7941. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7942. // because all functions have linkage.
  7943. if (!NewFD->isInvalidDecl() &&
  7944. NewFD->getReturnType()->isVariablyModifiedType()) {
  7945. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7946. NewFD->setInvalidDecl();
  7947. }
  7948. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7949. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7950. !NewFD->hasAttr<SectionAttr>()) {
  7951. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7952. PragmaClangTextSection.SectionName,
  7953. PragmaClangTextSection.PragmaLocation));
  7954. }
  7955. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7956. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7957. !NewFD->hasAttr<SectionAttr>()) {
  7958. NewFD->addAttr(
  7959. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7960. CodeSegStack.CurrentValue->getString(),
  7961. CodeSegStack.CurrentPragmaLocation));
  7962. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7963. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7964. ASTContext::PSF_Read,
  7965. NewFD))
  7966. NewFD->dropAttr<SectionAttr>();
  7967. }
  7968. // Apply an implicit CodeSegAttr from class declspec or
  7969. // apply an implicit SectionAttr from #pragma code_seg if active.
  7970. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7971. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7972. D.isFunctionDefinition())) {
  7973. NewFD->addAttr(SAttr);
  7974. }
  7975. }
  7976. // Handle attributes.
  7977. ProcessDeclAttributes(S, NewFD, D);
  7978. if (getLangOpts().OpenCL) {
  7979. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7980. // type declaration will generate a compilation error.
  7981. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7982. if (AddressSpace != LangAS::Default) {
  7983. Diag(NewFD->getLocation(),
  7984. diag::err_opencl_return_value_with_address_space);
  7985. NewFD->setInvalidDecl();
  7986. }
  7987. }
  7988. if (!getLangOpts().CPlusPlus) {
  7989. // Perform semantic checking on the function declaration.
  7990. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7991. CheckMain(NewFD, D.getDeclSpec());
  7992. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7993. CheckMSVCRTEntryPoint(NewFD);
  7994. if (!NewFD->isInvalidDecl())
  7995. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7996. isMemberSpecialization));
  7997. else if (!Previous.empty())
  7998. // Recover gracefully from an invalid redeclaration.
  7999. D.setRedeclaration(true);
  8000. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8001. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8002. "previous declaration set still overloaded");
  8003. // Diagnose no-prototype function declarations with calling conventions that
  8004. // don't support variadic calls. Only do this in C and do it after merging
  8005. // possibly prototyped redeclarations.
  8006. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  8007. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  8008. CallingConv CC = FT->getExtInfo().getCC();
  8009. if (!supportsVariadicCall(CC)) {
  8010. // Windows system headers sometimes accidentally use stdcall without
  8011. // (void) parameters, so we relax this to a warning.
  8012. int DiagID =
  8013. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  8014. Diag(NewFD->getLocation(), DiagID)
  8015. << FunctionType::getNameForCallConv(CC);
  8016. }
  8017. }
  8018. } else {
  8019. // C++11 [replacement.functions]p3:
  8020. // The program's definitions shall not be specified as inline.
  8021. //
  8022. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  8023. //
  8024. // Suppress the diagnostic if the function is __attribute__((used)), since
  8025. // that forces an external definition to be emitted.
  8026. if (D.getDeclSpec().isInlineSpecified() &&
  8027. NewFD->isReplaceableGlobalAllocationFunction() &&
  8028. !NewFD->hasAttr<UsedAttr>())
  8029. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8030. diag::ext_operator_new_delete_declared_inline)
  8031. << NewFD->getDeclName();
  8032. // If the declarator is a template-id, translate the parser's template
  8033. // argument list into our AST format.
  8034. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8035. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  8036. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  8037. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  8038. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  8039. TemplateId->NumArgs);
  8040. translateTemplateArguments(TemplateArgsPtr,
  8041. TemplateArgs);
  8042. HasExplicitTemplateArgs = true;
  8043. if (NewFD->isInvalidDecl()) {
  8044. HasExplicitTemplateArgs = false;
  8045. } else if (FunctionTemplate) {
  8046. // Function template with explicit template arguments.
  8047. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  8048. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  8049. HasExplicitTemplateArgs = false;
  8050. } else {
  8051. assert((isFunctionTemplateSpecialization ||
  8052. D.getDeclSpec().isFriendSpecified()) &&
  8053. "should have a 'template<>' for this decl");
  8054. // "friend void foo<>(int);" is an implicit specialization decl.
  8055. isFunctionTemplateSpecialization = true;
  8056. }
  8057. } else if (isFriend && isFunctionTemplateSpecialization) {
  8058. // This combination is only possible in a recovery case; the user
  8059. // wrote something like:
  8060. // template <> friend void foo(int);
  8061. // which we're recovering from as if the user had written:
  8062. // friend void foo<>(int);
  8063. // Go ahead and fake up a template id.
  8064. HasExplicitTemplateArgs = true;
  8065. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  8066. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  8067. }
  8068. // We do not add HD attributes to specializations here because
  8069. // they may have different constexpr-ness compared to their
  8070. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  8071. // may end up with different effective targets. Instead, a
  8072. // specialization inherits its target attributes from its template
  8073. // in the CheckFunctionTemplateSpecialization() call below.
  8074. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  8075. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  8076. // If it's a friend (and only if it's a friend), it's possible
  8077. // that either the specialized function type or the specialized
  8078. // template is dependent, and therefore matching will fail. In
  8079. // this case, don't check the specialization yet.
  8080. bool InstantiationDependent = false;
  8081. if (isFunctionTemplateSpecialization && isFriend &&
  8082. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  8083. TemplateSpecializationType::anyDependentTemplateArguments(
  8084. TemplateArgs,
  8085. InstantiationDependent))) {
  8086. assert(HasExplicitTemplateArgs &&
  8087. "friend function specialization without template args");
  8088. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  8089. Previous))
  8090. NewFD->setInvalidDecl();
  8091. } else if (isFunctionTemplateSpecialization) {
  8092. if (CurContext->isDependentContext() && CurContext->isRecord()
  8093. && !isFriend) {
  8094. isDependentClassScopeExplicitSpecialization = true;
  8095. } else if (!NewFD->isInvalidDecl() &&
  8096. CheckFunctionTemplateSpecialization(
  8097. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  8098. Previous))
  8099. NewFD->setInvalidDecl();
  8100. // C++ [dcl.stc]p1:
  8101. // A storage-class-specifier shall not be specified in an explicit
  8102. // specialization (14.7.3)
  8103. FunctionTemplateSpecializationInfo *Info =
  8104. NewFD->getTemplateSpecializationInfo();
  8105. if (Info && SC != SC_None) {
  8106. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  8107. Diag(NewFD->getLocation(),
  8108. diag::err_explicit_specialization_inconsistent_storage_class)
  8109. << SC
  8110. << FixItHint::CreateRemoval(
  8111. D.getDeclSpec().getStorageClassSpecLoc());
  8112. else
  8113. Diag(NewFD->getLocation(),
  8114. diag::ext_explicit_specialization_storage_class)
  8115. << FixItHint::CreateRemoval(
  8116. D.getDeclSpec().getStorageClassSpecLoc());
  8117. }
  8118. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8119. if (CheckMemberSpecialization(NewFD, Previous))
  8120. NewFD->setInvalidDecl();
  8121. }
  8122. // Perform semantic checking on the function declaration.
  8123. if (!isDependentClassScopeExplicitSpecialization) {
  8124. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8125. CheckMain(NewFD, D.getDeclSpec());
  8126. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8127. CheckMSVCRTEntryPoint(NewFD);
  8128. if (!NewFD->isInvalidDecl())
  8129. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8130. isMemberSpecialization));
  8131. else if (!Previous.empty())
  8132. // Recover gracefully from an invalid redeclaration.
  8133. D.setRedeclaration(true);
  8134. }
  8135. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8136. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8137. "previous declaration set still overloaded");
  8138. NamedDecl *PrincipalDecl = (FunctionTemplate
  8139. ? cast<NamedDecl>(FunctionTemplate)
  8140. : NewFD);
  8141. if (isFriend && NewFD->getPreviousDecl()) {
  8142. AccessSpecifier Access = AS_public;
  8143. if (!NewFD->isInvalidDecl())
  8144. Access = NewFD->getPreviousDecl()->getAccess();
  8145. NewFD->setAccess(Access);
  8146. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8147. }
  8148. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8149. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8150. PrincipalDecl->setNonMemberOperator();
  8151. // If we have a function template, check the template parameter
  8152. // list. This will check and merge default template arguments.
  8153. if (FunctionTemplate) {
  8154. FunctionTemplateDecl *PrevTemplate =
  8155. FunctionTemplate->getPreviousDecl();
  8156. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8157. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8158. : nullptr,
  8159. D.getDeclSpec().isFriendSpecified()
  8160. ? (D.isFunctionDefinition()
  8161. ? TPC_FriendFunctionTemplateDefinition
  8162. : TPC_FriendFunctionTemplate)
  8163. : (D.getCXXScopeSpec().isSet() &&
  8164. DC && DC->isRecord() &&
  8165. DC->isDependentContext())
  8166. ? TPC_ClassTemplateMember
  8167. : TPC_FunctionTemplate);
  8168. }
  8169. if (NewFD->isInvalidDecl()) {
  8170. // Ignore all the rest of this.
  8171. } else if (!D.isRedeclaration()) {
  8172. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8173. AddToScope };
  8174. // Fake up an access specifier if it's supposed to be a class member.
  8175. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8176. NewFD->setAccess(AS_public);
  8177. // Qualified decls generally require a previous declaration.
  8178. if (D.getCXXScopeSpec().isSet()) {
  8179. // ...with the major exception of templated-scope or
  8180. // dependent-scope friend declarations.
  8181. // TODO: we currently also suppress this check in dependent
  8182. // contexts because (1) the parameter depth will be off when
  8183. // matching friend templates and (2) we might actually be
  8184. // selecting a friend based on a dependent factor. But there
  8185. // are situations where these conditions don't apply and we
  8186. // can actually do this check immediately.
  8187. //
  8188. // Unless the scope is dependent, it's always an error if qualified
  8189. // redeclaration lookup found nothing at all. Diagnose that now;
  8190. // nothing will diagnose that error later.
  8191. if (isFriend &&
  8192. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8193. (!Previous.empty() && CurContext->isDependentContext()))) {
  8194. // ignore these
  8195. } else {
  8196. // The user tried to provide an out-of-line definition for a
  8197. // function that is a member of a class or namespace, but there
  8198. // was no such member function declared (C++ [class.mfct]p2,
  8199. // C++ [namespace.memdef]p2). For example:
  8200. //
  8201. // class X {
  8202. // void f() const;
  8203. // };
  8204. //
  8205. // void X::f() { } // ill-formed
  8206. //
  8207. // Complain about this problem, and attempt to suggest close
  8208. // matches (e.g., those that differ only in cv-qualifiers and
  8209. // whether the parameter types are references).
  8210. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8211. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8212. AddToScope = ExtraArgs.AddToScope;
  8213. return Result;
  8214. }
  8215. }
  8216. // Unqualified local friend declarations are required to resolve
  8217. // to something.
  8218. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8219. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8220. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8221. AddToScope = ExtraArgs.AddToScope;
  8222. return Result;
  8223. }
  8224. }
  8225. } else if (!D.isFunctionDefinition() &&
  8226. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8227. !isFriend && !isFunctionTemplateSpecialization &&
  8228. !isMemberSpecialization) {
  8229. // An out-of-line member function declaration must also be a
  8230. // definition (C++ [class.mfct]p2).
  8231. // Note that this is not the case for explicit specializations of
  8232. // function templates or member functions of class templates, per
  8233. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8234. // extension for compatibility with old SWIG code which likes to
  8235. // generate them.
  8236. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8237. << D.getCXXScopeSpec().getRange();
  8238. }
  8239. }
  8240. ProcessPragmaWeak(S, NewFD);
  8241. checkAttributesAfterMerging(*this, *NewFD);
  8242. AddKnownFunctionAttributes(NewFD);
  8243. if (NewFD->hasAttr<OverloadableAttr>() &&
  8244. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8245. Diag(NewFD->getLocation(),
  8246. diag::err_attribute_overloadable_no_prototype)
  8247. << NewFD;
  8248. // Turn this into a variadic function with no parameters.
  8249. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8250. FunctionProtoType::ExtProtoInfo EPI(
  8251. Context.getDefaultCallingConvention(true, false));
  8252. EPI.Variadic = true;
  8253. EPI.ExtInfo = FT->getExtInfo();
  8254. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8255. NewFD->setType(R);
  8256. }
  8257. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8258. // member, set the visibility of this function.
  8259. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8260. AddPushedVisibilityAttribute(NewFD);
  8261. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8262. // marking the function.
  8263. AddCFAuditedAttribute(NewFD);
  8264. // If this is a function definition, check if we have to apply optnone due to
  8265. // a pragma.
  8266. if(D.isFunctionDefinition())
  8267. AddRangeBasedOptnone(NewFD);
  8268. // If this is the first declaration of an extern C variable, update
  8269. // the map of such variables.
  8270. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8271. isIncompleteDeclExternC(*this, NewFD))
  8272. RegisterLocallyScopedExternCDecl(NewFD, S);
  8273. // Set this FunctionDecl's range up to the right paren.
  8274. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8275. if (D.isRedeclaration() && !Previous.empty()) {
  8276. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8277. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8278. isMemberSpecialization ||
  8279. isFunctionTemplateSpecialization,
  8280. D.isFunctionDefinition());
  8281. }
  8282. if (getLangOpts().CUDA) {
  8283. IdentifierInfo *II = NewFD->getIdentifier();
  8284. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8285. !NewFD->isInvalidDecl() &&
  8286. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8287. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8288. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8289. << getCudaConfigureFuncName();
  8290. Context.setcudaConfigureCallDecl(NewFD);
  8291. }
  8292. // Variadic functions, other than a *declaration* of printf, are not allowed
  8293. // in device-side CUDA code, unless someone passed
  8294. // -fcuda-allow-variadic-functions.
  8295. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8296. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8297. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8298. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8299. !D.isFunctionDefinition())) {
  8300. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8301. }
  8302. }
  8303. MarkUnusedFileScopedDecl(NewFD);
  8304. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8305. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8306. if ((getLangOpts().OpenCLVersion >= 120)
  8307. && (SC == SC_Static)) {
  8308. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8309. D.setInvalidType();
  8310. }
  8311. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8312. if (!NewFD->getReturnType()->isVoidType()) {
  8313. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8314. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8315. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8316. : FixItHint());
  8317. D.setInvalidType();
  8318. }
  8319. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8320. for (auto Param : NewFD->parameters())
  8321. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8322. if (getLangOpts().OpenCLCPlusPlus) {
  8323. if (DC->isRecord()) {
  8324. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8325. D.setInvalidType();
  8326. }
  8327. if (FunctionTemplate) {
  8328. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8329. D.setInvalidType();
  8330. }
  8331. }
  8332. }
  8333. if (getLangOpts().CPlusPlus) {
  8334. if (FunctionTemplate) {
  8335. if (NewFD->isInvalidDecl())
  8336. FunctionTemplate->setInvalidDecl();
  8337. return FunctionTemplate;
  8338. }
  8339. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8340. CompleteMemberSpecialization(NewFD, Previous);
  8341. }
  8342. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8343. QualType PT = Param->getType();
  8344. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8345. // types.
  8346. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8347. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8348. QualType ElemTy = PipeTy->getElementType();
  8349. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8350. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8351. D.setInvalidType();
  8352. }
  8353. }
  8354. }
  8355. }
  8356. // Here we have an function template explicit specialization at class scope.
  8357. // The actual specialization will be postponed to template instatiation
  8358. // time via the ClassScopeFunctionSpecializationDecl node.
  8359. if (isDependentClassScopeExplicitSpecialization) {
  8360. ClassScopeFunctionSpecializationDecl *NewSpec =
  8361. ClassScopeFunctionSpecializationDecl::Create(
  8362. Context, CurContext, NewFD->getLocation(),
  8363. cast<CXXMethodDecl>(NewFD),
  8364. HasExplicitTemplateArgs, TemplateArgs);
  8365. CurContext->addDecl(NewSpec);
  8366. AddToScope = false;
  8367. }
  8368. // Diagnose availability attributes. Availability cannot be used on functions
  8369. // that are run during load/unload.
  8370. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8371. if (NewFD->hasAttr<ConstructorAttr>()) {
  8372. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8373. << 1;
  8374. NewFD->dropAttr<AvailabilityAttr>();
  8375. }
  8376. if (NewFD->hasAttr<DestructorAttr>()) {
  8377. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8378. << 2;
  8379. NewFD->dropAttr<AvailabilityAttr>();
  8380. }
  8381. }
  8382. return NewFD;
  8383. }
  8384. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8385. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8386. /// the class and nested classes -- this includes compiler-generated special
  8387. /// member functions -- are put in the specified segment."
  8388. /// The actual behavior is a little more complicated. The Microsoft compiler
  8389. /// won't check outer classes if there is an active value from #pragma code_seg.
  8390. /// The CodeSeg is always applied from the direct parent but only from outer
  8391. /// classes when the #pragma code_seg stack is empty. See:
  8392. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8393. /// available since MS has removed the page.
  8394. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8395. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8396. if (!Method)
  8397. return nullptr;
  8398. const CXXRecordDecl *Parent = Method->getParent();
  8399. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8400. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8401. NewAttr->setImplicit(true);
  8402. return NewAttr;
  8403. }
  8404. // The Microsoft compiler won't check outer classes for the CodeSeg
  8405. // when the #pragma code_seg stack is active.
  8406. if (S.CodeSegStack.CurrentValue)
  8407. return nullptr;
  8408. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8409. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8410. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8411. NewAttr->setImplicit(true);
  8412. return NewAttr;
  8413. }
  8414. }
  8415. return nullptr;
  8416. }
  8417. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8418. /// containing class. Otherwise it will return implicit SectionAttr if the
  8419. /// function is a definition and there is an active value on CodeSegStack
  8420. /// (from the current #pragma code-seg value).
  8421. ///
  8422. /// \param FD Function being declared.
  8423. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8424. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8425. /// nullptr if no attribute should be added.
  8426. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8427. bool IsDefinition) {
  8428. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8429. return A;
  8430. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8431. CodeSegStack.CurrentValue) {
  8432. return SectionAttr::CreateImplicit(getASTContext(),
  8433. SectionAttr::Declspec_allocate,
  8434. CodeSegStack.CurrentValue->getString(),
  8435. CodeSegStack.CurrentPragmaLocation);
  8436. }
  8437. return nullptr;
  8438. }
  8439. /// Determines if we can perform a correct type check for \p D as a
  8440. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8441. /// best-effort check.
  8442. ///
  8443. /// \param NewD The new declaration.
  8444. /// \param OldD The old declaration.
  8445. /// \param NewT The portion of the type of the new declaration to check.
  8446. /// \param OldT The portion of the type of the old declaration to check.
  8447. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8448. QualType NewT, QualType OldT) {
  8449. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8450. return true;
  8451. // For dependently-typed local extern declarations and friends, we can't
  8452. // perform a correct type check in general until instantiation:
  8453. //
  8454. // int f();
  8455. // template<typename T> void g() { T f(); }
  8456. //
  8457. // (valid if g() is only instantiated with T = int).
  8458. if (NewT->isDependentType() &&
  8459. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8460. return false;
  8461. // Similarly, if the previous declaration was a dependent local extern
  8462. // declaration, we don't really know its type yet.
  8463. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8464. return false;
  8465. return true;
  8466. }
  8467. /// Checks if the new declaration declared in dependent context must be
  8468. /// put in the same redeclaration chain as the specified declaration.
  8469. ///
  8470. /// \param D Declaration that is checked.
  8471. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8472. /// same declaration name.
  8473. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8474. /// belongs to.
  8475. ///
  8476. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8477. if (!D->getLexicalDeclContext()->isDependentContext())
  8478. return true;
  8479. // Don't chain dependent friend function definitions until instantiation, to
  8480. // permit cases like
  8481. //
  8482. // void func();
  8483. // template<typename T> class C1 { friend void func() {} };
  8484. // template<typename T> class C2 { friend void func() {} };
  8485. //
  8486. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8487. //
  8488. // FIXME: This need only apply to function definitions. For now, we proxy
  8489. // this by checking for a file-scope function. We do not want this to apply
  8490. // to friend declarations nominating member functions, because that gets in
  8491. // the way of access checks.
  8492. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8493. return false;
  8494. auto *VD = dyn_cast<ValueDecl>(D);
  8495. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8496. return !VD || !PrevVD ||
  8497. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8498. PrevVD->getType());
  8499. }
  8500. /// Check the target attribute of the function for MultiVersion
  8501. /// validity.
  8502. ///
  8503. /// Returns true if there was an error, false otherwise.
  8504. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8505. const auto *TA = FD->getAttr<TargetAttr>();
  8506. assert(TA && "MultiVersion Candidate requires a target attribute");
  8507. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8508. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8509. enum ErrType { Feature = 0, Architecture = 1 };
  8510. if (!ParseInfo.Architecture.empty() &&
  8511. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8512. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8513. << Architecture << ParseInfo.Architecture;
  8514. return true;
  8515. }
  8516. for (const auto &Feat : ParseInfo.Features) {
  8517. auto BareFeat = StringRef{Feat}.substr(1);
  8518. if (Feat[0] == '-') {
  8519. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8520. << Feature << ("no-" + BareFeat).str();
  8521. return true;
  8522. }
  8523. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8524. !TargetInfo.isValidFeatureName(BareFeat)) {
  8525. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8526. << Feature << BareFeat;
  8527. return true;
  8528. }
  8529. }
  8530. return false;
  8531. }
  8532. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8533. MultiVersionKind MVType) {
  8534. for (const Attr *A : FD->attrs()) {
  8535. switch (A->getKind()) {
  8536. case attr::CPUDispatch:
  8537. case attr::CPUSpecific:
  8538. if (MVType != MultiVersionKind::CPUDispatch &&
  8539. MVType != MultiVersionKind::CPUSpecific)
  8540. return true;
  8541. break;
  8542. case attr::Target:
  8543. if (MVType != MultiVersionKind::Target)
  8544. return true;
  8545. break;
  8546. default:
  8547. return true;
  8548. }
  8549. }
  8550. return false;
  8551. }
  8552. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8553. const FunctionDecl *NewFD,
  8554. bool CausesMV,
  8555. MultiVersionKind MVType) {
  8556. enum DoesntSupport {
  8557. FuncTemplates = 0,
  8558. VirtFuncs = 1,
  8559. DeducedReturn = 2,
  8560. Constructors = 3,
  8561. Destructors = 4,
  8562. DeletedFuncs = 5,
  8563. DefaultedFuncs = 6,
  8564. ConstexprFuncs = 7,
  8565. ConstevalFuncs = 8,
  8566. };
  8567. enum Different {
  8568. CallingConv = 0,
  8569. ReturnType = 1,
  8570. ConstexprSpec = 2,
  8571. InlineSpec = 3,
  8572. StorageClass = 4,
  8573. Linkage = 5
  8574. };
  8575. bool IsCPUSpecificCPUDispatchMVType =
  8576. MVType == MultiVersionKind::CPUDispatch ||
  8577. MVType == MultiVersionKind::CPUSpecific;
  8578. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8579. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8580. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8581. return true;
  8582. }
  8583. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8584. return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8585. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8586. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8587. if (OldFD)
  8588. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8589. return true;
  8590. }
  8591. // For now, disallow all other attributes. These should be opt-in, but
  8592. // an analysis of all of them is a future FIXME.
  8593. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8594. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8595. << IsCPUSpecificCPUDispatchMVType;
  8596. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8597. return true;
  8598. }
  8599. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8600. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8601. << IsCPUSpecificCPUDispatchMVType;
  8602. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8603. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8604. << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
  8605. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8606. if (NewCXXFD->isVirtual())
  8607. return S.Diag(NewCXXFD->getLocation(),
  8608. diag::err_multiversion_doesnt_support)
  8609. << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
  8610. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8611. return S.Diag(NewCXXCtor->getLocation(),
  8612. diag::err_multiversion_doesnt_support)
  8613. << IsCPUSpecificCPUDispatchMVType << Constructors;
  8614. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8615. return S.Diag(NewCXXDtor->getLocation(),
  8616. diag::err_multiversion_doesnt_support)
  8617. << IsCPUSpecificCPUDispatchMVType << Destructors;
  8618. }
  8619. if (NewFD->isDeleted())
  8620. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8621. << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
  8622. if (NewFD->isDefaulted())
  8623. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8624. << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
  8625. if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
  8626. MVType == MultiVersionKind::CPUSpecific))
  8627. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8628. << IsCPUSpecificCPUDispatchMVType
  8629. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8630. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8631. const auto *NewType = cast<FunctionType>(NewQType);
  8632. QualType NewReturnType = NewType->getReturnType();
  8633. if (NewReturnType->isUndeducedType())
  8634. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8635. << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
  8636. // Only allow transition to MultiVersion if it hasn't been used.
  8637. if (OldFD && CausesMV && OldFD->isUsed(false))
  8638. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8639. // Ensure the return type is identical.
  8640. if (OldFD) {
  8641. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8642. const auto *OldType = cast<FunctionType>(OldQType);
  8643. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8644. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8645. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8646. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8647. << CallingConv;
  8648. QualType OldReturnType = OldType->getReturnType();
  8649. if (OldReturnType != NewReturnType)
  8650. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8651. << ReturnType;
  8652. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8653. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8654. << ConstexprSpec;
  8655. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8656. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8657. << InlineSpec;
  8658. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8659. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8660. << StorageClass;
  8661. if (OldFD->isExternC() != NewFD->isExternC())
  8662. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8663. << Linkage;
  8664. if (S.CheckEquivalentExceptionSpec(
  8665. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8666. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8667. return true;
  8668. }
  8669. return false;
  8670. }
  8671. /// Check the validity of a multiversion function declaration that is the
  8672. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8673. ///
  8674. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8675. ///
  8676. /// Returns true if there was an error, false otherwise.
  8677. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8678. MultiVersionKind MVType,
  8679. const TargetAttr *TA) {
  8680. assert(MVType != MultiVersionKind::None &&
  8681. "Function lacks multiversion attribute");
  8682. // Target only causes MV if it is default, otherwise this is a normal
  8683. // function.
  8684. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8685. return false;
  8686. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8687. FD->setInvalidDecl();
  8688. return true;
  8689. }
  8690. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8691. FD->setInvalidDecl();
  8692. return true;
  8693. }
  8694. FD->setIsMultiVersion();
  8695. return false;
  8696. }
  8697. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8698. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8699. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8700. return true;
  8701. }
  8702. return false;
  8703. }
  8704. static bool CheckTargetCausesMultiVersioning(
  8705. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8706. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8707. LookupResult &Previous) {
  8708. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8709. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8710. // Sort order doesn't matter, it just needs to be consistent.
  8711. llvm::sort(NewParsed.Features);
  8712. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8713. // to change, this is a simple redeclaration.
  8714. if (!NewTA->isDefaultVersion() &&
  8715. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8716. return false;
  8717. // Otherwise, this decl causes MultiVersioning.
  8718. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8719. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8720. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8721. NewFD->setInvalidDecl();
  8722. return true;
  8723. }
  8724. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8725. MultiVersionKind::Target)) {
  8726. NewFD->setInvalidDecl();
  8727. return true;
  8728. }
  8729. if (CheckMultiVersionValue(S, NewFD)) {
  8730. NewFD->setInvalidDecl();
  8731. return true;
  8732. }
  8733. // If this is 'default', permit the forward declaration.
  8734. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8735. Redeclaration = true;
  8736. OldDecl = OldFD;
  8737. OldFD->setIsMultiVersion();
  8738. NewFD->setIsMultiVersion();
  8739. return false;
  8740. }
  8741. if (CheckMultiVersionValue(S, OldFD)) {
  8742. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8743. NewFD->setInvalidDecl();
  8744. return true;
  8745. }
  8746. TargetAttr::ParsedTargetAttr OldParsed =
  8747. OldTA->parse(std::less<std::string>());
  8748. if (OldParsed == NewParsed) {
  8749. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8750. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8751. NewFD->setInvalidDecl();
  8752. return true;
  8753. }
  8754. for (const auto *FD : OldFD->redecls()) {
  8755. const auto *CurTA = FD->getAttr<TargetAttr>();
  8756. // We allow forward declarations before ANY multiversioning attributes, but
  8757. // nothing after the fact.
  8758. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8759. (!CurTA || CurTA->isInherited())) {
  8760. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8761. << 0;
  8762. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8763. NewFD->setInvalidDecl();
  8764. return true;
  8765. }
  8766. }
  8767. OldFD->setIsMultiVersion();
  8768. NewFD->setIsMultiVersion();
  8769. Redeclaration = false;
  8770. MergeTypeWithPrevious = false;
  8771. OldDecl = nullptr;
  8772. Previous.clear();
  8773. return false;
  8774. }
  8775. /// Check the validity of a new function declaration being added to an existing
  8776. /// multiversioned declaration collection.
  8777. static bool CheckMultiVersionAdditionalDecl(
  8778. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8779. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8780. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8781. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8782. LookupResult &Previous) {
  8783. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8784. // Disallow mixing of multiversioning types.
  8785. if ((OldMVType == MultiVersionKind::Target &&
  8786. NewMVType != MultiVersionKind::Target) ||
  8787. (NewMVType == MultiVersionKind::Target &&
  8788. OldMVType != MultiVersionKind::Target)) {
  8789. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8790. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8791. NewFD->setInvalidDecl();
  8792. return true;
  8793. }
  8794. TargetAttr::ParsedTargetAttr NewParsed;
  8795. if (NewTA) {
  8796. NewParsed = NewTA->parse();
  8797. llvm::sort(NewParsed.Features);
  8798. }
  8799. bool UseMemberUsingDeclRules =
  8800. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8801. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8802. // previous member of the MultiVersion set.
  8803. for (NamedDecl *ND : Previous) {
  8804. FunctionDecl *CurFD = ND->getAsFunction();
  8805. if (!CurFD)
  8806. continue;
  8807. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8808. continue;
  8809. if (NewMVType == MultiVersionKind::Target) {
  8810. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8811. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8812. NewFD->setIsMultiVersion();
  8813. Redeclaration = true;
  8814. OldDecl = ND;
  8815. return false;
  8816. }
  8817. TargetAttr::ParsedTargetAttr CurParsed =
  8818. CurTA->parse(std::less<std::string>());
  8819. if (CurParsed == NewParsed) {
  8820. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8821. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8822. NewFD->setInvalidDecl();
  8823. return true;
  8824. }
  8825. } else {
  8826. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8827. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8828. // Handle CPUDispatch/CPUSpecific versions.
  8829. // Only 1 CPUDispatch function is allowed, this will make it go through
  8830. // the redeclaration errors.
  8831. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8832. CurFD->hasAttr<CPUDispatchAttr>()) {
  8833. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8834. std::equal(
  8835. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8836. NewCPUDisp->cpus_begin(),
  8837. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8838. return Cur->getName() == New->getName();
  8839. })) {
  8840. NewFD->setIsMultiVersion();
  8841. Redeclaration = true;
  8842. OldDecl = ND;
  8843. return false;
  8844. }
  8845. // If the declarations don't match, this is an error condition.
  8846. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8847. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8848. NewFD->setInvalidDecl();
  8849. return true;
  8850. }
  8851. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8852. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8853. std::equal(
  8854. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8855. NewCPUSpec->cpus_begin(),
  8856. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8857. return Cur->getName() == New->getName();
  8858. })) {
  8859. NewFD->setIsMultiVersion();
  8860. Redeclaration = true;
  8861. OldDecl = ND;
  8862. return false;
  8863. }
  8864. // Only 1 version of CPUSpecific is allowed for each CPU.
  8865. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8866. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8867. if (CurII == NewII) {
  8868. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8869. << NewII;
  8870. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8871. NewFD->setInvalidDecl();
  8872. return true;
  8873. }
  8874. }
  8875. }
  8876. }
  8877. // If the two decls aren't the same MVType, there is no possible error
  8878. // condition.
  8879. }
  8880. }
  8881. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8882. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8883. // handled in the attribute adding step.
  8884. if (NewMVType == MultiVersionKind::Target &&
  8885. CheckMultiVersionValue(S, NewFD)) {
  8886. NewFD->setInvalidDecl();
  8887. return true;
  8888. }
  8889. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8890. !OldFD->isMultiVersion(), NewMVType)) {
  8891. NewFD->setInvalidDecl();
  8892. return true;
  8893. }
  8894. // Permit forward declarations in the case where these two are compatible.
  8895. if (!OldFD->isMultiVersion()) {
  8896. OldFD->setIsMultiVersion();
  8897. NewFD->setIsMultiVersion();
  8898. Redeclaration = true;
  8899. OldDecl = OldFD;
  8900. return false;
  8901. }
  8902. NewFD->setIsMultiVersion();
  8903. Redeclaration = false;
  8904. MergeTypeWithPrevious = false;
  8905. OldDecl = nullptr;
  8906. Previous.clear();
  8907. return false;
  8908. }
  8909. /// Check the validity of a mulitversion function declaration.
  8910. /// Also sets the multiversion'ness' of the function itself.
  8911. ///
  8912. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8913. ///
  8914. /// Returns true if there was an error, false otherwise.
  8915. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8916. bool &Redeclaration, NamedDecl *&OldDecl,
  8917. bool &MergeTypeWithPrevious,
  8918. LookupResult &Previous) {
  8919. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8920. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8921. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8922. // Mixing Multiversioning types is prohibited.
  8923. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8924. (NewCPUDisp && NewCPUSpec)) {
  8925. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8926. NewFD->setInvalidDecl();
  8927. return true;
  8928. }
  8929. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8930. // Main isn't allowed to become a multiversion function, however it IS
  8931. // permitted to have 'main' be marked with the 'target' optimization hint.
  8932. if (NewFD->isMain()) {
  8933. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8934. MVType == MultiVersionKind::CPUDispatch ||
  8935. MVType == MultiVersionKind::CPUSpecific) {
  8936. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8937. NewFD->setInvalidDecl();
  8938. return true;
  8939. }
  8940. return false;
  8941. }
  8942. if (!OldDecl || !OldDecl->getAsFunction() ||
  8943. OldDecl->getDeclContext()->getRedeclContext() !=
  8944. NewFD->getDeclContext()->getRedeclContext()) {
  8945. // If there's no previous declaration, AND this isn't attempting to cause
  8946. // multiversioning, this isn't an error condition.
  8947. if (MVType == MultiVersionKind::None)
  8948. return false;
  8949. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8950. }
  8951. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8952. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8953. return false;
  8954. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8955. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8956. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8957. NewFD->setInvalidDecl();
  8958. return true;
  8959. }
  8960. // Handle the target potentially causes multiversioning case.
  8961. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8962. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8963. Redeclaration, OldDecl,
  8964. MergeTypeWithPrevious, Previous);
  8965. // At this point, we have a multiversion function decl (in OldFD) AND an
  8966. // appropriate attribute in the current function decl. Resolve that these are
  8967. // still compatible with previous declarations.
  8968. return CheckMultiVersionAdditionalDecl(
  8969. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8970. OldDecl, MergeTypeWithPrevious, Previous);
  8971. }
  8972. /// Perform semantic checking of a new function declaration.
  8973. ///
  8974. /// Performs semantic analysis of the new function declaration
  8975. /// NewFD. This routine performs all semantic checking that does not
  8976. /// require the actual declarator involved in the declaration, and is
  8977. /// used both for the declaration of functions as they are parsed
  8978. /// (called via ActOnDeclarator) and for the declaration of functions
  8979. /// that have been instantiated via C++ template instantiation (called
  8980. /// via InstantiateDecl).
  8981. ///
  8982. /// \param IsMemberSpecialization whether this new function declaration is
  8983. /// a member specialization (that replaces any definition provided by the
  8984. /// previous declaration).
  8985. ///
  8986. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8987. ///
  8988. /// \returns true if the function declaration is a redeclaration.
  8989. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8990. LookupResult &Previous,
  8991. bool IsMemberSpecialization) {
  8992. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8993. "Variably modified return types are not handled here");
  8994. // Determine whether the type of this function should be merged with
  8995. // a previous visible declaration. This never happens for functions in C++,
  8996. // and always happens in C if the previous declaration was visible.
  8997. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8998. !Previous.isShadowed();
  8999. bool Redeclaration = false;
  9000. NamedDecl *OldDecl = nullptr;
  9001. bool MayNeedOverloadableChecks = false;
  9002. // Merge or overload the declaration with an existing declaration of
  9003. // the same name, if appropriate.
  9004. if (!Previous.empty()) {
  9005. // Determine whether NewFD is an overload of PrevDecl or
  9006. // a declaration that requires merging. If it's an overload,
  9007. // there's no more work to do here; we'll just add the new
  9008. // function to the scope.
  9009. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  9010. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  9011. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  9012. Redeclaration = true;
  9013. OldDecl = Candidate;
  9014. }
  9015. } else {
  9016. MayNeedOverloadableChecks = true;
  9017. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  9018. /*NewIsUsingDecl*/ false)) {
  9019. case Ovl_Match:
  9020. Redeclaration = true;
  9021. break;
  9022. case Ovl_NonFunction:
  9023. Redeclaration = true;
  9024. break;
  9025. case Ovl_Overload:
  9026. Redeclaration = false;
  9027. break;
  9028. }
  9029. }
  9030. }
  9031. // Check for a previous extern "C" declaration with this name.
  9032. if (!Redeclaration &&
  9033. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  9034. if (!Previous.empty()) {
  9035. // This is an extern "C" declaration with the same name as a previous
  9036. // declaration, and thus redeclares that entity...
  9037. Redeclaration = true;
  9038. OldDecl = Previous.getFoundDecl();
  9039. MergeTypeWithPrevious = false;
  9040. // ... except in the presence of __attribute__((overloadable)).
  9041. if (OldDecl->hasAttr<OverloadableAttr>() ||
  9042. NewFD->hasAttr<OverloadableAttr>()) {
  9043. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  9044. MayNeedOverloadableChecks = true;
  9045. Redeclaration = false;
  9046. OldDecl = nullptr;
  9047. }
  9048. }
  9049. }
  9050. }
  9051. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  9052. MergeTypeWithPrevious, Previous))
  9053. return Redeclaration;
  9054. // C++11 [dcl.constexpr]p8:
  9055. // A constexpr specifier for a non-static member function that is not
  9056. // a constructor declares that member function to be const.
  9057. //
  9058. // This needs to be delayed until we know whether this is an out-of-line
  9059. // definition of a static member function.
  9060. //
  9061. // This rule is not present in C++1y, so we produce a backwards
  9062. // compatibility warning whenever it happens in C++11.
  9063. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  9064. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  9065. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  9066. !MD->getMethodQualifiers().hasConst()) {
  9067. CXXMethodDecl *OldMD = nullptr;
  9068. if (OldDecl)
  9069. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  9070. if (!OldMD || !OldMD->isStatic()) {
  9071. const FunctionProtoType *FPT =
  9072. MD->getType()->castAs<FunctionProtoType>();
  9073. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9074. EPI.TypeQuals.addConst();
  9075. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  9076. FPT->getParamTypes(), EPI));
  9077. // Warn that we did this, if we're not performing template instantiation.
  9078. // In that case, we'll have warned already when the template was defined.
  9079. if (!inTemplateInstantiation()) {
  9080. SourceLocation AddConstLoc;
  9081. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  9082. .IgnoreParens().getAs<FunctionTypeLoc>())
  9083. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  9084. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  9085. << FixItHint::CreateInsertion(AddConstLoc, " const");
  9086. }
  9087. }
  9088. }
  9089. if (Redeclaration) {
  9090. // NewFD and OldDecl represent declarations that need to be
  9091. // merged.
  9092. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  9093. NewFD->setInvalidDecl();
  9094. return Redeclaration;
  9095. }
  9096. Previous.clear();
  9097. Previous.addDecl(OldDecl);
  9098. if (FunctionTemplateDecl *OldTemplateDecl =
  9099. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  9100. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  9101. FunctionTemplateDecl *NewTemplateDecl
  9102. = NewFD->getDescribedFunctionTemplate();
  9103. assert(NewTemplateDecl && "Template/non-template mismatch");
  9104. // The call to MergeFunctionDecl above may have created some state in
  9105. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  9106. // can add it as a redeclaration.
  9107. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  9108. NewFD->setPreviousDeclaration(OldFD);
  9109. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9110. if (NewFD->isCXXClassMember()) {
  9111. NewFD->setAccess(OldTemplateDecl->getAccess());
  9112. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9113. }
  9114. // If this is an explicit specialization of a member that is a function
  9115. // template, mark it as a member specialization.
  9116. if (IsMemberSpecialization &&
  9117. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9118. NewTemplateDecl->setMemberSpecialization();
  9119. assert(OldTemplateDecl->isMemberSpecialization());
  9120. // Explicit specializations of a member template do not inherit deleted
  9121. // status from the parent member template that they are specializing.
  9122. if (OldFD->isDeleted()) {
  9123. // FIXME: This assert will not hold in the presence of modules.
  9124. assert(OldFD->getCanonicalDecl() == OldFD);
  9125. // FIXME: We need an update record for this AST mutation.
  9126. OldFD->setDeletedAsWritten(false);
  9127. }
  9128. }
  9129. } else {
  9130. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9131. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9132. // This needs to happen first so that 'inline' propagates.
  9133. NewFD->setPreviousDeclaration(OldFD);
  9134. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9135. if (NewFD->isCXXClassMember())
  9136. NewFD->setAccess(OldFD->getAccess());
  9137. }
  9138. }
  9139. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9140. !NewFD->getAttr<OverloadableAttr>()) {
  9141. assert((Previous.empty() ||
  9142. llvm::any_of(Previous,
  9143. [](const NamedDecl *ND) {
  9144. return ND->hasAttr<OverloadableAttr>();
  9145. })) &&
  9146. "Non-redecls shouldn't happen without overloadable present");
  9147. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9148. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9149. return FD && !FD->hasAttr<OverloadableAttr>();
  9150. });
  9151. if (OtherUnmarkedIter != Previous.end()) {
  9152. Diag(NewFD->getLocation(),
  9153. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9154. Diag((*OtherUnmarkedIter)->getLocation(),
  9155. diag::note_attribute_overloadable_prev_overload)
  9156. << false;
  9157. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9158. }
  9159. }
  9160. // Semantic checking for this function declaration (in isolation).
  9161. if (getLangOpts().CPlusPlus) {
  9162. // C++-specific checks.
  9163. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9164. CheckConstructor(Constructor);
  9165. } else if (CXXDestructorDecl *Destructor =
  9166. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9167. CXXRecordDecl *Record = Destructor->getParent();
  9168. QualType ClassType = Context.getTypeDeclType(Record);
  9169. // FIXME: Shouldn't we be able to perform this check even when the class
  9170. // type is dependent? Both gcc and edg can handle that.
  9171. if (!ClassType->isDependentType()) {
  9172. DeclarationName Name
  9173. = Context.DeclarationNames.getCXXDestructorName(
  9174. Context.getCanonicalType(ClassType));
  9175. if (NewFD->getDeclName() != Name) {
  9176. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9177. NewFD->setInvalidDecl();
  9178. return Redeclaration;
  9179. }
  9180. }
  9181. } else if (CXXConversionDecl *Conversion
  9182. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9183. ActOnConversionDeclarator(Conversion);
  9184. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9185. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9186. CheckDeductionGuideTemplate(TD);
  9187. // A deduction guide is not on the list of entities that can be
  9188. // explicitly specialized.
  9189. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9190. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9191. << /*explicit specialization*/ 1;
  9192. }
  9193. // Find any virtual functions that this function overrides.
  9194. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9195. if (!Method->isFunctionTemplateSpecialization() &&
  9196. !Method->getDescribedFunctionTemplate() &&
  9197. Method->isCanonicalDecl()) {
  9198. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9199. // If the function was marked as "static", we have a problem.
  9200. if (NewFD->getStorageClass() == SC_Static) {
  9201. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9202. }
  9203. }
  9204. }
  9205. if (Method->isStatic())
  9206. checkThisInStaticMemberFunctionType(Method);
  9207. }
  9208. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9209. if (NewFD->isOverloadedOperator() &&
  9210. CheckOverloadedOperatorDeclaration(NewFD)) {
  9211. NewFD->setInvalidDecl();
  9212. return Redeclaration;
  9213. }
  9214. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9215. if (NewFD->getLiteralIdentifier() &&
  9216. CheckLiteralOperatorDeclaration(NewFD)) {
  9217. NewFD->setInvalidDecl();
  9218. return Redeclaration;
  9219. }
  9220. // In C++, check default arguments now that we have merged decls. Unless
  9221. // the lexical context is the class, because in this case this is done
  9222. // during delayed parsing anyway.
  9223. if (!CurContext->isRecord())
  9224. CheckCXXDefaultArguments(NewFD);
  9225. // If this function declares a builtin function, check the type of this
  9226. // declaration against the expected type for the builtin.
  9227. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9228. ASTContext::GetBuiltinTypeError Error;
  9229. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9230. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9231. // If the type of the builtin differs only in its exception
  9232. // specification, that's OK.
  9233. // FIXME: If the types do differ in this way, it would be better to
  9234. // retain the 'noexcept' form of the type.
  9235. if (!T.isNull() &&
  9236. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9237. NewFD->getType()))
  9238. // The type of this function differs from the type of the builtin,
  9239. // so forget about the builtin entirely.
  9240. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9241. }
  9242. // If this function is declared as being extern "C", then check to see if
  9243. // the function returns a UDT (class, struct, or union type) that is not C
  9244. // compatible, and if it does, warn the user.
  9245. // But, issue any diagnostic on the first declaration only.
  9246. if (Previous.empty() && NewFD->isExternC()) {
  9247. QualType R = NewFD->getReturnType();
  9248. if (R->isIncompleteType() && !R->isVoidType())
  9249. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9250. << NewFD << R;
  9251. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9252. !R->isObjCObjectPointerType())
  9253. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9254. }
  9255. // C++1z [dcl.fct]p6:
  9256. // [...] whether the function has a non-throwing exception-specification
  9257. // [is] part of the function type
  9258. //
  9259. // This results in an ABI break between C++14 and C++17 for functions whose
  9260. // declared type includes an exception-specification in a parameter or
  9261. // return type. (Exception specifications on the function itself are OK in
  9262. // most cases, and exception specifications are not permitted in most other
  9263. // contexts where they could make it into a mangling.)
  9264. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9265. auto HasNoexcept = [&](QualType T) -> bool {
  9266. // Strip off declarator chunks that could be between us and a function
  9267. // type. We don't need to look far, exception specifications are very
  9268. // restricted prior to C++17.
  9269. if (auto *RT = T->getAs<ReferenceType>())
  9270. T = RT->getPointeeType();
  9271. else if (T->isAnyPointerType())
  9272. T = T->getPointeeType();
  9273. else if (auto *MPT = T->getAs<MemberPointerType>())
  9274. T = MPT->getPointeeType();
  9275. if (auto *FPT = T->getAs<FunctionProtoType>())
  9276. if (FPT->isNothrow())
  9277. return true;
  9278. return false;
  9279. };
  9280. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9281. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9282. for (QualType T : FPT->param_types())
  9283. AnyNoexcept |= HasNoexcept(T);
  9284. if (AnyNoexcept)
  9285. Diag(NewFD->getLocation(),
  9286. diag::warn_cxx17_compat_exception_spec_in_signature)
  9287. << NewFD;
  9288. }
  9289. if (!Redeclaration && LangOpts.CUDA)
  9290. checkCUDATargetOverload(NewFD, Previous);
  9291. }
  9292. return Redeclaration;
  9293. }
  9294. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9295. // C++11 [basic.start.main]p3:
  9296. // A program that [...] declares main to be inline, static or
  9297. // constexpr is ill-formed.
  9298. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9299. // appear in a declaration of main.
  9300. // static main is not an error under C99, but we should warn about it.
  9301. // We accept _Noreturn main as an extension.
  9302. if (FD->getStorageClass() == SC_Static)
  9303. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9304. ? diag::err_static_main : diag::warn_static_main)
  9305. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9306. if (FD->isInlineSpecified())
  9307. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9308. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9309. if (DS.isNoreturnSpecified()) {
  9310. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9311. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9312. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9313. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9314. << FixItHint::CreateRemoval(NoreturnRange);
  9315. }
  9316. if (FD->isConstexpr()) {
  9317. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9318. << FD->isConsteval()
  9319. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9320. FD->setConstexprKind(CSK_unspecified);
  9321. }
  9322. if (getLangOpts().OpenCL) {
  9323. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9324. << FD->hasAttr<OpenCLKernelAttr>();
  9325. FD->setInvalidDecl();
  9326. return;
  9327. }
  9328. QualType T = FD->getType();
  9329. assert(T->isFunctionType() && "function decl is not of function type");
  9330. const FunctionType* FT = T->castAs<FunctionType>();
  9331. // Set default calling convention for main()
  9332. if (FT->getCallConv() != CC_C) {
  9333. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9334. FD->setType(QualType(FT, 0));
  9335. T = Context.getCanonicalType(FD->getType());
  9336. }
  9337. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9338. // In C with GNU extensions we allow main() to have non-integer return
  9339. // type, but we should warn about the extension, and we disable the
  9340. // implicit-return-zero rule.
  9341. // GCC in C mode accepts qualified 'int'.
  9342. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9343. FD->setHasImplicitReturnZero(true);
  9344. else {
  9345. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9346. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9347. if (RTRange.isValid())
  9348. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9349. << FixItHint::CreateReplacement(RTRange, "int");
  9350. }
  9351. } else {
  9352. // In C and C++, main magically returns 0 if you fall off the end;
  9353. // set the flag which tells us that.
  9354. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9355. // All the standards say that main() should return 'int'.
  9356. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9357. FD->setHasImplicitReturnZero(true);
  9358. else {
  9359. // Otherwise, this is just a flat-out error.
  9360. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9361. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9362. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9363. : FixItHint());
  9364. FD->setInvalidDecl(true);
  9365. }
  9366. }
  9367. // Treat protoless main() as nullary.
  9368. if (isa<FunctionNoProtoType>(FT)) return;
  9369. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9370. unsigned nparams = FTP->getNumParams();
  9371. assert(FD->getNumParams() == nparams);
  9372. bool HasExtraParameters = (nparams > 3);
  9373. if (FTP->isVariadic()) {
  9374. Diag(FD->getLocation(), diag::ext_variadic_main);
  9375. // FIXME: if we had information about the location of the ellipsis, we
  9376. // could add a FixIt hint to remove it as a parameter.
  9377. }
  9378. // Darwin passes an undocumented fourth argument of type char**. If
  9379. // other platforms start sprouting these, the logic below will start
  9380. // getting shifty.
  9381. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9382. HasExtraParameters = false;
  9383. if (HasExtraParameters) {
  9384. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9385. FD->setInvalidDecl(true);
  9386. nparams = 3;
  9387. }
  9388. // FIXME: a lot of the following diagnostics would be improved
  9389. // if we had some location information about types.
  9390. QualType CharPP =
  9391. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9392. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9393. for (unsigned i = 0; i < nparams; ++i) {
  9394. QualType AT = FTP->getParamType(i);
  9395. bool mismatch = true;
  9396. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9397. mismatch = false;
  9398. else if (Expected[i] == CharPP) {
  9399. // As an extension, the following forms are okay:
  9400. // char const **
  9401. // char const * const *
  9402. // char * const *
  9403. QualifierCollector qs;
  9404. const PointerType* PT;
  9405. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9406. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9407. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9408. Context.CharTy)) {
  9409. qs.removeConst();
  9410. mismatch = !qs.empty();
  9411. }
  9412. }
  9413. if (mismatch) {
  9414. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9415. // TODO: suggest replacing given type with expected type
  9416. FD->setInvalidDecl(true);
  9417. }
  9418. }
  9419. if (nparams == 1 && !FD->isInvalidDecl()) {
  9420. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9421. }
  9422. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9423. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9424. FD->setInvalidDecl();
  9425. }
  9426. }
  9427. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9428. QualType T = FD->getType();
  9429. assert(T->isFunctionType() && "function decl is not of function type");
  9430. const FunctionType *FT = T->castAs<FunctionType>();
  9431. // Set an implicit return of 'zero' if the function can return some integral,
  9432. // enumeration, pointer or nullptr type.
  9433. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9434. FT->getReturnType()->isAnyPointerType() ||
  9435. FT->getReturnType()->isNullPtrType())
  9436. // DllMain is exempt because a return value of zero means it failed.
  9437. if (FD->getName() != "DllMain")
  9438. FD->setHasImplicitReturnZero(true);
  9439. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9440. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9441. FD->setInvalidDecl();
  9442. }
  9443. }
  9444. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9445. // FIXME: Need strict checking. In C89, we need to check for
  9446. // any assignment, increment, decrement, function-calls, or
  9447. // commas outside of a sizeof. In C99, it's the same list,
  9448. // except that the aforementioned are allowed in unevaluated
  9449. // expressions. Everything else falls under the
  9450. // "may accept other forms of constant expressions" exception.
  9451. // (We never end up here for C++, so the constant expression
  9452. // rules there don't matter.)
  9453. const Expr *Culprit;
  9454. if (Init->isConstantInitializer(Context, false, &Culprit))
  9455. return false;
  9456. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9457. << Culprit->getSourceRange();
  9458. return true;
  9459. }
  9460. namespace {
  9461. // Visits an initialization expression to see if OrigDecl is evaluated in
  9462. // its own initialization and throws a warning if it does.
  9463. class SelfReferenceChecker
  9464. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9465. Sema &S;
  9466. Decl *OrigDecl;
  9467. bool isRecordType;
  9468. bool isPODType;
  9469. bool isReferenceType;
  9470. bool isInitList;
  9471. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9472. public:
  9473. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9474. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9475. S(S), OrigDecl(OrigDecl) {
  9476. isPODType = false;
  9477. isRecordType = false;
  9478. isReferenceType = false;
  9479. isInitList = false;
  9480. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9481. isPODType = VD->getType().isPODType(S.Context);
  9482. isRecordType = VD->getType()->isRecordType();
  9483. isReferenceType = VD->getType()->isReferenceType();
  9484. }
  9485. }
  9486. // For most expressions, just call the visitor. For initializer lists,
  9487. // track the index of the field being initialized since fields are
  9488. // initialized in order allowing use of previously initialized fields.
  9489. void CheckExpr(Expr *E) {
  9490. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9491. if (!InitList) {
  9492. Visit(E);
  9493. return;
  9494. }
  9495. // Track and increment the index here.
  9496. isInitList = true;
  9497. InitFieldIndex.push_back(0);
  9498. for (auto Child : InitList->children()) {
  9499. CheckExpr(cast<Expr>(Child));
  9500. ++InitFieldIndex.back();
  9501. }
  9502. InitFieldIndex.pop_back();
  9503. }
  9504. // Returns true if MemberExpr is checked and no further checking is needed.
  9505. // Returns false if additional checking is required.
  9506. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9507. llvm::SmallVector<FieldDecl*, 4> Fields;
  9508. Expr *Base = E;
  9509. bool ReferenceField = false;
  9510. // Get the field members used.
  9511. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9512. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9513. if (!FD)
  9514. return false;
  9515. Fields.push_back(FD);
  9516. if (FD->getType()->isReferenceType())
  9517. ReferenceField = true;
  9518. Base = ME->getBase()->IgnoreParenImpCasts();
  9519. }
  9520. // Keep checking only if the base Decl is the same.
  9521. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9522. if (!DRE || DRE->getDecl() != OrigDecl)
  9523. return false;
  9524. // A reference field can be bound to an unininitialized field.
  9525. if (CheckReference && !ReferenceField)
  9526. return true;
  9527. // Convert FieldDecls to their index number.
  9528. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9529. for (const FieldDecl *I : llvm::reverse(Fields))
  9530. UsedFieldIndex.push_back(I->getFieldIndex());
  9531. // See if a warning is needed by checking the first difference in index
  9532. // numbers. If field being used has index less than the field being
  9533. // initialized, then the use is safe.
  9534. for (auto UsedIter = UsedFieldIndex.begin(),
  9535. UsedEnd = UsedFieldIndex.end(),
  9536. OrigIter = InitFieldIndex.begin(),
  9537. OrigEnd = InitFieldIndex.end();
  9538. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9539. if (*UsedIter < *OrigIter)
  9540. return true;
  9541. if (*UsedIter > *OrigIter)
  9542. break;
  9543. }
  9544. // TODO: Add a different warning which will print the field names.
  9545. HandleDeclRefExpr(DRE);
  9546. return true;
  9547. }
  9548. // For most expressions, the cast is directly above the DeclRefExpr.
  9549. // For conditional operators, the cast can be outside the conditional
  9550. // operator if both expressions are DeclRefExpr's.
  9551. void HandleValue(Expr *E) {
  9552. E = E->IgnoreParens();
  9553. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9554. HandleDeclRefExpr(DRE);
  9555. return;
  9556. }
  9557. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9558. Visit(CO->getCond());
  9559. HandleValue(CO->getTrueExpr());
  9560. HandleValue(CO->getFalseExpr());
  9561. return;
  9562. }
  9563. if (BinaryConditionalOperator *BCO =
  9564. dyn_cast<BinaryConditionalOperator>(E)) {
  9565. Visit(BCO->getCond());
  9566. HandleValue(BCO->getFalseExpr());
  9567. return;
  9568. }
  9569. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9570. HandleValue(OVE->getSourceExpr());
  9571. return;
  9572. }
  9573. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9574. if (BO->getOpcode() == BO_Comma) {
  9575. Visit(BO->getLHS());
  9576. HandleValue(BO->getRHS());
  9577. return;
  9578. }
  9579. }
  9580. if (isa<MemberExpr>(E)) {
  9581. if (isInitList) {
  9582. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9583. false /*CheckReference*/))
  9584. return;
  9585. }
  9586. Expr *Base = E->IgnoreParenImpCasts();
  9587. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9588. // Check for static member variables and don't warn on them.
  9589. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9590. return;
  9591. Base = ME->getBase()->IgnoreParenImpCasts();
  9592. }
  9593. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9594. HandleDeclRefExpr(DRE);
  9595. return;
  9596. }
  9597. Visit(E);
  9598. }
  9599. // Reference types not handled in HandleValue are handled here since all
  9600. // uses of references are bad, not just r-value uses.
  9601. void VisitDeclRefExpr(DeclRefExpr *E) {
  9602. if (isReferenceType)
  9603. HandleDeclRefExpr(E);
  9604. }
  9605. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9606. if (E->getCastKind() == CK_LValueToRValue) {
  9607. HandleValue(E->getSubExpr());
  9608. return;
  9609. }
  9610. Inherited::VisitImplicitCastExpr(E);
  9611. }
  9612. void VisitMemberExpr(MemberExpr *E) {
  9613. if (isInitList) {
  9614. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9615. return;
  9616. }
  9617. // Don't warn on arrays since they can be treated as pointers.
  9618. if (E->getType()->canDecayToPointerType()) return;
  9619. // Warn when a non-static method call is followed by non-static member
  9620. // field accesses, which is followed by a DeclRefExpr.
  9621. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9622. bool Warn = (MD && !MD->isStatic());
  9623. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9624. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9625. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9626. Warn = false;
  9627. Base = ME->getBase()->IgnoreParenImpCasts();
  9628. }
  9629. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9630. if (Warn)
  9631. HandleDeclRefExpr(DRE);
  9632. return;
  9633. }
  9634. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9635. // Visit that expression.
  9636. Visit(Base);
  9637. }
  9638. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9639. Expr *Callee = E->getCallee();
  9640. if (isa<UnresolvedLookupExpr>(Callee))
  9641. return Inherited::VisitCXXOperatorCallExpr(E);
  9642. Visit(Callee);
  9643. for (auto Arg: E->arguments())
  9644. HandleValue(Arg->IgnoreParenImpCasts());
  9645. }
  9646. void VisitUnaryOperator(UnaryOperator *E) {
  9647. // For POD record types, addresses of its own members are well-defined.
  9648. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9649. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9650. if (!isPODType)
  9651. HandleValue(E->getSubExpr());
  9652. return;
  9653. }
  9654. if (E->isIncrementDecrementOp()) {
  9655. HandleValue(E->getSubExpr());
  9656. return;
  9657. }
  9658. Inherited::VisitUnaryOperator(E);
  9659. }
  9660. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9661. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9662. if (E->getConstructor()->isCopyConstructor()) {
  9663. Expr *ArgExpr = E->getArg(0);
  9664. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9665. if (ILE->getNumInits() == 1)
  9666. ArgExpr = ILE->getInit(0);
  9667. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9668. if (ICE->getCastKind() == CK_NoOp)
  9669. ArgExpr = ICE->getSubExpr();
  9670. HandleValue(ArgExpr);
  9671. return;
  9672. }
  9673. Inherited::VisitCXXConstructExpr(E);
  9674. }
  9675. void VisitCallExpr(CallExpr *E) {
  9676. // Treat std::move as a use.
  9677. if (E->isCallToStdMove()) {
  9678. HandleValue(E->getArg(0));
  9679. return;
  9680. }
  9681. Inherited::VisitCallExpr(E);
  9682. }
  9683. void VisitBinaryOperator(BinaryOperator *E) {
  9684. if (E->isCompoundAssignmentOp()) {
  9685. HandleValue(E->getLHS());
  9686. Visit(E->getRHS());
  9687. return;
  9688. }
  9689. Inherited::VisitBinaryOperator(E);
  9690. }
  9691. // A custom visitor for BinaryConditionalOperator is needed because the
  9692. // regular visitor would check the condition and true expression separately
  9693. // but both point to the same place giving duplicate diagnostics.
  9694. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9695. Visit(E->getCond());
  9696. Visit(E->getFalseExpr());
  9697. }
  9698. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9699. Decl* ReferenceDecl = DRE->getDecl();
  9700. if (OrigDecl != ReferenceDecl) return;
  9701. unsigned diag;
  9702. if (isReferenceType) {
  9703. diag = diag::warn_uninit_self_reference_in_reference_init;
  9704. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9705. diag = diag::warn_static_self_reference_in_init;
  9706. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9707. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9708. DRE->getDecl()->getType()->isRecordType()) {
  9709. diag = diag::warn_uninit_self_reference_in_init;
  9710. } else {
  9711. // Local variables will be handled by the CFG analysis.
  9712. return;
  9713. }
  9714. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9715. S.PDiag(diag)
  9716. << DRE->getDecl() << OrigDecl->getLocation()
  9717. << DRE->getSourceRange());
  9718. }
  9719. };
  9720. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9721. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9722. bool DirectInit) {
  9723. // Parameters arguments are occassionially constructed with itself,
  9724. // for instance, in recursive functions. Skip them.
  9725. if (isa<ParmVarDecl>(OrigDecl))
  9726. return;
  9727. E = E->IgnoreParens();
  9728. // Skip checking T a = a where T is not a record or reference type.
  9729. // Doing so is a way to silence uninitialized warnings.
  9730. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9731. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9732. if (ICE->getCastKind() == CK_LValueToRValue)
  9733. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9734. if (DRE->getDecl() == OrigDecl)
  9735. return;
  9736. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9737. }
  9738. } // end anonymous namespace
  9739. namespace {
  9740. // Simple wrapper to add the name of a variable or (if no variable is
  9741. // available) a DeclarationName into a diagnostic.
  9742. struct VarDeclOrName {
  9743. VarDecl *VDecl;
  9744. DeclarationName Name;
  9745. friend const Sema::SemaDiagnosticBuilder &
  9746. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9747. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9748. }
  9749. };
  9750. } // end anonymous namespace
  9751. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9752. DeclarationName Name, QualType Type,
  9753. TypeSourceInfo *TSI,
  9754. SourceRange Range, bool DirectInit,
  9755. Expr *Init) {
  9756. bool IsInitCapture = !VDecl;
  9757. assert((!VDecl || !VDecl->isInitCapture()) &&
  9758. "init captures are expected to be deduced prior to initialization");
  9759. VarDeclOrName VN{VDecl, Name};
  9760. DeducedType *Deduced = Type->getContainedDeducedType();
  9761. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9762. // C++11 [dcl.spec.auto]p3
  9763. if (!Init) {
  9764. assert(VDecl && "no init for init capture deduction?");
  9765. // Except for class argument deduction, and then for an initializing
  9766. // declaration only, i.e. no static at class scope or extern.
  9767. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9768. VDecl->hasExternalStorage() ||
  9769. VDecl->isStaticDataMember()) {
  9770. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9771. << VDecl->getDeclName() << Type;
  9772. return QualType();
  9773. }
  9774. }
  9775. ArrayRef<Expr*> DeduceInits;
  9776. if (Init)
  9777. DeduceInits = Init;
  9778. if (DirectInit) {
  9779. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9780. DeduceInits = PL->exprs();
  9781. }
  9782. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9783. assert(VDecl && "non-auto type for init capture deduction?");
  9784. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9785. InitializationKind Kind = InitializationKind::CreateForInit(
  9786. VDecl->getLocation(), DirectInit, Init);
  9787. // FIXME: Initialization should not be taking a mutable list of inits.
  9788. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9789. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9790. InitsCopy);
  9791. }
  9792. if (DirectInit) {
  9793. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9794. DeduceInits = IL->inits();
  9795. }
  9796. // Deduction only works if we have exactly one source expression.
  9797. if (DeduceInits.empty()) {
  9798. // It isn't possible to write this directly, but it is possible to
  9799. // end up in this situation with "auto x(some_pack...);"
  9800. Diag(Init->getBeginLoc(), IsInitCapture
  9801. ? diag::err_init_capture_no_expression
  9802. : diag::err_auto_var_init_no_expression)
  9803. << VN << Type << Range;
  9804. return QualType();
  9805. }
  9806. if (DeduceInits.size() > 1) {
  9807. Diag(DeduceInits[1]->getBeginLoc(),
  9808. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9809. : diag::err_auto_var_init_multiple_expressions)
  9810. << VN << Type << Range;
  9811. return QualType();
  9812. }
  9813. Expr *DeduceInit = DeduceInits[0];
  9814. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9815. Diag(Init->getBeginLoc(), IsInitCapture
  9816. ? diag::err_init_capture_paren_braces
  9817. : diag::err_auto_var_init_paren_braces)
  9818. << isa<InitListExpr>(Init) << VN << Type << Range;
  9819. return QualType();
  9820. }
  9821. // Expressions default to 'id' when we're in a debugger.
  9822. bool DefaultedAnyToId = false;
  9823. if (getLangOpts().DebuggerCastResultToId &&
  9824. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9825. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9826. if (Result.isInvalid()) {
  9827. return QualType();
  9828. }
  9829. Init = Result.get();
  9830. DefaultedAnyToId = true;
  9831. }
  9832. // C++ [dcl.decomp]p1:
  9833. // If the assignment-expression [...] has array type A and no ref-qualifier
  9834. // is present, e has type cv A
  9835. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9836. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9837. DeduceInit->getType()->isConstantArrayType())
  9838. return Context.getQualifiedType(DeduceInit->getType(),
  9839. Type.getQualifiers());
  9840. QualType DeducedType;
  9841. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9842. if (!IsInitCapture)
  9843. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9844. else if (isa<InitListExpr>(Init))
  9845. Diag(Range.getBegin(),
  9846. diag::err_init_capture_deduction_failure_from_init_list)
  9847. << VN
  9848. << (DeduceInit->getType().isNull() ? TSI->getType()
  9849. : DeduceInit->getType())
  9850. << DeduceInit->getSourceRange();
  9851. else
  9852. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9853. << VN << TSI->getType()
  9854. << (DeduceInit->getType().isNull() ? TSI->getType()
  9855. : DeduceInit->getType())
  9856. << DeduceInit->getSourceRange();
  9857. }
  9858. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9859. // 'id' instead of a specific object type prevents most of our usual
  9860. // checks.
  9861. // We only want to warn outside of template instantiations, though:
  9862. // inside a template, the 'id' could have come from a parameter.
  9863. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9864. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9865. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9866. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9867. }
  9868. return DeducedType;
  9869. }
  9870. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9871. Expr *Init) {
  9872. QualType DeducedType = deduceVarTypeFromInitializer(
  9873. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9874. VDecl->getSourceRange(), DirectInit, Init);
  9875. if (DeducedType.isNull()) {
  9876. VDecl->setInvalidDecl();
  9877. return true;
  9878. }
  9879. VDecl->setType(DeducedType);
  9880. assert(VDecl->isLinkageValid());
  9881. // In ARC, infer lifetime.
  9882. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9883. VDecl->setInvalidDecl();
  9884. // If this is a redeclaration, check that the type we just deduced matches
  9885. // the previously declared type.
  9886. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9887. // We never need to merge the type, because we cannot form an incomplete
  9888. // array of auto, nor deduce such a type.
  9889. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9890. }
  9891. // Check the deduced type is valid for a variable declaration.
  9892. CheckVariableDeclarationType(VDecl);
  9893. return VDecl->isInvalidDecl();
  9894. }
  9895. /// AddInitializerToDecl - Adds the initializer Init to the
  9896. /// declaration dcl. If DirectInit is true, this is C++ direct
  9897. /// initialization rather than copy initialization.
  9898. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9899. // If there is no declaration, there was an error parsing it. Just ignore
  9900. // the initializer.
  9901. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9902. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9903. return;
  9904. }
  9905. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9906. // Pure-specifiers are handled in ActOnPureSpecifier.
  9907. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9908. << Method->getDeclName() << Init->getSourceRange();
  9909. Method->setInvalidDecl();
  9910. return;
  9911. }
  9912. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9913. if (!VDecl) {
  9914. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9915. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9916. RealDecl->setInvalidDecl();
  9917. return;
  9918. }
  9919. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9920. if (VDecl->getType()->isUndeducedType()) {
  9921. // Attempt typo correction early so that the type of the init expression can
  9922. // be deduced based on the chosen correction if the original init contains a
  9923. // TypoExpr.
  9924. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9925. if (!Res.isUsable()) {
  9926. RealDecl->setInvalidDecl();
  9927. return;
  9928. }
  9929. Init = Res.get();
  9930. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9931. return;
  9932. }
  9933. // dllimport cannot be used on variable definitions.
  9934. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9935. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9936. VDecl->setInvalidDecl();
  9937. return;
  9938. }
  9939. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9940. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9941. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9942. VDecl->setInvalidDecl();
  9943. return;
  9944. }
  9945. if (!VDecl->getType()->isDependentType()) {
  9946. // A definition must end up with a complete type, which means it must be
  9947. // complete with the restriction that an array type might be completed by
  9948. // the initializer; note that later code assumes this restriction.
  9949. QualType BaseDeclType = VDecl->getType();
  9950. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9951. BaseDeclType = Array->getElementType();
  9952. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9953. diag::err_typecheck_decl_incomplete_type)) {
  9954. RealDecl->setInvalidDecl();
  9955. return;
  9956. }
  9957. // The variable can not have an abstract class type.
  9958. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9959. diag::err_abstract_type_in_decl,
  9960. AbstractVariableType))
  9961. VDecl->setInvalidDecl();
  9962. }
  9963. // If adding the initializer will turn this declaration into a definition,
  9964. // and we already have a definition for this variable, diagnose or otherwise
  9965. // handle the situation.
  9966. VarDecl *Def;
  9967. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9968. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9969. !VDecl->isThisDeclarationADemotedDefinition() &&
  9970. checkVarDeclRedefinition(Def, VDecl))
  9971. return;
  9972. if (getLangOpts().CPlusPlus) {
  9973. // C++ [class.static.data]p4
  9974. // If a static data member is of const integral or const
  9975. // enumeration type, its declaration in the class definition can
  9976. // specify a constant-initializer which shall be an integral
  9977. // constant expression (5.19). In that case, the member can appear
  9978. // in integral constant expressions. The member shall still be
  9979. // defined in a namespace scope if it is used in the program and the
  9980. // namespace scope definition shall not contain an initializer.
  9981. //
  9982. // We already performed a redefinition check above, but for static
  9983. // data members we also need to check whether there was an in-class
  9984. // declaration with an initializer.
  9985. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9986. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9987. << VDecl->getDeclName();
  9988. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9989. diag::note_previous_initializer)
  9990. << 0;
  9991. return;
  9992. }
  9993. if (VDecl->hasLocalStorage())
  9994. setFunctionHasBranchProtectedScope();
  9995. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9996. VDecl->setInvalidDecl();
  9997. return;
  9998. }
  9999. }
  10000. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10001. // a kernel function cannot be initialized."
  10002. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10003. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10004. VDecl->setInvalidDecl();
  10005. return;
  10006. }
  10007. // Get the decls type and save a reference for later, since
  10008. // CheckInitializerTypes may change it.
  10009. QualType DclT = VDecl->getType(), SavT = DclT;
  10010. // Expressions default to 'id' when we're in a debugger
  10011. // and we are assigning it to a variable of Objective-C pointer type.
  10012. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10013. Init->getType() == Context.UnknownAnyTy) {
  10014. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10015. if (Result.isInvalid()) {
  10016. VDecl->setInvalidDecl();
  10017. return;
  10018. }
  10019. Init = Result.get();
  10020. }
  10021. // Perform the initialization.
  10022. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10023. if (!VDecl->isInvalidDecl()) {
  10024. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10025. InitializationKind Kind = InitializationKind::CreateForInit(
  10026. VDecl->getLocation(), DirectInit, Init);
  10027. MultiExprArg Args = Init;
  10028. if (CXXDirectInit)
  10029. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10030. CXXDirectInit->getNumExprs());
  10031. // Try to correct any TypoExprs in the initialization arguments.
  10032. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10033. ExprResult Res = CorrectDelayedTyposInExpr(
  10034. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10035. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10036. return Init.Failed() ? ExprError() : E;
  10037. });
  10038. if (Res.isInvalid()) {
  10039. VDecl->setInvalidDecl();
  10040. } else if (Res.get() != Args[Idx]) {
  10041. Args[Idx] = Res.get();
  10042. }
  10043. }
  10044. if (VDecl->isInvalidDecl())
  10045. return;
  10046. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10047. /*TopLevelOfInitList=*/false,
  10048. /*TreatUnavailableAsInvalid=*/false);
  10049. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10050. if (Result.isInvalid()) {
  10051. VDecl->setInvalidDecl();
  10052. return;
  10053. }
  10054. Init = Result.getAs<Expr>();
  10055. }
  10056. // Check for self-references within variable initializers.
  10057. // Variables declared within a function/method body (except for references)
  10058. // are handled by a dataflow analysis.
  10059. // This is undefined behavior in C++, but valid in C.
  10060. if (getLangOpts().CPlusPlus) {
  10061. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10062. VDecl->getType()->isReferenceType()) {
  10063. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10064. }
  10065. }
  10066. // If the type changed, it means we had an incomplete type that was
  10067. // completed by the initializer. For example:
  10068. // int ary[] = { 1, 3, 5 };
  10069. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10070. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10071. VDecl->setType(DclT);
  10072. if (!VDecl->isInvalidDecl()) {
  10073. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10074. if (VDecl->hasAttr<BlocksAttr>())
  10075. checkRetainCycles(VDecl, Init);
  10076. // It is safe to assign a weak reference into a strong variable.
  10077. // Although this code can still have problems:
  10078. // id x = self.weakProp;
  10079. // id y = self.weakProp;
  10080. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10081. // paths through the function. This should be revisited if
  10082. // -Wrepeated-use-of-weak is made flow-sensitive.
  10083. if (FunctionScopeInfo *FSI = getCurFunction())
  10084. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10085. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10086. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10087. Init->getBeginLoc()))
  10088. FSI->markSafeWeakUse(Init);
  10089. }
  10090. // The initialization is usually a full-expression.
  10091. //
  10092. // FIXME: If this is a braced initialization of an aggregate, it is not
  10093. // an expression, and each individual field initializer is a separate
  10094. // full-expression. For instance, in:
  10095. //
  10096. // struct Temp { ~Temp(); };
  10097. // struct S { S(Temp); };
  10098. // struct T { S a, b; } t = { Temp(), Temp() }
  10099. //
  10100. // we should destroy the first Temp before constructing the second.
  10101. ExprResult Result =
  10102. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10103. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10104. if (Result.isInvalid()) {
  10105. VDecl->setInvalidDecl();
  10106. return;
  10107. }
  10108. Init = Result.get();
  10109. // Attach the initializer to the decl.
  10110. VDecl->setInit(Init);
  10111. if (VDecl->isLocalVarDecl()) {
  10112. // Don't check the initializer if the declaration is malformed.
  10113. if (VDecl->isInvalidDecl()) {
  10114. // do nothing
  10115. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10116. // This is true even in C++ for OpenCL.
  10117. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10118. CheckForConstantInitializer(Init, DclT);
  10119. // Otherwise, C++ does not restrict the initializer.
  10120. } else if (getLangOpts().CPlusPlus) {
  10121. // do nothing
  10122. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10123. // static storage duration shall be constant expressions or string literals.
  10124. } else if (VDecl->getStorageClass() == SC_Static) {
  10125. CheckForConstantInitializer(Init, DclT);
  10126. // C89 is stricter than C99 for aggregate initializers.
  10127. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10128. // for an object that has aggregate or union type shall be
  10129. // constant expressions.
  10130. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10131. isa<InitListExpr>(Init)) {
  10132. const Expr *Culprit;
  10133. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10134. Diag(Culprit->getExprLoc(),
  10135. diag::ext_aggregate_init_not_constant)
  10136. << Culprit->getSourceRange();
  10137. }
  10138. }
  10139. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10140. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10141. if (VDecl->hasLocalStorage())
  10142. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10143. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10144. VDecl->getLexicalDeclContext()->isRecord()) {
  10145. // This is an in-class initialization for a static data member, e.g.,
  10146. //
  10147. // struct S {
  10148. // static const int value = 17;
  10149. // };
  10150. // C++ [class.mem]p4:
  10151. // A member-declarator can contain a constant-initializer only
  10152. // if it declares a static member (9.4) of const integral or
  10153. // const enumeration type, see 9.4.2.
  10154. //
  10155. // C++11 [class.static.data]p3:
  10156. // If a non-volatile non-inline const static data member is of integral
  10157. // or enumeration type, its declaration in the class definition can
  10158. // specify a brace-or-equal-initializer in which every initializer-clause
  10159. // that is an assignment-expression is a constant expression. A static
  10160. // data member of literal type can be declared in the class definition
  10161. // with the constexpr specifier; if so, its declaration shall specify a
  10162. // brace-or-equal-initializer in which every initializer-clause that is
  10163. // an assignment-expression is a constant expression.
  10164. // Do nothing on dependent types.
  10165. if (DclT->isDependentType()) {
  10166. // Allow any 'static constexpr' members, whether or not they are of literal
  10167. // type. We separately check that every constexpr variable is of literal
  10168. // type.
  10169. } else if (VDecl->isConstexpr()) {
  10170. // Require constness.
  10171. } else if (!DclT.isConstQualified()) {
  10172. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10173. << Init->getSourceRange();
  10174. VDecl->setInvalidDecl();
  10175. // We allow integer constant expressions in all cases.
  10176. } else if (DclT->isIntegralOrEnumerationType()) {
  10177. // Check whether the expression is a constant expression.
  10178. SourceLocation Loc;
  10179. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10180. // In C++11, a non-constexpr const static data member with an
  10181. // in-class initializer cannot be volatile.
  10182. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10183. else if (Init->isValueDependent())
  10184. ; // Nothing to check.
  10185. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10186. ; // Ok, it's an ICE!
  10187. else if (Init->getType()->isScopedEnumeralType() &&
  10188. Init->isCXX11ConstantExpr(Context))
  10189. ; // Ok, it is a scoped-enum constant expression.
  10190. else if (Init->isEvaluatable(Context)) {
  10191. // If we can constant fold the initializer through heroics, accept it,
  10192. // but report this as a use of an extension for -pedantic.
  10193. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10194. << Init->getSourceRange();
  10195. } else {
  10196. // Otherwise, this is some crazy unknown case. Report the issue at the
  10197. // location provided by the isIntegerConstantExpr failed check.
  10198. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10199. << Init->getSourceRange();
  10200. VDecl->setInvalidDecl();
  10201. }
  10202. // We allow foldable floating-point constants as an extension.
  10203. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10204. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10205. // it anyway and provide a fixit to add the 'constexpr'.
  10206. if (getLangOpts().CPlusPlus11) {
  10207. Diag(VDecl->getLocation(),
  10208. diag::ext_in_class_initializer_float_type_cxx11)
  10209. << DclT << Init->getSourceRange();
  10210. Diag(VDecl->getBeginLoc(),
  10211. diag::note_in_class_initializer_float_type_cxx11)
  10212. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10213. } else {
  10214. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10215. << DclT << Init->getSourceRange();
  10216. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10217. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10218. << Init->getSourceRange();
  10219. VDecl->setInvalidDecl();
  10220. }
  10221. }
  10222. // Suggest adding 'constexpr' in C++11 for literal types.
  10223. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10224. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10225. << DclT << Init->getSourceRange()
  10226. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10227. VDecl->setConstexpr(true);
  10228. } else {
  10229. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10230. << DclT << Init->getSourceRange();
  10231. VDecl->setInvalidDecl();
  10232. }
  10233. } else if (VDecl->isFileVarDecl()) {
  10234. // In C, extern is typically used to avoid tentative definitions when
  10235. // declaring variables in headers, but adding an intializer makes it a
  10236. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10237. // In C++, extern is often used to give implictly static const variables
  10238. // external linkage, so don't warn in that case. If selectany is present,
  10239. // this might be header code intended for C and C++ inclusion, so apply the
  10240. // C++ rules.
  10241. if (VDecl->getStorageClass() == SC_Extern &&
  10242. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10243. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10244. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10245. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10246. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10247. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10248. // external linkage by default if the variable is declared with
  10249. // __declspec(dllexport).
  10250. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10251. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10252. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10253. VDecl->setStorageClass(SC_Extern);
  10254. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10255. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10256. CheckForConstantInitializer(Init, DclT);
  10257. }
  10258. // We will represent direct-initialization similarly to copy-initialization:
  10259. // int x(1); -as-> int x = 1;
  10260. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10261. //
  10262. // Clients that want to distinguish between the two forms, can check for
  10263. // direct initializer using VarDecl::getInitStyle().
  10264. // A major benefit is that clients that don't particularly care about which
  10265. // exactly form was it (like the CodeGen) can handle both cases without
  10266. // special case code.
  10267. // C++ 8.5p11:
  10268. // The form of initialization (using parentheses or '=') is generally
  10269. // insignificant, but does matter when the entity being initialized has a
  10270. // class type.
  10271. if (CXXDirectInit) {
  10272. assert(DirectInit && "Call-style initializer must be direct init.");
  10273. VDecl->setInitStyle(VarDecl::CallInit);
  10274. } else if (DirectInit) {
  10275. // This must be list-initialization. No other way is direct-initialization.
  10276. VDecl->setInitStyle(VarDecl::ListInit);
  10277. }
  10278. CheckCompleteVariableDeclaration(VDecl);
  10279. }
  10280. /// ActOnInitializerError - Given that there was an error parsing an
  10281. /// initializer for the given declaration, try to return to some form
  10282. /// of sanity.
  10283. void Sema::ActOnInitializerError(Decl *D) {
  10284. // Our main concern here is re-establishing invariants like "a
  10285. // variable's type is either dependent or complete".
  10286. if (!D || D->isInvalidDecl()) return;
  10287. VarDecl *VD = dyn_cast<VarDecl>(D);
  10288. if (!VD) return;
  10289. // Bindings are not usable if we can't make sense of the initializer.
  10290. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10291. for (auto *BD : DD->bindings())
  10292. BD->setInvalidDecl();
  10293. // Auto types are meaningless if we can't make sense of the initializer.
  10294. if (ParsingInitForAutoVars.count(D)) {
  10295. D->setInvalidDecl();
  10296. return;
  10297. }
  10298. QualType Ty = VD->getType();
  10299. if (Ty->isDependentType()) return;
  10300. // Require a complete type.
  10301. if (RequireCompleteType(VD->getLocation(),
  10302. Context.getBaseElementType(Ty),
  10303. diag::err_typecheck_decl_incomplete_type)) {
  10304. VD->setInvalidDecl();
  10305. return;
  10306. }
  10307. // Require a non-abstract type.
  10308. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10309. diag::err_abstract_type_in_decl,
  10310. AbstractVariableType)) {
  10311. VD->setInvalidDecl();
  10312. return;
  10313. }
  10314. // Don't bother complaining about constructors or destructors,
  10315. // though.
  10316. }
  10317. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10318. // If there is no declaration, there was an error parsing it. Just ignore it.
  10319. if (!RealDecl)
  10320. return;
  10321. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10322. QualType Type = Var->getType();
  10323. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10324. if (isa<DecompositionDecl>(RealDecl)) {
  10325. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10326. Var->setInvalidDecl();
  10327. return;
  10328. }
  10329. if (Type->isUndeducedType() &&
  10330. DeduceVariableDeclarationType(Var, false, nullptr))
  10331. return;
  10332. // C++11 [class.static.data]p3: A static data member can be declared with
  10333. // the constexpr specifier; if so, its declaration shall specify
  10334. // a brace-or-equal-initializer.
  10335. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10336. // the definition of a variable [...] or the declaration of a static data
  10337. // member.
  10338. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10339. !Var->isThisDeclarationADemotedDefinition()) {
  10340. if (Var->isStaticDataMember()) {
  10341. // C++1z removes the relevant rule; the in-class declaration is always
  10342. // a definition there.
  10343. if (!getLangOpts().CPlusPlus17) {
  10344. Diag(Var->getLocation(),
  10345. diag::err_constexpr_static_mem_var_requires_init)
  10346. << Var->getDeclName();
  10347. Var->setInvalidDecl();
  10348. return;
  10349. }
  10350. } else {
  10351. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10352. Var->setInvalidDecl();
  10353. return;
  10354. }
  10355. }
  10356. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10357. // be initialized.
  10358. if (!Var->isInvalidDecl() &&
  10359. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10360. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10361. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10362. Var->setInvalidDecl();
  10363. return;
  10364. }
  10365. switch (Var->isThisDeclarationADefinition()) {
  10366. case VarDecl::Definition:
  10367. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10368. break;
  10369. // We have an out-of-line definition of a static data member
  10370. // that has an in-class initializer, so we type-check this like
  10371. // a declaration.
  10372. //
  10373. LLVM_FALLTHROUGH;
  10374. case VarDecl::DeclarationOnly:
  10375. // It's only a declaration.
  10376. // Block scope. C99 6.7p7: If an identifier for an object is
  10377. // declared with no linkage (C99 6.2.2p6), the type for the
  10378. // object shall be complete.
  10379. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10380. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10381. RequireCompleteType(Var->getLocation(), Type,
  10382. diag::err_typecheck_decl_incomplete_type))
  10383. Var->setInvalidDecl();
  10384. // Make sure that the type is not abstract.
  10385. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10386. RequireNonAbstractType(Var->getLocation(), Type,
  10387. diag::err_abstract_type_in_decl,
  10388. AbstractVariableType))
  10389. Var->setInvalidDecl();
  10390. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10391. Var->getStorageClass() == SC_PrivateExtern) {
  10392. Diag(Var->getLocation(), diag::warn_private_extern);
  10393. Diag(Var->getLocation(), diag::note_private_extern);
  10394. }
  10395. return;
  10396. case VarDecl::TentativeDefinition:
  10397. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10398. // object that has file scope without an initializer, and without a
  10399. // storage-class specifier or with the storage-class specifier "static",
  10400. // constitutes a tentative definition. Note: A tentative definition with
  10401. // external linkage is valid (C99 6.2.2p5).
  10402. if (!Var->isInvalidDecl()) {
  10403. if (const IncompleteArrayType *ArrayT
  10404. = Context.getAsIncompleteArrayType(Type)) {
  10405. if (RequireCompleteType(Var->getLocation(),
  10406. ArrayT->getElementType(),
  10407. diag::err_illegal_decl_array_incomplete_type))
  10408. Var->setInvalidDecl();
  10409. } else if (Var->getStorageClass() == SC_Static) {
  10410. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10411. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10412. // declared type shall not be an incomplete type.
  10413. // NOTE: code such as the following
  10414. // static struct s;
  10415. // struct s { int a; };
  10416. // is accepted by gcc. Hence here we issue a warning instead of
  10417. // an error and we do not invalidate the static declaration.
  10418. // NOTE: to avoid multiple warnings, only check the first declaration.
  10419. if (Var->isFirstDecl())
  10420. RequireCompleteType(Var->getLocation(), Type,
  10421. diag::ext_typecheck_decl_incomplete_type);
  10422. }
  10423. }
  10424. // Record the tentative definition; we're done.
  10425. if (!Var->isInvalidDecl())
  10426. TentativeDefinitions.push_back(Var);
  10427. return;
  10428. }
  10429. // Provide a specific diagnostic for uninitialized variable
  10430. // definitions with incomplete array type.
  10431. if (Type->isIncompleteArrayType()) {
  10432. Diag(Var->getLocation(),
  10433. diag::err_typecheck_incomplete_array_needs_initializer);
  10434. Var->setInvalidDecl();
  10435. return;
  10436. }
  10437. // Provide a specific diagnostic for uninitialized variable
  10438. // definitions with reference type.
  10439. if (Type->isReferenceType()) {
  10440. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10441. << Var->getDeclName()
  10442. << SourceRange(Var->getLocation(), Var->getLocation());
  10443. Var->setInvalidDecl();
  10444. return;
  10445. }
  10446. // Do not attempt to type-check the default initializer for a
  10447. // variable with dependent type.
  10448. if (Type->isDependentType())
  10449. return;
  10450. if (Var->isInvalidDecl())
  10451. return;
  10452. if (!Var->hasAttr<AliasAttr>()) {
  10453. if (RequireCompleteType(Var->getLocation(),
  10454. Context.getBaseElementType(Type),
  10455. diag::err_typecheck_decl_incomplete_type)) {
  10456. Var->setInvalidDecl();
  10457. return;
  10458. }
  10459. } else {
  10460. return;
  10461. }
  10462. // The variable can not have an abstract class type.
  10463. if (RequireNonAbstractType(Var->getLocation(), Type,
  10464. diag::err_abstract_type_in_decl,
  10465. AbstractVariableType)) {
  10466. Var->setInvalidDecl();
  10467. return;
  10468. }
  10469. // Check for jumps past the implicit initializer. C++0x
  10470. // clarifies that this applies to a "variable with automatic
  10471. // storage duration", not a "local variable".
  10472. // C++11 [stmt.dcl]p3
  10473. // A program that jumps from a point where a variable with automatic
  10474. // storage duration is not in scope to a point where it is in scope is
  10475. // ill-formed unless the variable has scalar type, class type with a
  10476. // trivial default constructor and a trivial destructor, a cv-qualified
  10477. // version of one of these types, or an array of one of the preceding
  10478. // types and is declared without an initializer.
  10479. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10480. if (const RecordType *Record
  10481. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10482. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10483. // Mark the function (if we're in one) for further checking even if the
  10484. // looser rules of C++11 do not require such checks, so that we can
  10485. // diagnose incompatibilities with C++98.
  10486. if (!CXXRecord->isPOD())
  10487. setFunctionHasBranchProtectedScope();
  10488. }
  10489. }
  10490. // In OpenCL, we can't initialize objects in the __local address space,
  10491. // even implicitly, so don't synthesize an implicit initializer.
  10492. if (getLangOpts().OpenCL &&
  10493. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10494. return;
  10495. // C++03 [dcl.init]p9:
  10496. // If no initializer is specified for an object, and the
  10497. // object is of (possibly cv-qualified) non-POD class type (or
  10498. // array thereof), the object shall be default-initialized; if
  10499. // the object is of const-qualified type, the underlying class
  10500. // type shall have a user-declared default
  10501. // constructor. Otherwise, if no initializer is specified for
  10502. // a non- static object, the object and its subobjects, if
  10503. // any, have an indeterminate initial value); if the object
  10504. // or any of its subobjects are of const-qualified type, the
  10505. // program is ill-formed.
  10506. // C++0x [dcl.init]p11:
  10507. // If no initializer is specified for an object, the object is
  10508. // default-initialized; [...].
  10509. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10510. InitializationKind Kind
  10511. = InitializationKind::CreateDefault(Var->getLocation());
  10512. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10513. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10514. if (Init.isInvalid())
  10515. Var->setInvalidDecl();
  10516. else if (Init.get()) {
  10517. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10518. // This is important for template substitution.
  10519. Var->setInitStyle(VarDecl::CallInit);
  10520. }
  10521. CheckCompleteVariableDeclaration(Var);
  10522. }
  10523. }
  10524. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10525. // If there is no declaration, there was an error parsing it. Ignore it.
  10526. if (!D)
  10527. return;
  10528. VarDecl *VD = dyn_cast<VarDecl>(D);
  10529. if (!VD) {
  10530. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10531. D->setInvalidDecl();
  10532. return;
  10533. }
  10534. VD->setCXXForRangeDecl(true);
  10535. // for-range-declaration cannot be given a storage class specifier.
  10536. int Error = -1;
  10537. switch (VD->getStorageClass()) {
  10538. case SC_None:
  10539. break;
  10540. case SC_Extern:
  10541. Error = 0;
  10542. break;
  10543. case SC_Static:
  10544. Error = 1;
  10545. break;
  10546. case SC_PrivateExtern:
  10547. Error = 2;
  10548. break;
  10549. case SC_Auto:
  10550. Error = 3;
  10551. break;
  10552. case SC_Register:
  10553. Error = 4;
  10554. break;
  10555. }
  10556. if (Error != -1) {
  10557. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10558. << VD->getDeclName() << Error;
  10559. D->setInvalidDecl();
  10560. }
  10561. }
  10562. StmtResult
  10563. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10564. IdentifierInfo *Ident,
  10565. ParsedAttributes &Attrs,
  10566. SourceLocation AttrEnd) {
  10567. // C++1y [stmt.iter]p1:
  10568. // A range-based for statement of the form
  10569. // for ( for-range-identifier : for-range-initializer ) statement
  10570. // is equivalent to
  10571. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10572. DeclSpec DS(Attrs.getPool().getFactory());
  10573. const char *PrevSpec;
  10574. unsigned DiagID;
  10575. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10576. getPrintingPolicy());
  10577. Declarator D(DS, DeclaratorContext::ForContext);
  10578. D.SetIdentifier(Ident, IdentLoc);
  10579. D.takeAttributes(Attrs, AttrEnd);
  10580. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10581. IdentLoc);
  10582. Decl *Var = ActOnDeclarator(S, D);
  10583. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10584. FinalizeDeclaration(Var);
  10585. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10586. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10587. }
  10588. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10589. if (var->isInvalidDecl()) return;
  10590. if (getLangOpts().OpenCL) {
  10591. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10592. // initialiser
  10593. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10594. !var->hasInit()) {
  10595. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10596. << 1 /*Init*/;
  10597. var->setInvalidDecl();
  10598. return;
  10599. }
  10600. }
  10601. // In Objective-C, don't allow jumps past the implicit initialization of a
  10602. // local retaining variable.
  10603. if (getLangOpts().ObjC &&
  10604. var->hasLocalStorage()) {
  10605. switch (var->getType().getObjCLifetime()) {
  10606. case Qualifiers::OCL_None:
  10607. case Qualifiers::OCL_ExplicitNone:
  10608. case Qualifiers::OCL_Autoreleasing:
  10609. break;
  10610. case Qualifiers::OCL_Weak:
  10611. case Qualifiers::OCL_Strong:
  10612. setFunctionHasBranchProtectedScope();
  10613. break;
  10614. }
  10615. }
  10616. if (var->hasLocalStorage() &&
  10617. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10618. setFunctionHasBranchProtectedScope();
  10619. // Warn about externally-visible variables being defined without a
  10620. // prior declaration. We only want to do this for global
  10621. // declarations, but we also specifically need to avoid doing it for
  10622. // class members because the linkage of an anonymous class can
  10623. // change if it's later given a typedef name.
  10624. if (var->isThisDeclarationADefinition() &&
  10625. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10626. var->isExternallyVisible() && var->hasLinkage() &&
  10627. !var->isInline() && !var->getDescribedVarTemplate() &&
  10628. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10629. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10630. var->getLocation())) {
  10631. // Find a previous declaration that's not a definition.
  10632. VarDecl *prev = var->getPreviousDecl();
  10633. while (prev && prev->isThisDeclarationADefinition())
  10634. prev = prev->getPreviousDecl();
  10635. if (!prev) {
  10636. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10637. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10638. << /* variable */ 0;
  10639. }
  10640. }
  10641. // Cache the result of checking for constant initialization.
  10642. Optional<bool> CacheHasConstInit;
  10643. const Expr *CacheCulprit = nullptr;
  10644. auto checkConstInit = [&]() mutable {
  10645. if (!CacheHasConstInit)
  10646. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10647. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10648. return *CacheHasConstInit;
  10649. };
  10650. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10651. if (var->getType().isDestructedType()) {
  10652. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10653. // The type of an object with thread storage duration shall not
  10654. // have a non-trivial destructor.
  10655. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10656. if (getLangOpts().CPlusPlus11)
  10657. Diag(var->getLocation(), diag::note_use_thread_local);
  10658. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10659. if (!checkConstInit()) {
  10660. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10661. // An object of thread storage duration shall not require dynamic
  10662. // initialization.
  10663. // FIXME: Need strict checking here.
  10664. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10665. << CacheCulprit->getSourceRange();
  10666. if (getLangOpts().CPlusPlus11)
  10667. Diag(var->getLocation(), diag::note_use_thread_local);
  10668. }
  10669. }
  10670. }
  10671. // Apply section attributes and pragmas to global variables.
  10672. bool GlobalStorage = var->hasGlobalStorage();
  10673. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10674. !inTemplateInstantiation()) {
  10675. PragmaStack<StringLiteral *> *Stack = nullptr;
  10676. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10677. if (var->getType().isConstQualified())
  10678. Stack = &ConstSegStack;
  10679. else if (!var->getInit()) {
  10680. Stack = &BSSSegStack;
  10681. SectionFlags |= ASTContext::PSF_Write;
  10682. } else {
  10683. Stack = &DataSegStack;
  10684. SectionFlags |= ASTContext::PSF_Write;
  10685. }
  10686. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10687. var->addAttr(SectionAttr::CreateImplicit(
  10688. Context, SectionAttr::Declspec_allocate,
  10689. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10690. }
  10691. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10692. if (UnifySection(SA->getName(), SectionFlags, var))
  10693. var->dropAttr<SectionAttr>();
  10694. // Apply the init_seg attribute if this has an initializer. If the
  10695. // initializer turns out to not be dynamic, we'll end up ignoring this
  10696. // attribute.
  10697. if (CurInitSeg && var->getInit())
  10698. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10699. CurInitSegLoc));
  10700. }
  10701. // All the following checks are C++ only.
  10702. if (!getLangOpts().CPlusPlus) {
  10703. // If this variable must be emitted, add it as an initializer for the
  10704. // current module.
  10705. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10706. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10707. return;
  10708. }
  10709. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10710. CheckCompleteDecompositionDeclaration(DD);
  10711. QualType type = var->getType();
  10712. if (type->isDependentType()) return;
  10713. if (var->hasAttr<BlocksAttr>())
  10714. getCurFunction()->addByrefBlockVar(var);
  10715. Expr *Init = var->getInit();
  10716. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10717. QualType baseType = Context.getBaseElementType(type);
  10718. if (Init && !Init->isValueDependent()) {
  10719. if (var->isConstexpr()) {
  10720. SmallVector<PartialDiagnosticAt, 8> Notes;
  10721. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10722. SourceLocation DiagLoc = var->getLocation();
  10723. // If the note doesn't add any useful information other than a source
  10724. // location, fold it into the primary diagnostic.
  10725. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10726. diag::note_invalid_subexpr_in_const_expr) {
  10727. DiagLoc = Notes[0].first;
  10728. Notes.clear();
  10729. }
  10730. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10731. << var << Init->getSourceRange();
  10732. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10733. Diag(Notes[I].first, Notes[I].second);
  10734. }
  10735. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  10736. // Check whether the initializer of a const variable of integral or
  10737. // enumeration type is an ICE now, since we can't tell whether it was
  10738. // initialized by a constant expression if we check later.
  10739. var->checkInitIsICE();
  10740. }
  10741. // Don't emit further diagnostics about constexpr globals since they
  10742. // were just diagnosed.
  10743. if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  10744. // FIXME: Need strict checking in C++03 here.
  10745. bool DiagErr = getLangOpts().CPlusPlus11
  10746. ? !var->checkInitIsICE() : !checkConstInit();
  10747. if (DiagErr) {
  10748. auto *Attr = var->getAttr<ConstInitAttr>();
  10749. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10750. << Init->getSourceRange();
  10751. Diag(Attr->getLocation(),
  10752. diag::note_declared_required_constant_init_here)
  10753. << Attr->getRange() << Attr->isConstinit();
  10754. if (getLangOpts().CPlusPlus11) {
  10755. APValue Value;
  10756. SmallVector<PartialDiagnosticAt, 8> Notes;
  10757. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10758. for (auto &it : Notes)
  10759. Diag(it.first, it.second);
  10760. } else {
  10761. Diag(CacheCulprit->getExprLoc(),
  10762. diag::note_invalid_subexpr_in_const_expr)
  10763. << CacheCulprit->getSourceRange();
  10764. }
  10765. }
  10766. }
  10767. else if (!var->isConstexpr() && IsGlobal &&
  10768. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10769. var->getLocation())) {
  10770. // Warn about globals which don't have a constant initializer. Don't
  10771. // warn about globals with a non-trivial destructor because we already
  10772. // warned about them.
  10773. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10774. if (!(RD && !RD->hasTrivialDestructor())) {
  10775. if (!checkConstInit())
  10776. Diag(var->getLocation(), diag::warn_global_constructor)
  10777. << Init->getSourceRange();
  10778. }
  10779. }
  10780. }
  10781. // Require the destructor.
  10782. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10783. FinalizeVarWithDestructor(var, recordType);
  10784. // If this variable must be emitted, add it as an initializer for the current
  10785. // module.
  10786. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10787. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10788. }
  10789. /// Determines if a variable's alignment is dependent.
  10790. static bool hasDependentAlignment(VarDecl *VD) {
  10791. if (VD->getType()->isDependentType())
  10792. return true;
  10793. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10794. if (I->isAlignmentDependent())
  10795. return true;
  10796. return false;
  10797. }
  10798. /// Check if VD needs to be dllexport/dllimport due to being in a
  10799. /// dllexport/import function.
  10800. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  10801. assert(VD->isStaticLocal());
  10802. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10803. // Find outermost function when VD is in lambda function.
  10804. while (FD && !getDLLAttr(FD) &&
  10805. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  10806. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  10807. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  10808. }
  10809. if (!FD)
  10810. return;
  10811. // Static locals inherit dll attributes from their function.
  10812. if (Attr *A = getDLLAttr(FD)) {
  10813. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10814. NewAttr->setInherited(true);
  10815. VD->addAttr(NewAttr);
  10816. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  10817. auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
  10818. getASTContext(),
  10819. A->getSpellingListIndex());
  10820. NewAttr->setInherited(true);
  10821. VD->addAttr(NewAttr);
  10822. // Export this function to enforce exporting this static variable even
  10823. // if it is not used in this compilation unit.
  10824. if (!FD->hasAttr<DLLExportAttr>())
  10825. FD->addAttr(NewAttr);
  10826. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  10827. auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
  10828. getASTContext(),
  10829. A->getSpellingListIndex());
  10830. NewAttr->setInherited(true);
  10831. VD->addAttr(NewAttr);
  10832. }
  10833. }
  10834. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10835. /// any semantic actions necessary after any initializer has been attached.
  10836. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10837. // Note that we are no longer parsing the initializer for this declaration.
  10838. ParsingInitForAutoVars.erase(ThisDecl);
  10839. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10840. if (!VD)
  10841. return;
  10842. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10843. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10844. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10845. if (PragmaClangBSSSection.Valid)
  10846. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10847. PragmaClangBSSSection.SectionName,
  10848. PragmaClangBSSSection.PragmaLocation));
  10849. if (PragmaClangDataSection.Valid)
  10850. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10851. PragmaClangDataSection.SectionName,
  10852. PragmaClangDataSection.PragmaLocation));
  10853. if (PragmaClangRodataSection.Valid)
  10854. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10855. PragmaClangRodataSection.SectionName,
  10856. PragmaClangRodataSection.PragmaLocation));
  10857. }
  10858. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10859. for (auto *BD : DD->bindings()) {
  10860. FinalizeDeclaration(BD);
  10861. }
  10862. }
  10863. checkAttributesAfterMerging(*this, *VD);
  10864. // Perform TLS alignment check here after attributes attached to the variable
  10865. // which may affect the alignment have been processed. Only perform the check
  10866. // if the target has a maximum TLS alignment (zero means no constraints).
  10867. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10868. // Protect the check so that it's not performed on dependent types and
  10869. // dependent alignments (we can't determine the alignment in that case).
  10870. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10871. !VD->isInvalidDecl()) {
  10872. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10873. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10874. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10875. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10876. << (unsigned)MaxAlignChars.getQuantity();
  10877. }
  10878. }
  10879. }
  10880. if (VD->isStaticLocal()) {
  10881. CheckStaticLocalForDllExport(VD);
  10882. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10883. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  10884. // function, only __shared__ variables or variables without any device
  10885. // memory qualifiers may be declared with static storage class.
  10886. // Note: It is unclear how a function-scope non-const static variable
  10887. // without device memory qualifier is implemented, therefore only static
  10888. // const variable without device memory qualifier is allowed.
  10889. [&]() {
  10890. if (!getLangOpts().CUDA)
  10891. return;
  10892. if (VD->hasAttr<CUDASharedAttr>())
  10893. return;
  10894. if (VD->getType().isConstQualified() &&
  10895. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10896. return;
  10897. if (CUDADiagIfDeviceCode(VD->getLocation(),
  10898. diag::err_device_static_local_var)
  10899. << CurrentCUDATarget())
  10900. VD->setInvalidDecl();
  10901. }();
  10902. }
  10903. }
  10904. // Perform check for initializers of device-side global variables.
  10905. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10906. // 7.5). We must also apply the same checks to all __shared__
  10907. // variables whether they are local or not. CUDA also allows
  10908. // constant initializers for __constant__ and __device__ variables.
  10909. if (getLangOpts().CUDA)
  10910. checkAllowedCUDAInitializer(VD);
  10911. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10912. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10913. // Imported static data members cannot be defined out-of-line.
  10914. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10915. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10916. VD->isThisDeclarationADefinition()) {
  10917. // We allow definitions of dllimport class template static data members
  10918. // with a warning.
  10919. CXXRecordDecl *Context =
  10920. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10921. bool IsClassTemplateMember =
  10922. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10923. Context->getDescribedClassTemplate();
  10924. Diag(VD->getLocation(),
  10925. IsClassTemplateMember
  10926. ? diag::warn_attribute_dllimport_static_field_definition
  10927. : diag::err_attribute_dllimport_static_field_definition);
  10928. Diag(IA->getLocation(), diag::note_attribute);
  10929. if (!IsClassTemplateMember)
  10930. VD->setInvalidDecl();
  10931. }
  10932. }
  10933. // dllimport/dllexport variables cannot be thread local, their TLS index
  10934. // isn't exported with the variable.
  10935. if (DLLAttr && VD->getTLSKind()) {
  10936. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10937. if (F && getDLLAttr(F)) {
  10938. assert(VD->isStaticLocal());
  10939. // But if this is a static local in a dlimport/dllexport function, the
  10940. // function will never be inlined, which means the var would never be
  10941. // imported, so having it marked import/export is safe.
  10942. } else {
  10943. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10944. << DLLAttr;
  10945. VD->setInvalidDecl();
  10946. }
  10947. }
  10948. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10949. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10950. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10951. VD->dropAttr<UsedAttr>();
  10952. }
  10953. }
  10954. const DeclContext *DC = VD->getDeclContext();
  10955. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10956. // member, set the visibility of this variable.
  10957. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10958. AddPushedVisibilityAttribute(VD);
  10959. // FIXME: Warn on unused var template partial specializations.
  10960. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10961. MarkUnusedFileScopedDecl(VD);
  10962. // Now we have parsed the initializer and can update the table of magic
  10963. // tag values.
  10964. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10965. !VD->getType()->isIntegralOrEnumerationType())
  10966. return;
  10967. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10968. const Expr *MagicValueExpr = VD->getInit();
  10969. if (!MagicValueExpr) {
  10970. continue;
  10971. }
  10972. llvm::APSInt MagicValueInt;
  10973. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10974. Diag(I->getRange().getBegin(),
  10975. diag::err_type_tag_for_datatype_not_ice)
  10976. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10977. continue;
  10978. }
  10979. if (MagicValueInt.getActiveBits() > 64) {
  10980. Diag(I->getRange().getBegin(),
  10981. diag::err_type_tag_for_datatype_too_large)
  10982. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10983. continue;
  10984. }
  10985. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10986. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10987. MagicValue,
  10988. I->getMatchingCType(),
  10989. I->getLayoutCompatible(),
  10990. I->getMustBeNull());
  10991. }
  10992. }
  10993. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10994. auto *VD = dyn_cast<VarDecl>(DD);
  10995. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10996. }
  10997. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10998. ArrayRef<Decl *> Group) {
  10999. SmallVector<Decl*, 8> Decls;
  11000. if (DS.isTypeSpecOwned())
  11001. Decls.push_back(DS.getRepAsDecl());
  11002. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11003. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11004. bool DiagnosedMultipleDecomps = false;
  11005. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11006. bool DiagnosedNonDeducedAuto = false;
  11007. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11008. if (Decl *D = Group[i]) {
  11009. // For declarators, there are some additional syntactic-ish checks we need
  11010. // to perform.
  11011. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11012. if (!FirstDeclaratorInGroup)
  11013. FirstDeclaratorInGroup = DD;
  11014. if (!FirstDecompDeclaratorInGroup)
  11015. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11016. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11017. !hasDeducedAuto(DD))
  11018. FirstNonDeducedAutoInGroup = DD;
  11019. if (FirstDeclaratorInGroup != DD) {
  11020. // A decomposition declaration cannot be combined with any other
  11021. // declaration in the same group.
  11022. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11023. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11024. diag::err_decomp_decl_not_alone)
  11025. << FirstDeclaratorInGroup->getSourceRange()
  11026. << DD->getSourceRange();
  11027. DiagnosedMultipleDecomps = true;
  11028. }
  11029. // A declarator that uses 'auto' in any way other than to declare a
  11030. // variable with a deduced type cannot be combined with any other
  11031. // declarator in the same group.
  11032. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11033. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11034. diag::err_auto_non_deduced_not_alone)
  11035. << FirstNonDeducedAutoInGroup->getType()
  11036. ->hasAutoForTrailingReturnType()
  11037. << FirstDeclaratorInGroup->getSourceRange()
  11038. << DD->getSourceRange();
  11039. DiagnosedNonDeducedAuto = true;
  11040. }
  11041. }
  11042. }
  11043. Decls.push_back(D);
  11044. }
  11045. }
  11046. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11047. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11048. handleTagNumbering(Tag, S);
  11049. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11050. getLangOpts().CPlusPlus)
  11051. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11052. }
  11053. }
  11054. return BuildDeclaratorGroup(Decls);
  11055. }
  11056. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11057. /// group, performing any necessary semantic checking.
  11058. Sema::DeclGroupPtrTy
  11059. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11060. // C++14 [dcl.spec.auto]p7: (DR1347)
  11061. // If the type that replaces the placeholder type is not the same in each
  11062. // deduction, the program is ill-formed.
  11063. if (Group.size() > 1) {
  11064. QualType Deduced;
  11065. VarDecl *DeducedDecl = nullptr;
  11066. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11067. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11068. if (!D || D->isInvalidDecl())
  11069. break;
  11070. DeducedType *DT = D->getType()->getContainedDeducedType();
  11071. if (!DT || DT->getDeducedType().isNull())
  11072. continue;
  11073. if (Deduced.isNull()) {
  11074. Deduced = DT->getDeducedType();
  11075. DeducedDecl = D;
  11076. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11077. auto *AT = dyn_cast<AutoType>(DT);
  11078. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11079. diag::err_auto_different_deductions)
  11080. << (AT ? (unsigned)AT->getKeyword() : 3)
  11081. << Deduced << DeducedDecl->getDeclName()
  11082. << DT->getDeducedType() << D->getDeclName()
  11083. << DeducedDecl->getInit()->getSourceRange()
  11084. << D->getInit()->getSourceRange();
  11085. D->setInvalidDecl();
  11086. break;
  11087. }
  11088. }
  11089. }
  11090. ActOnDocumentableDecls(Group);
  11091. return DeclGroupPtrTy::make(
  11092. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11093. }
  11094. void Sema::ActOnDocumentableDecl(Decl *D) {
  11095. ActOnDocumentableDecls(D);
  11096. }
  11097. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11098. // Don't parse the comment if Doxygen diagnostics are ignored.
  11099. if (Group.empty() || !Group[0])
  11100. return;
  11101. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11102. Group[0]->getLocation()) &&
  11103. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11104. Group[0]->getLocation()))
  11105. return;
  11106. if (Group.size() >= 2) {
  11107. // This is a decl group. Normally it will contain only declarations
  11108. // produced from declarator list. But in case we have any definitions or
  11109. // additional declaration references:
  11110. // 'typedef struct S {} S;'
  11111. // 'typedef struct S *S;'
  11112. // 'struct S *pS;'
  11113. // FinalizeDeclaratorGroup adds these as separate declarations.
  11114. Decl *MaybeTagDecl = Group[0];
  11115. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11116. Group = Group.slice(1);
  11117. }
  11118. }
  11119. // FIMXE: We assume every Decl in the group is in the same file.
  11120. // This is false when preprocessor constructs the group from decls in
  11121. // different files (e. g. macros or #include).
  11122. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  11123. }
  11124. /// Common checks for a parameter-declaration that should apply to both function
  11125. /// parameters and non-type template parameters.
  11126. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11127. // Check that there are no default arguments inside the type of this
  11128. // parameter.
  11129. if (getLangOpts().CPlusPlus)
  11130. CheckExtraCXXDefaultArguments(D);
  11131. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11132. if (D.getCXXScopeSpec().isSet()) {
  11133. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11134. << D.getCXXScopeSpec().getRange();
  11135. }
  11136. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11137. // simple identifier except [...irrelevant cases...].
  11138. switch (D.getName().getKind()) {
  11139. case UnqualifiedIdKind::IK_Identifier:
  11140. break;
  11141. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11142. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11143. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11144. case UnqualifiedIdKind::IK_ConstructorName:
  11145. case UnqualifiedIdKind::IK_DestructorName:
  11146. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11147. case UnqualifiedIdKind::IK_DeductionGuideName:
  11148. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11149. << GetNameForDeclarator(D).getName();
  11150. break;
  11151. case UnqualifiedIdKind::IK_TemplateId:
  11152. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11153. // GetNameForDeclarator would not produce a useful name in this case.
  11154. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11155. break;
  11156. }
  11157. }
  11158. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11159. /// to introduce parameters into function prototype scope.
  11160. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11161. const DeclSpec &DS = D.getDeclSpec();
  11162. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11163. // C++03 [dcl.stc]p2 also permits 'auto'.
  11164. StorageClass SC = SC_None;
  11165. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11166. SC = SC_Register;
  11167. // In C++11, the 'register' storage class specifier is deprecated.
  11168. // In C++17, it is not allowed, but we tolerate it as an extension.
  11169. if (getLangOpts().CPlusPlus11) {
  11170. Diag(DS.getStorageClassSpecLoc(),
  11171. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11172. : diag::warn_deprecated_register)
  11173. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11174. }
  11175. } else if (getLangOpts().CPlusPlus &&
  11176. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11177. SC = SC_Auto;
  11178. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11179. Diag(DS.getStorageClassSpecLoc(),
  11180. diag::err_invalid_storage_class_in_func_decl);
  11181. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11182. }
  11183. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11184. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11185. << DeclSpec::getSpecifierName(TSCS);
  11186. if (DS.isInlineSpecified())
  11187. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11188. << getLangOpts().CPlusPlus17;
  11189. if (DS.hasConstexprSpecifier())
  11190. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11191. << 0 << D.getDeclSpec().getConstexprSpecifier();
  11192. DiagnoseFunctionSpecifiers(DS);
  11193. CheckFunctionOrTemplateParamDeclarator(S, D);
  11194. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11195. QualType parmDeclType = TInfo->getType();
  11196. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11197. IdentifierInfo *II = D.getIdentifier();
  11198. if (II) {
  11199. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11200. ForVisibleRedeclaration);
  11201. LookupName(R, S);
  11202. if (R.isSingleResult()) {
  11203. NamedDecl *PrevDecl = R.getFoundDecl();
  11204. if (PrevDecl->isTemplateParameter()) {
  11205. // Maybe we will complain about the shadowed template parameter.
  11206. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11207. // Just pretend that we didn't see the previous declaration.
  11208. PrevDecl = nullptr;
  11209. } else if (S->isDeclScope(PrevDecl)) {
  11210. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11211. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11212. // Recover by removing the name
  11213. II = nullptr;
  11214. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11215. D.setInvalidType(true);
  11216. }
  11217. }
  11218. }
  11219. // Temporarily put parameter variables in the translation unit, not
  11220. // the enclosing context. This prevents them from accidentally
  11221. // looking like class members in C++.
  11222. ParmVarDecl *New =
  11223. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11224. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11225. if (D.isInvalidType())
  11226. New->setInvalidDecl();
  11227. assert(S->isFunctionPrototypeScope());
  11228. assert(S->getFunctionPrototypeDepth() >= 1);
  11229. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11230. S->getNextFunctionPrototypeIndex());
  11231. // Add the parameter declaration into this scope.
  11232. S->AddDecl(New);
  11233. if (II)
  11234. IdResolver.AddDecl(New);
  11235. ProcessDeclAttributes(S, New, D);
  11236. if (D.getDeclSpec().isModulePrivateSpecified())
  11237. Diag(New->getLocation(), diag::err_module_private_local)
  11238. << 1 << New->getDeclName()
  11239. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11240. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11241. if (New->hasAttr<BlocksAttr>()) {
  11242. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11243. }
  11244. return New;
  11245. }
  11246. /// Synthesizes a variable for a parameter arising from a
  11247. /// typedef.
  11248. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11249. SourceLocation Loc,
  11250. QualType T) {
  11251. /* FIXME: setting StartLoc == Loc.
  11252. Would it be worth to modify callers so as to provide proper source
  11253. location for the unnamed parameters, embedding the parameter's type? */
  11254. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11255. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11256. SC_None, nullptr);
  11257. Param->setImplicit();
  11258. return Param;
  11259. }
  11260. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11261. // Don't diagnose unused-parameter errors in template instantiations; we
  11262. // will already have done so in the template itself.
  11263. if (inTemplateInstantiation())
  11264. return;
  11265. for (const ParmVarDecl *Parameter : Parameters) {
  11266. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11267. !Parameter->hasAttr<UnusedAttr>()) {
  11268. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11269. << Parameter->getDeclName();
  11270. }
  11271. }
  11272. }
  11273. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11274. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11275. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11276. return;
  11277. // Warn if the return value is pass-by-value and larger than the specified
  11278. // threshold.
  11279. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11280. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11281. if (Size > LangOpts.NumLargeByValueCopy)
  11282. Diag(D->getLocation(), diag::warn_return_value_size)
  11283. << D->getDeclName() << Size;
  11284. }
  11285. // Warn if any parameter is pass-by-value and larger than the specified
  11286. // threshold.
  11287. for (const ParmVarDecl *Parameter : Parameters) {
  11288. QualType T = Parameter->getType();
  11289. if (T->isDependentType() || !T.isPODType(Context))
  11290. continue;
  11291. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11292. if (Size > LangOpts.NumLargeByValueCopy)
  11293. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11294. << Parameter->getDeclName() << Size;
  11295. }
  11296. }
  11297. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11298. SourceLocation NameLoc, IdentifierInfo *Name,
  11299. QualType T, TypeSourceInfo *TSInfo,
  11300. StorageClass SC) {
  11301. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11302. if (getLangOpts().ObjCAutoRefCount &&
  11303. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11304. T->isObjCLifetimeType()) {
  11305. Qualifiers::ObjCLifetime lifetime;
  11306. // Special cases for arrays:
  11307. // - if it's const, use __unsafe_unretained
  11308. // - otherwise, it's an error
  11309. if (T->isArrayType()) {
  11310. if (!T.isConstQualified()) {
  11311. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11312. DelayedDiagnostics.add(
  11313. sema::DelayedDiagnostic::makeForbiddenType(
  11314. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11315. else
  11316. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11317. << TSInfo->getTypeLoc().getSourceRange();
  11318. }
  11319. lifetime = Qualifiers::OCL_ExplicitNone;
  11320. } else {
  11321. lifetime = T->getObjCARCImplicitLifetime();
  11322. }
  11323. T = Context.getLifetimeQualifiedType(T, lifetime);
  11324. }
  11325. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11326. Context.getAdjustedParameterType(T),
  11327. TSInfo, SC, nullptr);
  11328. // Make a note if we created a new pack in the scope of a lambda, so that
  11329. // we know that references to that pack must also be expanded within the
  11330. // lambda scope.
  11331. if (New->isParameterPack())
  11332. if (auto *LSI = getEnclosingLambda())
  11333. LSI->LocalPacks.push_back(New);
  11334. // Parameters can not be abstract class types.
  11335. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11336. // the class has been completely parsed.
  11337. if (!CurContext->isRecord() &&
  11338. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11339. AbstractParamType))
  11340. New->setInvalidDecl();
  11341. // Parameter declarators cannot be interface types. All ObjC objects are
  11342. // passed by reference.
  11343. if (T->isObjCObjectType()) {
  11344. SourceLocation TypeEndLoc =
  11345. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11346. Diag(NameLoc,
  11347. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11348. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11349. T = Context.getObjCObjectPointerType(T);
  11350. New->setType(T);
  11351. }
  11352. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11353. // duration shall not be qualified by an address-space qualifier."
  11354. // Since all parameters have automatic store duration, they can not have
  11355. // an address space.
  11356. if (T.getAddressSpace() != LangAS::Default &&
  11357. // OpenCL allows function arguments declared to be an array of a type
  11358. // to be qualified with an address space.
  11359. !(getLangOpts().OpenCL &&
  11360. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11361. Diag(NameLoc, diag::err_arg_with_address_space);
  11362. New->setInvalidDecl();
  11363. }
  11364. return New;
  11365. }
  11366. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11367. SourceLocation LocAfterDecls) {
  11368. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11369. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11370. // for a K&R function.
  11371. if (!FTI.hasPrototype) {
  11372. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11373. --i;
  11374. if (FTI.Params[i].Param == nullptr) {
  11375. SmallString<256> Code;
  11376. llvm::raw_svector_ostream(Code)
  11377. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11378. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11379. << FTI.Params[i].Ident
  11380. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11381. // Implicitly declare the argument as type 'int' for lack of a better
  11382. // type.
  11383. AttributeFactory attrs;
  11384. DeclSpec DS(attrs);
  11385. const char* PrevSpec; // unused
  11386. unsigned DiagID; // unused
  11387. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11388. DiagID, Context.getPrintingPolicy());
  11389. // Use the identifier location for the type source range.
  11390. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11391. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11392. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11393. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11394. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11395. }
  11396. }
  11397. }
  11398. }
  11399. Decl *
  11400. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11401. MultiTemplateParamsArg TemplateParameterLists,
  11402. SkipBodyInfo *SkipBody) {
  11403. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11404. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11405. Scope *ParentScope = FnBodyScope->getParent();
  11406. D.setFunctionDefinitionKind(FDK_Definition);
  11407. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11408. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11409. }
  11410. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11411. Consumer.HandleInlineFunctionDefinition(D);
  11412. }
  11413. static bool
  11414. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11415. const FunctionDecl *&PossiblePrototype) {
  11416. // Don't warn about invalid declarations.
  11417. if (FD->isInvalidDecl())
  11418. return false;
  11419. // Or declarations that aren't global.
  11420. if (!FD->isGlobal())
  11421. return false;
  11422. // Don't warn about C++ member functions.
  11423. if (isa<CXXMethodDecl>(FD))
  11424. return false;
  11425. // Don't warn about 'main'.
  11426. if (FD->isMain())
  11427. return false;
  11428. // Don't warn about inline functions.
  11429. if (FD->isInlined())
  11430. return false;
  11431. // Don't warn about function templates.
  11432. if (FD->getDescribedFunctionTemplate())
  11433. return false;
  11434. // Don't warn about function template specializations.
  11435. if (FD->isFunctionTemplateSpecialization())
  11436. return false;
  11437. // Don't warn for OpenCL kernels.
  11438. if (FD->hasAttr<OpenCLKernelAttr>())
  11439. return false;
  11440. // Don't warn on explicitly deleted functions.
  11441. if (FD->isDeleted())
  11442. return false;
  11443. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11444. Prev; Prev = Prev->getPreviousDecl()) {
  11445. // Ignore any declarations that occur in function or method
  11446. // scope, because they aren't visible from the header.
  11447. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11448. continue;
  11449. PossiblePrototype = Prev;
  11450. return Prev->getType()->isFunctionNoProtoType();
  11451. }
  11452. return true;
  11453. }
  11454. void
  11455. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11456. const FunctionDecl *EffectiveDefinition,
  11457. SkipBodyInfo *SkipBody) {
  11458. const FunctionDecl *Definition = EffectiveDefinition;
  11459. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11460. // If this is a friend function defined in a class template, it does not
  11461. // have a body until it is used, nevertheless it is a definition, see
  11462. // [temp.inst]p2:
  11463. //
  11464. // ... for the purpose of determining whether an instantiated redeclaration
  11465. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11466. // corresponds to a definition in the template is considered to be a
  11467. // definition.
  11468. //
  11469. // The following code must produce redefinition error:
  11470. //
  11471. // template<typename T> struct C20 { friend void func_20() {} };
  11472. // C20<int> c20i;
  11473. // void func_20() {}
  11474. //
  11475. for (auto I : FD->redecls()) {
  11476. if (I != FD && !I->isInvalidDecl() &&
  11477. I->getFriendObjectKind() != Decl::FOK_None) {
  11478. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11479. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11480. // A merged copy of the same function, instantiated as a member of
  11481. // the same class, is OK.
  11482. if (declaresSameEntity(OrigFD, Original) &&
  11483. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11484. cast<Decl>(FD->getLexicalDeclContext())))
  11485. continue;
  11486. }
  11487. if (Original->isThisDeclarationADefinition()) {
  11488. Definition = I;
  11489. break;
  11490. }
  11491. }
  11492. }
  11493. }
  11494. }
  11495. if (!Definition)
  11496. // Similar to friend functions a friend function template may be a
  11497. // definition and do not have a body if it is instantiated in a class
  11498. // template.
  11499. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11500. for (auto I : FTD->redecls()) {
  11501. auto D = cast<FunctionTemplateDecl>(I);
  11502. if (D != FTD) {
  11503. assert(!D->isThisDeclarationADefinition() &&
  11504. "More than one definition in redeclaration chain");
  11505. if (D->getFriendObjectKind() != Decl::FOK_None)
  11506. if (FunctionTemplateDecl *FT =
  11507. D->getInstantiatedFromMemberTemplate()) {
  11508. if (FT->isThisDeclarationADefinition()) {
  11509. Definition = D->getTemplatedDecl();
  11510. break;
  11511. }
  11512. }
  11513. }
  11514. }
  11515. }
  11516. if (!Definition)
  11517. return;
  11518. if (canRedefineFunction(Definition, getLangOpts()))
  11519. return;
  11520. // Don't emit an error when this is redefinition of a typo-corrected
  11521. // definition.
  11522. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11523. return;
  11524. // If we don't have a visible definition of the function, and it's inline or
  11525. // a template, skip the new definition.
  11526. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11527. (Definition->getFormalLinkage() == InternalLinkage ||
  11528. Definition->isInlined() ||
  11529. Definition->getDescribedFunctionTemplate() ||
  11530. Definition->getNumTemplateParameterLists())) {
  11531. SkipBody->ShouldSkip = true;
  11532. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11533. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11534. makeMergedDefinitionVisible(TD);
  11535. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11536. return;
  11537. }
  11538. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11539. Definition->getStorageClass() == SC_Extern)
  11540. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11541. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11542. else
  11543. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11544. Diag(Definition->getLocation(), diag::note_previous_definition);
  11545. FD->setInvalidDecl();
  11546. }
  11547. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11548. Sema &S) {
  11549. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11550. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11551. LSI->CallOperator = CallOperator;
  11552. LSI->Lambda = LambdaClass;
  11553. LSI->ReturnType = CallOperator->getReturnType();
  11554. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11555. if (LCD == LCD_None)
  11556. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11557. else if (LCD == LCD_ByCopy)
  11558. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11559. else if (LCD == LCD_ByRef)
  11560. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11561. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11562. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11563. LSI->Mutable = !CallOperator->isConst();
  11564. // Add the captures to the LSI so they can be noted as already
  11565. // captured within tryCaptureVar.
  11566. auto I = LambdaClass->field_begin();
  11567. for (const auto &C : LambdaClass->captures()) {
  11568. if (C.capturesVariable()) {
  11569. VarDecl *VD = C.getCapturedVar();
  11570. if (VD->isInitCapture())
  11571. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11572. QualType CaptureType = VD->getType();
  11573. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11574. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11575. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11576. /*EllipsisLoc*/C.isPackExpansion()
  11577. ? C.getEllipsisLoc() : SourceLocation(),
  11578. CaptureType, /*Invalid*/false);
  11579. } else if (C.capturesThis()) {
  11580. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11581. C.getCaptureKind() == LCK_StarThis);
  11582. } else {
  11583. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11584. I->getType());
  11585. }
  11586. ++I;
  11587. }
  11588. }
  11589. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11590. SkipBodyInfo *SkipBody) {
  11591. if (!D) {
  11592. // Parsing the function declaration failed in some way. Push on a fake scope
  11593. // anyway so we can try to parse the function body.
  11594. PushFunctionScope();
  11595. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11596. return D;
  11597. }
  11598. FunctionDecl *FD = nullptr;
  11599. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11600. FD = FunTmpl->getTemplatedDecl();
  11601. else
  11602. FD = cast<FunctionDecl>(D);
  11603. // Do not push if it is a lambda because one is already pushed when building
  11604. // the lambda in ActOnStartOfLambdaDefinition().
  11605. if (!isLambdaCallOperator(FD))
  11606. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11607. // Check for defining attributes before the check for redefinition.
  11608. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11609. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11610. FD->dropAttr<AliasAttr>();
  11611. FD->setInvalidDecl();
  11612. }
  11613. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11614. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11615. FD->dropAttr<IFuncAttr>();
  11616. FD->setInvalidDecl();
  11617. }
  11618. // See if this is a redefinition. If 'will have body' is already set, then
  11619. // these checks were already performed when it was set.
  11620. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11621. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11622. // If we're skipping the body, we're done. Don't enter the scope.
  11623. if (SkipBody && SkipBody->ShouldSkip)
  11624. return D;
  11625. }
  11626. // Mark this function as "will have a body eventually". This lets users to
  11627. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11628. // this function.
  11629. FD->setWillHaveBody();
  11630. // If we are instantiating a generic lambda call operator, push
  11631. // a LambdaScopeInfo onto the function stack. But use the information
  11632. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11633. // LambdaScopeInfo.
  11634. // When the template operator is being specialized, the LambdaScopeInfo,
  11635. // has to be properly restored so that tryCaptureVariable doesn't try
  11636. // and capture any new variables. In addition when calculating potential
  11637. // captures during transformation of nested lambdas, it is necessary to
  11638. // have the LSI properly restored.
  11639. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11640. assert(inTemplateInstantiation() &&
  11641. "There should be an active template instantiation on the stack "
  11642. "when instantiating a generic lambda!");
  11643. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11644. } else {
  11645. // Enter a new function scope
  11646. PushFunctionScope();
  11647. }
  11648. // Builtin functions cannot be defined.
  11649. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11650. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11651. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11652. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11653. FD->setInvalidDecl();
  11654. }
  11655. }
  11656. // The return type of a function definition must be complete
  11657. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11658. QualType ResultType = FD->getReturnType();
  11659. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11660. !FD->isInvalidDecl() &&
  11661. RequireCompleteType(FD->getLocation(), ResultType,
  11662. diag::err_func_def_incomplete_result))
  11663. FD->setInvalidDecl();
  11664. if (FnBodyScope)
  11665. PushDeclContext(FnBodyScope, FD);
  11666. // Check the validity of our function parameters
  11667. CheckParmsForFunctionDef(FD->parameters(),
  11668. /*CheckParameterNames=*/true);
  11669. // Add non-parameter declarations already in the function to the current
  11670. // scope.
  11671. if (FnBodyScope) {
  11672. for (Decl *NPD : FD->decls()) {
  11673. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11674. if (!NonParmDecl)
  11675. continue;
  11676. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11677. "parameters should not be in newly created FD yet");
  11678. // If the decl has a name, make it accessible in the current scope.
  11679. if (NonParmDecl->getDeclName())
  11680. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11681. // Similarly, dive into enums and fish their constants out, making them
  11682. // accessible in this scope.
  11683. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11684. for (auto *EI : ED->enumerators())
  11685. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11686. }
  11687. }
  11688. }
  11689. // Introduce our parameters into the function scope
  11690. for (auto Param : FD->parameters()) {
  11691. Param->setOwningFunction(FD);
  11692. // If this has an identifier, add it to the scope stack.
  11693. if (Param->getIdentifier() && FnBodyScope) {
  11694. CheckShadow(FnBodyScope, Param);
  11695. PushOnScopeChains(Param, FnBodyScope);
  11696. }
  11697. }
  11698. // Ensure that the function's exception specification is instantiated.
  11699. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11700. ResolveExceptionSpec(D->getLocation(), FPT);
  11701. // dllimport cannot be applied to non-inline function definitions.
  11702. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11703. !FD->isTemplateInstantiation()) {
  11704. assert(!FD->hasAttr<DLLExportAttr>());
  11705. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11706. FD->setInvalidDecl();
  11707. return D;
  11708. }
  11709. // We want to attach documentation to original Decl (which might be
  11710. // a function template).
  11711. ActOnDocumentableDecl(D);
  11712. if (getCurLexicalContext()->isObjCContainer() &&
  11713. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11714. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11715. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11716. return D;
  11717. }
  11718. /// Given the set of return statements within a function body,
  11719. /// compute the variables that are subject to the named return value
  11720. /// optimization.
  11721. ///
  11722. /// Each of the variables that is subject to the named return value
  11723. /// optimization will be marked as NRVO variables in the AST, and any
  11724. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11725. /// use the named return value optimization.
  11726. ///
  11727. /// This function applies a very simplistic algorithm for NRVO: if every return
  11728. /// statement in the scope of a variable has the same NRVO candidate, that
  11729. /// candidate is an NRVO variable.
  11730. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11731. ReturnStmt **Returns = Scope->Returns.data();
  11732. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11733. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11734. if (!NRVOCandidate->isNRVOVariable())
  11735. Returns[I]->setNRVOCandidate(nullptr);
  11736. }
  11737. }
  11738. }
  11739. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11740. // We can't delay parsing the body of a constexpr function template (yet).
  11741. if (D.getDeclSpec().hasConstexprSpecifier())
  11742. return false;
  11743. // We can't delay parsing the body of a function template with a deduced
  11744. // return type (yet).
  11745. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11746. // If the placeholder introduces a non-deduced trailing return type,
  11747. // we can still delay parsing it.
  11748. if (D.getNumTypeObjects()) {
  11749. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11750. if (Outer.Kind == DeclaratorChunk::Function &&
  11751. Outer.Fun.hasTrailingReturnType()) {
  11752. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11753. return Ty.isNull() || !Ty->isUndeducedType();
  11754. }
  11755. }
  11756. return false;
  11757. }
  11758. return true;
  11759. }
  11760. bool Sema::canSkipFunctionBody(Decl *D) {
  11761. // We cannot skip the body of a function (or function template) which is
  11762. // constexpr, since we may need to evaluate its body in order to parse the
  11763. // rest of the file.
  11764. // We cannot skip the body of a function with an undeduced return type,
  11765. // because any callers of that function need to know the type.
  11766. if (const FunctionDecl *FD = D->getAsFunction()) {
  11767. if (FD->isConstexpr())
  11768. return false;
  11769. // We can't simply call Type::isUndeducedType here, because inside template
  11770. // auto can be deduced to a dependent type, which is not considered
  11771. // "undeduced".
  11772. if (FD->getReturnType()->getContainedDeducedType())
  11773. return false;
  11774. }
  11775. return Consumer.shouldSkipFunctionBody(D);
  11776. }
  11777. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11778. if (!Decl)
  11779. return nullptr;
  11780. if (FunctionDecl *FD = Decl->getAsFunction())
  11781. FD->setHasSkippedBody();
  11782. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11783. MD->setHasSkippedBody();
  11784. return Decl;
  11785. }
  11786. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11787. return ActOnFinishFunctionBody(D, BodyArg, false);
  11788. }
  11789. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  11790. /// body.
  11791. class ExitFunctionBodyRAII {
  11792. public:
  11793. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  11794. ~ExitFunctionBodyRAII() {
  11795. if (!IsLambda)
  11796. S.PopExpressionEvaluationContext();
  11797. }
  11798. private:
  11799. Sema &S;
  11800. bool IsLambda = false;
  11801. };
  11802. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  11803. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  11804. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  11805. if (EscapeInfo.count(BD))
  11806. return EscapeInfo[BD];
  11807. bool R = false;
  11808. const BlockDecl *CurBD = BD;
  11809. do {
  11810. R = !CurBD->doesNotEscape();
  11811. if (R)
  11812. break;
  11813. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  11814. } while (CurBD);
  11815. return EscapeInfo[BD] = R;
  11816. };
  11817. // If the location where 'self' is implicitly retained is inside a escaping
  11818. // block, emit a diagnostic.
  11819. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  11820. S.ImplicitlyRetainedSelfLocs)
  11821. if (IsOrNestedInEscapingBlock(P.second))
  11822. S.Diag(P.first, diag::warn_implicitly_retains_self)
  11823. << FixItHint::CreateInsertion(P.first, "self->");
  11824. }
  11825. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11826. bool IsInstantiation) {
  11827. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11828. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11829. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11830. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  11831. CheckCompletedCoroutineBody(FD, Body);
  11832. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  11833. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  11834. // meant to pop the context added in ActOnStartOfFunctionDef().
  11835. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  11836. if (FD) {
  11837. FD->setBody(Body);
  11838. FD->setWillHaveBody(false);
  11839. if (getLangOpts().CPlusPlus14) {
  11840. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11841. FD->getReturnType()->isUndeducedType()) {
  11842. // If the function has a deduced result type but contains no 'return'
  11843. // statements, the result type as written must be exactly 'auto', and
  11844. // the deduced result type is 'void'.
  11845. if (!FD->getReturnType()->getAs<AutoType>()) {
  11846. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11847. << FD->getReturnType();
  11848. FD->setInvalidDecl();
  11849. } else {
  11850. // Substitute 'void' for the 'auto' in the type.
  11851. TypeLoc ResultType = getReturnTypeLoc(FD);
  11852. Context.adjustDeducedFunctionResultType(
  11853. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11854. }
  11855. }
  11856. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11857. // In C++11, we don't use 'auto' deduction rules for lambda call
  11858. // operators because we don't support return type deduction.
  11859. auto *LSI = getCurLambda();
  11860. if (LSI->HasImplicitReturnType) {
  11861. deduceClosureReturnType(*LSI);
  11862. // C++11 [expr.prim.lambda]p4:
  11863. // [...] if there are no return statements in the compound-statement
  11864. // [the deduced type is] the type void
  11865. QualType RetType =
  11866. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11867. // Update the return type to the deduced type.
  11868. const FunctionProtoType *Proto =
  11869. FD->getType()->getAs<FunctionProtoType>();
  11870. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11871. Proto->getExtProtoInfo()));
  11872. }
  11873. }
  11874. // If the function implicitly returns zero (like 'main') or is naked,
  11875. // don't complain about missing return statements.
  11876. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  11877. WP.disableCheckFallThrough();
  11878. // MSVC permits the use of pure specifier (=0) on function definition,
  11879. // defined at class scope, warn about this non-standard construct.
  11880. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  11881. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  11882. if (!FD->isInvalidDecl()) {
  11883. // Don't diagnose unused parameters of defaulted or deleted functions.
  11884. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  11885. DiagnoseUnusedParameters(FD->parameters());
  11886. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11887. FD->getReturnType(), FD);
  11888. // If this is a structor, we need a vtable.
  11889. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11890. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11891. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11892. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11893. // Try to apply the named return value optimization. We have to check
  11894. // if we can do this here because lambdas keep return statements around
  11895. // to deduce an implicit return type.
  11896. if (FD->getReturnType()->isRecordType() &&
  11897. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  11898. computeNRVO(Body, getCurFunction());
  11899. }
  11900. // GNU warning -Wmissing-prototypes:
  11901. // Warn if a global function is defined without a previous
  11902. // prototype declaration. This warning is issued even if the
  11903. // definition itself provides a prototype. The aim is to detect
  11904. // global functions that fail to be declared in header files.
  11905. const FunctionDecl *PossiblePrototype = nullptr;
  11906. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  11907. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11908. if (PossiblePrototype) {
  11909. // We found a declaration that is not a prototype,
  11910. // but that could be a zero-parameter prototype
  11911. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  11912. TypeLoc TL = TI->getTypeLoc();
  11913. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11914. Diag(PossiblePrototype->getLocation(),
  11915. diag::note_declaration_not_a_prototype)
  11916. << (FD->getNumParams() != 0)
  11917. << (FD->getNumParams() == 0
  11918. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  11919. : FixItHint{});
  11920. }
  11921. } else {
  11922. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  11923. << /* function */ 1
  11924. << (FD->getStorageClass() == SC_None
  11925. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  11926. "static ")
  11927. : FixItHint{});
  11928. }
  11929. // GNU warning -Wstrict-prototypes
  11930. // Warn if K&R function is defined without a previous declaration.
  11931. // This warning is issued only if the definition itself does not provide
  11932. // a prototype. Only K&R definitions do not provide a prototype.
  11933. // An empty list in a function declarator that is part of a definition
  11934. // of that function specifies that the function has no parameters
  11935. // (C99 6.7.5.3p14)
  11936. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11937. !LangOpts.CPlusPlus) {
  11938. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11939. TypeLoc TL = TI->getTypeLoc();
  11940. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11941. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11942. }
  11943. }
  11944. // Warn on CPUDispatch with an actual body.
  11945. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  11946. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  11947. if (!CmpndBody->body_empty())
  11948. Diag(CmpndBody->body_front()->getBeginLoc(),
  11949. diag::warn_dispatch_body_ignored);
  11950. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11951. const CXXMethodDecl *KeyFunction;
  11952. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11953. MD->isVirtual() &&
  11954. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11955. MD == KeyFunction->getCanonicalDecl()) {
  11956. // Update the key-function state if necessary for this ABI.
  11957. if (FD->isInlined() &&
  11958. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11959. Context.setNonKeyFunction(MD);
  11960. // If the newly-chosen key function is already defined, then we
  11961. // need to mark the vtable as used retroactively.
  11962. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11963. const FunctionDecl *Definition;
  11964. if (KeyFunction && KeyFunction->isDefined(Definition))
  11965. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11966. } else {
  11967. // We just defined they key function; mark the vtable as used.
  11968. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11969. }
  11970. }
  11971. }
  11972. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11973. "Function parsing confused");
  11974. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11975. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11976. MD->setBody(Body);
  11977. if (!MD->isInvalidDecl()) {
  11978. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11979. MD->getReturnType(), MD);
  11980. if (Body)
  11981. computeNRVO(Body, getCurFunction());
  11982. }
  11983. if (getCurFunction()->ObjCShouldCallSuper) {
  11984. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  11985. << MD->getSelector().getAsString();
  11986. getCurFunction()->ObjCShouldCallSuper = false;
  11987. }
  11988. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11989. const ObjCMethodDecl *InitMethod = nullptr;
  11990. bool isDesignated =
  11991. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11992. assert(isDesignated && InitMethod);
  11993. (void)isDesignated;
  11994. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11995. auto IFace = MD->getClassInterface();
  11996. if (!IFace)
  11997. return false;
  11998. auto SuperD = IFace->getSuperClass();
  11999. if (!SuperD)
  12000. return false;
  12001. return SuperD->getIdentifier() ==
  12002. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12003. };
  12004. // Don't issue this warning for unavailable inits or direct subclasses
  12005. // of NSObject.
  12006. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12007. Diag(MD->getLocation(),
  12008. diag::warn_objc_designated_init_missing_super_call);
  12009. Diag(InitMethod->getLocation(),
  12010. diag::note_objc_designated_init_marked_here);
  12011. }
  12012. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12013. }
  12014. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12015. // Don't issue this warning for unavaialable inits.
  12016. if (!MD->isUnavailable())
  12017. Diag(MD->getLocation(),
  12018. diag::warn_objc_secondary_init_missing_init_call);
  12019. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12020. }
  12021. diagnoseImplicitlyRetainedSelf(*this);
  12022. } else {
  12023. // Parsing the function declaration failed in some way. Pop the fake scope
  12024. // we pushed on.
  12025. PopFunctionScopeInfo(ActivePolicy, dcl);
  12026. return nullptr;
  12027. }
  12028. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12029. DiagnoseUnguardedAvailabilityViolations(dcl);
  12030. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12031. "This should only be set for ObjC methods, which should have been "
  12032. "handled in the block above.");
  12033. // Verify and clean out per-function state.
  12034. if (Body && (!FD || !FD->isDefaulted())) {
  12035. // C++ constructors that have function-try-blocks can't have return
  12036. // statements in the handlers of that block. (C++ [except.handle]p14)
  12037. // Verify this.
  12038. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12039. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12040. // Verify that gotos and switch cases don't jump into scopes illegally.
  12041. if (getCurFunction()->NeedsScopeChecking() &&
  12042. !PP.isCodeCompletionEnabled())
  12043. DiagnoseInvalidJumps(Body);
  12044. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12045. if (!Destructor->getParent()->isDependentType())
  12046. CheckDestructor(Destructor);
  12047. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12048. Destructor->getParent());
  12049. }
  12050. // If any errors have occurred, clear out any temporaries that may have
  12051. // been leftover. This ensures that these temporaries won't be picked up for
  12052. // deletion in some later function.
  12053. if (getDiagnostics().hasErrorOccurred() ||
  12054. getDiagnostics().getSuppressAllDiagnostics()) {
  12055. DiscardCleanupsInEvaluationContext();
  12056. }
  12057. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12058. !isa<FunctionTemplateDecl>(dcl)) {
  12059. // Since the body is valid, issue any analysis-based warnings that are
  12060. // enabled.
  12061. ActivePolicy = &WP;
  12062. }
  12063. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12064. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  12065. FD->setInvalidDecl();
  12066. if (FD && FD->hasAttr<NakedAttr>()) {
  12067. for (const Stmt *S : Body->children()) {
  12068. // Allow local register variables without initializer as they don't
  12069. // require prologue.
  12070. bool RegisterVariables = false;
  12071. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12072. for (const auto *Decl : DS->decls()) {
  12073. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12074. RegisterVariables =
  12075. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12076. if (!RegisterVariables)
  12077. break;
  12078. }
  12079. }
  12080. }
  12081. if (RegisterVariables)
  12082. continue;
  12083. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12084. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12085. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12086. FD->setInvalidDecl();
  12087. break;
  12088. }
  12089. }
  12090. }
  12091. assert(ExprCleanupObjects.size() ==
  12092. ExprEvalContexts.back().NumCleanupObjects &&
  12093. "Leftover temporaries in function");
  12094. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12095. assert(MaybeODRUseExprs.empty() &&
  12096. "Leftover expressions for odr-use checking");
  12097. }
  12098. if (!IsInstantiation)
  12099. PopDeclContext();
  12100. PopFunctionScopeInfo(ActivePolicy, dcl);
  12101. // If any errors have occurred, clear out any temporaries that may have
  12102. // been leftover. This ensures that these temporaries won't be picked up for
  12103. // deletion in some later function.
  12104. if (getDiagnostics().hasErrorOccurred()) {
  12105. DiscardCleanupsInEvaluationContext();
  12106. }
  12107. return dcl;
  12108. }
  12109. /// When we finish delayed parsing of an attribute, we must attach it to the
  12110. /// relevant Decl.
  12111. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12112. ParsedAttributes &Attrs) {
  12113. // Always attach attributes to the underlying decl.
  12114. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12115. D = TD->getTemplatedDecl();
  12116. ProcessDeclAttributeList(S, D, Attrs);
  12117. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12118. if (Method->isStatic())
  12119. checkThisInStaticMemberFunctionAttributes(Method);
  12120. }
  12121. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12122. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12123. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12124. IdentifierInfo &II, Scope *S) {
  12125. // Find the scope in which the identifier is injected and the corresponding
  12126. // DeclContext.
  12127. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12128. // In that case, we inject the declaration into the translation unit scope
  12129. // instead.
  12130. Scope *BlockScope = S;
  12131. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12132. BlockScope = BlockScope->getParent();
  12133. Scope *ContextScope = BlockScope;
  12134. while (!ContextScope->getEntity())
  12135. ContextScope = ContextScope->getParent();
  12136. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12137. // Before we produce a declaration for an implicitly defined
  12138. // function, see whether there was a locally-scoped declaration of
  12139. // this name as a function or variable. If so, use that
  12140. // (non-visible) declaration, and complain about it.
  12141. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12142. if (ExternCPrev) {
  12143. // We still need to inject the function into the enclosing block scope so
  12144. // that later (non-call) uses can see it.
  12145. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12146. // C89 footnote 38:
  12147. // If in fact it is not defined as having type "function returning int",
  12148. // the behavior is undefined.
  12149. if (!isa<FunctionDecl>(ExternCPrev) ||
  12150. !Context.typesAreCompatible(
  12151. cast<FunctionDecl>(ExternCPrev)->getType(),
  12152. Context.getFunctionNoProtoType(Context.IntTy))) {
  12153. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12154. << ExternCPrev << !getLangOpts().C99;
  12155. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12156. return ExternCPrev;
  12157. }
  12158. }
  12159. // Extension in C99. Legal in C90, but warn about it.
  12160. unsigned diag_id;
  12161. if (II.getName().startswith("__builtin_"))
  12162. diag_id = diag::warn_builtin_unknown;
  12163. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12164. else if (getLangOpts().OpenCL)
  12165. diag_id = diag::err_opencl_implicit_function_decl;
  12166. else if (getLangOpts().C99)
  12167. diag_id = diag::ext_implicit_function_decl;
  12168. else
  12169. diag_id = diag::warn_implicit_function_decl;
  12170. Diag(Loc, diag_id) << &II;
  12171. // If we found a prior declaration of this function, don't bother building
  12172. // another one. We've already pushed that one into scope, so there's nothing
  12173. // more to do.
  12174. if (ExternCPrev)
  12175. return ExternCPrev;
  12176. // Because typo correction is expensive, only do it if the implicit
  12177. // function declaration is going to be treated as an error.
  12178. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12179. TypoCorrection Corrected;
  12180. DeclFilterCCC<FunctionDecl> CCC{};
  12181. if (S && (Corrected =
  12182. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12183. S, nullptr, CCC, CTK_NonError)))
  12184. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12185. /*ErrorRecovery*/false);
  12186. }
  12187. // Set a Declarator for the implicit definition: int foo();
  12188. const char *Dummy;
  12189. AttributeFactory attrFactory;
  12190. DeclSpec DS(attrFactory);
  12191. unsigned DiagID;
  12192. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12193. Context.getPrintingPolicy());
  12194. (void)Error; // Silence warning.
  12195. assert(!Error && "Error setting up implicit decl!");
  12196. SourceLocation NoLoc;
  12197. Declarator D(DS, DeclaratorContext::BlockContext);
  12198. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12199. /*IsAmbiguous=*/false,
  12200. /*LParenLoc=*/NoLoc,
  12201. /*Params=*/nullptr,
  12202. /*NumParams=*/0,
  12203. /*EllipsisLoc=*/NoLoc,
  12204. /*RParenLoc=*/NoLoc,
  12205. /*RefQualifierIsLvalueRef=*/true,
  12206. /*RefQualifierLoc=*/NoLoc,
  12207. /*MutableLoc=*/NoLoc, EST_None,
  12208. /*ESpecRange=*/SourceRange(),
  12209. /*Exceptions=*/nullptr,
  12210. /*ExceptionRanges=*/nullptr,
  12211. /*NumExceptions=*/0,
  12212. /*NoexceptExpr=*/nullptr,
  12213. /*ExceptionSpecTokens=*/nullptr,
  12214. /*DeclsInPrototype=*/None, Loc,
  12215. Loc, D),
  12216. std::move(DS.getAttributes()), SourceLocation());
  12217. D.SetIdentifier(&II, Loc);
  12218. // Insert this function into the enclosing block scope.
  12219. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12220. FD->setImplicit();
  12221. AddKnownFunctionAttributes(FD);
  12222. return FD;
  12223. }
  12224. /// Adds any function attributes that we know a priori based on
  12225. /// the declaration of this function.
  12226. ///
  12227. /// These attributes can apply both to implicitly-declared builtins
  12228. /// (like __builtin___printf_chk) or to library-declared functions
  12229. /// like NSLog or printf.
  12230. ///
  12231. /// We need to check for duplicate attributes both here and where user-written
  12232. /// attributes are applied to declarations.
  12233. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12234. if (FD->isInvalidDecl())
  12235. return;
  12236. // If this is a built-in function, map its builtin attributes to
  12237. // actual attributes.
  12238. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12239. // Handle printf-formatting attributes.
  12240. unsigned FormatIdx;
  12241. bool HasVAListArg;
  12242. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12243. if (!FD->hasAttr<FormatAttr>()) {
  12244. const char *fmt = "printf";
  12245. unsigned int NumParams = FD->getNumParams();
  12246. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12247. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12248. fmt = "NSString";
  12249. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12250. &Context.Idents.get(fmt),
  12251. FormatIdx+1,
  12252. HasVAListArg ? 0 : FormatIdx+2,
  12253. FD->getLocation()));
  12254. }
  12255. }
  12256. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12257. HasVAListArg)) {
  12258. if (!FD->hasAttr<FormatAttr>())
  12259. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12260. &Context.Idents.get("scanf"),
  12261. FormatIdx+1,
  12262. HasVAListArg ? 0 : FormatIdx+2,
  12263. FD->getLocation()));
  12264. }
  12265. // Handle automatically recognized callbacks.
  12266. SmallVector<int, 4> Encoding;
  12267. if (!FD->hasAttr<CallbackAttr>() &&
  12268. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12269. FD->addAttr(CallbackAttr::CreateImplicit(
  12270. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12271. // Mark const if we don't care about errno and that is the only thing
  12272. // preventing the function from being const. This allows IRgen to use LLVM
  12273. // intrinsics for such functions.
  12274. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12275. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12276. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12277. // We make "fma" on some platforms const because we know it does not set
  12278. // errno in those environments even though it could set errno based on the
  12279. // C standard.
  12280. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12281. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12282. !FD->hasAttr<ConstAttr>()) {
  12283. switch (BuiltinID) {
  12284. case Builtin::BI__builtin_fma:
  12285. case Builtin::BI__builtin_fmaf:
  12286. case Builtin::BI__builtin_fmal:
  12287. case Builtin::BIfma:
  12288. case Builtin::BIfmaf:
  12289. case Builtin::BIfmal:
  12290. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12291. break;
  12292. default:
  12293. break;
  12294. }
  12295. }
  12296. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12297. !FD->hasAttr<ReturnsTwiceAttr>())
  12298. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12299. FD->getLocation()));
  12300. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12301. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12302. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12303. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12304. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12305. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12306. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12307. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12308. // Add the appropriate attribute, depending on the CUDA compilation mode
  12309. // and which target the builtin belongs to. For example, during host
  12310. // compilation, aux builtins are __device__, while the rest are __host__.
  12311. if (getLangOpts().CUDAIsDevice !=
  12312. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12313. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12314. else
  12315. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12316. }
  12317. }
  12318. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12319. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12320. // across.
  12321. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12322. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12323. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12324. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12325. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12326. }
  12327. IdentifierInfo *Name = FD->getIdentifier();
  12328. if (!Name)
  12329. return;
  12330. if ((!getLangOpts().CPlusPlus &&
  12331. FD->getDeclContext()->isTranslationUnit()) ||
  12332. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12333. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12334. LinkageSpecDecl::lang_c)) {
  12335. // Okay: this could be a libc/libm/Objective-C function we know
  12336. // about.
  12337. } else
  12338. return;
  12339. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12340. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12341. // target-specific builtins, perhaps?
  12342. if (!FD->hasAttr<FormatAttr>())
  12343. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12344. &Context.Idents.get("printf"), 2,
  12345. Name->isStr("vasprintf") ? 0 : 3,
  12346. FD->getLocation()));
  12347. }
  12348. if (Name->isStr("__CFStringMakeConstantString")) {
  12349. // We already have a __builtin___CFStringMakeConstantString,
  12350. // but builds that use -fno-constant-cfstrings don't go through that.
  12351. if (!FD->hasAttr<FormatArgAttr>())
  12352. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12353. FD->getLocation()));
  12354. }
  12355. }
  12356. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12357. TypeSourceInfo *TInfo) {
  12358. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12359. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12360. if (!TInfo) {
  12361. assert(D.isInvalidType() && "no declarator info for valid type");
  12362. TInfo = Context.getTrivialTypeSourceInfo(T);
  12363. }
  12364. // Scope manipulation handled by caller.
  12365. TypedefDecl *NewTD =
  12366. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12367. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12368. // Bail out immediately if we have an invalid declaration.
  12369. if (D.isInvalidType()) {
  12370. NewTD->setInvalidDecl();
  12371. return NewTD;
  12372. }
  12373. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12374. if (CurContext->isFunctionOrMethod())
  12375. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12376. << 2 << NewTD->getDeclName()
  12377. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12378. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12379. else
  12380. NewTD->setModulePrivate();
  12381. }
  12382. // C++ [dcl.typedef]p8:
  12383. // If the typedef declaration defines an unnamed class (or
  12384. // enum), the first typedef-name declared by the declaration
  12385. // to be that class type (or enum type) is used to denote the
  12386. // class type (or enum type) for linkage purposes only.
  12387. // We need to check whether the type was declared in the declaration.
  12388. switch (D.getDeclSpec().getTypeSpecType()) {
  12389. case TST_enum:
  12390. case TST_struct:
  12391. case TST_interface:
  12392. case TST_union:
  12393. case TST_class: {
  12394. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12395. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12396. break;
  12397. }
  12398. default:
  12399. break;
  12400. }
  12401. return NewTD;
  12402. }
  12403. /// Check that this is a valid underlying type for an enum declaration.
  12404. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12405. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12406. QualType T = TI->getType();
  12407. if (T->isDependentType())
  12408. return false;
  12409. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12410. if (BT->isInteger())
  12411. return false;
  12412. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12413. return true;
  12414. }
  12415. /// Check whether this is a valid redeclaration of a previous enumeration.
  12416. /// \return true if the redeclaration was invalid.
  12417. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12418. QualType EnumUnderlyingTy, bool IsFixed,
  12419. const EnumDecl *Prev) {
  12420. if (IsScoped != Prev->isScoped()) {
  12421. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12422. << Prev->isScoped();
  12423. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12424. return true;
  12425. }
  12426. if (IsFixed && Prev->isFixed()) {
  12427. if (!EnumUnderlyingTy->isDependentType() &&
  12428. !Prev->getIntegerType()->isDependentType() &&
  12429. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12430. Prev->getIntegerType())) {
  12431. // TODO: Highlight the underlying type of the redeclaration.
  12432. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12433. << EnumUnderlyingTy << Prev->getIntegerType();
  12434. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12435. << Prev->getIntegerTypeRange();
  12436. return true;
  12437. }
  12438. } else if (IsFixed != Prev->isFixed()) {
  12439. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12440. << Prev->isFixed();
  12441. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12442. return true;
  12443. }
  12444. return false;
  12445. }
  12446. /// Get diagnostic %select index for tag kind for
  12447. /// redeclaration diagnostic message.
  12448. /// WARNING: Indexes apply to particular diagnostics only!
  12449. ///
  12450. /// \returns diagnostic %select index.
  12451. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12452. switch (Tag) {
  12453. case TTK_Struct: return 0;
  12454. case TTK_Interface: return 1;
  12455. case TTK_Class: return 2;
  12456. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12457. }
  12458. }
  12459. /// Determine if tag kind is a class-key compatible with
  12460. /// class for redeclaration (class, struct, or __interface).
  12461. ///
  12462. /// \returns true iff the tag kind is compatible.
  12463. static bool isClassCompatTagKind(TagTypeKind Tag)
  12464. {
  12465. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12466. }
  12467. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12468. TagTypeKind TTK) {
  12469. if (isa<TypedefDecl>(PrevDecl))
  12470. return NTK_Typedef;
  12471. else if (isa<TypeAliasDecl>(PrevDecl))
  12472. return NTK_TypeAlias;
  12473. else if (isa<ClassTemplateDecl>(PrevDecl))
  12474. return NTK_Template;
  12475. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12476. return NTK_TypeAliasTemplate;
  12477. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12478. return NTK_TemplateTemplateArgument;
  12479. switch (TTK) {
  12480. case TTK_Struct:
  12481. case TTK_Interface:
  12482. case TTK_Class:
  12483. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12484. case TTK_Union:
  12485. return NTK_NonUnion;
  12486. case TTK_Enum:
  12487. return NTK_NonEnum;
  12488. }
  12489. llvm_unreachable("invalid TTK");
  12490. }
  12491. /// Determine whether a tag with a given kind is acceptable
  12492. /// as a redeclaration of the given tag declaration.
  12493. ///
  12494. /// \returns true if the new tag kind is acceptable, false otherwise.
  12495. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12496. TagTypeKind NewTag, bool isDefinition,
  12497. SourceLocation NewTagLoc,
  12498. const IdentifierInfo *Name) {
  12499. // C++ [dcl.type.elab]p3:
  12500. // The class-key or enum keyword present in the
  12501. // elaborated-type-specifier shall agree in kind with the
  12502. // declaration to which the name in the elaborated-type-specifier
  12503. // refers. This rule also applies to the form of
  12504. // elaborated-type-specifier that declares a class-name or
  12505. // friend class since it can be construed as referring to the
  12506. // definition of the class. Thus, in any
  12507. // elaborated-type-specifier, the enum keyword shall be used to
  12508. // refer to an enumeration (7.2), the union class-key shall be
  12509. // used to refer to a union (clause 9), and either the class or
  12510. // struct class-key shall be used to refer to a class (clause 9)
  12511. // declared using the class or struct class-key.
  12512. TagTypeKind OldTag = Previous->getTagKind();
  12513. if (OldTag != NewTag &&
  12514. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12515. return false;
  12516. // Tags are compatible, but we might still want to warn on mismatched tags.
  12517. // Non-class tags can't be mismatched at this point.
  12518. if (!isClassCompatTagKind(NewTag))
  12519. return true;
  12520. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12521. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12522. // declarations in system headers that are designed to be specialized, but if
  12523. // a user asks us to warn, we should warn if their code contains mismatched
  12524. // declarations.
  12525. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12526. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12527. Loc);
  12528. };
  12529. if (IsIgnoredLoc(NewTagLoc))
  12530. return true;
  12531. auto IsIgnored = [&](const TagDecl *Tag) {
  12532. return IsIgnoredLoc(Tag->getLocation());
  12533. };
  12534. while (IsIgnored(Previous)) {
  12535. Previous = Previous->getPreviousDecl();
  12536. if (!Previous)
  12537. return true;
  12538. OldTag = Previous->getTagKind();
  12539. }
  12540. bool isTemplate = false;
  12541. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12542. isTemplate = Record->getDescribedClassTemplate();
  12543. if (inTemplateInstantiation()) {
  12544. if (OldTag != NewTag) {
  12545. // In a template instantiation, do not offer fix-its for tag mismatches
  12546. // since they usually mess up the template instead of fixing the problem.
  12547. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12548. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12549. << getRedeclDiagFromTagKind(OldTag);
  12550. // FIXME: Note previous location?
  12551. }
  12552. return true;
  12553. }
  12554. if (isDefinition) {
  12555. // On definitions, check all previous tags and issue a fix-it for each
  12556. // one that doesn't match the current tag.
  12557. if (Previous->getDefinition()) {
  12558. // Don't suggest fix-its for redefinitions.
  12559. return true;
  12560. }
  12561. bool previousMismatch = false;
  12562. for (const TagDecl *I : Previous->redecls()) {
  12563. if (I->getTagKind() != NewTag) {
  12564. // Ignore previous declarations for which the warning was disabled.
  12565. if (IsIgnored(I))
  12566. continue;
  12567. if (!previousMismatch) {
  12568. previousMismatch = true;
  12569. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12570. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12571. << getRedeclDiagFromTagKind(I->getTagKind());
  12572. }
  12573. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12574. << getRedeclDiagFromTagKind(NewTag)
  12575. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12576. TypeWithKeyword::getTagTypeKindName(NewTag));
  12577. }
  12578. }
  12579. return true;
  12580. }
  12581. // Identify the prevailing tag kind: this is the kind of the definition (if
  12582. // there is a non-ignored definition), or otherwise the kind of the prior
  12583. // (non-ignored) declaration.
  12584. const TagDecl *PrevDef = Previous->getDefinition();
  12585. if (PrevDef && IsIgnored(PrevDef))
  12586. PrevDef = nullptr;
  12587. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12588. if (Redecl->getTagKind() != NewTag) {
  12589. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12590. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12591. << getRedeclDiagFromTagKind(OldTag);
  12592. Diag(Redecl->getLocation(), diag::note_previous_use);
  12593. // If there is a previous definition, suggest a fix-it.
  12594. if (PrevDef) {
  12595. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12596. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12597. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12598. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12599. }
  12600. }
  12601. return true;
  12602. }
  12603. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12604. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12605. /// This should provide the commented out code in the following snippet:
  12606. /// namespace N {
  12607. /// struct X;
  12608. /// namespace M {
  12609. /// struct Y { friend struct /*N::*/ X; };
  12610. /// }
  12611. /// }
  12612. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12613. SourceLocation NameLoc) {
  12614. // While the decl is in a namespace, do repeated lookup of that name and see
  12615. // if we get the same namespace back. If we do not, continue until
  12616. // translation unit scope, at which point we have a fully qualified NNS.
  12617. SmallVector<IdentifierInfo *, 4> Namespaces;
  12618. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12619. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12620. // This tag should be declared in a namespace, which can only be enclosed by
  12621. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12622. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12623. if (!Namespace || Namespace->isAnonymousNamespace())
  12624. return FixItHint();
  12625. IdentifierInfo *II = Namespace->getIdentifier();
  12626. Namespaces.push_back(II);
  12627. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12628. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12629. if (Lookup == Namespace)
  12630. break;
  12631. }
  12632. // Once we have all the namespaces, reverse them to go outermost first, and
  12633. // build an NNS.
  12634. SmallString<64> Insertion;
  12635. llvm::raw_svector_ostream OS(Insertion);
  12636. if (DC->isTranslationUnit())
  12637. OS << "::";
  12638. std::reverse(Namespaces.begin(), Namespaces.end());
  12639. for (auto *II : Namespaces)
  12640. OS << II->getName() << "::";
  12641. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12642. }
  12643. /// Determine whether a tag originally declared in context \p OldDC can
  12644. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12645. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12646. /// using-declaration).
  12647. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12648. DeclContext *NewDC) {
  12649. OldDC = OldDC->getRedeclContext();
  12650. NewDC = NewDC->getRedeclContext();
  12651. if (OldDC->Equals(NewDC))
  12652. return true;
  12653. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12654. // encloses the other).
  12655. if (S.getLangOpts().MSVCCompat &&
  12656. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12657. return true;
  12658. return false;
  12659. }
  12660. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12661. /// former case, Name will be non-null. In the later case, Name will be null.
  12662. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12663. /// reference/declaration/definition of a tag.
  12664. ///
  12665. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12666. /// trailing-type-specifier) other than one in an alias-declaration.
  12667. ///
  12668. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12669. /// skip the definition of this tag and treat it as if it were a declaration.
  12670. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12671. SourceLocation KWLoc, CXXScopeSpec &SS,
  12672. IdentifierInfo *Name, SourceLocation NameLoc,
  12673. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12674. SourceLocation ModulePrivateLoc,
  12675. MultiTemplateParamsArg TemplateParameterLists,
  12676. bool &OwnedDecl, bool &IsDependent,
  12677. SourceLocation ScopedEnumKWLoc,
  12678. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12679. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12680. SkipBodyInfo *SkipBody) {
  12681. // If this is not a definition, it must have a name.
  12682. IdentifierInfo *OrigName = Name;
  12683. assert((Name != nullptr || TUK == TUK_Definition) &&
  12684. "Nameless record must be a definition!");
  12685. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12686. OwnedDecl = false;
  12687. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12688. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12689. // FIXME: Check member specializations more carefully.
  12690. bool isMemberSpecialization = false;
  12691. bool Invalid = false;
  12692. // We only need to do this matching if we have template parameters
  12693. // or a scope specifier, which also conveniently avoids this work
  12694. // for non-C++ cases.
  12695. if (TemplateParameterLists.size() > 0 ||
  12696. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12697. if (TemplateParameterList *TemplateParams =
  12698. MatchTemplateParametersToScopeSpecifier(
  12699. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12700. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12701. if (Kind == TTK_Enum) {
  12702. Diag(KWLoc, diag::err_enum_template);
  12703. return nullptr;
  12704. }
  12705. if (TemplateParams->size() > 0) {
  12706. // This is a declaration or definition of a class template (which may
  12707. // be a member of another template).
  12708. if (Invalid)
  12709. return nullptr;
  12710. OwnedDecl = false;
  12711. DeclResult Result = CheckClassTemplate(
  12712. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12713. AS, ModulePrivateLoc,
  12714. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12715. TemplateParameterLists.data(), SkipBody);
  12716. return Result.get();
  12717. } else {
  12718. // The "template<>" header is extraneous.
  12719. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12720. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12721. isMemberSpecialization = true;
  12722. }
  12723. }
  12724. }
  12725. // Figure out the underlying type if this a enum declaration. We need to do
  12726. // this early, because it's needed to detect if this is an incompatible
  12727. // redeclaration.
  12728. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12729. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12730. if (Kind == TTK_Enum) {
  12731. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12732. // No underlying type explicitly specified, or we failed to parse the
  12733. // type, default to int.
  12734. EnumUnderlying = Context.IntTy.getTypePtr();
  12735. } else if (UnderlyingType.get()) {
  12736. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12737. // integral type; any cv-qualification is ignored.
  12738. TypeSourceInfo *TI = nullptr;
  12739. GetTypeFromParser(UnderlyingType.get(), &TI);
  12740. EnumUnderlying = TI;
  12741. if (CheckEnumUnderlyingType(TI))
  12742. // Recover by falling back to int.
  12743. EnumUnderlying = Context.IntTy.getTypePtr();
  12744. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12745. UPPC_FixedUnderlyingType))
  12746. EnumUnderlying = Context.IntTy.getTypePtr();
  12747. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12748. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12749. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12750. // the underlying type unless the user enables -fms-compatibility. This
  12751. // makes unfixed forward declared enums incomplete and is more conforming.
  12752. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12753. EnumUnderlying = Context.IntTy.getTypePtr();
  12754. }
  12755. }
  12756. DeclContext *SearchDC = CurContext;
  12757. DeclContext *DC = CurContext;
  12758. bool isStdBadAlloc = false;
  12759. bool isStdAlignValT = false;
  12760. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12761. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12762. Redecl = NotForRedeclaration;
  12763. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12764. /// implemented asks for structural equivalence checking, the returned decl
  12765. /// here is passed back to the parser, allowing the tag body to be parsed.
  12766. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12767. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12768. // If there is an identifier, use the location of the identifier as the
  12769. // location of the decl, otherwise use the location of the struct/union
  12770. // keyword.
  12771. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12772. TagDecl *New = nullptr;
  12773. if (Kind == TTK_Enum) {
  12774. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12775. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12776. // If this is an undefined enum, bail.
  12777. if (TUK != TUK_Definition && !Invalid)
  12778. return nullptr;
  12779. if (EnumUnderlying) {
  12780. EnumDecl *ED = cast<EnumDecl>(New);
  12781. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12782. ED->setIntegerTypeSourceInfo(TI);
  12783. else
  12784. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12785. ED->setPromotionType(ED->getIntegerType());
  12786. }
  12787. } else { // struct/union
  12788. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12789. nullptr);
  12790. }
  12791. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12792. // Add alignment attributes if necessary; these attributes are checked
  12793. // when the ASTContext lays out the structure.
  12794. //
  12795. // It is important for implementing the correct semantics that this
  12796. // happen here (in ActOnTag). The #pragma pack stack is
  12797. // maintained as a result of parser callbacks which can occur at
  12798. // many points during the parsing of a struct declaration (because
  12799. // the #pragma tokens are effectively skipped over during the
  12800. // parsing of the struct).
  12801. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  12802. AddAlignmentAttributesForRecord(RD);
  12803. AddMsStructLayoutForRecord(RD);
  12804. }
  12805. }
  12806. New->setLexicalDeclContext(CurContext);
  12807. return New;
  12808. };
  12809. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12810. if (Name && SS.isNotEmpty()) {
  12811. // We have a nested-name tag ('struct foo::bar').
  12812. // Check for invalid 'foo::'.
  12813. if (SS.isInvalid()) {
  12814. Name = nullptr;
  12815. goto CreateNewDecl;
  12816. }
  12817. // If this is a friend or a reference to a class in a dependent
  12818. // context, don't try to make a decl for it.
  12819. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12820. DC = computeDeclContext(SS, false);
  12821. if (!DC) {
  12822. IsDependent = true;
  12823. return nullptr;
  12824. }
  12825. } else {
  12826. DC = computeDeclContext(SS, true);
  12827. if (!DC) {
  12828. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12829. << SS.getRange();
  12830. return nullptr;
  12831. }
  12832. }
  12833. if (RequireCompleteDeclContext(SS, DC))
  12834. return nullptr;
  12835. SearchDC = DC;
  12836. // Look-up name inside 'foo::'.
  12837. LookupQualifiedName(Previous, DC);
  12838. if (Previous.isAmbiguous())
  12839. return nullptr;
  12840. if (Previous.empty()) {
  12841. // Name lookup did not find anything. However, if the
  12842. // nested-name-specifier refers to the current instantiation,
  12843. // and that current instantiation has any dependent base
  12844. // classes, we might find something at instantiation time: treat
  12845. // this as a dependent elaborated-type-specifier.
  12846. // But this only makes any sense for reference-like lookups.
  12847. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12848. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12849. IsDependent = true;
  12850. return nullptr;
  12851. }
  12852. // A tag 'foo::bar' must already exist.
  12853. Diag(NameLoc, diag::err_not_tag_in_scope)
  12854. << Kind << Name << DC << SS.getRange();
  12855. Name = nullptr;
  12856. Invalid = true;
  12857. goto CreateNewDecl;
  12858. }
  12859. } else if (Name) {
  12860. // C++14 [class.mem]p14:
  12861. // If T is the name of a class, then each of the following shall have a
  12862. // name different from T:
  12863. // -- every member of class T that is itself a type
  12864. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12865. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12866. return nullptr;
  12867. // If this is a named struct, check to see if there was a previous forward
  12868. // declaration or definition.
  12869. // FIXME: We're looking into outer scopes here, even when we
  12870. // shouldn't be. Doing so can result in ambiguities that we
  12871. // shouldn't be diagnosing.
  12872. LookupName(Previous, S);
  12873. // When declaring or defining a tag, ignore ambiguities introduced
  12874. // by types using'ed into this scope.
  12875. if (Previous.isAmbiguous() &&
  12876. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  12877. LookupResult::Filter F = Previous.makeFilter();
  12878. while (F.hasNext()) {
  12879. NamedDecl *ND = F.next();
  12880. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  12881. SearchDC->getRedeclContext()))
  12882. F.erase();
  12883. }
  12884. F.done();
  12885. }
  12886. // C++11 [namespace.memdef]p3:
  12887. // If the name in a friend declaration is neither qualified nor
  12888. // a template-id and the declaration is a function or an
  12889. // elaborated-type-specifier, the lookup to determine whether
  12890. // the entity has been previously declared shall not consider
  12891. // any scopes outside the innermost enclosing namespace.
  12892. //
  12893. // MSVC doesn't implement the above rule for types, so a friend tag
  12894. // declaration may be a redeclaration of a type declared in an enclosing
  12895. // scope. They do implement this rule for friend functions.
  12896. //
  12897. // Does it matter that this should be by scope instead of by
  12898. // semantic context?
  12899. if (!Previous.empty() && TUK == TUK_Friend) {
  12900. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  12901. LookupResult::Filter F = Previous.makeFilter();
  12902. bool FriendSawTagOutsideEnclosingNamespace = false;
  12903. while (F.hasNext()) {
  12904. NamedDecl *ND = F.next();
  12905. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12906. if (DC->isFileContext() &&
  12907. !EnclosingNS->Encloses(ND->getDeclContext())) {
  12908. if (getLangOpts().MSVCCompat)
  12909. FriendSawTagOutsideEnclosingNamespace = true;
  12910. else
  12911. F.erase();
  12912. }
  12913. }
  12914. F.done();
  12915. // Diagnose this MSVC extension in the easy case where lookup would have
  12916. // unambiguously found something outside the enclosing namespace.
  12917. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  12918. NamedDecl *ND = Previous.getFoundDecl();
  12919. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  12920. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  12921. }
  12922. }
  12923. // Note: there used to be some attempt at recovery here.
  12924. if (Previous.isAmbiguous())
  12925. return nullptr;
  12926. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  12927. // FIXME: This makes sure that we ignore the contexts associated
  12928. // with C structs, unions, and enums when looking for a matching
  12929. // tag declaration or definition. See the similar lookup tweak
  12930. // in Sema::LookupName; is there a better way to deal with this?
  12931. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  12932. SearchDC = SearchDC->getParent();
  12933. }
  12934. }
  12935. if (Previous.isSingleResult() &&
  12936. Previous.getFoundDecl()->isTemplateParameter()) {
  12937. // Maybe we will complain about the shadowed template parameter.
  12938. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  12939. // Just pretend that we didn't see the previous declaration.
  12940. Previous.clear();
  12941. }
  12942. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  12943. DC->Equals(getStdNamespace())) {
  12944. if (Name->isStr("bad_alloc")) {
  12945. // This is a declaration of or a reference to "std::bad_alloc".
  12946. isStdBadAlloc = true;
  12947. // If std::bad_alloc has been implicitly declared (but made invisible to
  12948. // name lookup), fill in this implicit declaration as the previous
  12949. // declaration, so that the declarations get chained appropriately.
  12950. if (Previous.empty() && StdBadAlloc)
  12951. Previous.addDecl(getStdBadAlloc());
  12952. } else if (Name->isStr("align_val_t")) {
  12953. isStdAlignValT = true;
  12954. if (Previous.empty() && StdAlignValT)
  12955. Previous.addDecl(getStdAlignValT());
  12956. }
  12957. }
  12958. // If we didn't find a previous declaration, and this is a reference
  12959. // (or friend reference), move to the correct scope. In C++, we
  12960. // also need to do a redeclaration lookup there, just in case
  12961. // there's a shadow friend decl.
  12962. if (Name && Previous.empty() &&
  12963. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12964. if (Invalid) goto CreateNewDecl;
  12965. assert(SS.isEmpty());
  12966. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12967. // C++ [basic.scope.pdecl]p5:
  12968. // -- for an elaborated-type-specifier of the form
  12969. //
  12970. // class-key identifier
  12971. //
  12972. // if the elaborated-type-specifier is used in the
  12973. // decl-specifier-seq or parameter-declaration-clause of a
  12974. // function defined in namespace scope, the identifier is
  12975. // declared as a class-name in the namespace that contains
  12976. // the declaration; otherwise, except as a friend
  12977. // declaration, the identifier is declared in the smallest
  12978. // non-class, non-function-prototype scope that contains the
  12979. // declaration.
  12980. //
  12981. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12982. // C structs and unions.
  12983. //
  12984. // It is an error in C++ to declare (rather than define) an enum
  12985. // type, including via an elaborated type specifier. We'll
  12986. // diagnose that later; for now, declare the enum in the same
  12987. // scope as we would have picked for any other tag type.
  12988. //
  12989. // GNU C also supports this behavior as part of its incomplete
  12990. // enum types extension, while GNU C++ does not.
  12991. //
  12992. // Find the context where we'll be declaring the tag.
  12993. // FIXME: We would like to maintain the current DeclContext as the
  12994. // lexical context,
  12995. SearchDC = getTagInjectionContext(SearchDC);
  12996. // Find the scope where we'll be declaring the tag.
  12997. S = getTagInjectionScope(S, getLangOpts());
  12998. } else {
  12999. assert(TUK == TUK_Friend);
  13000. // C++ [namespace.memdef]p3:
  13001. // If a friend declaration in a non-local class first declares a
  13002. // class or function, the friend class or function is a member of
  13003. // the innermost enclosing namespace.
  13004. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13005. }
  13006. // In C++, we need to do a redeclaration lookup to properly
  13007. // diagnose some problems.
  13008. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13009. // hidden declaration so that we don't get ambiguity errors when using a
  13010. // type declared by an elaborated-type-specifier. In C that is not correct
  13011. // and we should instead merge compatible types found by lookup.
  13012. if (getLangOpts().CPlusPlus) {
  13013. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13014. LookupQualifiedName(Previous, SearchDC);
  13015. } else {
  13016. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13017. LookupName(Previous, S);
  13018. }
  13019. }
  13020. // If we have a known previous declaration to use, then use it.
  13021. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13022. Previous.addDecl(SkipBody->Previous);
  13023. if (!Previous.empty()) {
  13024. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13025. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13026. // It's okay to have a tag decl in the same scope as a typedef
  13027. // which hides a tag decl in the same scope. Finding this
  13028. // insanity with a redeclaration lookup can only actually happen
  13029. // in C++.
  13030. //
  13031. // This is also okay for elaborated-type-specifiers, which is
  13032. // technically forbidden by the current standard but which is
  13033. // okay according to the likely resolution of an open issue;
  13034. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13035. if (getLangOpts().CPlusPlus) {
  13036. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13037. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13038. TagDecl *Tag = TT->getDecl();
  13039. if (Tag->getDeclName() == Name &&
  13040. Tag->getDeclContext()->getRedeclContext()
  13041. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13042. PrevDecl = Tag;
  13043. Previous.clear();
  13044. Previous.addDecl(Tag);
  13045. Previous.resolveKind();
  13046. }
  13047. }
  13048. }
  13049. }
  13050. // If this is a redeclaration of a using shadow declaration, it must
  13051. // declare a tag in the same context. In MSVC mode, we allow a
  13052. // redefinition if either context is within the other.
  13053. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13054. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13055. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13056. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13057. !(OldTag && isAcceptableTagRedeclContext(
  13058. *this, OldTag->getDeclContext(), SearchDC))) {
  13059. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13060. Diag(Shadow->getTargetDecl()->getLocation(),
  13061. diag::note_using_decl_target);
  13062. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13063. << 0;
  13064. // Recover by ignoring the old declaration.
  13065. Previous.clear();
  13066. goto CreateNewDecl;
  13067. }
  13068. }
  13069. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13070. // If this is a use of a previous tag, or if the tag is already declared
  13071. // in the same scope (so that the definition/declaration completes or
  13072. // rementions the tag), reuse the decl.
  13073. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13074. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13075. SS.isNotEmpty() || isMemberSpecialization)) {
  13076. // Make sure that this wasn't declared as an enum and now used as a
  13077. // struct or something similar.
  13078. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13079. TUK == TUK_Definition, KWLoc,
  13080. Name)) {
  13081. bool SafeToContinue
  13082. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13083. Kind != TTK_Enum);
  13084. if (SafeToContinue)
  13085. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13086. << Name
  13087. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13088. PrevTagDecl->getKindName());
  13089. else
  13090. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13091. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13092. if (SafeToContinue)
  13093. Kind = PrevTagDecl->getTagKind();
  13094. else {
  13095. // Recover by making this an anonymous redefinition.
  13096. Name = nullptr;
  13097. Previous.clear();
  13098. Invalid = true;
  13099. }
  13100. }
  13101. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13102. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13103. // If this is an elaborated-type-specifier for a scoped enumeration,
  13104. // the 'class' keyword is not necessary and not permitted.
  13105. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13106. if (ScopedEnum)
  13107. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13108. << PrevEnum->isScoped()
  13109. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13110. return PrevTagDecl;
  13111. }
  13112. QualType EnumUnderlyingTy;
  13113. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13114. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13115. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13116. EnumUnderlyingTy = QualType(T, 0);
  13117. // All conflicts with previous declarations are recovered by
  13118. // returning the previous declaration, unless this is a definition,
  13119. // in which case we want the caller to bail out.
  13120. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13121. ScopedEnum, EnumUnderlyingTy,
  13122. IsFixed, PrevEnum))
  13123. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13124. }
  13125. // C++11 [class.mem]p1:
  13126. // A member shall not be declared twice in the member-specification,
  13127. // except that a nested class or member class template can be declared
  13128. // and then later defined.
  13129. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13130. S->isDeclScope(PrevDecl)) {
  13131. Diag(NameLoc, diag::ext_member_redeclared);
  13132. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13133. }
  13134. if (!Invalid) {
  13135. // If this is a use, just return the declaration we found, unless
  13136. // we have attributes.
  13137. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13138. if (!Attrs.empty()) {
  13139. // FIXME: Diagnose these attributes. For now, we create a new
  13140. // declaration to hold them.
  13141. } else if (TUK == TUK_Reference &&
  13142. (PrevTagDecl->getFriendObjectKind() ==
  13143. Decl::FOK_Undeclared ||
  13144. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13145. SS.isEmpty()) {
  13146. // This declaration is a reference to an existing entity, but
  13147. // has different visibility from that entity: it either makes
  13148. // a friend visible or it makes a type visible in a new module.
  13149. // In either case, create a new declaration. We only do this if
  13150. // the declaration would have meant the same thing if no prior
  13151. // declaration were found, that is, if it was found in the same
  13152. // scope where we would have injected a declaration.
  13153. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13154. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13155. return PrevTagDecl;
  13156. // This is in the injected scope, create a new declaration in
  13157. // that scope.
  13158. S = getTagInjectionScope(S, getLangOpts());
  13159. } else {
  13160. return PrevTagDecl;
  13161. }
  13162. }
  13163. // Diagnose attempts to redefine a tag.
  13164. if (TUK == TUK_Definition) {
  13165. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13166. // If we're defining a specialization and the previous definition
  13167. // is from an implicit instantiation, don't emit an error
  13168. // here; we'll catch this in the general case below.
  13169. bool IsExplicitSpecializationAfterInstantiation = false;
  13170. if (isMemberSpecialization) {
  13171. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13172. IsExplicitSpecializationAfterInstantiation =
  13173. RD->getTemplateSpecializationKind() !=
  13174. TSK_ExplicitSpecialization;
  13175. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13176. IsExplicitSpecializationAfterInstantiation =
  13177. ED->getTemplateSpecializationKind() !=
  13178. TSK_ExplicitSpecialization;
  13179. }
  13180. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13181. // not keep more that one definition around (merge them). However,
  13182. // ensure the decl passes the structural compatibility check in
  13183. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13184. NamedDecl *Hidden = nullptr;
  13185. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13186. // There is a definition of this tag, but it is not visible. We
  13187. // explicitly make use of C++'s one definition rule here, and
  13188. // assume that this definition is identical to the hidden one
  13189. // we already have. Make the existing definition visible and
  13190. // use it in place of this one.
  13191. if (!getLangOpts().CPlusPlus) {
  13192. // Postpone making the old definition visible until after we
  13193. // complete parsing the new one and do the structural
  13194. // comparison.
  13195. SkipBody->CheckSameAsPrevious = true;
  13196. SkipBody->New = createTagFromNewDecl();
  13197. SkipBody->Previous = Def;
  13198. return Def;
  13199. } else {
  13200. SkipBody->ShouldSkip = true;
  13201. SkipBody->Previous = Def;
  13202. makeMergedDefinitionVisible(Hidden);
  13203. // Carry on and handle it like a normal definition. We'll
  13204. // skip starting the definitiion later.
  13205. }
  13206. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13207. // A redeclaration in function prototype scope in C isn't
  13208. // visible elsewhere, so merely issue a warning.
  13209. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13210. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13211. else
  13212. Diag(NameLoc, diag::err_redefinition) << Name;
  13213. notePreviousDefinition(Def,
  13214. NameLoc.isValid() ? NameLoc : KWLoc);
  13215. // If this is a redefinition, recover by making this
  13216. // struct be anonymous, which will make any later
  13217. // references get the previous definition.
  13218. Name = nullptr;
  13219. Previous.clear();
  13220. Invalid = true;
  13221. }
  13222. } else {
  13223. // If the type is currently being defined, complain
  13224. // about a nested redefinition.
  13225. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13226. if (TD->isBeingDefined()) {
  13227. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13228. Diag(PrevTagDecl->getLocation(),
  13229. diag::note_previous_definition);
  13230. Name = nullptr;
  13231. Previous.clear();
  13232. Invalid = true;
  13233. }
  13234. }
  13235. // Okay, this is definition of a previously declared or referenced
  13236. // tag. We're going to create a new Decl for it.
  13237. }
  13238. // Okay, we're going to make a redeclaration. If this is some kind
  13239. // of reference, make sure we build the redeclaration in the same DC
  13240. // as the original, and ignore the current access specifier.
  13241. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13242. SearchDC = PrevTagDecl->getDeclContext();
  13243. AS = AS_none;
  13244. }
  13245. }
  13246. // If we get here we have (another) forward declaration or we
  13247. // have a definition. Just create a new decl.
  13248. } else {
  13249. // If we get here, this is a definition of a new tag type in a nested
  13250. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13251. // new decl/type. We set PrevDecl to NULL so that the entities
  13252. // have distinct types.
  13253. Previous.clear();
  13254. }
  13255. // If we get here, we're going to create a new Decl. If PrevDecl
  13256. // is non-NULL, it's a definition of the tag declared by
  13257. // PrevDecl. If it's NULL, we have a new definition.
  13258. // Otherwise, PrevDecl is not a tag, but was found with tag
  13259. // lookup. This is only actually possible in C++, where a few
  13260. // things like templates still live in the tag namespace.
  13261. } else {
  13262. // Use a better diagnostic if an elaborated-type-specifier
  13263. // found the wrong kind of type on the first
  13264. // (non-redeclaration) lookup.
  13265. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13266. !Previous.isForRedeclaration()) {
  13267. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13268. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13269. << Kind;
  13270. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13271. Invalid = true;
  13272. // Otherwise, only diagnose if the declaration is in scope.
  13273. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13274. SS.isNotEmpty() || isMemberSpecialization)) {
  13275. // do nothing
  13276. // Diagnose implicit declarations introduced by elaborated types.
  13277. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13278. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13279. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13280. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13281. Invalid = true;
  13282. // Otherwise it's a declaration. Call out a particularly common
  13283. // case here.
  13284. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13285. unsigned Kind = 0;
  13286. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13287. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13288. << Name << Kind << TND->getUnderlyingType();
  13289. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13290. Invalid = true;
  13291. // Otherwise, diagnose.
  13292. } else {
  13293. // The tag name clashes with something else in the target scope,
  13294. // issue an error and recover by making this tag be anonymous.
  13295. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13296. notePreviousDefinition(PrevDecl, NameLoc);
  13297. Name = nullptr;
  13298. Invalid = true;
  13299. }
  13300. // The existing declaration isn't relevant to us; we're in a
  13301. // new scope, so clear out the previous declaration.
  13302. Previous.clear();
  13303. }
  13304. }
  13305. CreateNewDecl:
  13306. TagDecl *PrevDecl = nullptr;
  13307. if (Previous.isSingleResult())
  13308. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13309. // If there is an identifier, use the location of the identifier as the
  13310. // location of the decl, otherwise use the location of the struct/union
  13311. // keyword.
  13312. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13313. // Otherwise, create a new declaration. If there is a previous
  13314. // declaration of the same entity, the two will be linked via
  13315. // PrevDecl.
  13316. TagDecl *New;
  13317. if (Kind == TTK_Enum) {
  13318. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13319. // enum X { A, B, C } D; D should chain to X.
  13320. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13321. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13322. ScopedEnumUsesClassTag, IsFixed);
  13323. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13324. StdAlignValT = cast<EnumDecl>(New);
  13325. // If this is an undefined enum, warn.
  13326. if (TUK != TUK_Definition && !Invalid) {
  13327. TagDecl *Def;
  13328. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13329. // C++0x: 7.2p2: opaque-enum-declaration.
  13330. // Conflicts are diagnosed above. Do nothing.
  13331. }
  13332. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13333. Diag(Loc, diag::ext_forward_ref_enum_def)
  13334. << New;
  13335. Diag(Def->getLocation(), diag::note_previous_definition);
  13336. } else {
  13337. unsigned DiagID = diag::ext_forward_ref_enum;
  13338. if (getLangOpts().MSVCCompat)
  13339. DiagID = diag::ext_ms_forward_ref_enum;
  13340. else if (getLangOpts().CPlusPlus)
  13341. DiagID = diag::err_forward_ref_enum;
  13342. Diag(Loc, DiagID);
  13343. }
  13344. }
  13345. if (EnumUnderlying) {
  13346. EnumDecl *ED = cast<EnumDecl>(New);
  13347. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13348. ED->setIntegerTypeSourceInfo(TI);
  13349. else
  13350. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13351. ED->setPromotionType(ED->getIntegerType());
  13352. assert(ED->isComplete() && "enum with type should be complete");
  13353. }
  13354. } else {
  13355. // struct/union/class
  13356. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13357. // struct X { int A; } D; D should chain to X.
  13358. if (getLangOpts().CPlusPlus) {
  13359. // FIXME: Look for a way to use RecordDecl for simple structs.
  13360. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13361. cast_or_null<CXXRecordDecl>(PrevDecl));
  13362. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13363. StdBadAlloc = cast<CXXRecordDecl>(New);
  13364. } else
  13365. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13366. cast_or_null<RecordDecl>(PrevDecl));
  13367. }
  13368. // C++11 [dcl.type]p3:
  13369. // A type-specifier-seq shall not define a class or enumeration [...].
  13370. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13371. TUK == TUK_Definition) {
  13372. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13373. << Context.getTagDeclType(New);
  13374. Invalid = true;
  13375. }
  13376. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13377. DC->getDeclKind() == Decl::Enum) {
  13378. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13379. << Context.getTagDeclType(New);
  13380. Invalid = true;
  13381. }
  13382. // Maybe add qualifier info.
  13383. if (SS.isNotEmpty()) {
  13384. if (SS.isSet()) {
  13385. // If this is either a declaration or a definition, check the
  13386. // nested-name-specifier against the current context.
  13387. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13388. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13389. isMemberSpecialization))
  13390. Invalid = true;
  13391. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13392. if (TemplateParameterLists.size() > 0) {
  13393. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13394. }
  13395. }
  13396. else
  13397. Invalid = true;
  13398. }
  13399. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13400. // Add alignment attributes if necessary; these attributes are checked when
  13401. // the ASTContext lays out the structure.
  13402. //
  13403. // It is important for implementing the correct semantics that this
  13404. // happen here (in ActOnTag). The #pragma pack stack is
  13405. // maintained as a result of parser callbacks which can occur at
  13406. // many points during the parsing of a struct declaration (because
  13407. // the #pragma tokens are effectively skipped over during the
  13408. // parsing of the struct).
  13409. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13410. AddAlignmentAttributesForRecord(RD);
  13411. AddMsStructLayoutForRecord(RD);
  13412. }
  13413. }
  13414. if (ModulePrivateLoc.isValid()) {
  13415. if (isMemberSpecialization)
  13416. Diag(New->getLocation(), diag::err_module_private_specialization)
  13417. << 2
  13418. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13419. // __module_private__ does not apply to local classes. However, we only
  13420. // diagnose this as an error when the declaration specifiers are
  13421. // freestanding. Here, we just ignore the __module_private__.
  13422. else if (!SearchDC->isFunctionOrMethod())
  13423. New->setModulePrivate();
  13424. }
  13425. // If this is a specialization of a member class (of a class template),
  13426. // check the specialization.
  13427. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13428. Invalid = true;
  13429. // If we're declaring or defining a tag in function prototype scope in C,
  13430. // note that this type can only be used within the function and add it to
  13431. // the list of decls to inject into the function definition scope.
  13432. if ((Name || Kind == TTK_Enum) &&
  13433. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13434. if (getLangOpts().CPlusPlus) {
  13435. // C++ [dcl.fct]p6:
  13436. // Types shall not be defined in return or parameter types.
  13437. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13438. Diag(Loc, diag::err_type_defined_in_param_type)
  13439. << Name;
  13440. Invalid = true;
  13441. }
  13442. } else if (!PrevDecl) {
  13443. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13444. }
  13445. }
  13446. if (Invalid)
  13447. New->setInvalidDecl();
  13448. // Set the lexical context. If the tag has a C++ scope specifier, the
  13449. // lexical context will be different from the semantic context.
  13450. New->setLexicalDeclContext(CurContext);
  13451. // Mark this as a friend decl if applicable.
  13452. // In Microsoft mode, a friend declaration also acts as a forward
  13453. // declaration so we always pass true to setObjectOfFriendDecl to make
  13454. // the tag name visible.
  13455. if (TUK == TUK_Friend)
  13456. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13457. // Set the access specifier.
  13458. if (!Invalid && SearchDC->isRecord())
  13459. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13460. if (PrevDecl)
  13461. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13462. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13463. New->startDefinition();
  13464. ProcessDeclAttributeList(S, New, Attrs);
  13465. AddPragmaAttributes(S, New);
  13466. // If this has an identifier, add it to the scope stack.
  13467. if (TUK == TUK_Friend) {
  13468. // We might be replacing an existing declaration in the lookup tables;
  13469. // if so, borrow its access specifier.
  13470. if (PrevDecl)
  13471. New->setAccess(PrevDecl->getAccess());
  13472. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13473. DC->makeDeclVisibleInContext(New);
  13474. if (Name) // can be null along some error paths
  13475. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13476. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13477. } else if (Name) {
  13478. S = getNonFieldDeclScope(S);
  13479. PushOnScopeChains(New, S, true);
  13480. } else {
  13481. CurContext->addDecl(New);
  13482. }
  13483. // If this is the C FILE type, notify the AST context.
  13484. if (IdentifierInfo *II = New->getIdentifier())
  13485. if (!New->isInvalidDecl() &&
  13486. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13487. II->isStr("FILE"))
  13488. Context.setFILEDecl(New);
  13489. if (PrevDecl)
  13490. mergeDeclAttributes(New, PrevDecl);
  13491. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  13492. inferGslOwnerPointerAttribute(CXXRD);
  13493. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13494. // record.
  13495. AddPushedVisibilityAttribute(New);
  13496. if (isMemberSpecialization && !New->isInvalidDecl())
  13497. CompleteMemberSpecialization(New, Previous);
  13498. OwnedDecl = true;
  13499. // In C++, don't return an invalid declaration. We can't recover well from
  13500. // the cases where we make the type anonymous.
  13501. if (Invalid && getLangOpts().CPlusPlus) {
  13502. if (New->isBeingDefined())
  13503. if (auto RD = dyn_cast<RecordDecl>(New))
  13504. RD->completeDefinition();
  13505. return nullptr;
  13506. } else if (SkipBody && SkipBody->ShouldSkip) {
  13507. return SkipBody->Previous;
  13508. } else {
  13509. return New;
  13510. }
  13511. }
  13512. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13513. AdjustDeclIfTemplate(TagD);
  13514. TagDecl *Tag = cast<TagDecl>(TagD);
  13515. // Enter the tag context.
  13516. PushDeclContext(S, Tag);
  13517. ActOnDocumentableDecl(TagD);
  13518. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13519. // record.
  13520. AddPushedVisibilityAttribute(Tag);
  13521. }
  13522. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13523. SkipBodyInfo &SkipBody) {
  13524. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13525. return false;
  13526. // Make the previous decl visible.
  13527. makeMergedDefinitionVisible(SkipBody.Previous);
  13528. return true;
  13529. }
  13530. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13531. assert(isa<ObjCContainerDecl>(IDecl) &&
  13532. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13533. DeclContext *OCD = cast<DeclContext>(IDecl);
  13534. assert(getContainingDC(OCD) == CurContext &&
  13535. "The next DeclContext should be lexically contained in the current one.");
  13536. CurContext = OCD;
  13537. return IDecl;
  13538. }
  13539. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13540. SourceLocation FinalLoc,
  13541. bool IsFinalSpelledSealed,
  13542. SourceLocation LBraceLoc) {
  13543. AdjustDeclIfTemplate(TagD);
  13544. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13545. FieldCollector->StartClass();
  13546. if (!Record->getIdentifier())
  13547. return;
  13548. if (FinalLoc.isValid())
  13549. Record->addAttr(new (Context)
  13550. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  13551. // C++ [class]p2:
  13552. // [...] The class-name is also inserted into the scope of the
  13553. // class itself; this is known as the injected-class-name. For
  13554. // purposes of access checking, the injected-class-name is treated
  13555. // as if it were a public member name.
  13556. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13557. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13558. Record->getLocation(), Record->getIdentifier(),
  13559. /*PrevDecl=*/nullptr,
  13560. /*DelayTypeCreation=*/true);
  13561. Context.getTypeDeclType(InjectedClassName, Record);
  13562. InjectedClassName->setImplicit();
  13563. InjectedClassName->setAccess(AS_public);
  13564. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13565. InjectedClassName->setDescribedClassTemplate(Template);
  13566. PushOnScopeChains(InjectedClassName, S);
  13567. assert(InjectedClassName->isInjectedClassName() &&
  13568. "Broken injected-class-name");
  13569. }
  13570. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13571. SourceRange BraceRange) {
  13572. AdjustDeclIfTemplate(TagD);
  13573. TagDecl *Tag = cast<TagDecl>(TagD);
  13574. Tag->setBraceRange(BraceRange);
  13575. // Make sure we "complete" the definition even it is invalid.
  13576. if (Tag->isBeingDefined()) {
  13577. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13578. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13579. RD->completeDefinition();
  13580. }
  13581. if (isa<CXXRecordDecl>(Tag)) {
  13582. FieldCollector->FinishClass();
  13583. }
  13584. // Exit this scope of this tag's definition.
  13585. PopDeclContext();
  13586. if (getCurLexicalContext()->isObjCContainer() &&
  13587. Tag->getDeclContext()->isFileContext())
  13588. Tag->setTopLevelDeclInObjCContainer();
  13589. // Notify the consumer that we've defined a tag.
  13590. if (!Tag->isInvalidDecl())
  13591. Consumer.HandleTagDeclDefinition(Tag);
  13592. }
  13593. void Sema::ActOnObjCContainerFinishDefinition() {
  13594. // Exit this scope of this interface definition.
  13595. PopDeclContext();
  13596. }
  13597. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13598. assert(DC == CurContext && "Mismatch of container contexts");
  13599. OriginalLexicalContext = DC;
  13600. ActOnObjCContainerFinishDefinition();
  13601. }
  13602. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13603. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13604. OriginalLexicalContext = nullptr;
  13605. }
  13606. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13607. AdjustDeclIfTemplate(TagD);
  13608. TagDecl *Tag = cast<TagDecl>(TagD);
  13609. Tag->setInvalidDecl();
  13610. // Make sure we "complete" the definition even it is invalid.
  13611. if (Tag->isBeingDefined()) {
  13612. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13613. RD->completeDefinition();
  13614. }
  13615. // We're undoing ActOnTagStartDefinition here, not
  13616. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13617. // the FieldCollector.
  13618. PopDeclContext();
  13619. }
  13620. // Note that FieldName may be null for anonymous bitfields.
  13621. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13622. IdentifierInfo *FieldName,
  13623. QualType FieldTy, bool IsMsStruct,
  13624. Expr *BitWidth, bool *ZeroWidth) {
  13625. // Default to true; that shouldn't confuse checks for emptiness
  13626. if (ZeroWidth)
  13627. *ZeroWidth = true;
  13628. // C99 6.7.2.1p4 - verify the field type.
  13629. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13630. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13631. // Handle incomplete types with specific error.
  13632. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13633. return ExprError();
  13634. if (FieldName)
  13635. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13636. << FieldName << FieldTy << BitWidth->getSourceRange();
  13637. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13638. << FieldTy << BitWidth->getSourceRange();
  13639. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13640. UPPC_BitFieldWidth))
  13641. return ExprError();
  13642. // If the bit-width is type- or value-dependent, don't try to check
  13643. // it now.
  13644. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13645. return BitWidth;
  13646. llvm::APSInt Value;
  13647. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13648. if (ICE.isInvalid())
  13649. return ICE;
  13650. BitWidth = ICE.get();
  13651. if (Value != 0 && ZeroWidth)
  13652. *ZeroWidth = false;
  13653. // Zero-width bitfield is ok for anonymous field.
  13654. if (Value == 0 && FieldName)
  13655. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13656. if (Value.isSigned() && Value.isNegative()) {
  13657. if (FieldName)
  13658. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13659. << FieldName << Value.toString(10);
  13660. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13661. << Value.toString(10);
  13662. }
  13663. if (!FieldTy->isDependentType()) {
  13664. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13665. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13666. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13667. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13668. // ABI.
  13669. bool CStdConstraintViolation =
  13670. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13671. bool MSBitfieldViolation =
  13672. Value.ugt(TypeStorageSize) &&
  13673. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13674. if (CStdConstraintViolation || MSBitfieldViolation) {
  13675. unsigned DiagWidth =
  13676. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13677. if (FieldName)
  13678. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13679. << FieldName << (unsigned)Value.getZExtValue()
  13680. << !CStdConstraintViolation << DiagWidth;
  13681. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13682. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13683. << DiagWidth;
  13684. }
  13685. // Warn on types where the user might conceivably expect to get all
  13686. // specified bits as value bits: that's all integral types other than
  13687. // 'bool'.
  13688. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13689. if (FieldName)
  13690. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13691. << FieldName << (unsigned)Value.getZExtValue()
  13692. << (unsigned)TypeWidth;
  13693. else
  13694. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13695. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13696. }
  13697. }
  13698. return BitWidth;
  13699. }
  13700. /// ActOnField - Each field of a C struct/union is passed into this in order
  13701. /// to create a FieldDecl object for it.
  13702. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13703. Declarator &D, Expr *BitfieldWidth) {
  13704. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13705. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13706. /*InitStyle=*/ICIS_NoInit, AS_public);
  13707. return Res;
  13708. }
  13709. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13710. ///
  13711. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13712. SourceLocation DeclStart,
  13713. Declarator &D, Expr *BitWidth,
  13714. InClassInitStyle InitStyle,
  13715. AccessSpecifier AS) {
  13716. if (D.isDecompositionDeclarator()) {
  13717. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13718. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13719. << Decomp.getSourceRange();
  13720. return nullptr;
  13721. }
  13722. IdentifierInfo *II = D.getIdentifier();
  13723. SourceLocation Loc = DeclStart;
  13724. if (II) Loc = D.getIdentifierLoc();
  13725. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13726. QualType T = TInfo->getType();
  13727. if (getLangOpts().CPlusPlus) {
  13728. CheckExtraCXXDefaultArguments(D);
  13729. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13730. UPPC_DataMemberType)) {
  13731. D.setInvalidType();
  13732. T = Context.IntTy;
  13733. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13734. }
  13735. }
  13736. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13737. if (D.getDeclSpec().isInlineSpecified())
  13738. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13739. << getLangOpts().CPlusPlus17;
  13740. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13741. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13742. diag::err_invalid_thread)
  13743. << DeclSpec::getSpecifierName(TSCS);
  13744. // Check to see if this name was declared as a member previously
  13745. NamedDecl *PrevDecl = nullptr;
  13746. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13747. ForVisibleRedeclaration);
  13748. LookupName(Previous, S);
  13749. switch (Previous.getResultKind()) {
  13750. case LookupResult::Found:
  13751. case LookupResult::FoundUnresolvedValue:
  13752. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13753. break;
  13754. case LookupResult::FoundOverloaded:
  13755. PrevDecl = Previous.getRepresentativeDecl();
  13756. break;
  13757. case LookupResult::NotFound:
  13758. case LookupResult::NotFoundInCurrentInstantiation:
  13759. case LookupResult::Ambiguous:
  13760. break;
  13761. }
  13762. Previous.suppressDiagnostics();
  13763. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13764. // Maybe we will complain about the shadowed template parameter.
  13765. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13766. // Just pretend that we didn't see the previous declaration.
  13767. PrevDecl = nullptr;
  13768. }
  13769. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13770. PrevDecl = nullptr;
  13771. bool Mutable
  13772. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13773. SourceLocation TSSL = D.getBeginLoc();
  13774. FieldDecl *NewFD
  13775. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13776. TSSL, AS, PrevDecl, &D);
  13777. if (NewFD->isInvalidDecl())
  13778. Record->setInvalidDecl();
  13779. if (D.getDeclSpec().isModulePrivateSpecified())
  13780. NewFD->setModulePrivate();
  13781. if (NewFD->isInvalidDecl() && PrevDecl) {
  13782. // Don't introduce NewFD into scope; there's already something
  13783. // with the same name in the same scope.
  13784. } else if (II) {
  13785. PushOnScopeChains(NewFD, S);
  13786. } else
  13787. Record->addDecl(NewFD);
  13788. return NewFD;
  13789. }
  13790. /// Build a new FieldDecl and check its well-formedness.
  13791. ///
  13792. /// This routine builds a new FieldDecl given the fields name, type,
  13793. /// record, etc. \p PrevDecl should refer to any previous declaration
  13794. /// with the same name and in the same scope as the field to be
  13795. /// created.
  13796. ///
  13797. /// \returns a new FieldDecl.
  13798. ///
  13799. /// \todo The Declarator argument is a hack. It will be removed once
  13800. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13801. TypeSourceInfo *TInfo,
  13802. RecordDecl *Record, SourceLocation Loc,
  13803. bool Mutable, Expr *BitWidth,
  13804. InClassInitStyle InitStyle,
  13805. SourceLocation TSSL,
  13806. AccessSpecifier AS, NamedDecl *PrevDecl,
  13807. Declarator *D) {
  13808. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13809. bool InvalidDecl = false;
  13810. if (D) InvalidDecl = D->isInvalidType();
  13811. // If we receive a broken type, recover by assuming 'int' and
  13812. // marking this declaration as invalid.
  13813. if (T.isNull()) {
  13814. InvalidDecl = true;
  13815. T = Context.IntTy;
  13816. }
  13817. QualType EltTy = Context.getBaseElementType(T);
  13818. if (!EltTy->isDependentType()) {
  13819. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13820. // Fields of incomplete type force their record to be invalid.
  13821. Record->setInvalidDecl();
  13822. InvalidDecl = true;
  13823. } else {
  13824. NamedDecl *Def;
  13825. EltTy->isIncompleteType(&Def);
  13826. if (Def && Def->isInvalidDecl()) {
  13827. Record->setInvalidDecl();
  13828. InvalidDecl = true;
  13829. }
  13830. }
  13831. }
  13832. // TR 18037 does not allow fields to be declared with address space
  13833. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  13834. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13835. Diag(Loc, diag::err_field_with_address_space);
  13836. Record->setInvalidDecl();
  13837. InvalidDecl = true;
  13838. }
  13839. if (LangOpts.OpenCL) {
  13840. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13841. // used as structure or union field: image, sampler, event or block types.
  13842. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  13843. T->isBlockPointerType()) {
  13844. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13845. Record->setInvalidDecl();
  13846. InvalidDecl = true;
  13847. }
  13848. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13849. if (BitWidth) {
  13850. Diag(Loc, diag::err_opencl_bitfields);
  13851. InvalidDecl = true;
  13852. }
  13853. }
  13854. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13855. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13856. T.hasQualifiers()) {
  13857. InvalidDecl = true;
  13858. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13859. }
  13860. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13861. // than a variably modified type.
  13862. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13863. bool SizeIsNegative;
  13864. llvm::APSInt Oversized;
  13865. TypeSourceInfo *FixedTInfo =
  13866. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13867. SizeIsNegative,
  13868. Oversized);
  13869. if (FixedTInfo) {
  13870. Diag(Loc, diag::warn_illegal_constant_array_size);
  13871. TInfo = FixedTInfo;
  13872. T = FixedTInfo->getType();
  13873. } else {
  13874. if (SizeIsNegative)
  13875. Diag(Loc, diag::err_typecheck_negative_array_size);
  13876. else if (Oversized.getBoolValue())
  13877. Diag(Loc, diag::err_array_too_large)
  13878. << Oversized.toString(10);
  13879. else
  13880. Diag(Loc, diag::err_typecheck_field_variable_size);
  13881. InvalidDecl = true;
  13882. }
  13883. }
  13884. // Fields can not have abstract class types
  13885. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  13886. diag::err_abstract_type_in_decl,
  13887. AbstractFieldType))
  13888. InvalidDecl = true;
  13889. bool ZeroWidth = false;
  13890. if (InvalidDecl)
  13891. BitWidth = nullptr;
  13892. // If this is declared as a bit-field, check the bit-field.
  13893. if (BitWidth) {
  13894. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  13895. &ZeroWidth).get();
  13896. if (!BitWidth) {
  13897. InvalidDecl = true;
  13898. BitWidth = nullptr;
  13899. ZeroWidth = false;
  13900. }
  13901. }
  13902. // Check that 'mutable' is consistent with the type of the declaration.
  13903. if (!InvalidDecl && Mutable) {
  13904. unsigned DiagID = 0;
  13905. if (T->isReferenceType())
  13906. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  13907. : diag::err_mutable_reference;
  13908. else if (T.isConstQualified())
  13909. DiagID = diag::err_mutable_const;
  13910. if (DiagID) {
  13911. SourceLocation ErrLoc = Loc;
  13912. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  13913. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  13914. Diag(ErrLoc, DiagID);
  13915. if (DiagID != diag::ext_mutable_reference) {
  13916. Mutable = false;
  13917. InvalidDecl = true;
  13918. }
  13919. }
  13920. }
  13921. // C++11 [class.union]p8 (DR1460):
  13922. // At most one variant member of a union may have a
  13923. // brace-or-equal-initializer.
  13924. if (InitStyle != ICIS_NoInit)
  13925. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  13926. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  13927. BitWidth, Mutable, InitStyle);
  13928. if (InvalidDecl)
  13929. NewFD->setInvalidDecl();
  13930. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  13931. Diag(Loc, diag::err_duplicate_member) << II;
  13932. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13933. NewFD->setInvalidDecl();
  13934. }
  13935. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  13936. if (Record->isUnion()) {
  13937. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13938. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13939. if (RDecl->getDefinition()) {
  13940. // C++ [class.union]p1: An object of a class with a non-trivial
  13941. // constructor, a non-trivial copy constructor, a non-trivial
  13942. // destructor, or a non-trivial copy assignment operator
  13943. // cannot be a member of a union, nor can an array of such
  13944. // objects.
  13945. if (CheckNontrivialField(NewFD))
  13946. NewFD->setInvalidDecl();
  13947. }
  13948. }
  13949. // C++ [class.union]p1: If a union contains a member of reference type,
  13950. // the program is ill-formed, except when compiling with MSVC extensions
  13951. // enabled.
  13952. if (EltTy->isReferenceType()) {
  13953. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13954. diag::ext_union_member_of_reference_type :
  13955. diag::err_union_member_of_reference_type)
  13956. << NewFD->getDeclName() << EltTy;
  13957. if (!getLangOpts().MicrosoftExt)
  13958. NewFD->setInvalidDecl();
  13959. }
  13960. }
  13961. }
  13962. // FIXME: We need to pass in the attributes given an AST
  13963. // representation, not a parser representation.
  13964. if (D) {
  13965. // FIXME: The current scope is almost... but not entirely... correct here.
  13966. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13967. if (NewFD->hasAttrs())
  13968. CheckAlignasUnderalignment(NewFD);
  13969. }
  13970. // In auto-retain/release, infer strong retension for fields of
  13971. // retainable type.
  13972. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13973. NewFD->setInvalidDecl();
  13974. if (T.isObjCGCWeak())
  13975. Diag(Loc, diag::warn_attribute_weak_on_field);
  13976. NewFD->setAccess(AS);
  13977. return NewFD;
  13978. }
  13979. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13980. assert(FD);
  13981. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13982. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13983. return false;
  13984. QualType EltTy = Context.getBaseElementType(FD->getType());
  13985. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13986. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13987. if (RDecl->getDefinition()) {
  13988. // We check for copy constructors before constructors
  13989. // because otherwise we'll never get complaints about
  13990. // copy constructors.
  13991. CXXSpecialMember member = CXXInvalid;
  13992. // We're required to check for any non-trivial constructors. Since the
  13993. // implicit default constructor is suppressed if there are any
  13994. // user-declared constructors, we just need to check that there is a
  13995. // trivial default constructor and a trivial copy constructor. (We don't
  13996. // worry about move constructors here, since this is a C++98 check.)
  13997. if (RDecl->hasNonTrivialCopyConstructor())
  13998. member = CXXCopyConstructor;
  13999. else if (!RDecl->hasTrivialDefaultConstructor())
  14000. member = CXXDefaultConstructor;
  14001. else if (RDecl->hasNonTrivialCopyAssignment())
  14002. member = CXXCopyAssignment;
  14003. else if (RDecl->hasNonTrivialDestructor())
  14004. member = CXXDestructor;
  14005. if (member != CXXInvalid) {
  14006. if (!getLangOpts().CPlusPlus11 &&
  14007. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14008. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14009. // a union. However, system headers in Objective-C programs
  14010. // occasionally have Objective-C lifetime objects within unions,
  14011. // and rather than cause the program to fail, we make those
  14012. // members unavailable.
  14013. SourceLocation Loc = FD->getLocation();
  14014. if (getSourceManager().isInSystemHeader(Loc)) {
  14015. if (!FD->hasAttr<UnavailableAttr>())
  14016. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14017. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14018. return false;
  14019. }
  14020. }
  14021. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14022. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14023. diag::err_illegal_union_or_anon_struct_member)
  14024. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14025. DiagnoseNontrivial(RDecl, member);
  14026. return !getLangOpts().CPlusPlus11;
  14027. }
  14028. }
  14029. }
  14030. return false;
  14031. }
  14032. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14033. /// AST enum value.
  14034. static ObjCIvarDecl::AccessControl
  14035. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14036. switch (ivarVisibility) {
  14037. default: llvm_unreachable("Unknown visitibility kind");
  14038. case tok::objc_private: return ObjCIvarDecl::Private;
  14039. case tok::objc_public: return ObjCIvarDecl::Public;
  14040. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14041. case tok::objc_package: return ObjCIvarDecl::Package;
  14042. }
  14043. }
  14044. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14045. /// in order to create an IvarDecl object for it.
  14046. Decl *Sema::ActOnIvar(Scope *S,
  14047. SourceLocation DeclStart,
  14048. Declarator &D, Expr *BitfieldWidth,
  14049. tok::ObjCKeywordKind Visibility) {
  14050. IdentifierInfo *II = D.getIdentifier();
  14051. Expr *BitWidth = (Expr*)BitfieldWidth;
  14052. SourceLocation Loc = DeclStart;
  14053. if (II) Loc = D.getIdentifierLoc();
  14054. // FIXME: Unnamed fields can be handled in various different ways, for
  14055. // example, unnamed unions inject all members into the struct namespace!
  14056. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14057. QualType T = TInfo->getType();
  14058. if (BitWidth) {
  14059. // 6.7.2.1p3, 6.7.2.1p4
  14060. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14061. if (!BitWidth)
  14062. D.setInvalidType();
  14063. } else {
  14064. // Not a bitfield.
  14065. // validate II.
  14066. }
  14067. if (T->isReferenceType()) {
  14068. Diag(Loc, diag::err_ivar_reference_type);
  14069. D.setInvalidType();
  14070. }
  14071. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14072. // than a variably modified type.
  14073. else if (T->isVariablyModifiedType()) {
  14074. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14075. D.setInvalidType();
  14076. }
  14077. // Get the visibility (access control) for this ivar.
  14078. ObjCIvarDecl::AccessControl ac =
  14079. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14080. : ObjCIvarDecl::None;
  14081. // Must set ivar's DeclContext to its enclosing interface.
  14082. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14083. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14084. return nullptr;
  14085. ObjCContainerDecl *EnclosingContext;
  14086. if (ObjCImplementationDecl *IMPDecl =
  14087. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14088. if (LangOpts.ObjCRuntime.isFragile()) {
  14089. // Case of ivar declared in an implementation. Context is that of its class.
  14090. EnclosingContext = IMPDecl->getClassInterface();
  14091. assert(EnclosingContext && "Implementation has no class interface!");
  14092. }
  14093. else
  14094. EnclosingContext = EnclosingDecl;
  14095. } else {
  14096. if (ObjCCategoryDecl *CDecl =
  14097. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14098. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14099. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14100. return nullptr;
  14101. }
  14102. }
  14103. EnclosingContext = EnclosingDecl;
  14104. }
  14105. // Construct the decl.
  14106. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14107. DeclStart, Loc, II, T,
  14108. TInfo, ac, (Expr *)BitfieldWidth);
  14109. if (II) {
  14110. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14111. ForVisibleRedeclaration);
  14112. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14113. && !isa<TagDecl>(PrevDecl)) {
  14114. Diag(Loc, diag::err_duplicate_member) << II;
  14115. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14116. NewID->setInvalidDecl();
  14117. }
  14118. }
  14119. // Process attributes attached to the ivar.
  14120. ProcessDeclAttributes(S, NewID, D);
  14121. if (D.isInvalidType())
  14122. NewID->setInvalidDecl();
  14123. // In ARC, infer 'retaining' for ivars of retainable type.
  14124. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14125. NewID->setInvalidDecl();
  14126. if (D.getDeclSpec().isModulePrivateSpecified())
  14127. NewID->setModulePrivate();
  14128. if (II) {
  14129. // FIXME: When interfaces are DeclContexts, we'll need to add
  14130. // these to the interface.
  14131. S->AddDecl(NewID);
  14132. IdResolver.AddDecl(NewID);
  14133. }
  14134. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14135. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14136. Diag(Loc, diag::warn_ivars_in_interface);
  14137. return NewID;
  14138. }
  14139. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14140. /// class and class extensions. For every class \@interface and class
  14141. /// extension \@interface, if the last ivar is a bitfield of any type,
  14142. /// then add an implicit `char :0` ivar to the end of that interface.
  14143. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14144. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14145. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14146. return;
  14147. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14148. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14149. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14150. return;
  14151. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14152. if (!ID) {
  14153. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14154. if (!CD->IsClassExtension())
  14155. return;
  14156. }
  14157. // No need to add this to end of @implementation.
  14158. else
  14159. return;
  14160. }
  14161. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14162. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14163. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14164. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14165. DeclLoc, DeclLoc, nullptr,
  14166. Context.CharTy,
  14167. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14168. DeclLoc),
  14169. ObjCIvarDecl::Private, BW,
  14170. true);
  14171. AllIvarDecls.push_back(Ivar);
  14172. }
  14173. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14174. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14175. SourceLocation RBrac,
  14176. const ParsedAttributesView &Attrs) {
  14177. assert(EnclosingDecl && "missing record or interface decl");
  14178. // If this is an Objective-C @implementation or category and we have
  14179. // new fields here we should reset the layout of the interface since
  14180. // it will now change.
  14181. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14182. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14183. switch (DC->getKind()) {
  14184. default: break;
  14185. case Decl::ObjCCategory:
  14186. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14187. break;
  14188. case Decl::ObjCImplementation:
  14189. Context.
  14190. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14191. break;
  14192. }
  14193. }
  14194. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14195. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14196. // Start counting up the number of named members; make sure to include
  14197. // members of anonymous structs and unions in the total.
  14198. unsigned NumNamedMembers = 0;
  14199. if (Record) {
  14200. for (const auto *I : Record->decls()) {
  14201. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14202. if (IFD->getDeclName())
  14203. ++NumNamedMembers;
  14204. }
  14205. }
  14206. // Verify that all the fields are okay.
  14207. SmallVector<FieldDecl*, 32> RecFields;
  14208. bool ObjCFieldLifetimeErrReported = false;
  14209. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14210. i != end; ++i) {
  14211. FieldDecl *FD = cast<FieldDecl>(*i);
  14212. // Get the type for the field.
  14213. const Type *FDTy = FD->getType().getTypePtr();
  14214. if (!FD->isAnonymousStructOrUnion()) {
  14215. // Remember all fields written by the user.
  14216. RecFields.push_back(FD);
  14217. }
  14218. // If the field is already invalid for some reason, don't emit more
  14219. // diagnostics about it.
  14220. if (FD->isInvalidDecl()) {
  14221. EnclosingDecl->setInvalidDecl();
  14222. continue;
  14223. }
  14224. // C99 6.7.2.1p2:
  14225. // A structure or union shall not contain a member with
  14226. // incomplete or function type (hence, a structure shall not
  14227. // contain an instance of itself, but may contain a pointer to
  14228. // an instance of itself), except that the last member of a
  14229. // structure with more than one named member may have incomplete
  14230. // array type; such a structure (and any union containing,
  14231. // possibly recursively, a member that is such a structure)
  14232. // shall not be a member of a structure or an element of an
  14233. // array.
  14234. bool IsLastField = (i + 1 == Fields.end());
  14235. if (FDTy->isFunctionType()) {
  14236. // Field declared as a function.
  14237. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14238. << FD->getDeclName();
  14239. FD->setInvalidDecl();
  14240. EnclosingDecl->setInvalidDecl();
  14241. continue;
  14242. } else if (FDTy->isIncompleteArrayType() &&
  14243. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14244. if (Record) {
  14245. // Flexible array member.
  14246. // Microsoft and g++ is more permissive regarding flexible array.
  14247. // It will accept flexible array in union and also
  14248. // as the sole element of a struct/class.
  14249. unsigned DiagID = 0;
  14250. if (!Record->isUnion() && !IsLastField) {
  14251. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14252. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14253. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14254. FD->setInvalidDecl();
  14255. EnclosingDecl->setInvalidDecl();
  14256. continue;
  14257. } else if (Record->isUnion())
  14258. DiagID = getLangOpts().MicrosoftExt
  14259. ? diag::ext_flexible_array_union_ms
  14260. : getLangOpts().CPlusPlus
  14261. ? diag::ext_flexible_array_union_gnu
  14262. : diag::err_flexible_array_union;
  14263. else if (NumNamedMembers < 1)
  14264. DiagID = getLangOpts().MicrosoftExt
  14265. ? diag::ext_flexible_array_empty_aggregate_ms
  14266. : getLangOpts().CPlusPlus
  14267. ? diag::ext_flexible_array_empty_aggregate_gnu
  14268. : diag::err_flexible_array_empty_aggregate;
  14269. if (DiagID)
  14270. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14271. << Record->getTagKind();
  14272. // While the layout of types that contain virtual bases is not specified
  14273. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14274. // virtual bases after the derived members. This would make a flexible
  14275. // array member declared at the end of an object not adjacent to the end
  14276. // of the type.
  14277. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14278. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14279. << FD->getDeclName() << Record->getTagKind();
  14280. if (!getLangOpts().C99)
  14281. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14282. << FD->getDeclName() << Record->getTagKind();
  14283. // If the element type has a non-trivial destructor, we would not
  14284. // implicitly destroy the elements, so disallow it for now.
  14285. //
  14286. // FIXME: GCC allows this. We should probably either implicitly delete
  14287. // the destructor of the containing class, or just allow this.
  14288. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14289. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14290. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14291. << FD->getDeclName() << FD->getType();
  14292. FD->setInvalidDecl();
  14293. EnclosingDecl->setInvalidDecl();
  14294. continue;
  14295. }
  14296. // Okay, we have a legal flexible array member at the end of the struct.
  14297. Record->setHasFlexibleArrayMember(true);
  14298. } else {
  14299. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14300. // unless they are followed by another ivar. That check is done
  14301. // elsewhere, after synthesized ivars are known.
  14302. }
  14303. } else if (!FDTy->isDependentType() &&
  14304. RequireCompleteType(FD->getLocation(), FD->getType(),
  14305. diag::err_field_incomplete)) {
  14306. // Incomplete type
  14307. FD->setInvalidDecl();
  14308. EnclosingDecl->setInvalidDecl();
  14309. continue;
  14310. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14311. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14312. // A type which contains a flexible array member is considered to be a
  14313. // flexible array member.
  14314. Record->setHasFlexibleArrayMember(true);
  14315. if (!Record->isUnion()) {
  14316. // If this is a struct/class and this is not the last element, reject
  14317. // it. Note that GCC supports variable sized arrays in the middle of
  14318. // structures.
  14319. if (!IsLastField)
  14320. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14321. << FD->getDeclName() << FD->getType();
  14322. else {
  14323. // We support flexible arrays at the end of structs in
  14324. // other structs as an extension.
  14325. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14326. << FD->getDeclName();
  14327. }
  14328. }
  14329. }
  14330. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14331. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14332. diag::err_abstract_type_in_decl,
  14333. AbstractIvarType)) {
  14334. // Ivars can not have abstract class types
  14335. FD->setInvalidDecl();
  14336. }
  14337. if (Record && FDTTy->getDecl()->hasObjectMember())
  14338. Record->setHasObjectMember(true);
  14339. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14340. Record->setHasVolatileMember(true);
  14341. if (Record && Record->isUnion() &&
  14342. FD->getType().isNonTrivialPrimitiveCType(Context))
  14343. Diag(FD->getLocation(),
  14344. diag::err_nontrivial_primitive_type_in_union);
  14345. } else if (FDTy->isObjCObjectType()) {
  14346. /// A field cannot be an Objective-c object
  14347. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14348. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14349. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14350. FD->setType(T);
  14351. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  14352. Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
  14353. !getLangOpts().CPlusPlus) {
  14354. // It's an error in ARC or Weak if a field has lifetime.
  14355. // We don't want to report this in a system header, though,
  14356. // so we just make the field unavailable.
  14357. // FIXME: that's really not sufficient; we need to make the type
  14358. // itself invalid to, say, initialize or copy.
  14359. QualType T = FD->getType();
  14360. if (T.hasNonTrivialObjCLifetime()) {
  14361. SourceLocation loc = FD->getLocation();
  14362. if (getSourceManager().isInSystemHeader(loc)) {
  14363. if (!FD->hasAttr<UnavailableAttr>()) {
  14364. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14365. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  14366. }
  14367. } else {
  14368. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  14369. << T->isBlockPointerType() << Record->getTagKind();
  14370. }
  14371. ObjCFieldLifetimeErrReported = true;
  14372. }
  14373. } else if (getLangOpts().ObjC &&
  14374. getLangOpts().getGC() != LangOptions::NonGC &&
  14375. Record && !Record->hasObjectMember()) {
  14376. if (FD->getType()->isObjCObjectPointerType() ||
  14377. FD->getType().isObjCGCStrong())
  14378. Record->setHasObjectMember(true);
  14379. else if (Context.getAsArrayType(FD->getType())) {
  14380. QualType BaseType = Context.getBaseElementType(FD->getType());
  14381. if (BaseType->isRecordType() &&
  14382. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  14383. Record->setHasObjectMember(true);
  14384. else if (BaseType->isObjCObjectPointerType() ||
  14385. BaseType.isObjCGCStrong())
  14386. Record->setHasObjectMember(true);
  14387. }
  14388. }
  14389. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  14390. QualType FT = FD->getType();
  14391. if (FT.isNonTrivialToPrimitiveDefaultInitialize())
  14392. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14393. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14394. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
  14395. Record->setNonTrivialToPrimitiveCopy(true);
  14396. if (FT.isDestructedType()) {
  14397. Record->setNonTrivialToPrimitiveDestroy(true);
  14398. Record->setParamDestroyedInCallee(true);
  14399. }
  14400. if (const auto *RT = FT->getAs<RecordType>()) {
  14401. if (RT->getDecl()->getArgPassingRestrictions() ==
  14402. RecordDecl::APK_CanNeverPassInRegs)
  14403. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14404. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14405. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14406. }
  14407. if (Record && FD->getType().isVolatileQualified())
  14408. Record->setHasVolatileMember(true);
  14409. // Keep track of the number of named members.
  14410. if (FD->getIdentifier())
  14411. ++NumNamedMembers;
  14412. }
  14413. // Okay, we successfully defined 'Record'.
  14414. if (Record) {
  14415. bool Completed = false;
  14416. if (CXXRecord) {
  14417. if (!CXXRecord->isInvalidDecl()) {
  14418. // Set access bits correctly on the directly-declared conversions.
  14419. for (CXXRecordDecl::conversion_iterator
  14420. I = CXXRecord->conversion_begin(),
  14421. E = CXXRecord->conversion_end(); I != E; ++I)
  14422. I.setAccess((*I)->getAccess());
  14423. }
  14424. if (!CXXRecord->isDependentType()) {
  14425. // Add any implicitly-declared members to this class.
  14426. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14427. if (!CXXRecord->isInvalidDecl()) {
  14428. // If we have virtual base classes, we may end up finding multiple
  14429. // final overriders for a given virtual function. Check for this
  14430. // problem now.
  14431. if (CXXRecord->getNumVBases()) {
  14432. CXXFinalOverriderMap FinalOverriders;
  14433. CXXRecord->getFinalOverriders(FinalOverriders);
  14434. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14435. MEnd = FinalOverriders.end();
  14436. M != MEnd; ++M) {
  14437. for (OverridingMethods::iterator SO = M->second.begin(),
  14438. SOEnd = M->second.end();
  14439. SO != SOEnd; ++SO) {
  14440. assert(SO->second.size() > 0 &&
  14441. "Virtual function without overriding functions?");
  14442. if (SO->second.size() == 1)
  14443. continue;
  14444. // C++ [class.virtual]p2:
  14445. // In a derived class, if a virtual member function of a base
  14446. // class subobject has more than one final overrider the
  14447. // program is ill-formed.
  14448. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14449. << (const NamedDecl *)M->first << Record;
  14450. Diag(M->first->getLocation(),
  14451. diag::note_overridden_virtual_function);
  14452. for (OverridingMethods::overriding_iterator
  14453. OM = SO->second.begin(),
  14454. OMEnd = SO->second.end();
  14455. OM != OMEnd; ++OM)
  14456. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14457. << (const NamedDecl *)M->first << OM->Method->getParent();
  14458. Record->setInvalidDecl();
  14459. }
  14460. }
  14461. CXXRecord->completeDefinition(&FinalOverriders);
  14462. Completed = true;
  14463. }
  14464. }
  14465. }
  14466. }
  14467. if (!Completed)
  14468. Record->completeDefinition();
  14469. // Handle attributes before checking the layout.
  14470. ProcessDeclAttributeList(S, Record, Attrs);
  14471. // We may have deferred checking for a deleted destructor. Check now.
  14472. if (CXXRecord) {
  14473. auto *Dtor = CXXRecord->getDestructor();
  14474. if (Dtor && Dtor->isImplicit() &&
  14475. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14476. CXXRecord->setImplicitDestructorIsDeleted();
  14477. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14478. }
  14479. }
  14480. if (Record->hasAttrs()) {
  14481. CheckAlignasUnderalignment(Record);
  14482. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14483. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14484. IA->getRange(), IA->getBestCase(),
  14485. IA->getSemanticSpelling());
  14486. }
  14487. // Check if the structure/union declaration is a type that can have zero
  14488. // size in C. For C this is a language extension, for C++ it may cause
  14489. // compatibility problems.
  14490. bool CheckForZeroSize;
  14491. if (!getLangOpts().CPlusPlus) {
  14492. CheckForZeroSize = true;
  14493. } else {
  14494. // For C++ filter out types that cannot be referenced in C code.
  14495. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14496. CheckForZeroSize =
  14497. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14498. !CXXRecord->isDependentType() &&
  14499. CXXRecord->isCLike();
  14500. }
  14501. if (CheckForZeroSize) {
  14502. bool ZeroSize = true;
  14503. bool IsEmpty = true;
  14504. unsigned NonBitFields = 0;
  14505. for (RecordDecl::field_iterator I = Record->field_begin(),
  14506. E = Record->field_end();
  14507. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14508. IsEmpty = false;
  14509. if (I->isUnnamedBitfield()) {
  14510. if (!I->isZeroLengthBitField(Context))
  14511. ZeroSize = false;
  14512. } else {
  14513. ++NonBitFields;
  14514. QualType FieldType = I->getType();
  14515. if (FieldType->isIncompleteType() ||
  14516. !Context.getTypeSizeInChars(FieldType).isZero())
  14517. ZeroSize = false;
  14518. }
  14519. }
  14520. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14521. // allowed in C++, but warn if its declaration is inside
  14522. // extern "C" block.
  14523. if (ZeroSize) {
  14524. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14525. diag::warn_zero_size_struct_union_in_extern_c :
  14526. diag::warn_zero_size_struct_union_compat)
  14527. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14528. }
  14529. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14530. // but are accepted by GCC.
  14531. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14532. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14533. diag::ext_no_named_members_in_struct_union)
  14534. << Record->isUnion();
  14535. }
  14536. }
  14537. } else {
  14538. ObjCIvarDecl **ClsFields =
  14539. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14540. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14541. ID->setEndOfDefinitionLoc(RBrac);
  14542. // Add ivar's to class's DeclContext.
  14543. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14544. ClsFields[i]->setLexicalDeclContext(ID);
  14545. ID->addDecl(ClsFields[i]);
  14546. }
  14547. // Must enforce the rule that ivars in the base classes may not be
  14548. // duplicates.
  14549. if (ID->getSuperClass())
  14550. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14551. } else if (ObjCImplementationDecl *IMPDecl =
  14552. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14553. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14554. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14555. // Ivar declared in @implementation never belongs to the implementation.
  14556. // Only it is in implementation's lexical context.
  14557. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14558. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14559. IMPDecl->setIvarLBraceLoc(LBrac);
  14560. IMPDecl->setIvarRBraceLoc(RBrac);
  14561. } else if (ObjCCategoryDecl *CDecl =
  14562. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14563. // case of ivars in class extension; all other cases have been
  14564. // reported as errors elsewhere.
  14565. // FIXME. Class extension does not have a LocEnd field.
  14566. // CDecl->setLocEnd(RBrac);
  14567. // Add ivar's to class extension's DeclContext.
  14568. // Diagnose redeclaration of private ivars.
  14569. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14570. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14571. if (IDecl) {
  14572. if (const ObjCIvarDecl *ClsIvar =
  14573. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14574. Diag(ClsFields[i]->getLocation(),
  14575. diag::err_duplicate_ivar_declaration);
  14576. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14577. continue;
  14578. }
  14579. for (const auto *Ext : IDecl->known_extensions()) {
  14580. if (const ObjCIvarDecl *ClsExtIvar
  14581. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14582. Diag(ClsFields[i]->getLocation(),
  14583. diag::err_duplicate_ivar_declaration);
  14584. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14585. continue;
  14586. }
  14587. }
  14588. }
  14589. ClsFields[i]->setLexicalDeclContext(CDecl);
  14590. CDecl->addDecl(ClsFields[i]);
  14591. }
  14592. CDecl->setIvarLBraceLoc(LBrac);
  14593. CDecl->setIvarRBraceLoc(RBrac);
  14594. }
  14595. }
  14596. }
  14597. /// Determine whether the given integral value is representable within
  14598. /// the given type T.
  14599. static bool isRepresentableIntegerValue(ASTContext &Context,
  14600. llvm::APSInt &Value,
  14601. QualType T) {
  14602. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14603. "Integral type required!");
  14604. unsigned BitWidth = Context.getIntWidth(T);
  14605. if (Value.isUnsigned() || Value.isNonNegative()) {
  14606. if (T->isSignedIntegerOrEnumerationType())
  14607. --BitWidth;
  14608. return Value.getActiveBits() <= BitWidth;
  14609. }
  14610. return Value.getMinSignedBits() <= BitWidth;
  14611. }
  14612. // Given an integral type, return the next larger integral type
  14613. // (or a NULL type of no such type exists).
  14614. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14615. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14616. // enum checking below.
  14617. assert((T->isIntegralType(Context) ||
  14618. T->isEnumeralType()) && "Integral type required!");
  14619. const unsigned NumTypes = 4;
  14620. QualType SignedIntegralTypes[NumTypes] = {
  14621. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14622. };
  14623. QualType UnsignedIntegralTypes[NumTypes] = {
  14624. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14625. Context.UnsignedLongLongTy
  14626. };
  14627. unsigned BitWidth = Context.getTypeSize(T);
  14628. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14629. : UnsignedIntegralTypes;
  14630. for (unsigned I = 0; I != NumTypes; ++I)
  14631. if (Context.getTypeSize(Types[I]) > BitWidth)
  14632. return Types[I];
  14633. return QualType();
  14634. }
  14635. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14636. EnumConstantDecl *LastEnumConst,
  14637. SourceLocation IdLoc,
  14638. IdentifierInfo *Id,
  14639. Expr *Val) {
  14640. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14641. llvm::APSInt EnumVal(IntWidth);
  14642. QualType EltTy;
  14643. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14644. Val = nullptr;
  14645. if (Val)
  14646. Val = DefaultLvalueConversion(Val).get();
  14647. if (Val) {
  14648. if (Enum->isDependentType() || Val->isTypeDependent())
  14649. EltTy = Context.DependentTy;
  14650. else {
  14651. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  14652. !getLangOpts().MSVCCompat) {
  14653. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14654. // constant-expression in the enumerator-definition shall be a converted
  14655. // constant expression of the underlying type.
  14656. EltTy = Enum->getIntegerType();
  14657. ExprResult Converted =
  14658. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14659. CCEK_Enumerator);
  14660. if (Converted.isInvalid())
  14661. Val = nullptr;
  14662. else
  14663. Val = Converted.get();
  14664. } else if (!Val->isValueDependent() &&
  14665. !(Val = VerifyIntegerConstantExpression(Val,
  14666. &EnumVal).get())) {
  14667. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14668. } else {
  14669. if (Enum->isComplete()) {
  14670. EltTy = Enum->getIntegerType();
  14671. // In Obj-C and Microsoft mode, require the enumeration value to be
  14672. // representable in the underlying type of the enumeration. In C++11,
  14673. // we perform a non-narrowing conversion as part of converted constant
  14674. // expression checking.
  14675. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14676. if (getLangOpts().MSVCCompat) {
  14677. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14678. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14679. } else
  14680. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14681. } else
  14682. Val = ImpCastExprToType(Val, EltTy,
  14683. EltTy->isBooleanType() ?
  14684. CK_IntegralToBoolean : CK_IntegralCast)
  14685. .get();
  14686. } else if (getLangOpts().CPlusPlus) {
  14687. // C++11 [dcl.enum]p5:
  14688. // If the underlying type is not fixed, the type of each enumerator
  14689. // is the type of its initializing value:
  14690. // - If an initializer is specified for an enumerator, the
  14691. // initializing value has the same type as the expression.
  14692. EltTy = Val->getType();
  14693. } else {
  14694. // C99 6.7.2.2p2:
  14695. // The expression that defines the value of an enumeration constant
  14696. // shall be an integer constant expression that has a value
  14697. // representable as an int.
  14698. // Complain if the value is not representable in an int.
  14699. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14700. Diag(IdLoc, diag::ext_enum_value_not_int)
  14701. << EnumVal.toString(10) << Val->getSourceRange()
  14702. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14703. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14704. // Force the type of the expression to 'int'.
  14705. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14706. }
  14707. EltTy = Val->getType();
  14708. }
  14709. }
  14710. }
  14711. }
  14712. if (!Val) {
  14713. if (Enum->isDependentType())
  14714. EltTy = Context.DependentTy;
  14715. else if (!LastEnumConst) {
  14716. // C++0x [dcl.enum]p5:
  14717. // If the underlying type is not fixed, the type of each enumerator
  14718. // is the type of its initializing value:
  14719. // - If no initializer is specified for the first enumerator, the
  14720. // initializing value has an unspecified integral type.
  14721. //
  14722. // GCC uses 'int' for its unspecified integral type, as does
  14723. // C99 6.7.2.2p3.
  14724. if (Enum->isFixed()) {
  14725. EltTy = Enum->getIntegerType();
  14726. }
  14727. else {
  14728. EltTy = Context.IntTy;
  14729. }
  14730. } else {
  14731. // Assign the last value + 1.
  14732. EnumVal = LastEnumConst->getInitVal();
  14733. ++EnumVal;
  14734. EltTy = LastEnumConst->getType();
  14735. // Check for overflow on increment.
  14736. if (EnumVal < LastEnumConst->getInitVal()) {
  14737. // C++0x [dcl.enum]p5:
  14738. // If the underlying type is not fixed, the type of each enumerator
  14739. // is the type of its initializing value:
  14740. //
  14741. // - Otherwise the type of the initializing value is the same as
  14742. // the type of the initializing value of the preceding enumerator
  14743. // unless the incremented value is not representable in that type,
  14744. // in which case the type is an unspecified integral type
  14745. // sufficient to contain the incremented value. If no such type
  14746. // exists, the program is ill-formed.
  14747. QualType T = getNextLargerIntegralType(Context, EltTy);
  14748. if (T.isNull() || Enum->isFixed()) {
  14749. // There is no integral type larger enough to represent this
  14750. // value. Complain, then allow the value to wrap around.
  14751. EnumVal = LastEnumConst->getInitVal();
  14752. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14753. ++EnumVal;
  14754. if (Enum->isFixed())
  14755. // When the underlying type is fixed, this is ill-formed.
  14756. Diag(IdLoc, diag::err_enumerator_wrapped)
  14757. << EnumVal.toString(10)
  14758. << EltTy;
  14759. else
  14760. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14761. << EnumVal.toString(10);
  14762. } else {
  14763. EltTy = T;
  14764. }
  14765. // Retrieve the last enumerator's value, extent that type to the
  14766. // type that is supposed to be large enough to represent the incremented
  14767. // value, then increment.
  14768. EnumVal = LastEnumConst->getInitVal();
  14769. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14770. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14771. ++EnumVal;
  14772. // If we're not in C++, diagnose the overflow of enumerator values,
  14773. // which in C99 means that the enumerator value is not representable in
  14774. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14775. // permits enumerator values that are representable in some larger
  14776. // integral type.
  14777. if (!getLangOpts().CPlusPlus && !T.isNull())
  14778. Diag(IdLoc, diag::warn_enum_value_overflow);
  14779. } else if (!getLangOpts().CPlusPlus &&
  14780. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14781. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14782. Diag(IdLoc, diag::ext_enum_value_not_int)
  14783. << EnumVal.toString(10) << 1;
  14784. }
  14785. }
  14786. }
  14787. if (!EltTy->isDependentType()) {
  14788. // Make the enumerator value match the signedness and size of the
  14789. // enumerator's type.
  14790. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14791. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14792. }
  14793. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14794. Val, EnumVal);
  14795. }
  14796. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14797. SourceLocation IILoc) {
  14798. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14799. !getLangOpts().CPlusPlus)
  14800. return SkipBodyInfo();
  14801. // We have an anonymous enum definition. Look up the first enumerator to
  14802. // determine if we should merge the definition with an existing one and
  14803. // skip the body.
  14804. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14805. forRedeclarationInCurContext());
  14806. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14807. if (!PrevECD)
  14808. return SkipBodyInfo();
  14809. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14810. NamedDecl *Hidden;
  14811. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14812. SkipBodyInfo Skip;
  14813. Skip.Previous = Hidden;
  14814. return Skip;
  14815. }
  14816. return SkipBodyInfo();
  14817. }
  14818. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14819. SourceLocation IdLoc, IdentifierInfo *Id,
  14820. const ParsedAttributesView &Attrs,
  14821. SourceLocation EqualLoc, Expr *Val) {
  14822. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14823. EnumConstantDecl *LastEnumConst =
  14824. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14825. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14826. // we find one that is.
  14827. S = getNonFieldDeclScope(S);
  14828. // Verify that there isn't already something declared with this name in this
  14829. // scope.
  14830. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  14831. LookupName(R, S);
  14832. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  14833. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14834. // Maybe we will complain about the shadowed template parameter.
  14835. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14836. // Just pretend that we didn't see the previous declaration.
  14837. PrevDecl = nullptr;
  14838. }
  14839. // C++ [class.mem]p15:
  14840. // If T is the name of a class, then each of the following shall have a name
  14841. // different from T:
  14842. // - every enumerator of every member of class T that is an unscoped
  14843. // enumerated type
  14844. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14845. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14846. DeclarationNameInfo(Id, IdLoc));
  14847. EnumConstantDecl *New =
  14848. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14849. if (!New)
  14850. return nullptr;
  14851. if (PrevDecl) {
  14852. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  14853. // Check for other kinds of shadowing not already handled.
  14854. CheckShadow(New, PrevDecl, R);
  14855. }
  14856. // When in C++, we may get a TagDecl with the same name; in this case the
  14857. // enum constant will 'hide' the tag.
  14858. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14859. "Received TagDecl when not in C++!");
  14860. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14861. if (isa<EnumConstantDecl>(PrevDecl))
  14862. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14863. else
  14864. Diag(IdLoc, diag::err_redefinition) << Id;
  14865. notePreviousDefinition(PrevDecl, IdLoc);
  14866. return nullptr;
  14867. }
  14868. }
  14869. // Process attributes.
  14870. ProcessDeclAttributeList(S, New, Attrs);
  14871. AddPragmaAttributes(S, New);
  14872. // Register this decl in the current scope stack.
  14873. New->setAccess(TheEnumDecl->getAccess());
  14874. PushOnScopeChains(New, S);
  14875. ActOnDocumentableDecl(New);
  14876. return New;
  14877. }
  14878. // Returns true when the enum initial expression does not trigger the
  14879. // duplicate enum warning. A few common cases are exempted as follows:
  14880. // Element2 = Element1
  14881. // Element2 = Element1 + 1
  14882. // Element2 = Element1 - 1
  14883. // Where Element2 and Element1 are from the same enum.
  14884. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14885. Expr *InitExpr = ECD->getInitExpr();
  14886. if (!InitExpr)
  14887. return true;
  14888. InitExpr = InitExpr->IgnoreImpCasts();
  14889. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14890. if (!BO->isAdditiveOp())
  14891. return true;
  14892. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14893. if (!IL)
  14894. return true;
  14895. if (IL->getValue() != 1)
  14896. return true;
  14897. InitExpr = BO->getLHS();
  14898. }
  14899. // This checks if the elements are from the same enum.
  14900. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  14901. if (!DRE)
  14902. return true;
  14903. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  14904. if (!EnumConstant)
  14905. return true;
  14906. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  14907. Enum)
  14908. return true;
  14909. return false;
  14910. }
  14911. // Emits a warning when an element is implicitly set a value that
  14912. // a previous element has already been set to.
  14913. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  14914. EnumDecl *Enum, QualType EnumType) {
  14915. // Avoid anonymous enums
  14916. if (!Enum->getIdentifier())
  14917. return;
  14918. // Only check for small enums.
  14919. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  14920. return;
  14921. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  14922. return;
  14923. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  14924. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  14925. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  14926. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  14927. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  14928. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  14929. llvm::APSInt Val = D->getInitVal();
  14930. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  14931. };
  14932. DuplicatesVector DupVector;
  14933. ValueToVectorMap EnumMap;
  14934. // Populate the EnumMap with all values represented by enum constants without
  14935. // an initializer.
  14936. for (auto *Element : Elements) {
  14937. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  14938. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  14939. // this constant. Skip this enum since it may be ill-formed.
  14940. if (!ECD) {
  14941. return;
  14942. }
  14943. // Constants with initalizers are handled in the next loop.
  14944. if (ECD->getInitExpr())
  14945. continue;
  14946. // Duplicate values are handled in the next loop.
  14947. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  14948. }
  14949. if (EnumMap.size() == 0)
  14950. return;
  14951. // Create vectors for any values that has duplicates.
  14952. for (auto *Element : Elements) {
  14953. // The last loop returned if any constant was null.
  14954. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  14955. if (!ValidDuplicateEnum(ECD, Enum))
  14956. continue;
  14957. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  14958. if (Iter == EnumMap.end())
  14959. continue;
  14960. DeclOrVector& Entry = Iter->second;
  14961. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14962. // Ensure constants are different.
  14963. if (D == ECD)
  14964. continue;
  14965. // Create new vector and push values onto it.
  14966. auto Vec = std::make_unique<ECDVector>();
  14967. Vec->push_back(D);
  14968. Vec->push_back(ECD);
  14969. // Update entry to point to the duplicates vector.
  14970. Entry = Vec.get();
  14971. // Store the vector somewhere we can consult later for quick emission of
  14972. // diagnostics.
  14973. DupVector.emplace_back(std::move(Vec));
  14974. continue;
  14975. }
  14976. ECDVector *Vec = Entry.get<ECDVector*>();
  14977. // Make sure constants are not added more than once.
  14978. if (*Vec->begin() == ECD)
  14979. continue;
  14980. Vec->push_back(ECD);
  14981. }
  14982. // Emit diagnostics.
  14983. for (const auto &Vec : DupVector) {
  14984. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14985. // Emit warning for one enum constant.
  14986. auto *FirstECD = Vec->front();
  14987. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  14988. << FirstECD << FirstECD->getInitVal().toString(10)
  14989. << FirstECD->getSourceRange();
  14990. // Emit one note for each of the remaining enum constants with
  14991. // the same value.
  14992. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  14993. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  14994. << ECD << ECD->getInitVal().toString(10)
  14995. << ECD->getSourceRange();
  14996. }
  14997. }
  14998. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14999. bool AllowMask) const {
  15000. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15001. assert(ED->isCompleteDefinition() && "expected enum definition");
  15002. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15003. llvm::APInt &FlagBits = R.first->second;
  15004. if (R.second) {
  15005. for (auto *E : ED->enumerators()) {
  15006. const auto &EVal = E->getInitVal();
  15007. // Only single-bit enumerators introduce new flag values.
  15008. if (EVal.isPowerOf2())
  15009. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15010. }
  15011. }
  15012. // A value is in a flag enum if either its bits are a subset of the enum's
  15013. // flag bits (the first condition) or we are allowing masks and the same is
  15014. // true of its complement (the second condition). When masks are allowed, we
  15015. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15016. //
  15017. // While it's true that any value could be used as a mask, the assumption is
  15018. // that a mask will have all of the insignificant bits set. Anything else is
  15019. // likely a logic error.
  15020. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15021. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15022. }
  15023. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15024. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15025. const ParsedAttributesView &Attrs) {
  15026. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15027. QualType EnumType = Context.getTypeDeclType(Enum);
  15028. ProcessDeclAttributeList(S, Enum, Attrs);
  15029. if (Enum->isDependentType()) {
  15030. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15031. EnumConstantDecl *ECD =
  15032. cast_or_null<EnumConstantDecl>(Elements[i]);
  15033. if (!ECD) continue;
  15034. ECD->setType(EnumType);
  15035. }
  15036. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15037. return;
  15038. }
  15039. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15040. // long value. ISO C does not support this, but GCC does as an extension,
  15041. // emit a warning.
  15042. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15043. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15044. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15045. // Verify that all the values are okay, compute the size of the values, and
  15046. // reverse the list.
  15047. unsigned NumNegativeBits = 0;
  15048. unsigned NumPositiveBits = 0;
  15049. // Keep track of whether all elements have type int.
  15050. bool AllElementsInt = true;
  15051. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15052. EnumConstantDecl *ECD =
  15053. cast_or_null<EnumConstantDecl>(Elements[i]);
  15054. if (!ECD) continue; // Already issued a diagnostic.
  15055. const llvm::APSInt &InitVal = ECD->getInitVal();
  15056. // Keep track of the size of positive and negative values.
  15057. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15058. NumPositiveBits = std::max(NumPositiveBits,
  15059. (unsigned)InitVal.getActiveBits());
  15060. else
  15061. NumNegativeBits = std::max(NumNegativeBits,
  15062. (unsigned)InitVal.getMinSignedBits());
  15063. // Keep track of whether every enum element has type int (very common).
  15064. if (AllElementsInt)
  15065. AllElementsInt = ECD->getType() == Context.IntTy;
  15066. }
  15067. // Figure out the type that should be used for this enum.
  15068. QualType BestType;
  15069. unsigned BestWidth;
  15070. // C++0x N3000 [conv.prom]p3:
  15071. // An rvalue of an unscoped enumeration type whose underlying
  15072. // type is not fixed can be converted to an rvalue of the first
  15073. // of the following types that can represent all the values of
  15074. // the enumeration: int, unsigned int, long int, unsigned long
  15075. // int, long long int, or unsigned long long int.
  15076. // C99 6.4.4.3p2:
  15077. // An identifier declared as an enumeration constant has type int.
  15078. // The C99 rule is modified by a gcc extension
  15079. QualType BestPromotionType;
  15080. bool Packed = Enum->hasAttr<PackedAttr>();
  15081. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15082. // enum definitions.
  15083. if (LangOpts.ShortEnums)
  15084. Packed = true;
  15085. // If the enum already has a type because it is fixed or dictated by the
  15086. // target, promote that type instead of analyzing the enumerators.
  15087. if (Enum->isComplete()) {
  15088. BestType = Enum->getIntegerType();
  15089. if (BestType->isPromotableIntegerType())
  15090. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15091. else
  15092. BestPromotionType = BestType;
  15093. BestWidth = Context.getIntWidth(BestType);
  15094. }
  15095. else if (NumNegativeBits) {
  15096. // If there is a negative value, figure out the smallest integer type (of
  15097. // int/long/longlong) that fits.
  15098. // If it's packed, check also if it fits a char or a short.
  15099. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15100. BestType = Context.SignedCharTy;
  15101. BestWidth = CharWidth;
  15102. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15103. NumPositiveBits < ShortWidth) {
  15104. BestType = Context.ShortTy;
  15105. BestWidth = ShortWidth;
  15106. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15107. BestType = Context.IntTy;
  15108. BestWidth = IntWidth;
  15109. } else {
  15110. BestWidth = Context.getTargetInfo().getLongWidth();
  15111. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15112. BestType = Context.LongTy;
  15113. } else {
  15114. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15115. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15116. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15117. BestType = Context.LongLongTy;
  15118. }
  15119. }
  15120. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15121. } else {
  15122. // If there is no negative value, figure out the smallest type that fits
  15123. // all of the enumerator values.
  15124. // If it's packed, check also if it fits a char or a short.
  15125. if (Packed && NumPositiveBits <= CharWidth) {
  15126. BestType = Context.UnsignedCharTy;
  15127. BestPromotionType = Context.IntTy;
  15128. BestWidth = CharWidth;
  15129. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15130. BestType = Context.UnsignedShortTy;
  15131. BestPromotionType = Context.IntTy;
  15132. BestWidth = ShortWidth;
  15133. } else if (NumPositiveBits <= IntWidth) {
  15134. BestType = Context.UnsignedIntTy;
  15135. BestWidth = IntWidth;
  15136. BestPromotionType
  15137. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15138. ? Context.UnsignedIntTy : Context.IntTy;
  15139. } else if (NumPositiveBits <=
  15140. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15141. BestType = Context.UnsignedLongTy;
  15142. BestPromotionType
  15143. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15144. ? Context.UnsignedLongTy : Context.LongTy;
  15145. } else {
  15146. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15147. assert(NumPositiveBits <= BestWidth &&
  15148. "How could an initializer get larger than ULL?");
  15149. BestType = Context.UnsignedLongLongTy;
  15150. BestPromotionType
  15151. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15152. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15153. }
  15154. }
  15155. // Loop over all of the enumerator constants, changing their types to match
  15156. // the type of the enum if needed.
  15157. for (auto *D : Elements) {
  15158. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15159. if (!ECD) continue; // Already issued a diagnostic.
  15160. // Standard C says the enumerators have int type, but we allow, as an
  15161. // extension, the enumerators to be larger than int size. If each
  15162. // enumerator value fits in an int, type it as an int, otherwise type it the
  15163. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15164. // that X has type 'int', not 'unsigned'.
  15165. // Determine whether the value fits into an int.
  15166. llvm::APSInt InitVal = ECD->getInitVal();
  15167. // If it fits into an integer type, force it. Otherwise force it to match
  15168. // the enum decl type.
  15169. QualType NewTy;
  15170. unsigned NewWidth;
  15171. bool NewSign;
  15172. if (!getLangOpts().CPlusPlus &&
  15173. !Enum->isFixed() &&
  15174. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15175. NewTy = Context.IntTy;
  15176. NewWidth = IntWidth;
  15177. NewSign = true;
  15178. } else if (ECD->getType() == BestType) {
  15179. // Already the right type!
  15180. if (getLangOpts().CPlusPlus)
  15181. // C++ [dcl.enum]p4: Following the closing brace of an
  15182. // enum-specifier, each enumerator has the type of its
  15183. // enumeration.
  15184. ECD->setType(EnumType);
  15185. continue;
  15186. } else {
  15187. NewTy = BestType;
  15188. NewWidth = BestWidth;
  15189. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15190. }
  15191. // Adjust the APSInt value.
  15192. InitVal = InitVal.extOrTrunc(NewWidth);
  15193. InitVal.setIsSigned(NewSign);
  15194. ECD->setInitVal(InitVal);
  15195. // Adjust the Expr initializer and type.
  15196. if (ECD->getInitExpr() &&
  15197. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15198. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15199. CK_IntegralCast,
  15200. ECD->getInitExpr(),
  15201. /*base paths*/ nullptr,
  15202. VK_RValue));
  15203. if (getLangOpts().CPlusPlus)
  15204. // C++ [dcl.enum]p4: Following the closing brace of an
  15205. // enum-specifier, each enumerator has the type of its
  15206. // enumeration.
  15207. ECD->setType(EnumType);
  15208. else
  15209. ECD->setType(NewTy);
  15210. }
  15211. Enum->completeDefinition(BestType, BestPromotionType,
  15212. NumPositiveBits, NumNegativeBits);
  15213. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15214. if (Enum->isClosedFlag()) {
  15215. for (Decl *D : Elements) {
  15216. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15217. if (!ECD) continue; // Already issued a diagnostic.
  15218. llvm::APSInt InitVal = ECD->getInitVal();
  15219. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15220. !IsValueInFlagEnum(Enum, InitVal, true))
  15221. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15222. << ECD << Enum;
  15223. }
  15224. }
  15225. // Now that the enum type is defined, ensure it's not been underaligned.
  15226. if (Enum->hasAttrs())
  15227. CheckAlignasUnderalignment(Enum);
  15228. }
  15229. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15230. SourceLocation StartLoc,
  15231. SourceLocation EndLoc) {
  15232. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15233. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15234. AsmString, StartLoc,
  15235. EndLoc);
  15236. CurContext->addDecl(New);
  15237. return New;
  15238. }
  15239. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15240. IdentifierInfo* AliasName,
  15241. SourceLocation PragmaLoc,
  15242. SourceLocation NameLoc,
  15243. SourceLocation AliasNameLoc) {
  15244. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15245. LookupOrdinaryName);
  15246. AsmLabelAttr *Attr =
  15247. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  15248. // If a declaration that:
  15249. // 1) declares a function or a variable
  15250. // 2) has external linkage
  15251. // already exists, add a label attribute to it.
  15252. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15253. if (isDeclExternC(PrevDecl))
  15254. PrevDecl->addAttr(Attr);
  15255. else
  15256. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15257. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15258. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15259. } else
  15260. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15261. }
  15262. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15263. SourceLocation PragmaLoc,
  15264. SourceLocation NameLoc) {
  15265. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15266. if (PrevDecl) {
  15267. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  15268. } else {
  15269. (void)WeakUndeclaredIdentifiers.insert(
  15270. std::pair<IdentifierInfo*,WeakInfo>
  15271. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15272. }
  15273. }
  15274. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15275. IdentifierInfo* AliasName,
  15276. SourceLocation PragmaLoc,
  15277. SourceLocation NameLoc,
  15278. SourceLocation AliasNameLoc) {
  15279. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15280. LookupOrdinaryName);
  15281. WeakInfo W = WeakInfo(Name, NameLoc);
  15282. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15283. if (!PrevDecl->hasAttr<AliasAttr>())
  15284. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15285. DeclApplyPragmaWeak(TUScope, ND, W);
  15286. } else {
  15287. (void)WeakUndeclaredIdentifiers.insert(
  15288. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15289. }
  15290. }
  15291. Decl *Sema::getObjCDeclContext() const {
  15292. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15293. }